text:
Q: WebDriver is unable to locate elements. But it locates when i directly access the webpage Automation: Booking bus ticket
Description:

*

*WebDriver is unable to locate the elements when i enter into the
webpage (passengerDetails)

*But when i access that page (passengerDetails) directly, it locates
the elements.
Note: Accessing SearchBus->SelectBus->SelectSeat->PassengerDetails - Unable to locate..
    Accessing directly PassengerDetails -Able to Locate..  I guess, this is since the URL changes from http to https. Anyhow suggest me a solution for this..

A: So your site is definitely using iframe type. Basically to make your code work, you need to switch back from "iframe" to your site.
try this code
driver.switchTo().defaultContent();

A: Find Below the code for your requirement. It worked for me till the point of entering passenger details. Let me know if this was not you were looking for.
package org.com.selen;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;

public class JetBus {

    protected static WebDriver driver;

    public static void main(String[] args) {

        System.setProperty("webdriver.ie.driver", "E:\\Books&Tutorials\\Selenium\\IEDriverServer.exe");
        driver = new InternetExplorerDriver();
        driver.get("www.jetbus.in");
        driver.findElement(By.id("o_source")).clear();
        driver.findElement(By.id("o_source")).sendKeys("Bangalore");
        driver.findElement(By.id("o_dest")).clear();
        driver.findElement(By.id("o_dest")).sendKeys("Hyderabad");
        driver.findElement(By.id("departDate")).click();
        driver.findElement(By.linkText("11")).click();
        driver.findElement(By.id("search")).click();
        driver.findElement(By.xpath("//img[contains(@src,'http://jetbus.in/images/viewseats.png')]")).click();

//We need to switch to the fancybox frame before performing next set of operations
driver.switchTo().frame("fancybox-frame");
        driver.findElement(By.id("availableSeatImgId33")).click();
        new Select(driver.findElement(By.id("boardingPoint"))).selectByVisibleText("Hebbal - 11:05 pm");
        driver.findElement(By.cssSelector("option[value=\"122989^11:05 pm\"]")).click();
        driver.findElement(By.id("continue")).click();

//After you click Continue, it directly returns to passenger details page.
new Select(driver.findElement(By.id("i_passengerGender"))).selectByVisibleText("Mr");
        driver.findElement(By.id("i_passengerName")).clear();
        driver.findElement(By.id("i_passengerName")).sendKeys("JetBusPassenger");
        driver.findElement(By.id("i_passengerAge")).clear();
        driver.findElement(By.id("i_passengerAge")).sendKeys("49");
        driver.findElement(By.id("i_passengerMobile")).clear();
        driver.findElement(By.id("i_passengerMobile")).sendKeys("3698521463");
        driver.findElement(By.id("i_passengerEmail")).clear();
        driver.findElement(By.id("i_passengerEmail")).sendKeys("a_b@jetbus.com");
        driver.findElement(By.name("ContinuePayNew")).click();
        driver.findElement(By.cssSelector("div.notAvailableDiv > a > span")).click();

    }

}


text:
Q: Custom PopUp modal component not showing when clicked in React I am trying to show a custom PopUp component on the screen when a user clicks on the Info icon but nothing is rendering in the UI when clicked.
I'm not exactly certain where I'm going wrong if anyone could provide some guidance?
Here is my Card component with PopUp inside the return:
import React, { useState } from 'react';
import { Card } from 'react-bootstrap';
import InfoIcon from '@material-ui/icons/Info';
import PopUp from './PopUp';

const WelcomeCard = (props) => {
  const [show, setShow] = useState(false);

  const togglePop = () => {
    setShow(true);
  };

  return (
    <Card className='m-3 p-2 welcome-card rounded'>
      <Card.Body>
        <Card.Text className='mt-4'>{props.text}</Card.Text>
        <Card.Title>{props.title}</Card.Title>
        <button>{props.button}</button>
        {show && <PopUp toggle={togglePop} />}
        <InfoIcon className='info-icon' onClick={togglePop} />
      </Card.Body>
    </Card>
  );
};

export default WelcomeCard;

And my actual PopUp component itself:
import React from 'react';

const PopUp = (props) => {
  const handleClick = () => {
    props.toggle();
  };

  return (

          ×

        <form>

Register!

            Name:
            <input type='text' name='name' />

          <input type='submit' />
        </form>

  );
};

export default PopUp;

Would really appreciate some help on this one to understand it better, thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Object change after calling call_user_func_array, but variable is not I am trying to build a custom event management.
However, I have something need help. Please check following code I did:
class A
{
    public $a = array();

    public function setA($value)
    {
        $this->a[] = $value;
    }
}

class B
{
    public function hook($arg)
    {
        $arg->setA('5');
    }

    public function hook2($arg)
    {
        $arg[] = 'my name';
    }
}
$a = new A();

call_user_func_array(array(new B, 'hook'), array($a));

var_dump($a->a);

$name = array();
call_user_func_array(array(new B, 'hook2'), array($name));

var_dump($name);

Here is what I see on my sceeen:
array (size=1)
  0 => string '5' (length=1)

array (size=0)
  empty

You can see object a was changed but array $name is not. I passed values to call_user_func_array, not reference.
I am abit confused by that. Can anyone explain how does it work?
Thank you so much

A: Object are always passed by reference (kinda - it's more like a copy of the identifier of the object), unlike other types, like array, that doesn't. To passing the parameter by reference, use the &:
public function hook2(&$arg)
{
    $arg[] = 'my name';
}

Then call it with
call_user_func_array(array(new B, 'hook2'), array(&$name));


text:
Q: my controller spec on email confirmation fails Here Im testing email confirmation fails. In dev mode everything works just ok. And I think that I've missed some configurations.
context 'with valid provider data' do
  before { session["devise.provider_data"] = { provider: 'twitter', uid: '123456' } }
  it "sends email confirmation" do
    expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)
  end
end

And the error
Failure/Error: expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)
   expected #count to have changed by 1, but was changed by 0

Coul anybody help with this?
context 'with valid provider data' do
  before { session["devise.provider_data"] = { provider: 'twitter', uid: '123456' } }
  before(:each) do
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []
  end

  after(:each) do
    ActionMailer::Base.deliveries.clear
  end

  it "sends email confirmation" do
    expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)
  end
end

A: You are missing some configuration. I usually do the setup in a before and after callback before tests that test email behaviour, such as:
before(:each) do
  ActionMailer::Base.delivery_method = :test
  ActionMailer::Base.perform_deliveries = true
  ActionMailer::Base.deliveries = []
end

after(:each) do
  ActionMailer::Base.deliveries.clear
end

If you want the above configuration to apply to all your test suite, you could include it in your spec/spec_helper.rb file in the configure block:
RSpec.configure do |config|
  ....

  config.before(:suite) do
      ActionMailer::Base.delivery_method = :test
      ActionMailer::Base.perform_deliveries = true
      ActionMailer::Base.deliveries = []
  end

  config.after(:suite) do
      ActionMailer::Base.deliveries.clear
  end
end


text:
Q: How do you delete a specific table in sqlite in android studio? Ive got an app that im creating where i want to be able to type in the users username and click delete then it will delete all of the data for that specific user, Eg-address, phone, birthdate. But for some reason when on the manage user activity when i click the remove button which should take me to the remove activity it takes me back to the main activity instead! Can anyone see what ive done wrong please!!!
Remove class:
public class Remove extends AppCompatActivity {

DatabaseHelperUser myDb;

Button btRemove = findViewById(R.id.buttonRemove);

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

    final EditText etUser = findViewById(R.id.editTextUser);
    myDb = new DatabaseHelperUser(this);

    btRemove.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            Integer deletedRows = myDb.deleteData(etUser.getText().toString());
            if(deletedRows > 0){
                Toast.makeText(getApplicationContext(), "Data Deleted", Toast.LENGTH_LONG).show();}
            else{
                Toast.makeText(getApplicationContext(), "Data has not been Deleted", Toast.LENGTH_LONG).show();}

        }
    });

}

}
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "UserNum";
public static final String COL2 = "UserName";
public static final String COL3 = "Password";
public static final String COL4 = "BirthDate";
public static final String COL5 = "Phone";
public static final String COL6 = "Address";

public  DatabaseHelperUser(Context context){
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("create table " + TABLE_NAME + " (UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
public Cursor getData(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
    return res;
}
public Integer deleteData(String UserName){
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName});

}

}
Manage user class:
public class ManagingUsers extends AppCompatActivity {

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

    final Button btadd = findViewById(R.id.buttonAdd);
    final Button btInventory = findViewById(R.id.buttonInventory2);
    final Button btView = findViewById(R.id.buttonView);
    final Button btRemove = findViewById(R.id.buttonRemove);

    btadd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(), Add.class);
            startActivity(i);
        }
    });
    btInventory.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(), Inventory.class);
            startActivity(i);
        }
    });
    btView.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(), com.example.assignment3.View.class);
            startActivity(i);
        }
    });
    btRemove.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(), com.example.assignment3.Remove.class);
            startActivity(i);

        }
    });

}

}


text:
Q: how to catch the unauthenticated response 401 from django rest api in react native Here in views.py
class StockList(APIView):
#authentication_classes = (TokenAuthentication,)
permission_classes = [IsAuthenticated]

def get(self,request):
     stocks = Stock.objects.all()
     serializer = StockSerializer(stocks,many=True)
     return Response({'user': serializer.data,'post': serializer.data})
def post(self):
     pass

Here if token is not valid then it doesnt send any data..
so in react native I have to patch that error and show their invalid credentials.
So here is my react.js file
  componentDidMount() {
  return fetch('http://10.42.0.1:8000/stocks/',
  {
    method: "GET",
    headers: {
      'Authorization': `JWT ${"eyJhbGciOiIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNhbSIsInVzZXJfaWQiOjYxLCJlbWFpbCI6IiIsImV4cCI6MTUwNDAxNTg4M30.o_NjgPNsxnLU6erGj5Tonap3FQFxN3Hh_SsU6IvLO9k"}`
  }
})

  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData.detail);
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.setState({
      isLoading: false,
      sa: ds.cloneWithRows(responseData.post),

    }, function() {

    });
  })
  .catch((error) => {
    console.error(error);
  });
}

here if json data is not provided then show some error..
how could I accopmlished that.
thank you.


text:
Q: Is it possible to display just the preview with markitUp? Is there a way to display only preview window with markitUp!, http://markitup.jaysalvat.com/, during text input from the user?
I found nothing about this in markitUp! documentation.
In fact, I think viewing source code of a message can be embarrassing for
an average user.


text:
Q: Using the ProgressBar with the Grid SO...

*

*I want to use this:
http://demos.telerik.com/kendo-ui/progressbar/angular

*With this:
http://docs.telerik.com/kendo-ui/AngularJS/the-grid-widget
We already have the Grid implemented and working, but the hurdle is that the basic progress indicator doesn't work for us and I'm tasked with getting the ProgressBar into place because in some cases we have extremely long load times for huge record sets.
Has anybody got this to work, and if so - do you have an example?
I made an attempt to hook into the Grid's data loading process (dataBinding and dataBound), but did not seem to get anywhere.  I have an understanding that another controller may be needed just for the ProgressBar to do its updating, but am hoping I can compartmentalize it to the binding events.
The trickiest part will be making the loading seem as realistic as possible, since the timing on this will vary widely.
We're using Breeze JS and WebAPI service endpoints for loading data.  Breeze is an OData data layer provider for the client-server relationship.
We are using very strict standards around Angular, so using Jquery is not an option to direct hook into the DOM unless I can really justify it cannot be done any other way.

*

*Here's the Progress Bar API:
http://docs.telerik.com/kendo-ui/api/javascript/ui/progressbar

*Here's the Grid API:
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid

*And the BreezeJS Api:
http://www.breezejs.com/sites/all/apidocs/index.html
Thanks in advance for any help or guidance anyone can provide.  Let me know if you need code samples, but the API pretty much provides everything.

A: I used a column template and got the progress bar working in the grid, all angular-zen.
With the grid set up using angular-kendo directives like this:

In the controller I put, say:
    $scope.columns = [

    { "field": "Name", "title": "File Name", width: 50 },

    {"field":"progressBar","title":"progress", width: 70,
      template: "

"}

    ];

and everything worked!
dataItem.Progress is a field  in your datasource, or underlying js array,and the value for your progressbar.


text:
Q: Method of a instance runs twice when called When I import a class to a different file, intance it and call one of it's methods, it runs twice
The class itself is:
class DBAuth(object):
    def __init__(self, driver=None, username=None, password=None,
                 host='localhost', port=None, database=None):
        self.driver = driver
        self.username = username
        self.password = password
        self.host = host
        self.port = port
        self.database = database

    def test_method(self):
        teststr = "database is '{0}' and your user is '{1}'".format(
                self.database, self.username)
        return teststr

And I'm using it like this:
from lbauth.model import DBAuth

dbauth = DBAuth(
    driver = 'postgresql',
    username = 'user',
    password = 'passwd',
    host = 'localhost',
    port = '5432',
    database = 'dbname'
)

print(dbauth.test_method())

which returns:
>database is 'dbname' and your user is 'user'
>database is 'dbname' and your user is 'user'

Why does it behave like this and what would be the correct way to call this method properly?

A: I found out the problem.
Turns out I was using __init__.py to import and test scripts, which is a bad practice.


text:
Q: RegEx - allow whitespace at start and end of the string with fixed length Currently I am working on a regex with the following conditions:

*

*Can accept whitespace at start and end of the string

*Can accept hyphen in mid/end of the string

*Length of the characters should not be more than 10 and less than 8 (excluding spaces)
I have created below regex but somehow length validation is not working as expected.
(^\s*?)((?!(-))([0-9-]*)){8,10}(\s*?)$
https://regex101.com/r/aJNmqj/1

A: You should be able to achieve this with a simple regex like this: ^(\s*?)[0-9-]{8,10}(\s*?)$
I believe your other one didn't work because negative lookaheads can't be operated on by the quantifier {8,10} Fortunately, the negative lookahead isn't actually necessary.
Your regex got convoluted while you were trying to do this I bet, because it's happened to me too.

A: From your original regex fragment [0-9-]* it looks like you want to allow only digits and dashes. Here is a solution that:

*

*allows 8-10 digits or dashes

*no dash in the beginning

*may have leading and trailing spaces

Code with test cases:

const regex = /^(?!\s*-)\s*[0-9-]{8,10}\s*$/;
[
  '1234567',
  ' 123 456 7 ',
  '12345678',
  '1234567-',
  '123-5678',
  '-2345678',
  ' 12345678 ',
  ' 123 456 78 ',
  '12345678',
  '12345678 ',
  '12 34 56 78 ',
  '123456789',
  ' 123456789',
  ' 12 34 56 78 9',
  '1234567890',
  ' 123 456 7890',
  '12345678901'
].forEach(str => {
  let ok = regex.test(str);
  console.log('"' + str + '" ==> ' + ok);
});

Explanation of regex:

*

*^ -- anchor at start of string

*(?!\s*-) -- negative lookahead for optional spaces and dash

*\s* -- optional spaces

*[0-9-]{8,10} -- 8 to 10 digits/dashes

*\s* -- optional spaces

*$ -- anchor at end of string

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

A: Your pattern matches too much because it first matches optional leading whitespace chars.
But when it gets to the first digit in the example string, in this part ((?!(-))([0-9-]*)){8,10} the assertion (?!(-) is true and then this part [0-9-]* matches to the last digit in the example string.
It can then fulfill repeating the quantifier {8,10} as it already is at the position after the last digit in the example string where there is no - following and it can match optional digits.

You could start the pattern with optional whitespace chars followed by a digit, and then match 7-9 digits or hyphens:
^\s*[0-9][0-9-]{7,9}\s*$

See a regex101 demo.


text:
Q: How can I authenticate users on a CMS for an iphone app? I am working on an iPhone app which will fetch data (images + text) from a CMS. I had a look at the Wordpress CMS, but the app is subscription based. How should I go about authenticating the subscribers which are being directed to the cms?
Can anyone guide me?
Thanks

A: Your question is a bit vague, and broad, perhaps if you broke it down a bit.
Are you using an iphone app, or a standard page with a Mobil browser?
If it's an standalone app are you having problems getting it to talk to your server/CMS?
You having problems authenticating https vs http?
If your having problems with your cms or are you after cms to start with?
From the sound of it Drupal could work well with the services module and probably Ubercart to handle the subscription. With zen (base theme) and some modifications** you can make it Mobil friendly.
http://drupal.org/start
http://drupal.org/project/services
http://drupal.org/project/ubercart
http://drupal.org/project/zen
** http://drupal.org/node/1008582


text:
Q: Uncaught TypeError: Cannot read property 'print' of undefined I have implemented Print functionality where a new print window will open upon click of a button. Due to change in requirement, I commented it out and everything was going fine. Client wanted to have the printing functionality again. So, I just uncommented

Uncaught TypeError: Cannot read property 'print' of undefined

I cleared cache, repackaged everything and redeployed. Nothing is helping me fix this. Can you please let me know where I am doing wrong.
UPDATE
Guys,
I was using the following code to print it.
myWindow=window.open(url, "myWindow", "width=2000, height=1000");
    myWindow.print();

I figured out the problem. The popup was blocked. Once I allowed the popup, it worked fine.

A: Popup was blocked and so I was getting this error. Once I allowed the popup, it worked fine.


text:
Q: Change color just of part of select list label HTML I want to make a select list with two different colors in the label, like this :
the number is in blue, and per page in green color

My simple HTML code is :
<select>
 <option value="50">50</option>
 <option value="100">100</option>
 <option value="150">150</option>
 <option value="200">200</option>
</select>

A: As the others says you would need to use a custom select, here is a very basic example

$("ul").on("click", ".init", function() {
    $(this).closest("ul").children('li:not(.init)').toggle();
});

var allOptions = $("ul").children('li:not(.init)');
$("ul").on("click", "li:not(.init)", function() {
    allOptions.removeClass('selected');
    $(this).addClass('selected');
    $("ul").children('.init').html($(this).html());
    allOptions.toggle();
});
body{
  padding:30px;
}
ul {
    height: 30px;
    width: 150px;
    border: 1px #000 solid;
}
.init {
  color: blue;
}
ul li { padding: 5px 10px; z-index: 2; }
ul li:not(.init) { float: left; width: 130px; display: none; background: #ddd; color: orange;}
ul li:not(.init):hover, ul li.selected:not(.init) { background: #09f; }
li.init { cursor: pointer; }

a#submit { z-index: 1; }
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

[SELECT]

Option 1

Option 2

Option 3

I hope this helps


text:
Q: Best Ways to send message or data to fax machine I currently am working on a web application that needs to collect data from a form and will take the information and put it in a report format and sent it to a fax machine and print it out.
What is the easiest way to do this. I would like it to act similar to collecting informastion off of a form and then sending an email, but I would like to send it to a fax instead.
Thanks!

A: The quickest way is to use a middleware package or service which provides an API. A quick google search came up with these people.
If you want to manage the modem locally, there is a Windows COM object on some versions of the operating system which can do faxing for you.


text:
Q: Why does subtracting two UTC timestamps give "subtraction must have the same timezones or no timezones"? I am trying to compare a Pandas datetime to a Python datetime.
The code
cur_t = pandas.Timestamp.utcnow()

Gives:
Timestamp('2019-02-14 14:31:40.283415+0000', tz='UTC')

And the code
data_t=indata.data.loc[2000].last_time

Gives:
Timestamp('2019-02-14 14:28:32+0000', tz='UTC')

However, subtracting data_t from cur_t gives TypeError: Timestamp subtraction must have the same timezones or no timezones
What is going on here? Why can't andas compare two times with the same timezone?


text:
Q: How to specify in which order to load S4 methods when using roxygen2 I ran into following problem already multiple times.
Say you have two classes, classA and classB described in the following files classA.R :
#' the class classA
#'
#' This is a class A blabla
#' \section{Slots}{\describe{\item{\code{A}}{a Character}}}
#' @ name classA
#' @rdname classA
#' @exportClass classA
setClass("classA",representation(A="character"))

And classB.R
#' the class classB
#'
#' This is a class B blabla
#' \section{Slots}{\describe{\item{\code{B}}{an object of class A}}}
#' @ name classB
#' @rdname classB
#' @exportClass classB
setClass("classB",representation(B="classA"))

I believed these files were read in alphabetical order by roxygen2, but that is not the case. If I try to build the package, I might get the following error:
roxygenize("./myExample")
Error in getClass(Class, where = topenv(parent.frame())) :
   "ClassA" is not a defined class

How can I make sure that roxygenize() knows in which order to read the files, i.e. which class definition should be read before the other?

Note : I know I answered my own question. That is because I ran into this problem rather often, and realized the proper way to do this after looking at the code of roxygen2. So for reference, here's my findings.

A: There are two ways to achieve this:
As described in ?collate_roclet, you can use the @include tag to specify which class should be read before which. In this case, you can add to the file classB.r the following line right before the actual R code:
#' @include classA.r

These tags are read specifically to update the Collate field in the DESCRIPTION file, and are the recommended way of dealing with the problem.
In some cases the dependencies might be so complex you want to keep an overview yourself and not rely completely on adding @include tags in your codebase. In that case you can just specify the Collate field at the end of the DESCRIPTION file, like this:
Package: myExample
Type: Package
...
Collate:
    'classA.R'
    'classB.R'

The function roxygenize() first checks the DESCRIPTION file, and loads whatever files are specified there first in the order they're specified. Only then the rest of the package is loaded.


text:
Q: Close browser tab I have a page that tells users to go to their email and click verification link. When they do, the link in the email message opens a new tab, so now the user has two tabs open, both related to email, which is a bit confusing.

*

*Is there any chance to have them click the link in their email and open confirmation within the first tab or

*Open the new tab but at the same time close the original tab?
There's gotta be way with JS, I hope.

A: You can check periodically from the 1st tab if the email got activated then close it  window.close() , thus the remaining open tab would be the 2nd one, typically, you would implement something like that using setInterval and an ajax request to your server backend to check if the email was activated or not yet.

A: No, but you could run a Javascript in your first tab that pings your server every 10 seconds or so, to check if the account was confirmed.
If it was, then the page redirects itself to the new user's dashboard (or some other "main account page").
setInterval(function(){
    $.get('/api/is_confirmed.php').then(
        function(response){
            if (response.status_code == '200')
                window.location = '/dashboard.php';
        }
    );
}, 10000);

I would advise against self.close()ing the window. Do not interfere with the user's control of the browser tabs. Having tabs suddenly disappear by themselves is unexpected for the user and annoying at best, frightening at worst.

A: One thing you could do is:
1- Instead of having a link to your page in that email, put a link to a special page that changes a database value then closes itself.
2- On the main page, have a thread constantly poll that database value and as soon as you see the change, update the page with ajax (or refresh) then bring the broser on top of other windows.


text:
Q: How to mock user object to use get function of User class in drupal 8? I have written a custom service function which receive user id and get user details as an array. I have create one UserWrapper for User::load static function. But when i am running the test case I am getting error for $user->get() function.
Please guide me how to mock user object to use $user->get(). Please see the mock i have used bellow,
   $user_data = (object)[
  'first_name' => (object)[
    'value' => 'test'
  ],
  'field_middle_name' => (object)[
    'value' => 'test'
  ],
  'last_name' => (object)[
    'value' => 'test'
  ],
  'mail' => (object)[
    'value' => 'test@test.com'
  ],
  'field_telephone_number' => (object)[
    'value' => '9876543210'
  ],
  'field_mobile_number' => (object)[
    'value' => '9876543210'
  ],
];

$this->user
  ->method('load')
  ->willReturn($user_data);

A: $userDrupal = $this
  ->getMockBuilder(\Drupal\user\Entity\User::class)
  ->disableOriginalConstructor()
  ->getMock();

$entityStorageInterface = $this
  ->getMockBuilder(EntityStorageInterface::class)
  ->disableOriginalConstructor()
  ->setMethods(get_class_methods(EntityStorageInterface::class))
  ->getMock();
$entityStorageInterface
  ->expects($this->any())
  ->method('load')
  ->willReturn($userDrupal);

$entityTypeRepository = $this
  ->getMockBuilder(EntityTypeRepository::class)
  ->disableOriginalConstructor()
  ->getMock();
$container->set('entity_type.repository', $entityTypeRepository);

$entityTypeManagerService = $this
  ->getMockBuilder(EntityTypeManagerInterface::class)
  ->getMock();
$entityTypeManagerService
  ->expects($this->any())
  ->method('getStorage')
  ->willReturn($entityStorageInterface);
$container->set('entity_type.manager', $entityTypeManagerService);


text:
Q: Error occured while connecting with database 1045 in mamp I want to Create a form and link user information in the databases, but faced a problem when a link "Error occured while connecting with database 1045 in mamp ",
my sirver is MAMP
this is my code for form , index.php  is file form and connect.php is code connect with mysql
index.php
<?php

include("connect.php");
if (isset($_POST['submit']))
{

$firstName =$_POST['fname'];
$lastName =$_POST['lname'];
$email =$_POST['email'];
$password =$_POST['password'];
$passwordCOnfirm =$_POST['passwordCOnfirm'];
$image =$_FILES['image']['name'];
$tmp_image =$_FILES['image']['tmp_name'];
$imageSize=$_FILES['image']['size'];

}

 ?>

<!doctype html>

    <title>regestration Page</title>
  <link rel="stylesheet" href="css/styles.css"/>

    <form method="POST" action ="index.php" enctype="multipart/form-data">
            First Name

        <input type="text" name="fname"/>

            last Name

    <input type="text" name="lname"/>

        Email

    <input type="text" name="email"/>

        Password

        <input type="password" name="password"/>

        Password Confirm

        <input type="$passwordCOnfirm" name="$passwordCOnfirm"/>

            Image

        <input type="file" name="image"/>

        <input type="submit" name="submit"/>

    </form>

connect.php
<?php

    $con = mysqli_connect("localhost","root","root","registration");

    if(mysqli_connect_errno())
    {
        echo "Error occured while connecting with database ".mysqli_connect_errno();
    }

?>

A: If you are sure your MySQL database is running and your username and password are correct, then you should try connecting to host 127.0.0.1 instead of 'localhost', which is interpreted as a 'socket' connection.


text:
Q: Security exception from UIAutomator test My UI automator test runs green on a (Lollipop) emulator, but gives this error on a Sony Xperia Z1 (Lollipop 5.1.1). Any ideas ? Workaround?
11-24 20:15:00.432 29892-29892/uk.co.xxx.tm D/LifecycleMonitor: Lifecycle status change: uk.co.xxx.tm.TmActivity@17d33faf in: STOPPED
11-24 20:15:00.433 29892-29892/uk.co.xxx.tm D/LifecycleMonitor: Lifecycle status change: uk.co.xxx.tm.TmActivity@17d33faf in: DESTROYED
11-24 20:15:00.460 29892-29932/uk.co.xxx.tm I/MonitoringInstrumentation: waitForActivitiesToComplete() took: 402ms
11-24 20:15:00.479 29892-29932/uk.co.xxx.tm E/AndroidRuntime: FATAL EXCEPTION: Instr: android.support.test.runner.AndroidJUnitRunner Process: uk.co.xxx.tm, PID: 29892                                                                java.lang.SecurityException: Permission Denial: getIntentSender() from pid=29854, uid=2000, (need uid=1000) is not allowed to send as package android
at android.os.Parcel.readException(Parcel.java:1553)
at android.os.Parcel.readException(Parcel.java:1505)
at android.app.IUiAutomationConnection$Stub$Proxy.disconnect(IUiAutomationConnection.java:225)
at android.app.UiAutomation.disconnect(UiAutomation.java:241)
at android.app.Instrumentation.finish(Instrumentation.java:198)
at android.support.test.runner.MonitoringInstrumentation.finish(MonitoringInstrumentation.java:232)
at android.support.test.runner.AndroidJUnitRunner.finish(AndroidJUnitRunner.java:248)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:237)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)

A: As per java.lang.SecurityException: Permission Denial: getIntentSender() when using UiAutomation in a test, I checked Accessibility settings and it's now running green with TalkBack and Switch Access both off.


text:
Q: Capture packet content using network analyzers I need to capture https traffic. In particular the client hello messages. But I need to analyse their content. I learned about wireshark. How can I to extract the data from the packet content? i.e. the client hellp content? The tool displays the packets. If I click on them, I see more information but how to aggregate them. i.e. I need the field length (as shown in the picture) for all client hello messages?
Are there any tools to do so? Or can Wireshark do this function?
EDIT: In the picture, this is a client hello message. I need some data like the length. How to extract this and aggregate it for large traffic?
Image for illustration

A: You can do this with wireshark with a filter of "ssl.handshake.type == 1". This will give you all Client Hello packets. From there you can manually inspect the client hello message or you can even make any field in the client hello message a column in Wireshark. To do this, drill-down into one of the packets to the field you want to see. Right-click that field and select "Apply as Column".
If you want to do this programmatically, you could also write a program that uses libpcap to capture packets. This is more work though since you would have to manually dissect the packets yourself.


text:
Q: NSToolBar for switchign views in storyboards - OS X (Objective-C) Have been searching quite a while, maybe someone can direct me to a step by step tutorial on understanding how to use NSToolbar to switch between different view controllers and show them below the toolbar. Possibly resizing the window based on the view height and width.
Not familiar with swift, so any objective-c stuff is much obliged. Thank you.

A: You can use an NSTabViewController with its tabStyle set to NSTabViewControllerTabStyleToolbar.
You can add an NSTabViewItem to the tab view controller for each view controller; with the image of the tab view item set to the image you want in the toolbar.
This can be setup programmatically or in an interface builder storyboard.


text:
Q: Can not write the value to a variable I have a function, which needs to return true if there is a row in a table with values which user inputs.
I need to write the value to a variable which Ii return, but I got an error:

Incorrect syntax near '@ret'.

USE BDLab5;
GO
Create Function WasComplaint (@date date, @component varchar)
    Returns BIT
    Begin
        Declare @was int, @ret bit
        Select @was = ComponentCode from Complaints
            Where ComplaintDate = @date AND
            ComponentCode = (Select ComponentCode from Components Where ComponentName = @component)

        if (@was = 0)
            @ret = 0
        else
            @ret = 1

        Return @ret
    End;

I tried different variant of if else syntax but it doesn't help.

A: Put the word SET before @ret when you give it a value

A: You need to use SET when assigning a value to a variable.
USE BDLab5;
GO
Create Function WasComplaint (@date date, @component varchar)
    Returns BIT
    Begin
        Declare @was int, @ret bit
        Select @was = ComponentCode from Complaints
            Where ComplaintDate = @date AND
            ComponentCode = (Select ComponentCode from Components Where ComponentName = @component)

        if (@was = 0)
            set @ret = 0
        else
            set @ret = 1

        Return @ret
    End;


text:
Q: Access violation in MiniDumpWriteDump when invoked out-of-process The documentation of the MiniDumpWriteDump function states that

MiniDumpWriteDump should be called from a separate process if at all possible, rather than from within the target process being dumped.

So I wrote a small MFC crash handler program that does just that. I followed the advice in this SO answer by Hans Passant, i.e. I am passing the value of the exception pointer from the crashing program to the crash handler program even though the exception pointer is not valid in the context of the crash handler program. This works well when I run tests in a debug build, but when I switch to a release build the crash handler program crashes, with an access violation that occurs inside the MiniDumpWriteDump function.
I am stumped. Why should this work in debug builds, but not in release builds? It's maddening because access violations often are indicators for accessing invalid pointers, and the exception pointer I am receiving in the crash handler program is indeed invalid - but on the other hand I am told that this should not matter, that MiniDumpWriteDump is interpreting the pointer in the context of the crashing process (from where the pointer originated).
Any ideas what I could be doing wrong?
On a sidenote: In his answer, Hans proposes a solution where the watchdog process is pre-launched, then goes to sleep and wakes up when it is triggeredd by the crashing process. My solution is slightly different: I am simply launching the crash handler program at the time when the crash occurs, then I pass the necessary information from the crashing program to the crash handler program via command line arguments. I double-checked that the information being passed is correct, specifically the exception pointer.

A: I struggled with a similar issue, and have now finally noticed what was wrong.
The MSDN documentation of MINIDUMP_EXCEPTION_INFORMATION states that the ClientPointers field must be TRUE if the ExceptionPointers address is from the target process instead of the local process.
After setting this field correctly, I can simply pass ThreadId and ExceptionPointers from the crashing process, fill them into a MINIDUMP_EXCEPTION_INFORMATION in the dump-writing process, and it works perfectly.

A: I changed my approach so that the final solution looks like the one suggested by Hans Passant: The watchdog process is pre-launched, then goes to sleep and wakes up when it is triggeredd by the crashing process. The crashing process makes a deep-copy of the EXCEPTION_POINTERS structure and passes that information to the watchdog process.
Here's the code that makes the deep-copy. As mentioned in the comments to the question, the main "problem" is EXCEPTION_RECORD which is a linked-list of potentially unlimited size.
// The maximum number of nested exception that we can handle. The value we
// use for this constant is an arbitrarily chosen number that is, hopefully,
// sufficiently high to support all realistic and surrealistic scenarios.
//
// sizeof(CrashInfo) for a maximum of 1000 = ca. 80 KB
const int MaximumNumberOfNestedExceptions = 1000;

// Structure with information about the crash that we can pass to the
// watchdog process
struct CrashInfo
{
    EXCEPTION_POINTERS exceptionPointers;
    int numberOfExceptionRecords;
    // Contiguous area of memory that can easily be processed by memcpy
    EXCEPTION_RECORD exceptionRecords[MaximumNumberOfNestedExceptions];
    CONTEXT contextRecord;
};

// The EXCEPTION_POINTERS parameter is the original exception pointer
// that we are going to deep-copy.
// The CrashInfo parameter receives the copy.
void FillCrashInfoWithExceptionPointers(CrashInfo& crashInfo, EXCEPTION_POINTERS* exceptionPointers)
{
    // De-referencing creates a copy
    crashInfo.exceptionPointers = *exceptionPointers;
    crashInfo.contextRecord = *(exceptionPointers->ContextRecord);

    int indexOfExceptionRecord = 0;
    crashInfo.numberOfExceptionRecords = 0;
    EXCEPTION_RECORD* exceptionRecord = exceptionPointers->ExceptionRecord;

    while (exceptionRecord != 0)
    {
        if (indexOfExceptionRecord >= MaximumNumberOfNestedExceptions)
        {
            // Yikes, maximum number of nested exceptions reached
            break;
        }

        // De-referencing creates a copy
        crashInfo.exceptionRecords[indexOfExceptionRecord] = *exceptionRecord;

        ++indexOfExceptionRecord;
        ++crashInfo.numberOfExceptionRecords;
        exceptionRecord = exceptionRecord->ExceptionRecord;
    }
}

When we receive the CrashInfo structure in the watchdog process we now have a problem: The EXCEPTION_RECORD references are pointing to invalid memory addresses, i.e. to memory addresses that are valid only in the crashing process. The following function (which must be run in the watchdog process) fixes those references.
// The CrashInfo parameter is both in/out
void FixExceptionPointersInCrashInfo(CrashInfo& crashInfo)
{
    crashInfo.exceptionPointers.ContextRecord = &(crashInfo.contextRecord);

    for (int indexOfExceptionRecord = 0; indexOfExceptionRecord < crashInfo.numberOfExceptionRecords; ++indexOfExceptionRecord)
    {
        if (0 == indexOfExceptionRecord)
            crashInfo.exceptionPointers.ExceptionRecord = &(crashInfo.exceptionRecords[indexOfExceptionRecord]);
        else
            crashInfo.exceptionRecords[indexOfExceptionRecord - 1].ExceptionRecord = &(crashInfo.exceptionRecords[indexOfExceptionRecord]);
    }
}

We are now ready to pass &(crashInfo.exceptionPointers) to the MiniDumpWriteDump function.
Note: Obviously this is not a complete solution. You will probably want to pass more info from the crashing process to the watchdog process. The CrashInfo structure is the candidate to hold this information. Also the way how the processes communicate with each other is not shown here. In my case I went with the solution presented by Hans Passant which is linked at the beginning of the question: Use an event for synchronization (CreateEvent + SetEvent) and a memory-mapped file (CreateFileMapping + MapViewOfFile) to shuffle the information from one process to the next. The (unique) names of the event and the memory-mapped file are determined by the main process and passed to the watchdog process via command line arguments.


text: Q: Image View showing warning as unknown attribute android:contentDescription in AS 3.4.1 When I updated my Android studio from 3.3 to 3.4.1, I was facing some interesting warning in my ImageView tag like: android:contentDescription attribute is unknown. How I can resolve this warning? Or is it a bug of new Android Studio 3.4.1?


text:
Q: How do I join a conference call in Skype for Linux? On Linux, the latest Skype client doesn't seem to allow joining conference calls, only creating new ones. Clicking on the call button (I think) calls each member separately, I've been told by the other participants. How can I join an existing conference call with that client? I tried running the Windows client under Wine, but login doesn't work.

A: There are two types of joining methods.  1. joining via a web-link. 2. joining from within Skype itself.
Although method 1 seems quite possible to do in a normal manner, I haven't actually got it working properly (yet?), but that may just be my system, and it may work for you. Howerver, I can explain how to use method 2.
If you aren't already in the conference/chat, you first need to know the conference ID. This is available by issueing the Group Chat Command /get uri  into the message area.  This creates a URL link that other people (or you) can use to join the group chat.
Clicking on the skype:?chat&blob=... URL ia any Skypw chat window or entering it into your web browser's address-bar will start Skype (if it isn't already running) and join the conference.
Now comes the problem I have encountered (which isn't much of a problem, really). Although this link works fine in Windows, it doesn't work properly for me. It starts Skype, but doesn't join the chat.. (one day, I may finally work it out ?), but it doesn't matter that much, as you don't need it after the first time you join the chat/converence.
To subsequently join the conference whenever you want to, you simply need to bookmark the chat/conference. To join the conference, click on your Skype bookmark. That's it.

A: UPDATE 2016:
My company used and uses Skype regularly, here is what we found lately:
Linux clients cannot join group calls started from Windows clients.
Windows clients can join group calls started from Linux clients.
On the Skype forums it looks like Microsoft have abbandoned the Linux development.
http://community.skype.com/t5/Linux/Why-is-Skype-on-Linux-still-so-grossly-out-of-date/td-p/4304329


text:
Q: VPN Connection site to site Alibaba Virtual Private Cloud Anyone have idea why "Phase 1 of IKE Tunnel Negotiation Failed" comes up when I try to use  IPsec method to establish connection between on-prem and Alibaba Cloud

A: IKE negotiates the IPSec security associations, called SAs, between two endpoints. Each security association has parameters that must match on both sides. Verify that you have configured the phase 1 policy with the same parameters for Encryption, Hash, Diffie-Hellman Group and Authentication.
Note: You have left a lot of important details out of your question.

A: the following recommend for you
IKE profile settings
Set the lifetime to a value configured on the Alibaba Cloud side between 900 and 28,800 (default) seconds.
Set the encryption algorithm to either AES-128 or AES-256.
Set the hashing algorithm to either SHA-1 or SHA-2(256).
Set the Pseudo Random Function (PRF) to the same algorithm as the hashing algorithm.
Enable one of the following Diffie-Hellman groups: 2, 14-18, 22, 23, or 24.
IPsec profile settings
Set the lifetime to a value configured on the Alibaba Cloud side between 900 and 3,600 (default) seconds, with less than phase 1 lifetime.
Set the encryption algorithm to either AES-128 or AES-256.
Set the hashing algorithm to either SHA-1 or SHA-2(256).
Enable perfect forward secrecy (PFS) using one of the following Diffie-Hellman groups: 2, 5, 14-18, 22, 23, or 24.


text:
Q: Python regex: alternative positive lookbehind assertion I have the following regex expression which is meant to find the "IF" keyword (case insensitive) in a string. Some constraints are imposed:

*

*It should be preceded by a whitespace or a ) character (from a previous expression)

*It should be followed by whitespace or ( character

The below expression accomplishes these constraints. However, this expression does not find the keyword when it's located at the start of a string (if(foo, 1, 2) for instance).
Using something like ^|(?<=[\s\)])(?i)if(?=[\s\(]) does not seem to work. I tried ?:^|[\s\)]) but that seems to also capture the space in front of the keyword.
This is what I have so far:
(?<=[\s\)])(?i)if(?=[\s\(])

A: You may use an alternation group with two zero-width assertions:
(?i)(?:^|(?<=[\s)]))if(?=[\s(])
    ^^^^^^^^^^^^^^^^

See the regex demo.
Here, (?:^|(?<=[\s)])) matches:

*

*^ - start of string

*| - or

*(?<=[\s)]) - a location that is immediately preceded with a whitespace or ) character.

Note that the (?i) inline case insensitive modifier in a Python re regex affects the whole pattern regardless of where it is located in it, so I suggest moving it to the pattern start for better visibility.
Also, there is no need to escape ( and ) inside character classes, [...] constructs, as they are treated as literal parentheses inside them.

A: The problem is that | is applied at top level, so it is an alteration between:
^ and (?<=[\s\)])(?i)if(?=[\s\(]).
Just add non-capturing group around ^ and (?<=[\s\)]):
(?:^|(?<=[\s\)]))(?i)if(?=[\s\(])

A: You can solve the problem (for this particular case that only involves single characters) using a double negation:
(?<![^\s)])

(not preceded by a character that is not a whitespace nor a closing parenthesis). This condition includes the start of the string too.


text:
Q: How do I pre-fill a PDF Web Form using URL Query String (or better method)? I need to fill in a PDF Web Form that will be available to the public with data taken from a URL Query String. I don't want the user to be able to edit anything on the form - only print or save it.
I realize this is not the most secure way as they could edit the query string to modify the data. Is there a more secure way?
I am currently trying to do this using the simplest way possible: a pdf form and javascript in the form.
Code follows but has not been tested properly. I am wondering if this is the right approach?
 // This code was taken from:
 // http://blogs.adobe.com/pdfdevjunkie/2009/12/populating_pdf_form_fields_fro.html
 // Accessed: June 15, 2015

 //only run the script if the PDF file is being viewed in a browser window
 if (this.external)
 {
     //The whiteList defines which fields are permitted to be changed by the URL.
     //If you want all fields to be changed, leave the array empty as in "[]"
     //whiteList = ["Name", "Address", "City", "State", "ZipCode"]
     whiteList = []

     //get the parameters portion of the URL and unescape it so we get the spaces and punctuation back
     parametersString = this.URL.substring(this.URL.indexOf("?")+1)
     //only run the script if there are parameters
     if (parametersString.length > 0)
     {
         //create an array of key/value pairs
         parameters = parametersString.split("&")
         //loop through the array...
         for each (parameter in parameters)
         {
             //create a 2 element array for each parameter as [key, value]
             kvPair = parameter.split("=")
             //set the field named "key" to "value"
             fieldName = unescape(kvPair[0])
             if (whiteList.length > 0)
             {
               if (whiteList.indexOf(fieldName) > -1)
               {
                   this.getField(fieldName).value = unescape(kvPair[1])
               }
             }
             else
             {
                this.getField(fieldName).value = unescape(kvPair[1])
             }
       }
   }
}


text:
Q: jQuery load on Scroll - fade in table rows as scroll to display block. Endless scrolling Is this possible without no PHP, SQL, .NET etc, just need jQuery, HMTL and CSS.
I have a table and rather than having pagination I want to be able to load in other rows as I scroll down the page, similar to that of Facebook and Twitter.

A: You may want to check this
http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Quote from plugin page :
"you don't need to code any custom backend stuff to enable this functionality!"


text:
Q: HTML to Wordpress: Add category block over featured image I've been playing around with html, css and wordpress lately. So far I have a site homepage completely done on HTML and CSS, so I began porting it to WP.
The problem is I can't seem to replicate this
HTML:

Category

CSS:
.featured-image
    {
    position: absolute;
    display: inline;
    width: 640px;
    height: 100px;
    z-index: 0;
    }
.category
    {
    font-size: 20px;
    color: #FFF;
    text-align: center;
    vertical-align: middle;
    text-transform: uppercase;
    text-decoration: none;
    position: relative;
    display: block;
    float: right;
    width: 90px;
    line-height: 100px;
    background-color: #555;
    opacity: 0.2;
    z-index: 1;
    word-wrap: break-word;
    }

.category span
{
    display: inline-block;
    line-height: 1em;
    width: 90px;
    vertical-align: middle;
}

This is what I have on Wordpress so far:

<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>

    <?php
    // Get the Name of First Category
    $category = get_the_category();
    echo $category[0]->cat_name;
    ?>

CSS:
.new-wrapper{
    background-color: Black;
    color:white;
    font-size: 12px;
    position:absolute;
    vertical-align: middle;
    bottom: 0px;
    top: 0px;
    right:-20px;
    padding-left:10px;
    padding: 10px;
    -moz-opacity:.80;
    filter:alpha(opacity=80);
    opacity:.80;
    width:90px;
    display: block;
}

.post-thumb {
float:left;
position:relative;
width: 640px;
overflow:hidden;
}

Any help with this?

A: I don't recommend overwrite the old template. Made your template from empty folder. Source would like this:

<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>

<?php
    // Get the Name of First Category
    $category = get_the_category();
    echo $category[0]->cat_name;
    ?>

.. css source you can copied to original file.


text:
Q: How to detect a tie in a numpy array when using argmax If I have an array like below, how can I detect that there is a tie of at least 3 or more values when using np.argmax()?
examp = np.array([[4, 0, 1, 4, 4],
                  [5, 5, 1, 5, 5],
                  [1, 2, 2, 4, 1],
                  [4, 6, 1, 2, 4],
                  [1, 4, 3, 3, 3]])

np.argmax(examp, axis=1)

which gives an output:
array([0, 0, 3, 1, 1]

Taking the first row as an example, there is a "3-way tie". 3 values of 4. np.argmax returns the first index that has the max value. But, how can I detect that there is a "3-way tie" going on and have it decide the tie breaker with a custom function (on the condition that there is at least a "3-way tie" occurring?
So, first row: sees that there is a "3-way tie" of 4s. Custom function runs so that it can decide the tie-breaker.
Second row: "4-way tie" same thing happens.
Third row: only "2-way tie" which is less than condition of at least a "3-way tie". Can default to np.argmax.

A: One way for finding the n-th maximum is np.partition (or np.argpartition). In this case you can do something like this:
>>> n = 3  # Size of tie
>>> i = examp.argpartition([-n, -1], axis=-1)

The values in the third-to-last and last columns are guaranteed to be in the correct sort order (and therefore the second-to-last as well, but only in this limited case). If those two values are equal to each other, then you have a 3-way tie:
>>> r = np.arange(examp.shape[0])
>>> examp[r, i[:, -n]] == examp[r, i[:, -1]]
array([ True,  True, False, False, False])

You can also use np.diff to compute the mask:
>>> np.diff(examp[r[:, None], i[:, [-n, -1]]], axis=1) == 0
array([[ True],
       [ True],
       [False],
       [False],
       [False]])

You can get a similar result by using np.take_along_axis instead of the first index r:
>>> np.diff(np.take_along_axis(examp, i[:, -n::n-1], 1), axis=1) == 0
array([[ True],
       [ True],
       [False],
       [False],
       [False]])

In all these cases, the value of argmax is just i[:, -1], since that's the index of the maximum value in the array.
Since you are already using numpy, I highly recommend that you vectorize the custom tie-breaking function as well. I've provided the output as a mask here so that you can do exactly that as efficiently as possible.

A: You are correct that np.argmax will only find the first max value. Although you could count how many of these argmax exist and base your logic of that number
indices = examp.argmax(0)
counts = (examp == examp[indices, np.r_[:3]]).sum(0)
# the same as
counts = np.count_nonzero(examp == examp[indices, np.r_[:3]], axis=0)

Will return
indices = array([0, 3, 2])
counts = array([4, 1, 2])


text:
Q: How can I extract submatches using C regex I have made GNU regex library work exactly as advertised in an extensive text processing alg that I wrote about 2 years ago, but unfortunately that platform is gone and I don't know whether its versions were older or newer than that referenced below.
Here is the code:
// GNU libc version: 2.28
// gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0

#include <stdio.h>
#include <regex.h>

int main() {

    regex_t preg;
    char str[] = "dave";
    char regex[] = "\\(.\\)ave";

    // flag REG_EXTENDED with unescaped parens in the r.e. doesn't fix anything
    int ret, cflags = REG_ICASE;

    // the elements of unused pmatches used to be set to -1 by regexec, but no longer. a clue perhaps.

    regmatch_t pmatch[2] = {{-1,-1},{-1,-1}};

    ret = regcomp(&preg, regex, cflags);
    if (ret) {
        puts("regcomp fail");
        return ret;
    }
    else
        // preg.re_nsub contains the correct number of groups that regcomp recognized in the r.e. Tests succeeded for 0, 1, 2, and 3 groups.
        printf("regcomp ok; re_nsub=%zu\n", preg.re_nsub);

    ret = regexec(&preg, str, 1, pmatch, 0);

    if(ret)
        puts("no match");
    else {
        printf("match offsets are %d %d\n", pmatch[0].rm_so, pmatch[0].rm_eo);
        printf("match[0]=%*s<\n", pmatch[0].rm_eo, &str[pmatch[0].rm_so]);

        printf("submatch offsets are %d %d\n", pmatch[1].rm_so, pmatch[1].rm_eo);
        if(pmatch[1].rm_so != -1)
            printf("match[1]=%*s<\n", pmatch[1].rm_eo, &str[pmatch[1].rm_so]);
    }
    return 0;
}
/*
output:
regcomp ok; re_nsub=1
match offsets are 0 4
match[0]=dave<
submatch offsets are -1 -1
*/

A: The issue you do not get offsets for the first capturing group is that you pass 1 as the third, size_t __nmatch, argument to regexec.
The 1 value should be changed to 2 as there will be two groups whenever \(.\)ave regex matches: Group 0 will be holding the whole match and Group 1 will hold the first capturing group value.
So, you need to use
ret = regexec(&preg, str, 2, pmatch, 0);
//                       ^^^

Also, to print the Group 1 value you can use
if(pmatch[1].rm_so != -1) {
    printf("match[1]=%.*s<\n", pmatch[1].rm_eo, &str[pmatch[1].rm_so]);
}

See this C demo:
#include <stdio.h>
#include <regex.h>
#include <string.h>

int main() {

    regex_t preg;
    char str[] = "dave";
    char regex[] = "\\(.\\)ave";

    // flag REG_EXTENDED with unescaped parens in the r.e. doesn't fix anything
    int ret, cflags = REG_ICASE;

    // the elements of unused pmatches used to be set to -1 by regexec, but no longer. a clue perhaps.

    regmatch_t pmatch[2] = {{-1,-1},{-1,-1}};

    ret = regcomp(&preg, regex, cflags);
    if (ret) {
        puts("regcomp fail");
        return ret;
    }
    else
        // preg.re_nsub contains the correct number of groups that regcomp recognized in the r.e. Tests succeeded for 0, 1, 2, and 3 groups.
        printf("regcomp ok; re_nsub=%zu\n", preg.re_nsub);

    ret = regexec(&preg, str, 2, pmatch, 0); // 1 changed to 2 as there is Group 0 (whole match) and Group 1 (for the first capturing group)

    if(ret)
        puts("no match");
    else {
        printf("match offsets are %d %d\n", pmatch[0].rm_so, pmatch[0].rm_eo);
        printf("match[0]=%*s<\n", pmatch[0].rm_eo, &str[pmatch[0].rm_so]);

        printf("submatch offsets are %d %d\n", pmatch[1].rm_so, pmatch[1].rm_eo);
        if(pmatch[1].rm_so != -1) {
            printf("match[1]=%.*s<\n", pmatch[1].rm_eo, &str[pmatch[1].rm_so]);
        }
    }
    return 0;
}
/*
regcomp ok; re_nsub=1
match offsets are 0 4
match[0]=dave<
submatch offsets are 0 1
match[1]=d<
*/


text:
Q: Syntax error in global.asax I have the code below in my global.asax file (in my asp.net application) ...

and I have the error below in stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Digita.Tustena.Global.Application_Start(Object sender, EventArgs e) +133

[HttpException (0x80004005): Object reference not set to an instance of an object.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext       context, HttpApplication app) +3985477
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +325
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375

[HttpException (0x80004005): Object reference not set to an instance of an object.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11524352
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4782309

What is the problem with my code? I appriciate your helps ...

A: Look in the method Application_Start in the file Global.asax.cs. You have a null reference there. Put a try/catch and use the debugger to see which object is null.
If you deploy the pdb files with your dll the stack trace will also contain the line number. Also do set the Debug Info to full: Project Properties -> Build -> Advanced -> Debug Info (http://stackoverflow.com/a/3791997/57369)


text:
Q: Implementing faster python inner product with BLAS I found this useful tutorial on using low-level BLAS functions (implemented in Cython) to get big speed improvements over standard numpy linear algebra routines in python. Now, I've successfully gotten the vector product working fine. First I save the following as linalg.pyx:
import cython
import numpy as np
cimport numpy as np

from libc.math cimport exp
from libc.string cimport memset

from scipy.linalg.blas import fblas

REAL = np.float64
ctypedef np.float64_t REAL_t

cdef extern from "/home/jlorince/flda/voidptr.h":
    void* PyCObject_AsVoidPtr(object obj)

ctypedef double (*ddot_ptr) (const int *N, const double *X, const int *incX, const double *Y, const int *incY) nogil
cdef ddot_ptr ddot=<ddot_ptr>PyCObject_AsVoidPtr(fblas.ddot._cpointer)  # vector-vector multiplication

cdef int ONE = 1
def vec_vec(syn0, syn1, size):
    cdef int lSize = size
    f = <REAL_t>ddot(&lSize, <REAL_t *>(np.PyArray_DATA(syn0)), &ONE, <REAL_t *>(np.PyArray_DATA(syn1)), &ONE)
    return f

(source code for voidptr.h available here)
Once I compile it, it works fine, and is definitely faster than np.inner:
In [1]: import linalg
In [2]: import numpy as np
In [3]: x = np.random.random(100)
In [4]: %timeit np.inner(x,x)
1000000 loops, best of 3: 1.61 µs per loop
In [5]: %timeit linalg.vec_vec(x,x,100)
1000000 loops, best of 3: 483 ns per loop
In [8]: np.all(np.inner(x,x)==linalg.vec_vec(x,x,100))
Out[8]: True

Now, this is great, but only works for the case of calculating the dot/inner product (equivalent in this case) of two vectors. What I need to do now, implement similar functions (that I hope will offer similar speedups) for doing vector-matrix inner products. That is, I want to replicate the functionality of np.inner when passed a 1D array and a 2D matrix:
In [4]: x = np.random.random(5)
In [5]: y = np.random.random((5,5))
In [6]: np.inner(x,y)
Out[6]: array([ 1.42116225,  1.13242989,  1.95690196,  1.87691992,  0.93967486])

This is equivalent to calculating the inner/dot products (again, equivalent for 1D arrays) of the 1D array and each row of the matrix:
In [32]: [np.inner(x,row) for row in y]
Out[32]:
[1.4211622497461549, 1.1324298918119025, 1.9569019618096966,1.8769199192990056, 0.93967485730285505]

From what I've seen of the BLAS documentation, I think I need to start with something like this (using dgemv):
ctypedef double (*dgemv_ptr) (const str *TRANS, const int *M, const int *N, const double *ALPHA, const double *A, const int *LDA, const double *X, const int *incX, const double *BETA, const double *Y, const int *incY)
cdef dgemv_ptr dgemv=<dgemv>PyCObject_AsVoidPtr(fblas.dgemv._cpointer)  # matrix vector multiplication

But I need help (a) defining the actual function that I can use in Python (i.e. a vec-matrix function analogous to vec_vec above), and (b) knowing how to use it to properly replicate the behavior of np.inner, which is what I need for the model I'm implementing.
Edit: Here is the link to relevant BLAS documentation for dgemv, that I need to be using, which is confirmed here:
In [13]: np.allclose(scipy.linalg.blas.fblas.dgemv(1.0,y,x), np.inner(x,y))
Out[13]: True

But using it out of the box like this is actually slower than pure np.inner, so I still need help with the Cython implementation.
Edit2 Here's my latest attempt at this, which compiles fine but crashes python with a segmentation fault whenever I try to run it:
cdef int ONE = 1
cdef char tr = 'n'
cdef REAL_t ZEROF = <REAL_t>0.0
cdef REAL_t ONEF = <REAL_t>1.0
def mat_vec(mat,vec,mat_rows,mat_cols):
    cdef int m = mat_rows
    cdef int n = mat_cols
    out = <REAL_t>dgemv(&tr, &m, &n, &ONEF, <REAL_t *>(np.PyArray_DATA(mat)), &m, <REAL_t *>(np.PyArray_DATA(vec)), &ONE, &ZEROF, NULL, &ONE)
    return out

After compiling, I try to run linalg.mat_vec(y,x,5,5), (using the same x and y as above) but this just crashes. I think I'm close, but don't know what else to change...

A: Per @Pietro Saccardi:
int dgemv_(char *trans, integer *m, integer *n, doublereal *
           alpha, doublereal *a, integer *lda, doublereal *x, integer *incx,
           doublereal *beta, doublereal *y, integer *incy)

...

Y      - DOUBLE PRECISION array of DIMENSION at least
         ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'
         and at least
         ( 1 + ( n - 1 )*abs( INCY ) ) otherwise.
         Before entry with BETA non-zero, the incremented array Y
         must contain the vector y. On exit, Y is overwritten by the
         updated vector y.

I doubt you can use NULL for Y in the call.


text:
Q: How do you know there may be an exception? Do I have to take a look at the java api everytime I instantiate an object / call a method from a class in it? Also, do I always have to know which classes are in the java api and which are not?

A: If the exception is checked, then the java compiler will force your invoking method to either catch the exception or declare that it could throw the exception.
If the exception that is thrown inherits from Error or RuntimeException - I.e. is unchecked, then you have no way of knowing besides javadoc and looking at the code.
A good example of the latter, is NumberFormatException, thrown by Double.parseDouble(String).  The only way to know is that the javadoc tells you it could throw this exception.
Modern IDEs (Eclipse, Netbeans, IntelliJ etc) provide easy access to this documentation.

A: I use Eclipse IDE which will make sure you account for all thrown exceptions.  I highly recommend it.
http://www.eclipse.org

A: Knowing what exceptions a function throw is not different from knowing what arguments it needs, and what type it returns.
You either know it, look it up, or use an IDE that does this for you. BTW for checked exceptions you will get a compile-time error, so that can also be an option.

A: For you second question, In general...
Packages that start with "java." or "javax." are in the J2SE API.
Most packages starting with a internet domain prefix like "com." or "org." are supplied by third parties.  Don't count on com.sun being stable though.
Packages with none of prefixes the above are likely not following the package naming guidelines or predate them.


text:
Q: apt-key is deprecated plex on a raspberry pi 3b Whats up guys, I'm still a huge noob and I don't understand what is going on even though there are similar problems and solutions.
I have a raspberry pi that i want to use for a nas. i followed the tutorial from network chuck on youtube and i am 19 minutes into the video video, im also following allong from his website website and I'm at "install plex media server"(nr2).
I pasted this:
curl https://downloads.plex.tv/plex-keys/PlexSign.key | sudo apt-key add -

in the terminal and got this in return
Warning: apt-key is deprecated.
Manage keyring files in trusted.gpg.d instead (see apt-key(8))

From what i understand the way of doing things changed in april or something but as i sayed, im a super noob, i only started messing arround with this raspberry pi and the termenal this month, so sorry if it is a really easy solution lol
please comment what i should do (ill just coppy and paste), thanks
Here is the full thing but it might be useless, idk
 pi@raspberrypi:~ $ sudo curl https://downloads.plex.tv/plex-keys/PlexSign.key | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  3072  100  3072    0     0  22100      0 --:--:-- --:--:-- --:--:-- 22100
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).

A: This has been covered several times, as per the duplicate link above.
However, for that particular scenario, these commands might help you.
To install the key:
curl https://downloads.plex.tv/plex-keys/PlexSign.key | sudo gpg --dearmor -o /etc/apt/keyrings/plex.gpg

To add the repo:
echo "deb [signed-by=/etc/apt/keyrings/plex.gpg] https://downloads.plex.tv/repo/deb public main" | sudo tee /etc/apt/sources.list.d/plexmediaserver.list

Now you should be able to continue the walkthrough.


text:
Q: How do I validate using pytest that my Python code is not logging any stack traces? I would like to use pytest to check that my function is not generating any stack trace data into logs, e.g. via logging.exception(), but the caplog object (docs) doesn't contain any information about the stack trace in the records or record_tuples attributes. What could I do?

A: From the LogCaptureFixture docs for the messages attribute:

Note that traceback or stack info (from logging.exception() or the exc_info or stack_info arguments to the logging functions) is not included, as this is added by the formatter in the handler.

This exclusion also appears to apply to the records and record_tuples attributes. The only place I could find the stack trace text was in the caplog.text attribute. So my test can do something like this:
assert "Traceback" not in caplog.text


text:
Q: Exporting data over an api from s3 using lambda I have some data stored in dynamo db and some highres images of each user stored in S3. The requirement is to be able to export a users data on demand. So by an api endpoint, collate all data and send it as a response. We are using aws lambda using node.js for business logic, s3 for storing images and sql db for storing relational data
I had set up a mechanism to connect api gateway to receive requests and put them in a sqs. The sqs would trigger a lambda which would run queries to gather all the data and image paths. We would copy all the images and data into a new bucket with custId as a folder name. Now heres where Im stuck. How to stream this data from our new aws bucket. All collected data is about 4gb. I have tried to stream via aws-lambda but keep failing. I am able to stream sigle files but not all data as zip. Hv done this in node, but would not want to set up an EC2 is possible and try to solve it directly with s3 and lambdas
CAnt seem to find a way to stream an entire folder from aws to the client as a response to an http request

A: Okay found the answer. Instead of trying to return a zip stream, Im now just zipping and saving the folder on the bucket itself and returning a signed url for it. Many node modules help us zip s3 folders without loading entire files in memory. Using that we have zipped our folder and returned a signed url. How it will behave under actual load remains to be seen. Will do that soon


text:
Q: How to handle more than one layouts from a child page in Nuxt.js? I am using Nuxt.js and Vue.js for the first time. So, I want to use a template as a parent which basically needs to have two columns. Each child has different data for both the columns.
layouts/content.vue:
<template>
    <b-container fluid>
        <b-row>
            <!--<b-col><nuxt/></b-col>
            <b-col><nuxt/></b-col>-->
        </b-row>
    </b-container>
</template>

This is let's say the child vue component:
pages/some-page/index.vue:
<template>
    <div>
        <!-- how to enter data for both the columns -->
    </div>
</template>

<script>
    export default {
        layout: 'content'
    }
</script>

How can I enter handle both the columns of my content.vue? I want to make two columns in some parent layout so that for later editing, I have only one file from which changes are reflected for all child pages.

A: You cannot pass data to layout (you can by using vuex), and you cannot use two times <nuxt />. You should use component slot instead:
layouts/content.vue:
<template>
    <b-container fluid>
        <nuxt />
    </b-container>
</template>

components/two-cols.vue:
<template>
    <b-row>
        <b-col><slot name="col-1"></slot></b-col>
        <b-col><slot name="col-2"></slot></b-col>
    </b-row>
</template>

pages/some-page/index.vue:
<template>
    <two-cols>
        <template slot="col-1>
            <!-- col-1 html here -->
        </template>
        <template slot="col-2>
            <!-- col-2 html here -->
        </template>
    </two-cols>
</template>

<script>
    import TwoCols from '~/components/two-cols.vue`
    export default {
        layout: 'content',
        components: {
            TwoCols
        }
    }
</script>


text:
Q: the difference between doMC and doParallel in R What's the difference between doParallel and doMC in R concerning foreach function? doParallel supports windows, unix-like, while doMC supports unix-like only. In other words, why doParallel cannot replace doMC directly? Thank you.
Update:
doParallel is built on parallel, which is essentially a merger of multicore and snow and automatically uses the appropriate tool for your system. As a result, we can use doParallel to support multi systems. In other words, we can use doParallel to replace doMC.
ref: http://michaeljkoontz.weebly.com/uploads/1/9/9/4/19940979/parallel.pdf
BTW, what is the difference between registerDoParallel(ncores=3) and
cl <- makeCluster(3)
registerDoParallel(cl)

It seems registerDoParallel(ncores=3) can stop cluster automatically, while the second do not stop automatically and needs stopCluster(cl).
ref: http://cran.r-project.org/web/packages/doParallel/vignettes/gettingstartedParallel.pdf

A: The doParallel package is a merger of doSNOW and doMC, much as parallel is a merger of snow and multicore. But although doParallel has all the features of doMC, I was told by Rich Calaway of Revolution Analytics that they wanted to keep doMC around because it was more efficient in certain circumstances, even though doMC now uses parallel just like doParallel. I haven't personally run any benchmarks to determine if and when there is a significant difference.
I tend to use doMC on a Linux or Mac OS X computer, doParallel on a Windows computer, and doMPI on a Linux cluster, but doParallel does work on all of those platforms.

As for the different registration methods, if you execute:
registerDoParallel(cores=3)

on a Windows machine, it will create a cluster object implicitly for later use with clusterApplyLB, whereas on Linux and Mac OS X, no cluster object is created or used. The number of cores is simply remembered and used as the value of the mc.cores argument later when calling mclapply.
If you execute:
cl <- makeCluster(3)
registerDoParallel(cl)

then the registered cluster object will be used with clusterApplyLB regardless of the platform. You are correct that in this case, it is your responsibility to shutdown the cluster object since you created it, whereas the implicit cluster object is automatically shutdown.


text:
Q: FSRM - Setting File Screen to block files types that are already inside some folders I have a file server without any kind of file screen to prevent users from saving certain types of files in their folders. Our management changed and now I have to apply file screens to block some file types like pictures, audio, etc on most of the folders, with some exceptions.
The thing is most of the users folders already have all those kind of files saved inside it.
Is there a problem setting the file screens with those files already in there? My idea is to prevent new users to save more files in there and then manage like move or delete the old files.
Is it viable?
Thanks.

A: Yes, setting a File Screen will only apply going forward. I recently did this at my workplace, and can confirm that existing files were not affected. However, this also means they cannot modify existing files that are part of the file screen.
File Screen to block .exe's on the J:\ drive:

Existing .exe on the J:\ drive:

Trying to copy a .exe to that folder:

A: It won't affect currently existing files.
It will simply prevent new ones from being added.
You can test this yourself, just make a demo folder and put a file in there, then create a filter for that file's extension. You won't be able to make new ones, but the existing will remain.


text:
Q: Get rid of redis as backplane when using loadbalancer Given
we have a site on 2 server on iis . Bevore this we have a loadbalancer. we deliver search results with an existing signalR hubg using redis for windows as backplane.
Problem
Now we have some bad issues with redis for windows .
I've found some posts that point out using sticky session would make the use of redis obsolete.
is this right ? When activating sticky sessions would signalR also automatically change its behavior or would I have to configure this?
Any hints are very welcome

A: Activated sticky sessions
removed signalr scaleout code
works!
Update Feedback:
After one month we can say that it worked perfectly and no problems have occured since then


text:
Q: Establish the equivalence of two inverse trigonometric function based formulas In a comment to
3D5D
user JimB provided an answer to the question posed there of finding the "two-quater[nionic]bit" absolute separability Hilbert-Schmidt probability. (Previously, in TwoQubit,
he had obtained the "two-qubit" counterpart.)
The answer now took the form
327574875999612773528659/95105071448064 - 2951081236201839/(524288 Sqrt[2]) - (15390446918294583135 \[Pi])/(17179869184 Sqrt[2]) + (15390446918294583135 ArcCsc[18/Sqrt[50 + 17 Sqrt[2]]])/(2147483648 Sqrt[2])

An earlier answer,
-((13 (-216449750678398795533760757497856 +
   176860737736399592490919645937664 Sqrt[2] +
   279292548969739228073088142369304501839785 Sqrt[2] \[Pi] -
   558572941247617043110461841280869072896000 Sqrt[2]
     ArcCot[Sqrt[2]] +
   23637916932187025487103667523337320 Sqrt[2]
     ArcCot[2 Sqrt[2]] -
   16178155879591789043088455851252390200 Sqrt[2]
     ArcCot[3 + Sqrt[2]] -
   558589165778586158484606527963549721006600 Sqrt[2]
     ArcTan[Sqrt[2]]))/816946343106356485029888)

of somewhat different form, to the very same question had been provided in eq. (36) in
2009paper
Both formulas above evaluate (N[,50]) to
0.000039870347068019928855365404975780992652117606213067

However, the FullSimplify command does not reveal the formulas' evident equivalence.
It might seem that some inverse trigonometric function transformations would be required to accomplish that.
So, can the evident equivalence of the two formulas be formally established employing Mathematica?

A: FindIntegerNullVector is your friend. Notice that this method allows you to obtain an even simpler expression.
A. Find relations between sets of different functions
v[1]={ArcCsc[18/Sqrt[50+17 Sqrt[2]]],ArcTan[Sqrt[2]],ArcCot[3+Sqrt[2]]};
v[2]={ArcCot[Sqrt[2]],ArcCot[2 Sqrt[2]],ArcCot[3+Sqrt[2]]};
v[3]={ArcCot[2 Sqrt[2]],ArcCot[Sqrt[2]],ArcTan[Sqrt[2]]};
v[4]={ArcCot[Sqrt[2]],ArcTan[Sqrt[2]],π/2};

B. This is the main part
Table[FindIntegerNullVector[N[v[i],1000]],{i,4}]
Out[1]= {{-3,-1,11},{-2,1,4},{1,1,-1},{1,1,-1}}

C. Make a list of replacement rules
r[1]={ArcCsc[18/Sqrt[50+17 Sqrt[2]]]->(-ArcTan[Sqrt[2]]+11ArcCot[3+Sqrt[2]])/3};
r[2]={ArcCot[3+Sqrt[2]]->1/4(2ArcCot[Sqrt[2]]-ArcCot[2 Sqrt[2]])};
r[3]={ArcCot[2 Sqrt[2]]->ArcTan[Sqrt[2]]-ArcCot[Sqrt[2]]};
r[4]={ArcCot[Sqrt[2]]->π/2-ArcTan[Sqrt[2]]};

D. Apply the rules
sx=Fold[ReplaceAll,x,Array[r,4]]//Expand;
sy=Fold[ReplaceAll,y,Array[r,4]]//Expand;
sx-sy
Out[2]= 0

Comment/observation
In principle, all but one identities found by the LLL method are easy to prove by hand. Only the first one, namely
$$11\,\mathrm{arccot}\big(3+\sqrt{2}\big) = \mathrm{arctan}\big(\sqrt{2}\big)+ 3\,\mathrm{arccsc}\!\Bigg\{\frac{18}{\sqrt{50+17 \sqrt{2}}}\Bigg\}$$
is somewhat unexpected.


text:
Q: How to change position of donut chart slices I am trying to produce a donut chart. Below is my code. I want the slices to appear in the same order they are listed in the code. Is there a way to do this?
library(ggpubr)
df <- data.frame(
group = c("Much lower",
        "A little\n lower",
        "The same \n as before",
        "A little \n higher",
        "Much\n higher"),
value = c(16, 29, 34, 14, 7))
# create labels
df$label <- paste(df$group,paste(df$value,"%"), sep = "\n")

ggpubr::ggdonutchart(df, "value",
                 label = "label", # add labels
                 lab.font = c(.1,"plain",'white'),
                 color = "white",fill = "group",
                 lab.adjust = ,
                 lab.pos = c("out"),
                 palette = c("gray82","gold1","gray36", "ivory","dodgerblue2")) +
theme(legend.position = "none") #DELETES LEGEND


text:
Q: blogger.com subdomains When one registers for a blog in blogger.com, a sub-domain gets created i.e. your_blog_name.blogger.com
My question is - Is there no limit to the number of sub-domains you can create with a single domain name?
I am just curious as to how blogger (or any other blog hosting platform) does this?

A: This can be done by a catch-all A record rule in your DNS server configuration. For example, in bind, you would use something like this:
*.example.com.  IN A    127.0.0.1

This would make anything.example.com resolve to 127.0.0.1. Then, using an appopriate VHost on your http server, you can redirect all requests to a particular server-side script (for example PHP), which can then detect the hostname that was used, and respond with the content required.

A: There are restrictions on the characters that can be used (actually, two separate sets of restrictions due to the way IDNs work). There are practical limitations in terms of length. Beyond that no. Indeed, it's not much different for the entity in charge of .blogger.com to create a subdomain of that than for the entity in charge of .com to do so, and there were 80,000,000 of those at the start of last year .


text:
Q: Getting location in android not working on newer device I am trying to find the current location in my project.So i found this post:
What is the simplest and most robust way to get the user's current location on Android?
I tried using locationclient but was not satisfied with the result.The code that i have used is as follows:
The Mylocation.java class:
package com.igloo.classes;

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 90000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }
    public void cancelTimer()
    {
        if(timer1!=null)
        {
         timer1.cancel();
         lm.removeUpdates(locationListenerGps);
         lm.removeUpdates(locationListenerNetwork);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

The code in my main class:I have used a callback method so as to get the location object.
locationResult = new LocationResult(){
            @Override
            public void gotLocation(Location location){
                if(location!=null)
                {
                current_latitude=location.getLatitude();
                current_longitude=location.getLongitude();
                }
                if(location!=null&&!isLocationRecieved)
                {
                    MarinaJobKeys.user_viewing_jobs=true;
                    isLocationRecieved=true;

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable(){

                        @Override
                        public void run() {
                            setcurrentlocation();

                        }

                    });

                }
                else if(location==null)
                {
                    Toast.makeText(getActivity(),"NULL LOCATION RETURNED",Toast.LENGTH_LONG).show();
                }

            }

        };

 myLocation = new MyLocation();
            myLocation.getLocation(getActivity(), locationResult);

The issue is this:
The code works fine on an older device.But when i run on a new device , the onLocationchanged method in the Mylocation class never gets called.But in the older device it gets called instantly.How do i fix this issue?
EDIT:The issue got fixed on restarting the device.But why does it happen?

A: you have to enable location from setting.
please check this link.
go to setting --> Location Access --> turn on Location.


text:
Q: API gives only the headers in Python but not the data I am trying to access an API from this website. (https://www.eia.gov/opendata/qb.php?category=717234)
I am able to call the API but I am getting only headers. Not sure if I am doing correctly or any additions are needed.
Code:
import urllib
import requests
import urllib.request

locu_api = 'WebAPI'
def locu_search(query):
    api_key = locu_api
    url = 'https://api.eia.gov/category?api_key=' + api_key
    locality = query.replace(' ', '%20')
    response = urllib.request.urlopen(url).read()
    json_obj = str(response, 'utf-8')
    data = json.loads(json_obj)

When I try to print the results to see whats there in data:
data

I am getting only the headers in JSON output. Can any one help me figure out how to do extract the data instead of headers.

A: Avi!
Look, the data you posted seems to be an application/json response. I tried to reorganize your snippet a little bit so you could reuse it for other purposes later.
import requests

API_KEY = "insert_it_here"

def get_categories_data(api_key, category_id):
    """
    Makes a request to gov API and returns its JSON response
    as a python dict.
    """
    host = "https://api.eia.gov/"
    endpoint = "category"
    url = f"{host}/{endpoint}"

    qry_string_params = {"api_key": api_key, "category_id": category_id}

    response = requests.post(url, params=qry_string_params)

    return response.json()

print(get_categories_data(api_key=API_KEY, category_id="717234"))

As far as I can tell, the response contains some categories and their names. If that's not what you were expecting, maybe there's another endpoint that you should look for. I'm sure this snippet can help you if that's the case.
Side note: isn't your API key supposed to be private? Not sure if you should share that.
Update:
Thanks to Brad Solomon, I've changed the snippet to pass query string arguments to the requests.post function by using the params parameter which will take care of the URL encoding, if necessary.

A: You haven't presented all of the data. But what I see here is first a dict that associates category_id (a number) with a variable name. For example category_id 717252 is associated with variable name 'Import quantity'. Next I see a dict that associates category_id with a description, but you haven't presented the whole of that dict so 717252 does not appear. And after that I would expect to see a third dict, here entirely missing, associating a category_id with a value, something like {'category_id': 717252, 'value': 123.456}.
I think you are just unaccustomed to the way some APIs aggressively decompose their data into key/value pairs. Look more closely at the data. Can't help any further without being able to see the data for myself.


text:
Q: How to convert null to string in Event Gridview RowDeleting on Textbox i want convert value null to string in Event Gridview RowDeleting on Textbox.
But error "Object reference not set to an instance of an object."
Code Behide:
protected void gvTerm_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TextBox txtCountryRate_Te = (TextBox)gvTerm.Rows[e.RowIndex].FindControl("txtCountryRate_Te");
            if (txtCountryRate_Te == null)
            {
                txtCountryRate_Te.Text = string.Empty;  //<== Error Object reference not set to an instance of an object.
            }
}

Thanks in advance. ;)

A: the error exactly tells what is happening. you are trying to access and set property of null object.
to set String.Empty as text to your object. just create new instance of object with empty text.
    protected void gvTerm_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        TextBox txtCountryRate_Te = (TextBox)gvTerm.Rows[e.RowIndex].FindControl("txtCountryRate_Te");
        if (txtCountryRate_Te == null)
        {
            txtCountryRate_Te = new TextBox
            {
                Text = String.Empty
            };
        }
    }

How ever the default value is String.Empty so you can simplify it to
txtCountryRate_Te = new TextBox();


text:
Q: Elasticsearch, sort aggs according to sibling fields but from different index Elasticsearch v7.5
Hello and good day!
We have 2 indices named socialmedia and influencers
Sample contents:
socialmedia:
{
    '_id' : 1001,
    'title' : "Title 1",
    'smp_id' : 1,
},
{
    '_id' : 1002,
    'title' : "Title 2",
    'smp_id' : 2,
},
{
    '_id' : 1003,
    'title' : "Title 3",
    'smp_id' : 3,
}
//omitted other documents

influencers
{
    '_id' : 1,
    'name' : "John",
    'smp_id' : 1,
    'smp_score' : 5
},
{
    '_id' : 2,
    'name' : "Peter",
    'smp_id' : 2,
    'smp_score' : 10
},
{
    '_id' : 3,
    'name' : "Mark",
    'smp_id' : 3,
    'smp_score' : 15
}
//omitted other documents

Now I have this simple query that determines which influencer has the most document in the socialmedia index
GET socialmedia/_search
{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "INFLUENCERS": {
      "terms": {
        "field": "smp_id.keyword"
        //smp_id is a **text** based field, that's why we have `.keyword` here
      }
    }
  }
}

SAMPLE OUTPUT:
"aggregations" : {
    "INFLUENCERS" : {
      "doc_count_error_upper_bound" : //omitted,
      "sum_other_doc_count" : //omitted,
      "buckets" : [
        {
          "key" : "1",
          "doc_count" : 87258
        },
        {
          "key" : "2",
          "doc_count" : 36518
        },
        {
          "key" : "3",
          "doc_count" : 34838
        },
      ]
  }
}

OBJECTIVE:
My query is able to sort the influencers according to doc_count of their posts in the socialmedia index, now, is there a way for us to sort the INFLUENCERS aggregation or make a way to sort out the influencers according to their SMP_SCORE?
With that idea, smp_id 3 which is Mark, should be the first one to appear since he has an smp_score of 15
Thank you in advance for your help!

A: What you are looking for is a JOIN operation. Note that Elasticsearch doesn't support JOIN operations unless they are modelled in a way as mentioned in this link.
Instead, a very simplistic approach is to denormalize your data and add the smp_score to your socialmedia index as below:
Mapping:
PUT socialmedia
{
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "fields": {
          "keyword":{
            "type":"keyword"
          }
        }
      },
      "smp_id": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      },
      "smp_score": {
        "type": "float"
      }
    }
  }
}

Your ES query would then have two Terms Aggregation as shown below:
Request Query:
POST socialmedia/_search
{
  "size": 0,
  "aggs": {
    "influencers_score_agg": {
      "terms": {
        "field": "smp_score",
        "order": { "_key": "desc" }
      },
      "aggs": {
        "influencers_id_agg": {
          "terms": {
            "field": "smp_id.keyword"
          }
        }
      }
    }
  }
}

Basically we are first aggregating on the smp_score and then introducing a sub-aggregation to display the smp_id.
Response:
{
  "took" : 10,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 3,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "my_influencers_score" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 15.0,
          "doc_count" : 1,
          "influencers" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "3",
                "doc_count" : 1
              }
            ]
          }
        },
        {
          "key" : 10.0,
          "doc_count" : 1,
          "influencers" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "2",
                "doc_count" : 1
              }
            ]
          }
        },
        {
          "key" : 5.0,
          "doc_count" : 1,
          "influencers" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "1",
                "doc_count" : 1
              }
            ]
          }
        }
      ]
    }
  }
}

Do spend sometime in reading the above link, however that would require you to model your index in a different way depending on the options mentioned in it. From what I understand, the solution I've provided would suffice.