text:
Q: 404 not found on phpmyadmin - nginx docker I want to run phpmyadmin and my API on same domain using docker and nginx, as:
api => localhost:8888/
phpmyadmin => localhost:8888/phpmyadmin/
Docker config for phpmyadmin service:
phpmyadmin:
  image: phpmyadmin
  restart: always
  environment:
    PMA_ARBITRARY: 1
    PMA_HOST: mysql
    PMA_USER: ${DATABASE_USER}
    PMA_PASSWORD: ${DATABASE_PASSWORD}
  depends_on:
    - mysql

This is nginx service config:
nginx:
  image: nginx:stable-alpine
  volumes:
    - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
  depends_on:
    - api
    - phpmyadmin
  restart: always
  ports:
    - '8888:80'

And this is nginx config file:
upstream pma {
  server phpmyadmin;
}

server {
  listen 80;
  server_name localhost;
  # resolver 127.0.0.1;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://api:8889/;
    proxy_redirect off;
  }

  location ~/phpmyadmin(.*)$ {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://pma/$1/;
    proxy_redirect off;
  }
}

Everything works fine, I can use the API, as localhost:8888/url and it works fine. But when I request localhost:8888/phpmyadmin/, it loads it, but js and all css gives 404 not found, here's the console preview:

I have been scratching my head from more than 3 hours to fix this, tried my best, but it doesn't work. I am pretty much new to nginx so can anyone please help me out.

A: Did you try adding PMA_ABSOLUTE_URI in the docker phpmyadmin service environments? Checkout this:

PMA_ABSOLUTE_URI - the full URL to phpMyAdmin. Sometimes needed when used in a reverse-proxy configuration.

Add it like:
PMA_ABSOLUTE_URI: localhost:8888/phpmyadmin/

Please notice the last / that is very very important, if you miss it, it will not work.


text:
Q: Ubuntu Server, listen for commit on external SVN repository? I have a Subversion repository which my team and I use for source control on a web application we are building. I would like to be able to have every commit to that repository automatically publish to our testing server. I have checked out the repository to a working copy on the server... is there any way to listen to the repository on the server so that every time somebody commits to the repository I can run a svn update?

A: Take a look at post commit. Here's an example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ gdi drawing ellipse problem ok i can draw ellipse the problem is this, im trying to draw one ellipse but change its x value to different one. like this i draw one ellipse and the x value is 1 after ten seconds i want it the x value to be 10 but it seems that im creating new ellipse with x value 10. here is my code
while(sd==1)//sd equal 1
{
    sf++;//sf equals 1
    onPaint(hdc);
    InvalidateRect(hWnd,0,true);
}
//on paint function
VOID onPaint(HDC hdc)
{
   Graphics graphics(hdc);
   Pen      pen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&pen,sf , 0, 50, 50);
}

well i thought that invalidate rect will clear everything have been painted and repaint it but it didn't work

A: You shouldn't try to draw multiple frames of an animation in one shot.
Save your variable sf somewhere, and in OnPaint(), increment sf, draw a single ellipse, and call Invalidate()
The Invalidate will trigger OnPaint() to be called again.
This should work, but will be very flickery :)  You can fix the flicker by double-buffering.

A: If you want to make an animation you are better setting a timer.
Using InvalidateRect as a way to generate WM_PAINTs seems overkill, it will do much more thant that. Instead you can draw directly in OnTimer call, since it is outside a WM_PAINT you will need to get a device context with GetDC.
For example if you can have the function DrawFrame(HDC hDC). OnTimer will update the current position and call DrawFrame, OnPaint will call DrawFrame but will not update the position (that way if you want to stop the animation you will have the last frame draw).
The DrawFrame will clear the background (probably with a FillRect), and draw the circle in the new position. If you have a large area this will flicker, to avoid it as Tom suggested you may use a memory DC and a HBITMAP for the double buffer.

A: InvalidateRect marks the window as "invalid", but that doesn't cause an erase and repaint to happen right away.  The erasing and painting happen only when your message pump is running (e.g., the loop with GetMessage and DispatchMessage).  When the message queue runs dry, GetMessage will synthesize WM_ERASEBKGND and WM_PAINT messages for the invalid windows.  When those messages are dispatched to the window procedure, the window gets a chance to draw.
Your onPaint function only draws, it doesn't erase.  And since your loop never exits, the message pump never gets to run.
For simple animations, the solution is to SetTimer.  In your handler for the WM_TIMER messages, update your variables for single frame, call InvalidateRect, and return (which lets the message pump keep running).  The erasing and painting message will happen, then the timer will fire again, and you'll get the next frame.


text:
Q: Change the value in massive by pressing button(React) Ok, so I am creating employers list with salary and Names. I want to change color of text by changing value of variable - "increase" from false to true for example. I already created code to change text taking value FROM variable

Now I need to change value of "increase" by clicking a button
Here is a full code:
const EmployeesListItem = ({name, salary, increase}) => {
    return (
//-------Here I check the value of variable----->

            {name}
            <input type="text" className="list-group-item-input" defaultValue={salary + "$"}/>

                <button type="button"
                    className="btn-cookie btn-sm ">
                     //by clicking in this button I wanna change value of increase variable
                </button>

                <button type="button"
                        className="btn-trash btn-sm ">

                </button>

    )
}

export default EmployeesListItem;

Here is EmployerList structure:
import EmployeesListItem from '../employeers-list-item/employeers-list-item'
import './employers-list.css'
const EmployersList = ({data}) => {

    const elements = data.map(item => {
        return(
             <EmployeesListItem {...item} data={data}/> //name={item.name}  salary={item.salary}
        )
    })

    return (

            {elements}

    )
}

export default EmployersList;

And here is App component:
function App() {

    const data = [
        {name: 'killer228brawlstarsassasin1993', salary:2300 ,increase: true},
        {name: 'jotaro', salary:800 ,increase: false},
        {name: 'Ktoh', salary:300 ,increase: true}
    ]

    return (

            <AppInfo/>

                <SearchPanel>
                </SearchPanel>
                <AppFilter/>

            <EmployersList data={data}/>
            <EmployeesAddForm/>

    )
}

export default App;

the program works, but still don't know how to change the value of the INCREASE variable in the APP component by clicking on the button

A: You should read about React Context, this will help you to store data so it is accessible from every component: https://reactjs.org/docs/context.html
The way your app works now you need to pass a "changeIncrease"-function as prop to the EmployeesListItem component.
const changeIncrease = (name) => {
  data.forEach(employee, index) => {
  if(employee.name == name) {
    data[index] = {...emloyee, increase: !employee.increase}
  }
}
}

Maybe there's a more elegant solution out there, but this should do it


text:
Q: A method not working after fragment orientation change In my Android project I use a class method to set a font type to all views here is the method :
    public  void overrideFonts(final Context context, final View v ) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
            }
        } else if (v instanceof TextView) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(),"font/aFont.ttf"));
        }
    } catch (Exception e) {

    }
}

It is working fine on my fragment except when I change the orientation of device. after that this method not working even by restoring the orientation to portrait!
I tried saveInstanceState (I think it's not about my problem)....
So what is the problem?!
here is my fragment class that I use this method in it.
public class aboutUs extends Fragment {

MUF option;
RelativeLayout relativeLayout;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    option = new MUF(getActivity(), getContext());
    relativeLayout = (RelativeLayout) getActivity().findViewById(R.id.aboutus_fragment);
    option.overrideFonts(getContext(), relativeLayout);
    Toast.makeText(getActivity(), "onActivityCreated", Toast.LENGTH_SHORT).show();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_about_us, container, false);
    return view;

}

}

A: <activity
        android:name=".ui.activities.MainActivity"//Your fragment's activity
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:screenOrientation="portrait" />

From your AndroidManifest.xml Just remove "orientation" and "screenSize" from android:configChanges and android:screenOrientation="portrait" too if added to the activity of your fragment


text:
Q: How to initialize C++17 vector of pairs with optional element In C++17, how do you declare and initialize a vector of pairs(or tuples) with an optional element?
    std::vector<std::pair<int, optional<bool> > > vec1 = { {1, true},
                                                           {2, false},
                                                           {3, nullptr}};

I have a pair where the second element may be null/optional.

A: You are looking for std::nullopt instead of nullptr.
std::vector<std::pair<int, std::optional<bool> > > vec1 =
  { {1, true}, {2,false}, {3,std::nullopt} };

A: Or simple use default construction:
std::vector<std::pair<int, std::optional<bool>>> vec1 {
    {1, true}, {2,false}, {3,{}}
};


text:
Q: Prove Zn=min{Sn,4} where Sn=X1+...+Xn is markov chain by definition Xn  are i.i.d random variables with P[Xn=1]=P[Xn=0]=1/2 and we we also have Sn=X1+...+Xn. Show that Zn=min{Sn,4} is a Markov Chain and find it transition matrix.
I know that Sn=Sn−1+Xn but I don't see how to use it in conditioning to make variables independent.

A: $(Z_n)_n$ is a Markov chain, because the distribution of $Z_{n+1}$ is determined by the distribution of $Z_n$ only, and it does not depend on the distribution of $Z_{i}, i \le n-1$. In general, independence is irrelevant for Markov chains.
Let $p(\cdot,\cdot)$ be the transition probability for $(Z_n)_n$.
Since $Z_n \le 4$, we need to consider $p(x,y)$ only for $x, y \in \{0,1,2,3,4\}$.
Since $S_n$ is non-decreasing, if $Z_n = 4$, then, $Z_{n+1} = 4$.
Hence, $p(4,i) = \begin{cases} 1 \ \ \ i = 4 \\  0 \ \ \ i \ne 4 \end{cases}$.
If $Z_n = 3$, then, $S_n = 3$ and hence $Z_{n+1} = S_{n+1}= 4$ iff $X_{n+1} = 1$ and $Z_{n+1} = S_{n+1} = 3$ iff $X_{n+1} = 0$.
Hence, $p(3,i) = \begin{cases} 1/2 \ \ \ i = 4 \\  1/2 \ \ \ i = 3 \end{cases}$.
In the same manner,
$p(2,i) = \begin{cases} 1/2 \ \ \ i = 3 \\  1/2 \ \ \ i = 2 \end{cases}$,
$p(1,i) = \begin{cases} 1/2 \ \ \ i = 2 \\  1/2 \ \ \ i = 1 \end{cases}$, and,
$p(0,i) = \begin{cases} 1/2 \ \ \ i = 1 \\  1/2 \ \ \ i = 0 \end{cases}$.
So, the transition matrix $P = (p(x,y))_{x,y = 0,1,2,3,4}$ is given by $$ P = \begin{pmatrix}1/2 & 1/2 & 0 & 0 & 0\\0 & 1/2 & 1/2 & 0 & 0\\ 0 & 0 & 1/2 & 1/2 & 0\\0 & 0 & 0 & 1/2 & 1/2\\0 & 0 & 0 & 0 & 1 \end{pmatrix}.$$


text:
Q: How to pass in data from Models, into Table View Controller and then to DetailViewController I have created quite a few classes and structs that have arrays from that data received from the end points of the Json API, and now I am in need of help passing in those arrays into a table view controller as well as a detail view controller that passes in the images and details from my model. Below are all of the models, "MealCategoryResponse", "MealDetailModel", "Meals" and MealDetailModel. I've included the Constants, as well as the ViewModels  that i've created for the data received from my API end points. How can I create a TableViewController that will list all of my Model as well as when the arrays of meals are clicked, take me to  detailViewController that has the details from my DetailModel? Please let me know if i need to add more information or if this question is not acceptable or if it needs to be edited. I am asking here because I have been trying to do this for the last days & I have covid.
    Constants that i've created to get the Url's link

        import Foundation
        struct Constants {
         struct Urls {

         static let mealsCategoriesUrl = URL(string:
 "https://www.themealdb.com/api/json/v1/1/categories.php")!

    static func  getMealNameCategoryUrl(_ strMeal: String) -> URL {
        return URL(string:"https://www.themealdb.com/api/json/v1/1/filter.php?c=Beef")!
    }

    static func  getMealByIdUrl(_ idMeal: String) -> URL { return URL(string:"https://www.themealdb.com/api/json/v1/1/lookup.php?i=52874")!
    }
}

static func getImagesUrl(strMealThumb: String) -> URL {
    return URL(string: "https://www.themealdb.com//images//category//beef.png")!
}

struct strMealThumbUrl  {

    static let  strMealThumb = URL(string:"https://www.themealdb.com//images//media//meals//vtqxtu1511784197.jpg")!
}

struct strYoutubeUrl {

    let strYoutube = URL (string:
                            "https://www.youtube.com/watch?v=nMyBC9staMU")!

}

}
             Model with arrays
            import Foundation
    struct MealCategoryResponse: Decodable {
     let  categories: [MealCategory]
   }

   struct MealCategory: Decodable {
  let idCategory: String //id
  let strCategory: String //name
  let strCategoryThumb: String //image//
  let strCategoryDescription: String
 }

    import Foundation
     struct Meals: Decodable {
     let meals: [Meals]
     let strMeal: String
     let strMealThumb: String //image
     let idMeal: String

      }

         import Foundation
         struct MealDetailModel: Codable {
         let meals: [MealDetail]
          }
        struct MealDetail: Codable {
        let idMeal: String
        let strMeal: String
        let strCategory: String
        let strInstructions: String
        let strIngredient: String
        let strMeasure: String
        let strYoutube: String
        let strMealThumb: String //image
       let meals: [[String: String?]]
      }

         ViewModels for passing in the data from API to the Model

       import Foundation
       @MainActor
       class MealsListModel: ObservableObject {
       @Published public var mealsCategories: [CategoryMealViewModel] = []
        private func loadCategories(strCategory: String) async {
        do {
        let mealCategoryResponse = try await

WebServiceRequest().parseData(url: Constants.Urls.mealsCategoriesUrl) { data in
return try?   JSONDecoder().decode(MealCategoryResponse.self, from:data )
}
        self.mealsCategories = mealCategoryResponse.categories.map(CategoryMealViewModel.init)

       } catch {
        print(ServiceError.decocorrupt)
       }

       }
      }

       import Foundation
       import UIKit

      //create View model for meals Category
     struct CategoryMealViewModel: Identifiable {
     let id =  UUID()

    private let mealCategory: MealCategory

    init(_ mealCategory: MealCategory) {

    self.mealCategory = mealCategory

       }

       var strCategory: String {
        mealCategory.strCategory
      }
       var strCategoryThumb: URL? {
       URL(string: mealCategory.strCategoryThumb)
     }
     }

import Foundation
import UIKit
@MainActor
class DetailViewModel: ObservableObject{
@Published   var strMeal: String = ""
@Published   var strInstructions: String
@Published   var strIngredient: String
@Published   var strMeasure: String
@Published   var strMealThumb:URL?

init(strInstructions: String, strIngredient: String, strMeasure: String) {
    self.strInstructions = strInstructions
    self.strIngredient = strIngredient
    self.strMeasure = strMeasure

    func loadMealDetails(idMeal: String) async {
        do {
            let mealDetailResponse = try await  WebServiceRequest().parseData(url: Constants.Urls.getMealByIdUrl(strMeal)) { data in
                return try?   JSONDecoder().decode(MealDetailModel.self, from:data )
            }
            let mealDetail = mealDetailResponse.meals
        } catch {
            print(error)
        }

       }

     }

   }


text:
Q: How to call a function in discord.py bot when script starts but not when bot is re-logging in? if you have a discord.py bot sometimes the bot goes offline and logs in again. Thats not really a problem but i want my script to automatically call a function when it started im now using on_ready(). like this:
global restockkk
restockkk = False

@bot.event
async def on_ready():
    logchannel = bot.get_channel(ID_CHANNEL)
    await logchannel.send(f'Logged in as {bot.user}'.format(bot))
    await bot.change_presence(activity=discord.Game(name="Buddy is busy being the GOAT"))
    await restock()

restock is the name of my function. but when it logs in again it runs the function again, this results in the function running like 40 times after a day which is insane spam. I tried setting a global restockkk that sets to true when the restock() function is run but i think the script just starts over again or something because it ignores the restockkk set to true in the restock() function and still runs if i use:
global restockkk
restockkk = False

@bot.event
async def on_ready():
    logchannel = bot.get_channel(ID_CHANNEL)
    await logchannel.send(f'Logged in as {bot.user}'.format(bot))
    await bot.change_presence(activity=discord.Game(name="Buddy is busy being the GOAT"))
    if not restockkk:
        await restock()

this is my restock function:
async def restock():
        logchannel = bot.get_channel(960147355691253800)
        await logchannel.send('Restock monitor on')
        restockkk = True
        while True:
            try:
                if not restockkk:
                    await bot.change_presence(activity=discord.Game(name="Buddy is busy being the GOAT"))
                    break
                #... first piece of code
                await asyncio.sleep(120)
                #... second piece of code
                await asyncio.sleep(120)
            except Exception:
                await logchannel.send('exception occurred')
                await restock()

(its an infinite loop). The above sadly didn't work, i run my bot with:
bot.run(MY_BOT_TOKEN)

I also have a stop command (that's why i use global restockkk)
@bot.command(pass_context = True)
    async def stop(message):
        if message.author.id == myId:
            restockkk = False
            await message.channel.send('Restock monitor is off')
        else:
            await message.channel.send('You are not allowed to use this command')

So my question is: how can i call a function when the bot starts for the first time and not when its on_ready?

A: You're looking for bot.setup_hook(), which is only called once when running the script. on_ready is disfavored for the exact reason you are running into - it's not only called once.

A: As mentioned by the other answer by Grace, on_ready is called multiple times and you should use setup_hook for things that should only run once on startup. However, there's more issues going on here.
You seem to misunderstand how the global keyword works. There's no point in using it at the top of your file, you should use it inside of functions where you want to modify the value of variables outside of the current scope. AKA, in your restock function.
By not using global inside of restock, you're just creating a local variable inside of that function instead of changing the value of that global variable, meaning that restockkk is always False.
global restockkk  # This doesn't do anything
restockkk = False

async def restock():
   ...
   restockkk = True  # This doesn't modify restockkk, it creates a local variable inside of the restock()-function

async def stop(...):
   ...
   restockkk = False  # This doesn't modify restockkk, it creates a local variable inside of the stop()-function

To modify a variable in a higher scope, use the global keyword inside of the function where you want to modify it.
restockkk = False

async def restockkk():
    global restockkk  # Use it inside of the function instead
    restockkk = True  # This does modify it

Additionally

*

*Don't change presence in on_ready

*Preferably, don't do anything at all in on_ready

*Instead of an infinite while True: loop, look into ext.tasks


text:
Q: Ruby - Control child threads from main thread The main program is creating a child thread. The child thread is running a loop and this thread needs to be paused and resumed based on events taking place in main thread.
What would the best way to accomplish this? IPC?

A: Communication between thread should be done using thread safe classes.
You can use Queue since it as a blocking method: pop.
If you want a more specific response you need to provide more details about your use case.


text:
Q: How to check NULL value of Date/Time while using UCanAccess JDBC Driver? While accessing MS Access DB using UCanAccess JDBC Driver i am facing too many problems in processing Date. I want to check where a Date/Time field is Null or Not. If there is Null then want to Update but i Cannot do that.
The field 'logout_time' is 'Date/Time' data type in MSAccess database.
String sqlString = "update user_Log set logout_time = #" +
                                    strEndDate + "# where (user_Id ="+
                                    userId +") & (logout_time = NULL)";

                    int l=stmt.executeUpdate(sqlString);

This will sends sqlString
update user_Log set logout_time = #12/13/2015 10:33:28# where (user_Id =3) & (logout_time = NULL);

This SQL statement execute well from MSAccess Query. But it can not execute from UCanAccess JDBC Driver. it will generating error:
    net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.3 incompatible data types in combination
 This exception may  happen if you add integers representing units of time directly to datetime values using the arithmetic plus operator but without specifying the unit of date.
   In this specific case you have to use, for example, <dateColumn> + 1 DAY.
    at net.ucanaccess.jdbc.UcanaccessStatement.executeUpdate(UcanaccessStatement.java:222)

A:
This SQL statement execute well from MSAccess Query.

Not really. It may execute, but it also might not do what you want. Your code ...
WHERE ... (logout_time = NULL)

... is non-standard SQL which can yield unexpected results (details here). You want
WHERE ... (logout_time IS NULL)

You should also stop using dynamic SQL and instead use a PreparedStatement and a parameterized query to perform your update.


text:
Q: operator in Android's Action Bar I am using action bar using following code,
 ActionBar actionBar = getActionBar();
 actionBar.setCustomView(R.layout.custom_action);
 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
                    | ActionBar.DISPLAY_SHOW_HOME);

According to above code there is symbol/operator single vertical bar (|)  in method called actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
so what is meaning of that single vertical bar ( | )..??

A: The operator | does a "bitwise OR". The output of bitwise OR on two bits is 1 if either bit is 1 or 0 if both bits are 0. Bitwise OR on two numbers just does a bitwise OR on each bit individually.
Heres how 3|4 works:

  3:  00000011
  4:  00000100
--------------
3|4:  00000111 = 7

reference


text:
Q: How to detect tautologies injection attacks I'm working on a new method to preventing sql injection attacks which its type is "tautology attack".
How can I detect a tautology bug in a web application?
I mean, I want a way to test my method and at last obtain a statistic that shows my method capability like Acunetix that shows the Blind Attacks.
How can I do it and compare my method?
best respects

A: Tautology: In the tautology attack the attacker tries to use a conditional query statement to be evaluated always true. Attacker uses WHERE clause to inject and turn the condition into a tautology which is always true. The simplest form of tautology
Example
       SELECT *FROM Accounts WHERE user=''or1=1—
      'AND pass=''AND eid=

The result would be all the data in accounts table because
the condition of the WHERE clause is always true.
To Detect:
As far I think their is no specific method to check, but you can give input in a such way to test it.(like shown above)
To Protect:

*

*Always use Parametrized query

*Also restrict user to input special character like " ' "(single quote) and other which are used to build query.

Hope it Helps..!!

A: You can avoid the whole problem by not using raw SQL in your code. You should at a minimum be using a parameterised query builder or stored procedures. Better yet, use an Object-Relational Mapper like Entity Framework, PetaPOCO or CakePHP.
Further to that, if you're expecting to return only one result, use

SELECT TOP 1

or

LIMIT 1,0

Depending on your DB.


text:
Q: Filling out and submitting a form for a newly opened window What I'd like to do is open a new window, then submit the form in that new window after automatically filling out he form elements from the original window. Here is what I tried to do:
var username = 'myuser';
var password = 'mypass';
var loginWindow = window.open('http://www.mysite.com/form.html', 'loginWindow');
loginWindow.document.getElementById('username').value=username;
loginWindow.document.getElementById('password').value=password;
loginWindow.document.form.submit();

This however does not work, and instead gives me the following error: "Result of expression 'loginWindow.document' [undefined] is not an object."
Is this even possible? Can jQuery solve this?

A: You will not be permitted to refer to objects in a document hosted on a different domain to the one the current document was retrieved from. Are both documents in the same domain? Are you using the 'www' prefix for one but not the other?
If you have to pass information across domains, consider passing it via the URL. Alternatively, is there any reason not to submit the data yourself directly to the location the target form would be submitting it to?


text:
Q: htaccess not showing images and css I have a problem, URL's have been rewritten like this
RewriteRule "^product-cate/([0-9]+).html$" "index.php?action=productcate&id=$1"
None of my images, nor css styles are being applied. I have tried , but it is not working.
can someone help me?


text:
Q: At which point does a control's event delegate call the base code For example, the constructor of a custom derived listbox has:
this.KeyDown += listbox_KeyDown;

And this is implemented as:
private void listbox_KeyDown( object sender, KeyEventArgs e )
{
}

At which point is the base parent code called?
Without delegates, it would like this:
protected override void OnKeyDown( KeyEventArgs e )
{
    base.OnKeyDown( e );
}

Thank you all.

A: Apparently, the base is called before any code is executed.


text:
Q: PIP fails all package installs Could not fetch url Read timeout Any package install with pip I do keeps failing with Could not fetch url error, I'm able to access https://pypi.org/simple/prefect/ directly and ping pypi.org.
I'm on ubuntu 20.04.4 on windows 10, I'm not on any proxy or vpn, PIP v20.0.2 and Python 3.8.10, I tried 3.9 and 3.10 and still the same issue.
OpenSSL 1.1.1f and method 1.2
Scoured a lot of posts on stackoverflow but still unable to resolve my issue.


text:
Q: The etale fundamental group of a field Background and motivation:
I am teaching the "covering space" section in an introductory algebraic topology course.  I thought that, in the last five minutes of my last lecture, I might briefly sketch how to compute the "fundamental group of a field," primarily as a way of illustrating the analogy between Galois theory and covering space theory, but also because this is the sort of thing that makes me eager to learn more about a subject when I am on the receiving end of a lecture.
Unfortunately, as yet, I myself know little more about the etale fundamental group than the definition and a bit of motivation (although I am certainly planning to learn more).  In particular, I realized that there is an obvious question I don't know how to answer.  When defining the fundamental group in an algebraic setting, we define it as an inverse limit because there is, in general, no natural analogue of a universal cover.  However, if we are looking at Spec k, there is an obvious candidate, namely the Spec of the algebraic closure of k.
Question:
Let $k$ be a field, with algebraic closure $K$.  How does the etale fundamental group of Spec $k$ compare to the automorphism group of $K$ over $k$?  Assuming they are different, what (in very general terms) are the reasons for working with one rather than the other?

A: Essentially by definition, the etale fundamental group of a field $k$ is the group of $k$-automorphisms of a separable algebraic closure $k^{\operatorname{sep}}$ over $k$.  If $k$ is perfect, then this is (well-defined up to an inner automorphism) $\operatorname{Aut}(\overline{k}/k)$.  On the other hand, any $k$-automorphism of $k^{\operatorname{sep}}$ extends uniquely to an automophism of the algebraic closure $\overline{k}$.  Therefore in every case the etale fundamental group of $k$ is isomoprhic to $\operatorname{Aut}(\overline{k}/k)$.

A: Also for the étale fundamental group there is in fact always some universal
cover. However, in the abstract way that Grothendieck formulated the theory of
coverings a universal cover would only exist as a pro-object. It then depends on
the precise situation (and the precise definitions) whether this pro-object can
be realised as an actual covering. Consider the case of a field $k$, the
question is whether
$$\mathrm{Spec}(\overline{k}) \rightarrow \mathrm{Spec}(k)$$
where $k\subseteq\overline k$ is a separable closure, is considered an étale map
or not (depending on your preferences only finite separable $k$-algebras may
give you étale covers).
Here is, I think, an even more instructive example. Consider $\mathbb C^\ast$ as
the algebraic variety $\mathrm{Spec}(\mathbb C[\mathbb Z])$, where the group
algebra $\mathbb C[\mathbb Z]$ is nothing but the Laurent polynomial ring
$\mathbb C[t,t^{-1}]$. A topological universal cover is given by
$\exp\colon\mathbb C \rightarrow \mathbb C^\ast $ whereas an étale universal cover
is given by the pro-covering
$$\{\mathrm{Spec}(\mathbb C[1/n\mathbb Z])\rightarrow
\mathrm{Spec}(\mathbb C[\mathbb Z])\}$$
(with transition maps induced by inclusions $1/n\mathbb Z\subseteq 1/mn\mathbb Z$). If one accepts such maps as étale covers one may take the direct limit of the rings involved and get an étale universal cover
$$\mathrm{Spec}(\mathbb C[\mathbb Q]) \rightarrow\mathrm{Spec}(\mathbb{C}[\mathbb Z]).$$
This algebraic universal cover is not (analytically) isomorphic to $\exp\colon\mathbb C \rightarrow \mathbb C^\ast $; the fibres of the algebraic
cover can be identified with the profinite completion of $\mathbb Z$ while the
fibres of the analytic/topological universal have fibres $\mathbb Z$
itself. There is a map of covers
$$\mathbb C^\ast \rightarrow \mathrm{Spec}(\mathbb C[\mathbb Q])$$
which on fibres correspond to the inclusion of $\mathbb Z$ into its profinite completion.

A: The étale fundamental group is defined using a reconstruction procedure that applies with minimal alteration to topological covering spaces.  Tyler Lawson explained the correspondence in his answer to a previous question.  For the case of fields, covering spaces correspond to spectra of finite étale $k$-algebras (which are isomorphic to finite products of finite separable extensions of $k$), and connected covering spaces correspond to spectra of finite separable extensions of $k$.
The category whose objects are finite étale $k$-algebras and whose morphisms are $k$-algebra maps is anti-equivalent to the category whose objects are finite sets equipped with continuous actions of a certain profinite group and whose morphisms are equivariant maps of sets.  This group (the fundamental group) is uniquely defined up to isomorphism by this property (and is actually defined as the automorphism group of a certain functor).  The fundamental group acts continuously on any separable closure of $k$ by field automorphisms, and in fact makes up all of its $k$-algebra automorphisms.  You can check this by using the fact that each element of a separable closure lies in some finite separable extension of $k$, together with the compatibility afforded by the anti-equivalence of categories.  If you pass to spectra, you get a covariant equivalence, and the maps of spectra of fields are the analogues of covering maps.
In the topological world, the reconstruction from the category of covering spaces of your space gives you a fundamental group that is usually not profinite, but if you were to restrict your view to covering maps with finite fibers, then the profinite completion of that group would appear.
It's not clear to me that this quantity of material can be reasonably covered in 5 minutes, but since you're giving a motivating discussion, I don't see a problem with using the Clark étale fundamental group.


text:
Q: Edit the form css of a django form so the submit button looks like this:
<input type="submit" id='register_submit' class= value="{% trans 'Submit' %}" />

and normall I would use a class to specify what the button looks like, but this has its own class that I cannot touch. What can I do here to give it a new class so I can customize the button?

A: An option would be to override the existing rule with a specific rule.  So, if your output HTML is:
<input type="submit" class="django-submit" />

You could wrap it to end up with:

    <input type="submit" class="django-submit" />

And then use your .my-button class to create a more specific CSS rule:
.my-button .django-submit {
    padding: 5px;
    color: #fff;
    background: #f00;
}

The following demo shows how the specific rule will override the generic rule.

A: You could give the button a style attribute which will always take precedence over any class attribute.


text:
Q: Pdf about conic optimization Because of COVID I can't go in library to do some research, so I ask you any reference to books dealing with conic optimization, conic duality and Fenchel's duality. I state that I don't know anything about these arguments, so I have to find a pdf not too complicated.
Could you please provide me any links? Thanks in advance.

A: The topics that you've mentioned are covered in the textbook by Stephen Boyd and Lieven Vandenberghe:
https://web.stanford.edu/~boyd/cvxbook/
Lecture notes by Aharon Ben-Tal and Arkadi Nemirovsky are also available online:
https://www2.isye.gatech.edu/~nemirovs/
These are both posted with the permission of the publisher.


text:
Q: Commutativity of tangent projection map and inner product I stumbled into this simple property, that I can't find a proof of, although I verified it holds in a number of cases.
Let $\mathbb{M}$ be a smooth manifold embedded into an ambient space $\mathbb{A}$ and let $\Pi_x:\mathbb{A}\to T_x\mathbb{M}$ denote an orthogonal projection to the tangent space $T_x\mathbb{M}$, namely $\Pi_x(a)\in T_x\mathbb{M}$ for every $a\in\mathbb{A}$. Furthermore, let $\langle\cdot.\cdot\rangle^\mathbb{A}$ denote an inner product in $\mathbb{A}$.
Now, take a curve $\gamma_{x,v}:[-\epsilon,\ \epsilon]\to\mathbb{M}$ such that $\gamma_{x,v}(0)=x\in\mathbb{M}$ and $\dot{\gamma}_{x,v}(0)=v\in T_x\mathbb{M}$ and consider the function $\Pi_{\gamma_{x,v}(t)}(a)$ for a given $a\in\mathbb{A}$. Define the following map:
\begin{equation}
\Pi_x^\bullet(a,v):=\left.\frac{\mathrm{d}}{\mathrm{d}t}\Pi_{\gamma_{x,v}(t)}(a)\right|_{t=0}.
\end{equation}
The property I was referring to is the following: Given $x\in\mathbb{M}$ and $a\in\mathbb{A}$, for every pair $v,w\in T_x\mathbb{M}$ it holds that
\begin{equation}
\langle\Pi_x^\bullet(a,v),w\rangle^\mathbb{A} = \langle\Pi_x^\bullet(a,w),v\rangle^\mathbb{A}.
\end{equation}
Does anyone know why is that so ?
Thanks in advance!

A: This is not an answer to your original question. I find the map you define, $\Pi_x$, to be awkward to work with. For me the easiest way to prove what you found is to use an orthonormal moving frame.
One of your comments indicates that you are trying to use $\Pi_x$ to define the Hessian of a function on the submanifold $M$. You're right that something like that should work. I show below how to define the Hessian of a function first on a submanifold of Euclidean space and then on a Riemannian manifold in a simple way without any mention of the Levi-Civita connection and Christoffel symbols.
$\newcommand\R{\mathbb{R}}$For convenience, let $\mathbb{A} = \R^n$ and $\langle \cdot,\cdot\rangle_{\mathbb{A}}$ be the standard dot product on $\R^n$.
Consider an $m$-dimensional submanifold, a smooth function $f: M \rightarrow \R$. Suppose we want to define the Hessian of $f$ at $x$. Since the Hessian is geometrically invariant, we can move $M$ so that $x$ is the origin and $T_xM$ is the $m$-plane
$$ T = \{x^{m+1} = \cdots = x^n = 0 \}$$
Near the origin, $M$ is the graph of a function $\phi: T \rightarrow T^\perp$, where $\phi(0) = 0$ and $d\phi(0) = 0$.
In other words, the map $\Phi: T \rightarrow \R^n$ given by
$$
\Phi(x) = (x,\phi(x))
$$
is the inclusion map of a neighborhood of $0 \in M$.
The Hessian of $f$ at $x$ is
$$
\nabla^2_{vw}f(0) = v^jw^k\partial^2_{jk}(f\circ\Phi)(0),
$$
where $v = (v^1, \dots, v^m)$ and $w=(w^1, \dots, w^m)$.
This definition makes it obvious that the Hessian is symmetric. It is easy to show that it is a symmetric bilinear tensor. It's also worth pointing out that the second fundamental form of $M$ at $0$ is simply the Hessian of $\phi$ at $0$.
The Hessian of a function on a Riemannian manifold is just as easy. Given a point $x_0 \in M$, it is an elementary calculation to show that in a neighborhood of $x_0 \in M$, there are local coordinates such that the metric $g$ satisfies
$$
g_{ij}(x_0) = \delta_{ij}\text{ and }\partial_kg_{ij}(x_0) = 0.
$$
In every exposition I've ever seen, this is proved using exponential coordinates, but this is a huge overkill. It is a simple exercise in calculus, and a proof can be found here. The Hessian of $f$ at $x_0$ is now given by
$$
\nabla^2_{vw}f(x_0) = v^jw^k\partial^2_{jk}f(x_0),
$$
where the partial derivatives are with respect to the local coordinates obtained above.
It is easily proved that this is a well-defined symmetric bilinear tensor and equal to the standard definition. Again, symmetry is automatic.


text:
Q: Setting up html preview mode in Webstorm I have been experiencing problems with html preview in Webstorm 2017.2 The preview keeps trying to open the file using the following:
http://localhost:63342/index.html/?_ijt=ou39u94jhtpams57t4o3l33qbd, which gives the warning of 404 Not Found.
Opening the file using the path (//file:/home/...) works perfectly fine.
Is there any way I can set the default settings so that Webstorm opens the path to the file instead of using localhost?
Thanks,
Marta


text:
Q: Fail2Ban - IP Tables REJECT not banning I have fail2ban running on Ubuntu 16, with a few jails running.
One is http-get-dos:
Within jail.conf
[http-get-dos]
enabled = true
port = http,https
filter = http-get-dos
logpath = /var/log/apache2/access.log
maxretry = 100
findtime = 60
#ban for 5 minutes
bantime = 600
action = iptables[name=HTTP, port=http, protocol=tcp]

Filter file:
# Fail2Ban configuration file
[Definition]

# Option: failregex
# Note: This regex will match any GET entry in your logs, so basically all valid and not valid entries are a match.
# You should set up in the jail.conf file, the maxretry and findtime carefully in order to avoid false positives.
failregex = ^<HOST> -.*"(GET|POST).*
# Option: ignoreregex
ignoreregex =

The jail within Fail2Ban seems to be working fine - I just tested it by hammering the URL, and my IP was added into the IP Tables.
However, I am not actually blocked - the IP Tables REJECT is not working it seems.
my.ip.address appears in IP Tables within Chain fail2ban-HTTP a REJECT, but I'm not rejected (can still access the site)
iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 2689 packets, 413K bytes)
num   pkts bytes target     prot opt in     out     source               destination
1       68  5849 fail2ban-HTTP  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80
2     3104  575K fail2ban-apache-overflows  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 80,443
3     3104  575K fail2ban-apache  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 80,443
4      728 43824 fail2ban-ssh  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 22

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 3325 packets, 4380K bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain fail2ban-HTTP (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 REJECT     all  --  *      *       my.ip.address
     0.0.0.0/0            reject-with icmp-port-unreachable
2       68  5849 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain fail2ban-apache (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1     3104  575K RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain fail2ban-apache-overflows (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1     3104  575K RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain fail2ban-ssh (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1      728 43824 RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

I'm wondering if it's an order problem - i.e. a global ACCEPT is trumping the fail2ban rule in IPTables. But if this is the problem, I don't know how to fix it, and why fail2ban didn't put it high enough in the first place.
Any advice, most appreciated.

A: You are monitoring both http and https but banning only http using iptables action. Use iptables-multiport action and ban both http and https.
action = iptables-multiport[name=HTTP, port="http,https", protocol=tcp]


text:
Q: marketing cloud - how to preview & test SMS? Does exist a capability similar to email preview and test for SMS in marketing cloud?
Thank you

A: It was added quite recently, along with the feature to send directly to Data Extensions.
You will need to create the SMS content in Content Builder.
However you can only create them in the real Content Builder, not from the one under Email Studio.

When you are creating your SMS message or open any of the existing ones, you'll have the option to use Subscriber Preview where you select your Data Extension and Subscriber.

A: *

*You have add field called Locale with Locale to the target extension.

*Then you can select that data extension at SMS subscribe preview mode.


text:
Q: First row of data not showing correct data I am looping thru and linking excel files.  Sometimes there is data with the top row having title names.  The problem is that when the column names are like "date" , "upc", "quatity" then when it links in what shows in the cell is "#Num!".  How can I get around this so I see "date" and the other field names.?
   Set wkb = objXL.Workbooks.Open(strFileName)
   ShtCount = wkb.Sheets.count
   i = 1
   x = 1

   For Each wks In wkb.Worksheets
        ' Link each sheet of the entire Spreadsheet file -----------------------
        'DoCmd.TransferSpreadsheet acLink, , _
        '      shortFilename & "_~" & wks.Name, strFileName, False, wks.Name & "$"

        'Progress Bar :::::::::::::::::::::::::::::::::::::
        RetVal = SysCmd(acSysCmdInitMeter, "Linking FILE: " & PathFilename & " - SHEET: " & Trim(str(x)) & " of " & Trim(str(ShtCount)), ShtCount)
        'Update the progress meter.
        RetVal = SysCmd(acSysCmdUpdateMeter, i)

        'TabName = wks.Name
        DoCmd.TransferSpreadsheet acLink, , _
              "TmpLinkXLS", strFileName, False, wks.Name & "$"

        ' Get the list of field names
        'Set tdf = db.TableDefs("[" & shortFilename & "_~" & wks.Name & "]")
        Set tdf = db.TableDefs("TmpLinkXLS")

        ' ---- Pause 1 second ------
        Const cTIME = 1000 'in MilliSeconds
        Call sSleep(cTIME)

        myfields = ""
        For Each fld In tdf.Fields
            myfields = myfields & "[" & fld.Name & "],"
        Next
        'myfields = Mid(myfields, 1, Len(myfields) - 1)
        i = i + 1
        RetVal = SysCmd(acSysCmdInitMeter, "Inserting FILE: " & PathFilename & " - SHEET: " & Trim(str(x)) & " of " & Trim(str(ShtCount)), ShtCount)
        'Update the progress meter.
        RetVal = SysCmd(acSysCmdUpdateMeter, i)

        ' Insert the data from the sheet into the local XLSData Table --------------------------
        'strsql = "Insert Into XLSData(" & myfields & "Fullimagepath,TabName" & ") Select " & myfields & Chr(34) & strFileName & Chr(34) & " as Fullimagepath, " & wks.Name & " as TabName From [" & shortFilename & "_~" & wks.Name & "] "
        strsql = "Insert Into XLSData(" & myfields & "Fullimagepath,TabName" & ") " & _
                    " Select " & myfields & Chr(34) & strFileName & Chr(34) & " as Fullimagepath, " & Chr(34) & wks.Name & Chr(34) & " as TabName " & _
                    " From TmpLinkXLS As x1 " & _
                    " Where Len(Trim(x1.F1)) > 0 OR Len(Trim(x1.F2)) > 0 OR Len(Trim(x1.F3)) > 0 OR Len(Trim(x1.F4)) > 0 OR Len(Trim(x1.F5)) > 0 OR Len(Trim(x1.F6)) > 0 OR Len(Trim(x1.F7)) > 0 OR Len(Trim(x1.F8)) > 0 OR Len(Trim(x1.F8)) > 0 "
        CurrentDb.Execute strsql, dbFailOnError

        ' ---- Pause 1 second ------
        'Const cTIME = 1000 'in MilliSeconds
        Call sSleep(cTIME)

        i = i + 1
        RetVal = SysCmd(acSysCmdInitMeter, "Dropping TmpLinkXLS", ShtCount)
        'Update the progress meter.
        RetVal = SysCmd(acSysCmdUpdateMeter, i)

        If TableExists("TmpLinkXLS") Then
            CurrentDb.Execute "Drop Table TmpLinkXLS", dbFailOnError
        End If

        Set tdf = Nothing

        RetVal = SysCmd(acSysCmdInitMeter, " ", 0)
        RetVal = SysCmd(acSysCmdRemoveMeter)

        i = 1
        x = x + 1

        'DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
        '      wks.Name, strFileName, True, wks.Name & "$"
   Next

A: Somehow you must know and then specify that the first row contains headers, setting that argument to True:
DoCmd.TransferSpreadsheet acLink, , "TmpLinkXLS", strFileName, True, wks.Name & "$"


text:
Q: Is the "expression problem" solvable in F#? I've been watching an interesting video in which type classes in Haskell are used to solve the so-called "expression problem".  About 15 minutes in, it shows how type classes can be used to "open up" a datatype based on a discriminated union for extension -- additional discriminators can be added separately without modifying / rebuilding the original definition.
I know type classes aren't available in F#, but is there a way using other language features to achieve this kind of extensibility?  If not, how close can we come to solving the expression problem in F#?
Clarification:  I'm assuming the problem is defined as described in the previous video
in the series -- extensibility of the datatype and operations on the datatype with the features of code-level modularization and separate compilation (extensions can be deployed as separate modules without needing to modify or recompile the original code) as well as static type safety.

A: See Vesa Karvonen's comment here for one SML solution (albeit cumbersome), which can easily be translated to F#.

A: As Jörg pointed out in a comment, it depends on what you mean by solve. If you mean solve including some form of type-checking that the you're not missing an implementation of some function for some case, then F# doesn't give you any elegant way (and I'm not sure if the Haskell solution is elegant). You may be able to encode it using the SML solution mentioned by kvb or maybe using one of the OO based solutions.
In reality, if I was developing a real-world system that needs to solve the problem, I would choose a solution that doesn't give you full checking, but is much easier to use.
A sketch would be to use obj as the representation of a type and use reflection to locate functions that provide implementation for individual cases. I would probably mark all parts using some attribute to make checking easier. A module adding application to an expression might look like this:
[<Extends("Expr")>]  // Specifies that this type should be treated as a case of 'Expr'
type App = App of obj * obj

module AppModule =
  [<Implements("format")>] // Specifies that this extends function 'format'
  let format (App(e1, e2)) =
    // We don't make recursive calls directly, but instead use `invoke` function
    // and some representation of the function named `formatFunc`. Alternatively
    // you could support 'e1?format' using dynamic invoke.
    sprintfn "(%s %s)" (invoke formatFunc e1) (invoke formatFunc e2)

This does not give you any type-checking, but it gives you a fairly elegant solution that is easy to use and not that difficult to implement (using reflection). Checking that you're not missing a case is not done at compile-time, but you can easily write unit tests for that.

A:
I know type classes aren't available in F#, but is there a way using other language features to achieve this kind of extensibility?

I do not believe so, no.

If not, how close can we come to solving the expression problem in F#?

The expression problem is about allowing the user to augment your library code with both new functions and new types without having to recompile your library. In F#, union types make it easy to add new functions (but impossible to add new union cases to an existing union type) and class types make it easy to derive new class types (but impossible to add new methods to an existing class hierarchy). These are the two forms of extensibility required in practice. The ability to extend in both directions simultaneously without sacrificing static type safety is just an academic curiosity, IME.
Incidentally, the most elegant way to provide this kind of extensibility that I have seen is to sacrifice type safety and use so-called "rule-based programming". Mathematica does this. For example, a function to compute the symbolic derivative of an expression that is an integer literal, variable or addition may be written in Mathematica like this:
D[_Integer, _] := 0
D[x_Symbol, x_] := 1
D[_Symbol, _] := 0
D[f_ + g_, x_] := D[f, x] + D[g, x]

We can retrofit support for multiplication like this:
D[f_ g_, x_] := f D[g, x] + g D[f, x]

and we can add a new function to evaluate an expression like this:
E[n_Integer] := n
E[f_ + g_] = E[f] + E[g]

To me, this is far more elegant than any of the solutions written in languages like OCaml, Haskell and Scala but, of course, it is not type safe.


text:
Q: using pandas to create new columns based on intra-group rank-order I have a pandas DataFrame with a large number of rows. I am trying to create new columns for the frame based on the intra-group rank-order of the members. Here is some fake data illustrating what I have:
Num_members = int(1.e7)
Num_groups = int(1.e5)
members = pd.DataFrame({
    'ID': np.arange(Num_members),
    'groupID': np.random.random_integers(0, 2*Num_groups, Num_members),
    'groupmass': np.zeros(Num_members),
    'brightness': np.random.uniform(8,12, Num_members),
    'color':np.random.uniform(0,1,Num_members)
})

I am trying to create two new columns for the members:

*

*The intra-group rank-order for the brightness, so that the brightest
member of a group would get a value of 0, the next-brightest 1, etc.

*The color of the brightest member of the group. So for this column, all members of the same group would be assigned the same value equal to the 'color' of the member with intra-group brightness-rank=0.
I know that the groupby operation is designed for exactly this sort of manipulation, but I haven't been able to figure out how to do this correctly. And speed is a significant issue, since my dataset is large and I need to do this within an MCMC likelihood analysis.

A: This is my toy example:
import pandas as pd
import numpy as np
numpy.random.seed(42)
Num_members = int(10)
Num_groups = int(1)
members = pd.DataFrame({
    'ID': np.arange(Num_members),
    'groupID': np.random.random_integers(0, 2*Num_groups, Num_members),
    'groupmass': np.zeros(Num_members),
    'brightness': np.random.uniform(8,12, Num_members),
    'color':np.random.uniform(0,1,Num_members)
})

With a custom function that calculates the rank and the maximum value for brightness:
def rank_max_fun(df):
    df["b_rank"] = df.brightness.rank(ascending=False)
    df["b_max"] = df.brightness.max()
    return df

Grouping and applying
 df = members.groupby("groupID", sort=False).apply(rank_max_fun)

yields:
    ID  brightness  color   groupID groupmass   b_rank  b_max
0   0   8.232334    0.304242    2   0   6   11.329771
1   1   11.464705   0.524756    0   0   2   11.879639
2   2   10.404460   0.431945    2   0   3   11.329771
3   3   10.832290   0.291229    2   0   2   11.329771
4   4   8.082338    0.611853    0   0   3   11.879639
5   5   11.879639   0.139494    0   0   1   11.879639
6   6   11.329771   0.292145    2   0   1   11.329771
7   7   8.849356    0.366362    1   0   1   8.849356
8   8   8.727300    0.456070    2   0   5   11.329771
9   9   8.733618    0.785176    2   0   4   11.329771

Downside: It takes quite some time on large datasets.

A: I'll give it another try:
import pandas as pd
import numpy as np
np.random.seed(42)
Num_members = int(10)
Num_groups = int(1)
members = pd.DataFrame({
    'ID': np.arange(Num_members),
    'groupID': np.random.random_integers(0, 2*Num_groups, Num_members),
    'groupmass': np.zeros(Num_members),
    'brightness': np.random.uniform(8,12, Num_members),
    'color':np.random.uniform(0,1,Num_members)
})

And the logic:
df = members.groupby("groupID").agg({"brightness": np.max})
df = df.reset_index()
df = df.merge(members[["groupID", "brightness", "color"]], on=("groupID", "brightness"))

First we do the grouping to find the maximum brightness value. After that we combine df with members to get the color value of the member with the highest brightness values. Basically, we combine all rows in members and df which have the same values of brightness and groupID.
Note that this may lead to unexpected duplication of rows, if there are multiple values with maximum score in a group.
df now looks as follows:
    groupID brightness  color
0   0   11.879639   0.139494
1   1   8.849356    0.366362
2   2   11.329771   0.292145

For each group it contains the groupID, the maximum value of brightness and the color of the element with the maximum brightness value.
We can now combine data frames members and df:
result = members.merge(df, on="groupID", suffixes=("_member", "_group"))

And get following result:
    ID  brightness_member   color_member    groupID groupmass   brightness_group    color_group
0   0   8.232334    0.304242    2   0   11.329771   0.292145
1   2   10.404460   0.431945    2   0   11.329771   0.292145
2   3   10.832290   0.291229    2   0   11.329771   0.292145
3   6   11.329771   0.292145    2   0   11.329771   0.292145
4   8   8.727300    0.456070    2   0   11.329771   0.292145
5   9   8.733618    0.785176    2   0   11.329771   0.292145
6   1   11.464705   0.524756    0   0   11.879639   0.139494
7   4   8.082338    0.611853    0   0   11.879639   0.139494
8   5   11.879639   0.139494    0   0   11.879639   0.139494
9   7   8.849356    0.366362    1   0   8.849356    0.366362


text:
Q: How do I get rid of question marks in the OS X Dock? How do I get rid of grey question marks in the Dock of a Mac desktop? I have dragged them off the dock in an attempt to remove them and it doesn't work.

A: You need to drag them off some distance (and wait for a second or so) until an image of a cloud appears next to the mouse pointer. Only then should you drop the icon.

Alternatively, right-click the icon on the Dock, and select Options » Remove from Dock.

A: Try left clicking, dragging the icon and holding it until you see a little cloud, and then the item should be deleted. However if this does not work, you can always delete you plist file com.apple.dock.plist; in /Users/YourName/Library/Preferences. Drag that file from the Preferences folder to the Trash, empty your Trash and restart your Mac. If the ? mark is still in the Dock, try dragging it back off.

A: If Drag-n-Drop or Right click on the icon → Options → Remove from Dock didn't work you could just reset your Dock to default using the command below
defaults delete com.apple.dock; killall Dock

Note : Anything that was added to Dock by you would need to be re-added


text:
Q: IIS is not serving my static file on Azure I have a static file, letsencrypt.txt, in the wwwroot folder on my website.
But going to http://{domain}.com/letsencrypt.txt gives 404.
This is not on a virtual machine, shared or otherwise. I do not have root access or CPanel access. I do not have any extra Azure Storage.
I do have a Subscription, a Resource Group, an App Service, an App Service Plan, and an API Management Service. I do have FTP access, so I can see the file structure and upload files and download log files.
In practice, all I really know is that the file is at /site/wwwroot.
The log shows

Requested URL	https://{domain}:80/letsencrypt.txt

Physical Path	**C:\home\site\wwwroot\letsencrypt.txt**

which is exactly where I think the file is located.
I can't see any reason for it to not be able to find the file.
Nothing in the log about access control or permissions.
I thought that perhaps the https issue was a result of the DNS redirect, but I get the same 404 if I go directly to {domain}.azurewebsites.net. And it still redirects to https.
One interesting point is that, here in the log, it specifies port 80 even though it says https.
Here is the entire web.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\SmartTagsAPI.dll" stdoutLogEnabled="false" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="inprocess" />
      <rewrite>
        <rules>

        </rules>
      </rewrite>
    </system.webServer>
  </location>
</configuration>

A: As you revealed more information, this question becomes more like "how to set up free certificates for Azure App Service D1 plan".
D1 does not support custom SSL binding, which is by design. So, Let's Encrypt won't work either, as even if you find a way to generate the certificate, you cannot install it to D1 plan.
Like you tested, you can alternatively set up a service like Cloudflare in front which offers you free certificates.


text:
Q: Cannot add data to database using ContentProvider I am learning Content Providers and stuff in Android. I cannot figure out why no data is being added using ProductProvider.
I have looked over every class but there is something wrong with the way data is being inserted or queried from the database but i just can't figure out what is broken.
Here are the code files
Activity
HomePage.java
   package com.example.tanmay.shoppingapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry;

public class HomePage extends AppCompatActivity {

    TextView idBox;
    TextView nameBox;

    String TAG = "com.whatever.tag";

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.home_page, menu);

        return true;

    }

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

        //Adding custom toolbar
        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.homePageToolBar);
        setSupportActionBar(toolbar);

        insertProduct();

        //Projection is just the name of the columns we would like to receive
        String[] projection = {

                ProductEntry._ID,
                ProductEntry.COLUMN_NAME_PRODUCT_NAME

        };

        Cursor cursorNew = getContentResolver().query(ProductEntry.CONTENT_URI, projection, null, null, null);
        cursorNew.moveToNext();
        int uweh = cursorNew.getInt(cursorNew.getColumnIndex(ProductEntry.COLUMN_NAME_PRODUCT_NAME));
        TextView coco = findViewById(R.id.e83957);
        coco.setText(uweh);

        ListView listView = findViewById(R.id.productList_homepage);
       listView.setAdapter(new productListAdapter(HomePage.this, cursorNew));

    }

    private void insertProduct() {

        ContentValues values = new ContentValues();

        //The values contains all the data to be entered into the table
        values.put(ProductEntry._ID, 67);
        values.put(ProductEntry.COLUMN_NAME_PRODUCT_NAME, R.string.product1Name);
        values.put(ProductEntry.COLUMN_NAME_PRODUCT_PRICE, R.integer.product1Price);
        values.put(ProductEntry.COLUMN_NAME_PRODUCT_THUMBNAIL, R.drawable.product1thumbnail);
        values.put(ProductEntry.COLUMN_NAME_PRODUCT_IMAGE, R.drawable.product1image);

        // values.put(ProductEntry.COLUMN_NAME_PRODUCT_NAME, R.string.product2Name);

        Uri newUri = getContentResolver().insert(ProductEntry.CONTENT_URI, values);

    }

    private class productListAdapter extends CursorAdapter {

        public productListAdapter(Context context, Cursor c) {
            super(context, c);
        }

        //Returns a new blank view
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {

            return LayoutInflater.from(context).inflate(R.layout.dummy_item, viewGroup, false);

        }

        //Actually responsible for the data binding
        @Override
        public void bindView(View view, Context context, Cursor cursor) {

            idBox = (TextView) findViewById(R.id.dummy_item_id_box);
            nameBox = (TextView) findViewById(R.id.dummy_item_name_box);

            id.setText(cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry._ID)));
            name.setText(getResources().getString(cursor.getInt(cursor.getColumnIndexOrThrow(ProductEntry.COLUMN_NAME_PRODUCT_NAME))));

        }

    }

}

ProductDbHelper
package com.example.tanmay.shoppingapp.DataSet;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_IMAGE;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_NAME;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_PRICE;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.COLUMN_NAME_PRODUCT_THUMBNAIL;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry.TABLE_NAME;
import static com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry._ID;

/**
 * Created by tanmay on 3/3/18.
 */

public class ProductDbHelper extends SQLiteOpenHelper {

    //Name of the database file
    public static final String DATABASE_NAME = "products.db";

    //Database version to be incremented on change in schema
    public static final int DATABASE_VERSION = 1;
    //  SQL command to create the table
    //  All columns contain integers because they don't contain the actual Strings and Images,
    //      instead they hold the integral resource identifiers (R.string.* / R.integer.* / R.drawable.*).
    public static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    _ID + " INTEGER PRIMARY KEY, " +
                    COLUMN_NAME_PRODUCT_NAME + " INTEGER, " +
                    COLUMN_NAME_PRODUCT_PRICE + "INTEGER, " +
                    COLUMN_NAME_PRODUCT_THUMBNAIL + "INTEGER, " +
                    COLUMN_NAME_PRODUCT_IMAGE + "INTEGER)";
    //  Checks if a particular table already exists and then deletes it.
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TABLE_NAME;

    //Default constructor
    public ProductDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //  Creates the database bu executing String as SQL command
        sqLiteDatabase.execSQL(ProductDbHelper.SQL_CREATE_ENTRIES);

    }

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

        //  Firsts deletes the old database then creates a new one
        sqLiteDatabase.execSQL(ProductDbHelper.SQL_DELETE_ENTRIES);
        onCreate(sqLiteDatabase);

    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        onUpgrade(db, oldVersion, newVersion);

    }

}

ProductListContract
package com.example.tanmay.shoppingapp.DataSet;

import android.content.ContentResolver;
import android.net.Uri;
import android.provider.BaseColumns;

/**
 * Created by tanmay on 26/2/18.
 */

public class ProductListContract {

    //  Refers to this particular application
    public static final String CONTENT_AUTHORITY = "com.example.tanmay.shoppingapp";
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

    //Empty constructor to prevent instantiation
    private ProductListContract() {
    }

    public static class ProductEntry implements BaseColumns {

        //  Name of the table
        public static final String TABLE_NAME = "productListPrimary";

        //  Uri pointing to this particular table
        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, ProductEntry.TABLE_NAME);

        //MIME type
        public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_NAME;
        public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + TABLE_NAME;

        //  Names of various columns
        public static final String COLUMN_NAME_PRODUCT_NAME = "name";
        public static final String _ID = BaseColumns._ID;
        public static final String COLUMN_NAME_PRODUCT_PRICE = "price";
        public static final String COLUMN_NAME_PRODUCT_THUMBNAIL = "thumbnail";
        public static final String COLUMN_NAME_PRODUCT_IMAGE = "image";

    }

}

ProductProvider.java
    package com.example.tanmay.shoppingapp.DataSet;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.tanmay.shoppingapp.DataSet.ProductListContract.ProductEntry;

/**
 * Created by tanmay on 28/2/18.
 */

public class ProductProvider extends ContentProvider {

    private static final int ProductListTable = 1;
    private static final int ProductListRow = 2;

    private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {

        sUriMatcher.addURI(ProductListContract.CONTENT_AUTHORITY, ProductEntry.TABLE_NAME, ProductListTable);
        sUriMatcher.addURI(ProductListContract.CONTENT_AUTHORITY, ProductEntry.TABLE_NAME + "/#", ProductListRow);

    }

    private ProductDbHelper mDbHelper;

    @Override
    public boolean onCreate() {

        //Creates a new DbHelper object
        mDbHelper = new ProductDbHelper(getContext());

        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {

        //  Obtain a read-only copy of the database
        SQLiteDatabase sqLiteDatabase = mDbHelper.getReadableDatabase();

        //  This cursor holds the result from the query.
        Cursor cursor = null;

        //  Switch to perform specific kind of query based on type of Uri
        switch (sUriMatcher.match(uri)) {

            //  Uri demanding entire table with the criteria defined in the fundtion params
            case ProductListTable:

                //  All the argumnets are the ones passed
                cursor = sqLiteDatabase.query(ProductEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);

                break;

            //  Uri demanding a particular row item.
            case ProductListRow:

                //  "?" is a wildcard which gets replaced by any integer
                selection = ProductEntry._ID + "=?";
                selectionArgs = new String[]{String.valueOf((ContentUris.parseId(uri)))};

                cursor = sqLiteDatabase.query(ProductEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);

                break;

            default:
                throw new IllegalArgumentException("Cannot query unkown URI " + uri);

        }

        //Return the cursor containing query results
        return cursor;

    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {

        final int match = sUriMatcher.match(uri);

        switch (match) {

            case ProductListTable:
                return ProductEntry.CONTENT_LIST_TYPE;

            case ProductListRow:
                return ProductEntry.CONTENT_ITEM_TYPE;

            default:
                throw new IllegalStateException("Unkown URI " + uri + " with match " + match);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {

        final int match = sUriMatcher.match(uri);

        switch (match) {

            case ProductListTable:

                return insertProduct(uri, contentValues);

            default:
                throw new IllegalArgumentException("Insertion is not supported for " + uri);

        }

    }

    public Uri insertProduct(Uri uri, ContentValues contentValues) {

        SQLiteDatabase db = mDbHelper.getWritableDatabase();

        long id = db.insert(ProductEntry.TABLE_NAME, null, contentValues);

        if (id == -1) {

            Log.e("com.whatever.tag", "Failed to insert row for " + uri);

            return null;

        }

        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
        return 0;
    }

}

LayoutFiles
HomePage Activities Layout File
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tanmay.shoppingapp.HomePage">

    <android.support.v7.widget.Toolbar
        android:id="@+id/homePageToolBar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <TextView
        android:id="@+id/e83957"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="wwt49832"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/productList_homepage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

Layout of one ListView element
DummyItem because a different layout will be applied once everything works.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_margin="8dp"
        android:text="327"
        android:id="@+id/dummy_item_id_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_margin="8dp"
        android:text="placeholder"
        android:id="@+id/dummy_item_name_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
Q: Count the number of blank lines at the end of file I have a file with blank lines at the end of the file.
Can I use grep to count the number of blank lines at the end of the file with the file name being passed as variable in the script?

A: Some more GNU tac/tail -r options:
tac file | awk 'NF{exit};END{print NR?NR-1:0}'

Or:
tac file | sed -n '/[^[:blank:]]/q;p' | wc -l

Note that on the output of:
printf 'x\n '

That is, where there is an extra space after the last full line (which some could consider as an extra blank line, but by the POSIX definition of text, is not valid text), those would give 0.
POSIXly:
awk 'NF{n=NR};END{print NR-n}' < file

but that means reading the file in full (tail -r/tac would read the file backward from the end on seekable files). That gives 1 on the output of printf 'x\n '.

A: Another awk solution. This variation resets the counter k each time there is a non-blank line. Then, every line increments the counter. (So, after the first non-blank length line, k==0.) At the end we output the number of lines we have counted.
Prepare the data file
cat <<'X' >input.txt
aaa

bbb
ccc

X

Count the trailing blank lines in the sample
awk 'NF {k=-1}; {k++}; END {print k+0}' input.txt
3

In this definition, a blank line might contain spaces or other blank characters; it's still blank. If you really want to count empty lines rather than blank lines, change NF for $0 != "".

A: As you are actually asking for a grep solution I add this one relying only on GNU grep (okay, also using shell syntax and echo ...):
#!/bin/sh
echo $(( $(grep -c "" "$1") - $(grep -B$(grep -cv . "$1") . "$1" |grep -c "") ))

What am I doing here? $(grep -c ".*" "$1") counts all lines in the file, then we substract the file without the trailing empty lines.
And how to get those? $(grep -B42 . "$1" would grep all non-empty-lines and 42 lines before them, so it would print everything until the last non-empty line, as long as there are not more than 42 consecutive empty lines before a non-empty line. To avoid that limit, I take $(grep -cv . "$1") as the parameter for the -B option, which is the total number of empty lines, so always big enough. This way I have stripped the trailing empty lines and can use |grep -c ".*" to count the lines.
Brilliant, isn't it? (-;

A:
to count the number of consecutive blank lines at the end of the file

Solid awk + tac solution:
Sample input.txt:
$ cat input.txt
aaa

bbb
ccc

$  # command line

The action:
awk '!NF{ if (NR==++c) { cnt++ } else exit }END{ print int(cnt) }' <(tac input.txt)

*

*!NF - ensures the current line is empty (has no fields)

*NR==++c - ensuring the consecutive order of blank lines. (NR - record number, ++c - evenly incremented auxiliary counter)

*cnt++ - counter of blank lines

The output:
3

A: If the blank lines are only at the end
grep  -c '^$' myFile

or:
grep -cx '' myFile

A: Just for fun, some spooky sed:
#!/bin/sh
sed '/./!H;//h;$!d;//d;x;s/\n//' "$1" | wc -l

Explanation:

*

*/./ addresses lines with any character, so /./! addresses empty lines (like /^$/, but I want to reuse the opposite pattern); for those, the H command append them to the hold space. Thus, if for each empty line we have added one line to the hold space, there is always one more line than the number of empty lines. We'll care for that later.

*//h the empty pattern matches the last regular expression , which was any character, so any non-empty line is addressed and moved to the hold space by the h command to "reset" the collected lines to 1. When the next empty line will get appended, there will be two again, as expected.

*$!d stops the script without output for every but the last line, so further commands are only executed after the last line. So whatever empty lines we collected in the hold space are at the end of the file. Good.

*//d: The d command is again executed for non-empty lines only. So if the last line was not empty, sed will exit without any output. Zero lines. Good.

*x exchanges hold space and pattern space, so the collected lines are in the pattern space now to be processed.

*But we remember that there is one line too much, so we reduce it by removing one newline with s/\n//.

*Voilà! The number of lines matches the number of empty lines at the end (note that the first line will not be empty, but who cares), so we can count them with wc -l.

A: IIUC, the following script called count-blank-at-the-end.sh would do the job:
#!/usr/bin/env sh

count=$(tail -n +"$(grep . "$1" -n | tail -n 1 | cut -d: -f1)" "$1" | wc -l)
num_of_blank_lines=$((count - 1))

printf "%s\n" "$num_of_blank_lines"

Example usage:
$ ./count-blank-at-the-end.sh FILE
4

I tested it in GNU bash, Android mksh and in ksh.

A: Alternative Python solution:
Sample input.txt:
$ cat input.txt
aaa

bbb
ccc

$  # command line

The action:
python -c 'import sys, itertools; f=open(sys.argv[1]);
lines=list(itertools.takewhile(str.isspace, f.readlines()[::-1]));
print(len(lines)); f.close()' input.txt

The output:
3

https://docs.python.org/3/library/itertools.html?highlight=itertools#itertools.takewhile


text:
Q: Websocket connection error on new Chrome version 56.0.2924.87 Recently we observed that Websocket connection is failing only on latest Chrome version 56.0.2924.87
It is working is rest of the browsers(ff,ie,safari) and works fine in previous Chrome version 55
Below is the error that i see
WebSocket connection to 'wss://abc.abcserver.com/ws-xmpp' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
Did anyone face similar issue.

A: Having the same issue on dozens of PCs here.
Re-creating the users' Chrome profile has resolved the issue, but Google needs to fix this.


text:
Q: elasticsearch nested query, i think I come from a related database background and something like this would be so simple there, but I can't figure this out.  I've been trying to learn Elasticsearch for a week or so and I'm trying to figure out what I think is a nested query.  Here's some sample data:
PUT /myindex/pets/_mapping
{
   "pets": {
      "properties": {
         "name": {
            "type": "string"
         },
         "pet": {
            "type": "nested",
            "properties": {
               "name": {"type": "string"}
            }
         }
      }
   }
}

POST /myindex/pets/
{"pet": {"name": "rosco"}, "name": "sam smith"}

POST /myindex/pets/
{"pet": {"name": "patches"}, "name": "sam smith"}

POST /myindex/pets
{"pet": {"name": "rosco"}, "name": "jack mitchell"}

What would the query look like that only returns documents matching:

*

*owner name is "sam smith"

*pet name is "rosco"

I've tried a mixmatch of bool, match, nested, filtered/filter type queries, but I just keep getting errors.  Stuff like this stands out in the errors:
nested: ElasticsearchParseException[Expected field name but got START_OBJECT \"nested\"];

Here was the query:
GET /myindex/pets/_search
{
  "query": {
    "match": {
      "name": "sam smith"
    },
    "nested": {
      "path": "pet",
      "query": {
        "match": {
          "pet.name": "rosco"
        }
      }
    }
  }
}

I'm beginning to think that I just can't target something this specific due to the relevant nature of Elasticsearch.
Any ideas?

A: Man, these queries are tricky sometimes...  This seems to work:
GET /myindex/pets/_search
{
  "query": {
    "filtered": {
      "query": {
        "match": {
          "name": "sam smith"
        }
      },
      "filter": {
        "nested": {
          "path": "pet",
          "query": {
            "match": {
              "pet.name": "rosco"
            }
          }
        }
      }
    }
  }
}


text:
Q: SVG path is rendered differently when imported into PaperJS I am trying to copy a SVG path from a SVG file to use in a PaperJS project.
Here is a Paper.JS Sketch of the SVG using new Path(svgPath)
Here is a JSFiddle of how it's supposed to look
Any idea why this is happening?

A: The pathData contains two subpaths (i.e. outside of character, inside hole). When dealing with multiple subpaths in PaperJS, I believe you need to use CompoundPath instead of Path. In your PaperJS example, change...
var path = new Path(pathData);

to...
var path = new CompoundPath(pathData);


text:
Q: How to use different css for queryset objects? I have different styles of heading in a 5- column layout newspaper template. I want to apply different css to the title of each column. The queryset is the {% block content %}How can I iterate over the queryset objects and apply different css to each {{ post.title }} variable? Note: html truncated for brevity.

    {% block content %}
    {% endblock %}

          May the Force be with you

Let go your conscious self and act on instinct

A: i think that {% cicle %} will help you.
{% for o in some_list %}

        ...

{% endfor %}

more about built-in template tags you could read
https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#cycle


text: Q: Analyzing data by segment I have to do analysis on a large data set but have to do it for certain segments. The data is for products and I have do the analysis per sku for all skus. For example finding percent change for sales for the sku and then finding the average, etc. How do I do that through python/pandas. I thought about using a while loop where I iterate through the sku names and to run the math if the one above matches the one below but pandas does not work with while loops well. How should I go about this problem?


text:
Q: this.props.history don't redirect I don't know where I'm going wrong
by clicking the enter button I validate my user and use this.props.history.push ("/ home");
and it doesn't work
my login . js
class LoginForm extends Component {
    constructor(props){
        super(props);
        this.state = {
            login:'',
            password:'',
        };
        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }
    async onSubmit(e){
        e.preventDefault();
        const {login, password } = this.state;

        const response = await api.post('/login', { login,password });
        const user = response.data.user.login;
        const {jwt} = response.data;

        localStorage.setItem('token', jwt);
        localStorage.setItem('user', user);
        this.props.history.push("/home");
    }
    onChange(e){
        this.setState({[e.target.name]: e.target.value});
    }

  render() {
    const { errors, login, password, isLoading } = this.state;
    return (
        <form onSubmit={this.onSubmit}>
            Login
            <input type="text" name="login" id="login" value={login}  onChange={(e) => this.onChange(e)} placeholder="Informe seu login" />
            Senha
            <input type="password" name="password" id="password" value={password} onChange={(e) => this.onChange(e)}   placeholder="Informe sua senha"/>
        <button className="btnEnt" type="submit">Entrar</button>
    </form>
    )
  }
}

export default LoginForm;

my router . js:
import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

import Login from './pages/login/index';
import DashBoard from './pages/dashboard/index';
import PrivateRoute from './auth';

export default function Routes(){
    console.log('a')
    return(
        <BrowserRouter>
            <Switch>
                <PrivateRoute path="/home" component = {DashBoard}/>
            </Switch>
        </BrowserRouter>
    );
}                <PrivateRoute path="/home" component = {DashBoard}/>
            </Switch>
        </BrowserRouter>
    );
}

my auth . js :
import { Route, Redirect} from 'react-router-dom';

const isAuth = () => {
    console.log('a');
    if(localStorage.getItem('token') !== null) {
        return true;
    }
    return false;
};

const PrivateRoute = ({component: Component, ...rest}) => {
    return (
        <Route
            {...rest}
            render={props =>
            isAuth() ? (
                <Component {...props} />
            ): (
                <Redirect
                to={{
                    pathname: '/',
                    state: {message: 'Usuário não autorizado'}
                }}
                />
            )}
        />
    );
}
export default PrivateRoute;

my dashboard / index
import React, { Component } from 'react';
import Home from '../../components/Home';
class DashBoard extends Component {
    render() {
      return (
          <Home />
      )
    }
  }

  export default DashBoard;

error:

Unhandled Rejection (TypeError): Cannot read property 'push' of
  undefined
  Uncaught (in promise) TypeError: Cannot read property 'push' of
  undefined I really do not know what I can is wrong is not redirecting,
  I have tried all possible alternatives.

A: Before you can use history in your React component, you need to wrap it in withRouter.
https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

A:     import history from 'add your path'
    export default function Routes() {
      console.log('a')
      return (
        <BrowserRouter history={history}>
          <Switch>
            <PrivateRoute exact path="/home" component={DashBoard} />
          </Switch>
        </BrowserRouter>
      )
    }

do changes in router file
 import { withRouter } from 'react-router-dom';
 export default withRouter(LoginForm);

add withRouter in this component


text:
Q: How to Delete ForeignKey (Cascade Delete) I have two model which are bound to each other with foreign key constraints.

*

*PurchaseOrder is the parent table

*PurchaseOrderQtyBreakDown is the child table

Now the problem is when I am trying to delete the parent table, this error occurs:

SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_POQtyBreakDown_PurchaseOrder_PurchaseOrderPoId". The conflict occurred in database "InfoSys_CommercialAPI", table "dbo.POQtyBreakDown", column 'PurchaseOrderPoId'

I have tried the followed the following method for implementing the Cascade Delete. But it's not working properly.
DbContext:
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }

    // Commercial Tables
    // Back-To-Back
    public DbSet<PurchaseOrder> PurchaseOrder { get; set; }
    public DbSet<PurchaseOrderQtyBreakDown> POQtyBreakDown { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PurchaseOrderQtyBreakDown>()
            .HasOne(s => s.PurchaseOrder)
            .WithMany(b => b.PurchaseOrderQtyBreakDown)
            .HasForeignKey(b => b.PurchaseOrderPoId)
            .OnDelete(DeleteBehavior.Cascade);

        base.OnModelCreating(modelBuilder);
    }
}

PurchaseOrder & PurchaseOrderQtyBreakDown model classes are shown here:
public class PurchaseOrder
{
    [Key]
    public int PoId { get; set; }
    [DisplayName("CONTRACT")]
    public int? ContractListId { get; set; }
    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }
    [DisplayName("ORDER NO")]
    [ValidateNever]
    public string? OrderNo { get; set; }
    public virtual List<PurchaseOrderQtyBreakDown> PurchaseOrderQtyBreakDown { get; set; } = new List<PurchaseOrderQtyBreakDown>();
}

public class PurchaseOrderQtyBreakDown
{
    public int Id { get; set; }

    public int? PurchaseOrderPoId { get; set; }
    [ForeignKey("PurchaseOrderPoId")]
    [ValidateNever]
    public PurchaseOrder? PurchaseOrder { get; set; }

    public int? ContractListId { get; set; }
    [ForeignKey("ContractListId")]
    [ValidateNever]
    public ContractList? ContractList { get; set; }

    public int? Qty { get; set; }

    public decimal? UnitPrice { get; set; }

    public string? OrderNo { get; set; }
}

Please help me solve this issue. Thanks a lot.

A: I got a solution from Microsoft Documentation . You just need to do the following actions :

*

*Go to the Database

*Select The Child Table

*Open Keys

*Select the FK Relation which you want to "Cascade"

*Right click and select modify

*Select INSERT And UPDATE Spec

*Select Delete Rule

*Set the option "Cascade"

*And Save.

From now you can delete the Parent Rows.


text:
Q: Securing a PHP/MySQL poll system I'm building a PHP/MySQL poll system and I was wondering if there's any more secure method than setting a cookie + saving user IP address and checking them later.
Thank you.

A: The problem with poll systems is that you want to be sure users can only vote once. This problem has no solution unless you ask for personal information which cannot be forged.

A: Yep, user/pass is the only way. If you want to keep it really simple while using user authentication, use Facebook Connect. Nowadays almost everyone has FB and in a few minutes you could have it running.

A: I agree with previous that most secure is to store vote and user account info (IDs).
But if you need simple vote without registration only way is:

*

*On client side use something more persistent (look at https://github.com/samyk/evercookie)

*On server side - store all possible info about voting guest user (OS, Browser, etc.)

*Perform sort of simple heuristic or conditions on this data (if os, IP, and some parameter is same this might be same user)

*Do not allow short time votes (if OS, IP and metric is same and time is less than X sec)

*Log maximal sort of information and adapt your system

*Properly inform user whats going on i.e. Your vote is been denied because you already voted etc.

*Refuse weird votes (no OS etc)

*Use MySQL indexes where is appropriate!

*You can also hash some portion of information and search only same hashes (IP, OS, Browser)

A: No, only thing you could do to secure a polling system is to require registration or valid email address.

A: Unless you're prepared to force people to create a user account (and then lock votes to an account) this is pretty much all you can do in my experience.


text:
Q: Excel Live linked files imported into Access as Short Text Data Type Instead of Number Data Type I am importing sheets from the same workbook in excel into Access. The data that I'm importing is set as a number for all sheets. Most sheets import as a Number Data Type for the imported field, but some are importing as a Short Text Data Type no matter if its set as a number field. I need to know what I can do to fix this since I cannot change the data type in access for the Imported Live Linked Excel Sheet.
Thank you,

A: Don't import the sheet, but link it. Then create a simpel select query with the linked table as source and where you convert and clean up the data.
Now, use this query for importing to the final table or your further processing.


text:
Q: Split features maintaining ordnance survey map details in QGIS I'm trying to split a polygon drawn over an ordnance survey map area that represents the total land of a farm, in order to create smaller polygons that represent individual fields. I wish to create the smaller polygons based on the exact field boundaries shown on the ordnance survey map.
When I select the polygon to split, it turns solid yellow, and I can no longer see the features on the map underneath. Is there are way to adjust the opacity of selected polygon in order to be able to cut along the ordnance survey map lines?
I'm aware the vector layer opacity can be altered via right click > properties > symbology. But when highlighting the polygon with the Select Features tool, to be cut using Split Features, it turns solid yellow.


text:
Q: Can U-Net be used for counting objects? If I understand the U-Net paper correctly, the NN output is segmentation of known objects on the image from the background. In other words, the network will try to mark all the pixels which are part of the detected objects, but it won't distinguish between object instances. Is my understanding correct?
If yes, is there an approach which would allow me to differentiate between object instances in the image?
For example, if we have a photo of a street I would like to know not only which pixels are taken by cars, but also "enumerate" the said instances (even partly overlapping ones).
The reason I am asking is that I believe NN already learns what the object is and should therefore intrinsically "detect" the instances, however the U-Net input and output do not match this expectation directly (or I have misunderstood something - quite possible as I am still a newbie at ML).

A: U-net outputs a segmentation, i.e. a binary map. If you want to get the number of objects detected, the most straightforward approach would be to compute the connected components of your binary maps. But as you mention, overlapping object might be a problem. There are CNN specifically design for this task. For instance:
http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Stewart_End-To-End_People_Detection_CVPR_2016_paper.pdf
which uses LSTM (recurrent network)
or
https://arxiv.org/pdf/1705.07999.pdf
which is designed for 3D.
I hope this helps!