text:
Q: Python validation when utilizing .append I am unsure how to add validation to my input, specifically a presence check, which looks like this:
team1.append(input("Please enter the name of a team member: "))

Normally with more traditional inputs, my validation would look like this:
exampleInput=input("enter input")
while exampleInput=="":
exampleInput=input("enter input")

But that doesn't seem to work, as the validation does nothing if I try something like this:
team1.append(input("Please enter the name of a team member: "))
while team1.append(input)=="":
team1.append(input("Please enter the name of a team member: "))

I'm not sure how I could add any sort of validation to this. Any ideas?

A: Something like this?:
inp = input("Please enter the name of a team member: ")
if inp != "":
    team1.append(inp)

A: It is not clear to me what you want to achieve: team implies that you want to append multiple members, ignore empty lines, and have a way to exit the loop: the logic presented so far will stop once one valid member (i.e. not empty space) is entered, hence you'll get a list of size 1.
For example, I think this would work for that purpose:
team1 = []
this_member = ""
while True:
    this_member = input("Please enter the name of a team member: ").strip()
    if this_member != "":
        if this_member.upper() == "EXIT":
            break
        team1.append(this_member)

print(team1)

So an interaction would be:
Please enter the name of a team member: Paul
Please enter the name of a team member: George
Please enter the name of a team member:
Please enter the name of a team member:
Please enter the name of a team member: Alan
Please enter the name of a team member: EXIT
['Paul', 'George', 'Alan']


text:
Q: display 2 tables on link by id i have a table with id, name, address, sector, financiar, link
on the link i when i press it i want to show me 2 tables from the id of row selected, ex: id 1.
http://postimg.org/image/khelg1m0z/
and the result: http://s28.postimg.org/srvcwj065/Capture2.jpg
now it's a static page with search clause where by id 1, but i need an automatically link show by id on each row.

<?php
include "connect.php";
$sql = "select * from studenti where id='1'";

$query = mysql_query($sql) or die (mysql_error());

?>

Id
Nume
Localitate
Judet
Sector Financiar
Link

<?php while ($row = mysql_fetch_array($query)) { ?>

<?php echo $row['id']; ?>
<?php echo $row['nume']; ?>
<?php echo $row['localitate']; ?>
<?php echo $row['judet']; ?>
<?php echo $row['sector_financiar']; ?>
<?php echo $row['link']; ?>

<?php } ?>

<?php
include "connect.php";
$sql1 = "select * from certificari where id='1' ";

$query = mysql_query($sql1) or die (mysql_error());

?>

Id
Denumire certificare
Serie si numar certificare
Data certificarii
Valabilitate certificare
Sector Financiar

<?php while ($row = mysql_fetch_array($query)) { ?>

<?php echo $row['id']; ?>
<?php echo $row['nume']; ?>
<?php echo $row['serie_numar']; ?>
<?php echo $row['data']; ?>
<?php echo $row['valabilitate']; ?>
<?php echo $row['sector_financiar']; ?>

<?php } ?>

A: You should not use the mysql_ functions since they are depricated and are very vulnerable to SQL injection attacks. Instead, I will use MySQLi in this answer, but you could also use PDO if you want to.
To display records for different ID's based on what the user selects you can pass an ID in the page URL. When you link to the page you add the desired ID to the address like this:
Link

The value of the variable id will now be available in page.php as $_GET['id'].
The actual PHP in your page would then look something like the code below. I have left out some of your HTML for brevity, but you can just add it int.
//Connect to the DB. Might want to put this in your connect.php and include it.
$db = new mysqli('localhost', 'user', 'pass', 'db');

//Prepare the statement. The ? will be your ID.
$statment = $db->prepare("SELECT * FROM studenti WHERE id = ?");

//Bind the parameters, so that the first (and only) question mark is turned into your ID.
//The 'i' means integer, if you store the id as a string your should use 's' instead.
$statement->bind_param('i', $_GET['id']);

//Execute the query.
$statement->execute();

//Get the results.
$result = $statement->get_result();

//Iterate over it to create the output.
while ($row = $result->fetch_assoc()) {

    ?>

         <?php echo $row['id']; ?>
         <?php echo $row['nume']; ?>
         <?php echo $row['localitate']; ?>
         <?php echo $row['judet']; ?>
         <?php echo $row['sector_financiar']; ?>
         <?php echo $row['link']; ?>

    <?

}

//Then do the same thing for the table certificari.
//Note that you only need to connect to the DB once.

This beginners guide to MySQLi is very helpful if you need some more guidance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: 2objects in 1 variable. Trying to get second object I have a variable (page) which contains 2 page objects.
print_r of the page-variable:
  Page Object
(
    [blocksAliasedFromMasterCollection:protected] =>
    [cID] => 233
    [attributes:protected] => Array
        (
        )

)
Page Object
(
    [blocksAliasedFromMasterCollection:protected] =>
    [cID] => 234
    [attributes:protected] => Array
        (
        )

)
{"rel":"SITEMAP","name":"something","cID":"234"}

How do I get the cID of the second page object?

A: It is not a single variable, you have an array. You can access all of the elements using indices.
$obj1 = $page[0]; // get first object
$obj2 = $page[1]; // get second object\

You can then use the object as normal:
$obj2->method(); or $obj2->property;

A: try to use below code
if $data contains the objects then
$i=0;
foreach($data as $ar)
{
    if(++$i==2)
    {
       echo $ar->cID;
    }
}

A: The print_r I posted was as stated by Jon incorrect.
What happened was that the function with the print_r in it was called 2 times. That is why the page object was printed 2 times and not in the same variable.
After putting up a check that the function was running for the 2nd time, I got the correct page object.


text:
Q: Scraping links for odds from nowgoal using Python I am working on getting the odds from Nowgoal. Firstly, I like to get the links for each of the match using Selenium and Beautiful Soup.
I do not wish to get link for all matches. but I will have an input text file, which is attached here and use the selected league and date.
The following code will initialize as input:
#Intialisation
league_index =[]
final_list = []
j = 0
#config load
config = RawConfigParser()
configFilePath = r'.\config.txt'
config.read(configFilePath)
date = config.get('database_config','date')                     #input file provided by user - provide in YYYY-MM-DD format
leagues = config.get('database_config','leagues')               #input file provided by user - provide in windows format
headless_param =config.get('database_config','headless')        #Headless param - set True if you want to see bowser operating in foreground!
leagues_list = leagues.split(',')
print(leagues_list)

After I initialized with the preferred date and league, I will set up for chrome driver as follow:
options = webdriver.ChromeOptions()         #initialise webdriver options
#options.binary_location = brave_path        #if you are running the script on brave - then enable it
if headless_param == 'True' :
    print('headless')
    options.headless = True                 # if headeless parameter is set to true - the chrome browser will not appear in foreground
options.add_argument('start-maximized')     # Start the chrome maximised
options.add_argument('disable-infobars')    # Disable infobars
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("prefs", {"profile.default_content_setting_values.cookies": 2})
options.add_experimental_option("prefs", {"profile.block_third_party_cookies": True})
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--incognito")         #Incognito mode

#intiate the driver
driver = webdriver.Chrome(resource_path('./drivers/chromedriver.exe'),options=options)
#Format the url

url =  'http://www.nowgoal3.com/football/fixture/?f=ft0&date='+date

#get the url
driver.get(url)
#wait for some time
time.sleep(3)

driver.find_element_by_xpath('//*[@id="li_league"]').click()
time.sleep(5)
#click on the -team ranking
driver.find_element_by_xpath('//*[@id="TeamOrderCheck"]').click()

After I run upto above code, I have the following error:
 > driver.find_element_by_xpath('//*[@id="TeamOrderCheck"]').click()
  File "C:\Users\A100732\AppData\Local\Continuum\anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

I cannot locate the xpath to change it. Therefore, I cannot run the program further. What can I try next?

A: Target the span. Also added webdriver waits to make it more stable instead of time.sleep().
wait = WebDriverWait(driver,3)
#wait for some time
wait.until(EC.element_to_be_clickable((By.ID, "li_league"))).click()
#click on the -team ranking
wait.until(EC.element_to_be_clickable((By.XPATH, "//label[@for='TeamOrderCheck']/span"))).click()

Imports
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


text:
Q: arithmatic operators as a function input (C++) Let's say I have a function
#include <iostream>
int do_math (num_1, num_2, "*"){
....
}

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.
I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

A: It can be done as well through templates
template<typename Input, typename BinaryOp>
auto do_math(Input a, Input b, BinaryOp op)
{
   return op(a,b);
}

This can be called like so:
auto res = do_math(5, 4, std::plus<int>());

A: Use char type for the operator and check it in the switch.
For example:
int do_math( const int a, const int b, const char op )
{
    switch ( op )
    {
    case '+':
        return a + b;

    // ...
    }
}

A: You can use lambda for any arbitrary operation.
#include <iostream>
#include <cmath>

template<typename T, typename F>
auto do_math(T a, T b, F&& op)
{
    return op(a, b);
}

int main() {
    auto ans = do_math(5, 4, [](int x, int y) -> int { return x+y; });
    std::cout << ans << std::endl;
    auto ans2 = do_math(5, 4, [](int x, int y) -> int { return std::pow(x, y); });
    std::cout << ans2 << std::endl;
    return 0;
}


text:
Q: Parameters passed by value displayed incorrectly in the visual studio 2015 x64 debugger? x86 works fine.
x86 debug values screenshot
But x64 display incorrectly.
x64 debug values screenshot
Here is the code.
struct vector3 { float x, y, z; };

vector3 mul(vector3 v1, vector3 v2)
{
    vector3 v3 = { v1.x * v2.x, v1.y * v2.y, v1.z * v2.z };
    return v3;
}

int main()
{
    vector3 a = { 1.0f, 1.0f, 1.0f };
    vector3 b = { 2.0f, 2.0f, 2.0f };
    vector3 c = mul(a, b);
    return 0;
}

I first noticed this in one of my personal projects and was able to replicate it in a new project (images above are from new project).
I'm wonder what is causing it.
Maybe a bad install, or a VS bug?
Is it able to be replicated on other machines?
This is as simple as I can make the code.
Note this code works fine on x64:
struct vector2 { float x, y; };

vector2 mul(vector2 v1, vector2 v2)
{
    vector2 v3 = { v1.x * v2.x, v1.y * v2.y };
    return v3;
}

int main()
{
    vector2 a = { 1.0f, 1.0f };
    vector2 b = { 2.0f, 2.0f };
    vector2 c = mul(a, b);
    return 0;
}

A: Reinstalling Visual studio fixed the problem.


text:
Q: Checking the series $\sum_{n=1}^{\infty}\frac{e^n+n^4}{(-3)^{n^2-n+1}+\ln(n+1)$ I have the following series:
$$
\sum_{n=1}^{\infty}\frac{e^n+n^4}{(-3)^{n^2-n+1}+\ln(n+1)}
$$
I'm trying to check if the series is absolutely convergent or conditionally convergent. I tried every possible test I could think of but I could not solve it.
Please show some guidelines on how to solve it.

A: The series is absolutely convergent.
$$
|\frac{e^n+n^4}{(-3)^{n^2-n+1}+\ln(n+1)} <\frac{e^n+n^4}{3^{n^2-n+1}-\ln(n+1)}.$$ Pull out $e^{n}$ from the numerator and $3^{n^{2}-n}$from the denominator. You will get $\frac {e^{n}} {3^{n^{2}-n}} b_n$ with $b_n \to \frac 1 3$. N0w compare the given series with $\sum \frac {e^{n}} {3^{n^{2}-n}}$
Note that $n^{2} -n >n$ for all $n >2$ and $\sum (\frac e 3)^{n}$ is convergent.


text:
Q: python OLS statsmodels T Stats of variables not entered into the model Hi have created a OLS regression using Statsmodels
I've written some code that loops through every variable in a dataframe and enters it into the model and then records the T Stat in a new dataframe and builds a list of potential variables.
However I have 20,000 variables so it takes ages to run each time.
Can anyone think of a better approach?
This is my current approach
TStatsOut=pd.DataFrame()

for i in VarsOut:
    try:
        xstrout='+'.join([baseterms,i])
        fout='ymod~'+xstrout
        modout = smf.ols(fout, data=df_train).fit()
        j=pd.DataFrame(modout.pvalues,index=[i],columns=['PValue'])
        k=pd.DataFrame(modout.params,index=[i],columns=['Coeff'])
        s=pd.concat([j, k], axis=1, join_axes=[j.index])
        TStatsOut=TStatsOut.append(s)

A: Here is what I have found in regards to your question.  My answer uses the approach of using dask for distributed computing, and also just general clean up of you current approach.
I made a smaller fake dataset with 1000 variables, one will be the outcome, and two will be the baseterms, so there is really 997 variables to loop through.
import dask
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

#make some toy data for the case you showed
df_train = pd.DataFrame(np.random.randint(low=0,high=10,size=(10000, 1000)))
df_train.columns = ['var'+str(x) for x in df_train.columns]
baseterms = 'var1+var2'
VarsOut = df_train.columns[3:]

Baseline for your current Code (20s +- 858ms):
%%timeit
TStatsOut=pd.DataFrame()

for i in VarsOut:
    xstrout='+'.join([baseterms,i])
    fout='var0~'+xstrout
    modout = smf.ols(fout, data=df_train).fit()
    j=pd.DataFrame(modout.pvalues,index=[i],columns=['PValue'])
    k=pd.DataFrame(modout.params,index=[i],columns=['Coeff'])
    s=pd.concat([j, k], axis=1)
    s=s.reindex(j.index)
    TStatsOut=TStatsOut.append(s)

Created a function for readability, but returns just the pval, and regression coefficient for each variable tested instead of the one line dataframes.
def testVar(i):
    xstrout='+'.join([baseterms,i])
    fout='var0~'+xstrout
    modout = smf.ols(fout, data=df_train).fit()
    pval=modout.pvalues[i]
    coef=modout.params[i]
    return pval, coef

Now runs at (14.1s +- 982ms)
%%timeit
pvals=[]
coefs=[]

for i in VarsOut:
    pval, coef = testVar(i)
    pvals.append(pval)
    coefs.append(coef)

TStatsOut = pd.DataFrame(data={'PValue':pvals, 'Coeff':coefs},
                         index=VarsOut)[['PValue','Coeff']]

Using Dask delayed for parallel processing.  Keep in mind each delayed task that is created cause a slight overhead as well, so sometimes it it may not be beneficial, but will depend on your exact dataset and how long the regressions are taking.  My data example may be too simple to show any benefit.
#define the same function as before, but tell dask how many outputs it has
@dask.delayed(nout=2)
def testVar(i):
    xstrout='+'.join([baseterms,i])
    fout='var0~'+xstrout
    modout = smf.ols(fout, data=df_train).fit()
    pval=modout.pvalues[i]
    coef=modout.params[i]
    return pval, coef

Now run through the 997 candidate variables and create the same dataframe with dask delayed.  (18.6s +- 588ms)
%%timeit
pvals=[]
coefs=[]

for i in VarsOut:
    pval, coef = dask.delayed(testVar)(i)
    pvals.append(pval)
    coefs.append(coef)

pvals, coefs = dask.compute(pvals,coefs)
TStatsOut = pd.DataFrame(data={'PValue':pvals, 'Coeff':coefs},
                         index=VarsOut)[['PValue','Coeff']]

Again, dask delayed creates more overhead as it creates the tasks to be sent across many processors, so any performance gain will depend on the time your data actually takes in the regressions as well as how many CPUs you have availible.  Dask can be scaled from a single workstation to a cluster of workstations.


text:
Q: Canonical inclusion $L^q(0,1) \to L^p(0,1)$ is compact? Does there exist $q>p$ such that the canonical inclusion $L^q(0,1) \to L^p(0,1)$ is compact?
My answer is no.
Since we know that $L^\infty (0,1) \to L^p(0,1)$ is not compact, take $\{\sin(nx)\}$ as a counter example; this counter example will also work for $L^q$.
Is my argument correct? And what if I change "compact" to "weakly compact"? Because then my counter example would fail.
Another question, is there any connection between the weak topology on $L^p$ and the strong topology on $L^q$? My guess is no, since the weak topology is not metrizable.

A: If $1\le p<q<\infty$, then the embedding
$$L^q(0, 1)\subset L^p(0, 1)$$
trivially is weakly compact. Indeed, an $L^q$-bounded sequence is $L^p$-bounded too, and by Banach-Alaoglu's theorem (which applies since $q\ne 1, \infty$) it has weakly convergent subsequences.


text:
Q: Error in using axios in react for getting data from springboot api I am trying to use axios in react to get the data from spring boot.But they are errors after running the "npm audit fix --force"
react server error:
ERROR in Module not found: Error: Can't resolve 'C:\Users\user\Desktop\frontend\tryreact\node_modules\@pmmmwh\react-refresh-webpack-plugin\client\ReactRefreshEntry.js' in 'C:\Users\user\Desktop\frontend\tryreact'

ERROR in Module not found: Error: Can't resolve 'C:\Users\user\Desktop\frontend\tryreact\node_modules\source-map-loader\dist\cjs.js' in 'C:\Users\user\Desktop\frontend\tryreact'

ERROR in Module not found: Error: Can't resolve 'C:\Users\user\Desktop\frontend\tryreact\node_modules\source-map-loader\dist\cjs.js' in 'C:\Users\user\Desktop\frontend\tryreact'

ERROR in main
Module not found: Error: Can't resolve 'C:\Users\user\Desktop\frontend\tryreact\node_modules\source-map-loader\dist\cjs.js' in 'C:\Users\user\Desktop\frontend\tryreact'

npm terminal error after running the "npm audit fix --force" again:
npm ERR! code FETCH_ERROR
npm ERR! errno FETCH_ERROR
npm ERR! invalid json response body at https://registry.npmjs.org/@typescript-eslint%2fscope-manager reason: Invalid response body while trying to fetch https://registry.npmjs.org/@typescript-eslint%2fscope-manager: read ECONNRESET

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Local\npm-cache\_logs\2022-10-22T07_37_06_937Z-debug-0.log

my service file in react:
import axios from "axios";

const PRODUCT_REST_API_URL='http://localhost:8080/Products';

class Productservice{

    getProduct(){
        axios.get(PRODUCT_REST_API_URL);

    }
}

export default new Productservice()

My component:
import '/node_modules/bootstrap/dist/css/bootstrap.min.css'
import React, { Component} from 'react';
import './new.css';
import Counter from './counter';

import Productservice from '../service/Productservice';
//must add '/' at the beginning when accessing the bootstrap

class New extends Component {
  state={
    count:0,
    imageUrl:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRrcsoU6qeWsvWdekWJhyI07HYQMfqKBWjWA3UVXraY&s",
    tags:["tag1","tag2","tag3"],
    counters:[
      {id:1,value:0,ppl:3},
      {id:2,value:8},
      {id:3,value:0},
      {id:4,value:0}],
    Products:[]
  };

  componentDidMount(){
    Productservice.getProduct().then((response)=>{
      this.setState({users: response.data})
    })

render part:
{this.state.Products.map(
        Products=>

          {Products.id}
          {Products.name}
          {Products.price}
          {Products.quantity}

      )}

the problem should not be the spring boot since the url has passed successfully in  postman


text:
Q: jQuery offset issue: not changing the position of a SWF I have written code to overlay a SWF above a HTML button. I use the offset function from jQuery to get the coordinates and move the SWF. Unfortunately, it seems like the SWF do not get moved.
var offset = $("#button").offset();

$("#SWF").offset(offset);
$("#SWF").css({'left':offset.left, 'top': offset.top});
$("#SWF").offset({ top: 10, left: 30});

I have tried those 3 lines, and the offset never changed, I do not know why.
I hope someone could please help me.
EDIT:
I realized that:
$("#SWF").css({'left': offset.left, 'top': offset.top});

is working but actually I was using DOMWindow, I had to change the position and the z-index. I still have one issue, the SWF is not directly above the button, it's right underneath it. Does anyone know why please?
Thank you very much,
Rudy

A: Set wmode to "transparent" on the SWF, and make sure that the z-index of the SWF is higher than the z-index of the button.


text:
Q: Drupal 7 - How to redirect a user to a certain page until they change a setting on that page? How can I force Drupal 7 to redirect the user to a certain page (which contains a form) wherever the user clicks on the site, after they logged in, until they fill out that form?
Eg.: Anon User arrives to the site, they can browse around no problem.
Once they login/register, I would like to show a page (with a form) and not allow
them to go anywhere else until they fill that form out.
This solution has to work with cached pages so hook_init() can't be used.
hook_boot() seemed a good idea, but it is loading too early and lots of required includes won't load.
Also, the solution has to check if the page request is the actual form submit (otherwise they won't be able to submit the form)
Any ideas, suggestions?

A: Ok, so it seems that hook_init() is the solution and the problem was caused by the $user object. The trick is, that you have to reload the $user object, as the global doesn't contain the field values.
Very simple example code:
function mymodule_init(){
    global $user;

    if($user->uid && $user->uid != 1){

        $account = user_load($user->uid);
        $account = entity_metadata_wrapper('user', $account);

        $destination = drupal_get_destination();

        if(!$account->field_setup_completed->value()){
            drupal_set_message('Setup incomplete.', 'error');

            if($destination['destination'] != 'setup-page' && $destination['destination'] != 'user/logout'){
                drupal_set_message('Redirecting to setup', 'error');
                drupal_goto('setup-page');
            }
        }
    }
}


text:
Q: TWiki & Cygwin configuration I'm trying to configure the cygwin to work with TWiki, I have to input this in the Cygwin bash shell:
mount -b -s c:/...
but it doesn't recognize the "-s", I already fixed the problem with -b, it changed the syntax and now is "mount -o binary" for the "mount -b"part. But now it says unknown option with the "-s" anyone?? help?? or what does the -s mean, so I can look it up :S

A: I would suggest that you don't use cygwin. Strawberry perl and native GnuWin32 ports of zip/rcs etc work better.


text:
Q: How to Read Json array values from file JSONArray jsonArray = (JSONArray) obj;

When I use the above code, it shows the error message:
java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray

Please anyone suggest any method to overcome this error or any other way to read json value form a file in Java (Desktop application).

A: Use this for get json value in string format from file
public String loadJSONFromFile() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

JsonObject is a child of a JsonArray, so as per my suggestion use like this
final JSONArray jsonArray = new JSONArray();
jsonArray.put(obj); //obj is your JsonObject

and you can get JsonObject from array like
jsonArray.getJSONObject(0); //0 is index of your JsonObject in JsonArray

Hope this help you.

A: Check the content of the file.
It seems that the content is not an array, but a json object.
Open the file with a text editor. If the content is something like:
{   // First character
    ...  content here
}   // Last character

it is an object, if it is similar to
[   // First character
    ... content here
]   // Last character

it is an array.
If you need to read an object you need to change your code as follow:
JSONObject jsonObject = (JSONObject) obj;

A: JSONArray jsonArray = (JSONArray) obj;

This obj is of JsonObject type, so change that line to
JSONObject jsonObject = (JSONObject)obj;


text:
Q: IE9/10 accessibility keyboard navigation issue Hi I'm having an issue on an app HTML5/JavaScript (sproutcore) I'm working on where pressing the tab key navigates through the links on the page. In IE 9/10 once all the links have been passed the and the focus reaches the address bar and becomes stuck there while in other browsers the cycle starts again at the first link as expected.
I open the app in a popup window via the javascript in a link such as below
onclick="window.open('https://myappurl:4020','myApp','location=no,menubar=no,resizable=yes,scrollbars=yes,titlebar=yes,toolbar=no').focus();"

I have noticed when setting toolbar=yes this issue no longer occurs.
Anyone else seen this issue before as I'm stuck wondering what could be causing this.
Thanks Tobias


text:
Q: Trying to add social buttons/ issues with instructions from "developers.facebook.com" I am building my first website ever, and I would like to add a couple of social buttons (facebook, twitter, etc.)
Now facebook has this great page/service, https://developers.facebook.com/docs/plugins/share-button#configurator that gives you detailed instructions on how to embed a variety of buttons on your website.
It also has the following detailed code for every button that might interests you (lets say the share button).
Problem is, the code does not work. I literally copy/pasted the example on a test.html file, I opened it to see the form of the button.. and nothing.
I even have experimented with heights, widths and background colors of the divs that suppose to carry the buttons but no button appears on the browser (latest mozilla).
Why this code doesnt work? It has all the tags, everything seems so detailed, and makes sense. I mean I wouldnt expect the button to be functional since I am not re-directing to any existing domain, but a button should appear right?

    <title>Your Website Title</title>

    <meta property="og:url"           content="http://www.your-domain.com/your-page.html" />
    <meta property="og:type"          content="website" />
    <meta property="og:title"         content="Your Website Title" />
    <meta property="og:description"   content="Your description" />
    <meta property="og:image"         content="http://www.your-domain.com/path/image.jpg" />

I even typed a paragraph to make sure that the html document is rightly configured..

</div


text:
Q: WP7 Pushpin tooltip/bubble I am porting an iPhone app to WP7 which contains a map with several markers/pushpins that I get from a webservice (location, icon and title).
I have setup the XAML required to display the map as well as some code for the pushpin:
<phone:PhoneApplicationPage.Resources>
    <ControlTemplate x:Key="customPushpin" TargetType="my:Pushpin">
        <Image Height="39" Source="Resources/Icons/Pushpins/pinGreen.png" Stretch="Fill" Width="32"/>
    </ControlTemplate>
</phone:PhoneApplicationPage.Resources>

<Grid x:Name="LayoutRoot" Background="Transparent">
    <my:Map Height="Auto" HorizontalAlignment="Stretch" Margin="0" x:Name="Map"
            VerticalAlignment="Stretch" Width="Auto" CredentialsProvider="{Binding CredentialsProvider}"
            CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" Center="{Binding Mode=TwoWay, Path=Center}"
            ZoomBarVisibility="Visible"
            ZoomLevel="{Binding Zoom, Mode=TwoWay}">
        <my:MapItemsControl ItemsSource="{Binding Pushpins}">
            <my:MapItemsControl.ItemTemplate>
                <DataTemplate>
                    <my:Pushpin MouseLeftButtonUp="Pushpin_MouseLeftButtonUp"
                                Location="{Binding Location}"
                                Template="{StaticResource customPushpin}">
                    </my:Pushpin>
                </DataTemplate>
            </my:MapItemsControl.ItemTemplate>
        </my:MapItemsControl>
    </my:Map>
</Grid>

I am looking for a way to add some sort of bubble when the user clicks on the pushpin. I have looked a bit into infoboxes/tooltips but since they work on hover, that's not something I can use for the phone (tap/click).
I am guessing there's no similar control in WP7 that creates a bubble - how could I go about creating something similar?
Thanks in advance,
Alex

A: You could simply put a square Border inside LayoutRoot with Visibility="Collapsed", then when you click your pushpin you update its content and make it visible.
Just make sure to put it after your map control (otherwise it will be rendered behind the map and will consequently be invisible).

A: The easiest way to achieve this is to Show/Hide the Content of the Pushpin on Tap  instead of MouseLeftButtonUp because of some performance considerations.
void pushPin_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
   this.border.Visibility = System.Windows.Visibility.Visible;

    //stop the event from going to the parent map control
    e.Handled = true;
}

private void map_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
   this.border.Visibility = System.Windows.Visibility.Collapsed;
}

A: You could create a custom popup.
A great video that exaplains how to do this is located here.

A: Other solution is using the ContextMenu from the Silverlight toolkit for Windows Phone!
Just go to the Coding4Fun page on CodePlex and download it ( it contains the toolkit ) and in your XAML inside the PushPin definition add following:
<map:Pushpin x:Name="currentLocation">
<toolkit:ContextMenuService.ContextMenu>
    <toolkit:ContextMenu IsZoomEnabled="False">
        <toolkit:MenuItem Header="this is menu item 1" Click="MenuItem_Click" />
        <toolkit:MenuItem Header="this is menu item 2" Click="MenuItem_Click" />
        <toolkit:MenuItem Header="this is menu item 3" Click="MenuItem_Click" />
    </toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu></map:Pushpin>

This way, when you tap and hold the pushpin, you'll get the contectmenu!
( good example also found here: example )


text:
Q: Is it possible to override HostAuthenticationFilter filter? Is it possible to override HostAuthenticationFilter filter for customize the response message ?
this is configure as below:
Its a bearer token authorization.
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

A: You can override this way:
public class HostAuthenticationFilterCustom : HostAuthenticationFilter
    {
        public HostAuthenticationFilterCustom(string authenticationType) : base(authenticationType)
        {
        }
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            return base.AuthenticateAsync(context,cancellationToken);
        }
        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return base.ChallengeAsync(context,cancellationToken);
        }
    }

A: You need to add IAuthenticationFilter to the base class because HostAuthenticationFilter does not have an override modifier set on the AuthenticateAsync function.  Also, you need to add "new" modifier on your AuthenticateAsync and other derived functions so that you don't get the error from the compiler that the same function is defined in the base class without override.
public class HostAuthenticationFilterCustom : HostAuthenticationFilter, IAuthenticationFilter
    {
        public HostAuthenticationFilterCustom(string authenticationType) : base(authenticationType)
        {
        }
        public new Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            return base.AuthenticateAsync(context,cancellationToken);
        }
        public new Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return base.ChallengeAsync(context,cancellationToken);
        }
    }


text:
Q: Unable to accept user's license agreement in Eclipse IDE Installed Eclipse IDE from the terminal in Ubuntu 12.04 for android app development. I was now asked to download the required files from "Install New Software" in the IDE itself where it asks me to accept the User's Licence Agreement. I click on the radio button which says that I'm accepting the agreement but the finish button doesn't get highlighted and I'm unable to click it!
Any Solutions?

A: It works.  Depending on what you're installing, you might have to:

*

*Accept multiple license agreements (accept each and click next).

*Toggle to accept all and accept all the agreements at once.

What @rafal said was right.  In some cases you need to scroll to the bottom of the window.
If none of this solves the problem, add a screenshot to your question so we can "see" your window.

A: for my case, Eclipse indigo / juno, Ubuntu 12.04, virtual box operating system, any reinstall or update or install other version of eclipse or close/restart do not work, and toot me more than 3 hrs.... (BUT MY WINDOWS 7 HOST ECLIPSE JUNO GOT IT WHEN INSTALLED) :(
The only way I've found and worked was that, and possibly where the bug was:
For example, we want to install the eclipse marketplace.
When you choose Help -> Install new Software -> select the version of your eclipse -> GENERAL PURPOSE TOOLS, DO NOT CLICK NEXT YET, but open the list of "general purpose tools", search the sub element you want, in our case is the "Marketplace", then click Next, follow all the requirements, and when I agreed with the licences, Finish Bottom enabled immediately.
Hopefully this is where exactly the bug is, and hope similar problems can be fixed in this way. Good luck guys!

A: The same happened for me when I was trying to install a plugin in eclipse. I went to HelpResolution:
In case Marketplace is available in the Help menu, go for Marketplace and search the plugin or software in the search menu of Marketplace.
You can see the finish button enabled at the end of Accept License page.

A: You probably need to read the licence agreement before accepting it.
Seriously.
Some applications check whether you have spent some reasonable time reading it, whether you have scrolled to the end, etc.

A: I had this problem with egit plugin. I tried it a few times in a row and after re-doing the entire wizard about the 5th time it worked. I had also exited and restarted Eclipse a few times in between.

A: After selecting all the items and "I agree" or words to that effect.
Hit the "Finish" button not the "Next" button

A: I had to leave the accept radio button at do not accept, scroll through the license condition text and THEN toggle the radio button to accept.


text:
Q: SQL using JOIN or not using IF into mysql sentence I'm trying to use join (optional) or not in case of:
if
   join
else
   blank (join does'n exists)

is it posible?

A: I think you want a left outer join:
select ...
from table1
left join table2 on ...

will return all rows from table1, but null values for table2 if there is no matching rows in table2


text:
Q: window re-sizing using tkinter I've coded a GUI based Othello game. Am having a bit trouble re-sizing the game board. here is the code I have so far:
BOXWIDTH=60
BOXHEIGHT=60

class player:
"""Make a user player to play the game via a GUI."""

 def __init__(self,row,column):
    # create the GUI state variables
    self.alive = True
    self.move = None
    self.move_played = False
    # create the GUI windows and handlers
    self.root = tkinter.Tk()
    self.root.wm_title('Othello')
    self.root.protocol("WM_DELETE_WINDOW", self.quit)
    # create a button to get the No move command from the user
    tkinter.Button(self.root, text="No Move", command = self.nomove).pack()
    # create a label for displaying the next player's name
    self.movemesg = tkinter.StringVar()
    tkinter.Label(self.root, textvariable=self.movemesg).pack()
    self.canvas = tkinter.Canvas(self.root, bg="darkgreen",
                                height = BOXHEIGHT*row,
                                width = BOXWIDTH*column)

    self.canvas.bind("<Button-1>", self.click)
    # create a box for highlighting the last move
    self.lastbox = self.canvas.create_rectangle(0, 0, BOXWIDTH*column,
                                                BOXHEIGHT*row,
                                                outline="red")
    # draw the game canvas
    for i in range(1,row):
        # horizontal lines
        self.canvas.create_line(0, i*BOXHEIGHT,
                               BOXWIDTH*column, i*BOXHEIGHT)
    for i in range(1,column):
        # vertical lines
        self.canvas.create_line(i*BOXWIDTH, 0,
                               i*BOXWIDTH, BOXHEIGHT*row)
    # the board will store the widgets to be displayed in each square
    self.board = [[None for y in range(row)]
                  for x in range(column)]
    # display the window
    self.canvas.pack()
    self.canvas.focus_set()
    self.root.update()

def draw_board(self, game, last_move):
    """Draw an othello game on the board."""
    ws = str(sum(x.count(1) for x in game.board))
    bs = str(sum(x.count(-1) for x in game.board))
    if game.player == -1:
        self.movemesg.set("Black to play  "+'\nSCORE: White = '+ws+'  Black = ' + bs)
    else:
        self.movemesg.set("White to play  "+'\nSCORE: White = '+ws+'  Black = ' + bs)

    for i in range(game.column):
        for j in range(game.row):
            color = game.get_color((i,j))
            if color == -1:
                board_color = "black"
            elif color == 1:
                board_color = "white"
            else:
                if self.board[i][j] is not None:
                    self.canvas.delete(self.board[i][j])
                    self.board[i][j] = None
                continue

            if self.board[i][j] is None:
                self.board[i][j] = self.canvas.create_oval(
                    i*BOXWIDTH+2, j*BOXHEIGHT+2, (i+1)*BOXWIDTH-2,
                    (j+1)*BOXHEIGHT-2, fill = board_color)
            else:
                self.canvas.itemconfig(self.board[i][j], fill=board_color)

I want the game board to resize i.e it must cause the area in which the board is drawn to change size correspondingly, with the game board redrawn to fill the available space. Any help on this would be great.

A: Your first problem is that the canvas wasn't told to grow when the main window grows. Change your pack statement to this:
self.canvas.pack(fill="both", expand=True)

Next, you will need to create a binding that gets called whenever the canvas resizes. You can do this by binding to <Configure>. For example:
self.canvas.bind("<Configure>", self.on_configure)

Finally, you will need to create a function that does nothing except redraw the board. You will call this method from the on_configure method.


text:
Q: setOnClickListener in RelativeLayout not working I have a structure in my android application

LinearLayout > FrameLayout >ImageView(used as a FrameLayout
  Background) & RelativeLayout > TextView & ImageView.

I need that when I click in the FrameLayout or RelativeLayout or FirstImageView ( because it is the Bigger Zone , the textView or 2nd Image view are small ) do an action.
I tried to add setOnClickListener to this item but didn't work.
This is my Code:
public class HomeFragment extends Fragment {
    View rootView;

    public HomeFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.home_fragment, container, false);

        RelativeLayout paleoFoodBackGround = (RelativeLayout) rootView.findViewById(R.id.relativeLytPaleoFoodHome);

        paleoFoodBackGround.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("1FOOD_LIST", "onClick: ");

            }
        });

        return rootView;
    }

    public void clickFood(){
        Log.d("2FOOD_LIST", "onClick: ");
    }

}

This is my Layout structure:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="50"
android:orientation="vertical"
android:paddingLeft="2.5dp"
android:paddingRight="5dp"
android:weightSum="100">

    <FrameLayout
    android:id="@+id/framePaleoFoodHome"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="50"
    android:paddingBottom="2.5dp">

        <ImageView
        android:id="@+id/imgViewPaleoFoodBackGround"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:scaleType="center"
        app:srcCompat="@drawable/recipes" />

        <RelativeLayout
        android:id="@+id/relativeLytPaleoFoodHome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"

        >

            <ImageView
            android:id="@+id/imgViewRecipesIconHome"
            style="@style/iconHome"
            app:srcCompat="@drawable/cooking"
            />

            <TextView
            android:id="@+id/txtViewRecipesTxtHome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/textViewHomeSquare"
            android:text="@string/RecipesHome"

            android:layout_below="@id/imgViewRecipesIconHome"/>

        </RelativeLayout>

    </FrameLayout>
    <Framelayout> .... </Framelayout>
</LinearLayout>

A: I recommend using ImageButton instead of image. Also set your RelativeLayout to have android:clickable="true". Also set all children views that are not clickable with android:clickable="false"


text:
Q: Tomcat 7 manager Undeploy button disabled Tomcat 7 is installed on CentOS. Tomcat has two copies of application X running on it: two different hosts, two manager applications (each copied to webapps/Xn/manager). Applications work fine, Tomcat manager UI works fine except that Undeploy button is inactive/disabled. No errors in catalina.out

A: From https://github.com/psi-probe/psi-probe/issues/374#issuecomment-81738169

I think this bug can be closed. I just received this from a tomcat
  maintainer:
"By design, if a Context is defined in server.xml then that context is
  excluded from the auto deployment process so neither an xml file in
  the config base nor an XML file in the WAR (or a directory) is
  considered."
So, from this, I am guessing that apps cant be autodeployed.

Also when attempting to undeploy app via URL
FAIL - Context /my-app is defined in server.xml and may not be undeployed


text:
Q: State transition graph for a table with a whole column with don't cares
I have this state transition table and I want to draw the state transition graphs
Didn't have problems until I reached the last column with the state 11 where the whole column consists of don't cares
How do I handle such don't care situations?

A: In don't care situations you can either do a transition to any state you want or do no transition at all. Usually, those don't care mean that they should not be achieved in a proper transition sequence but can be implemented in any way in order to optimize the code/circuit used to implement that automaton/FSM.


text:
Q: can't write after format ext 4 by gparted I received a response from bodhi.zazen, but I don't have enough knowledge to understand what I need to do as Xubuntu is new to me.

You set ownership and permissions with chown and chmod . As the files
  are owned by root use sudo sudo chown your_user:your_user /mount/point
  . – bodhi.zazen

I am working from a live cd, and need to enable a 320GB external HDD so that it can be used for data storage.
I found the path to the drive by using gparted, it was /dev/sda1. I entered in terminal, the following command:
sudo chown artie:artie /dev/sda1
It didn't like the artie:artie part of the entry.  I thought it would be ok to enter any username, because I booted to the live cd. What am I doing wrong?

A: The change of ownership should be made to the mount point (e.g., /data), and not the partition (e.g., /dev/sda1).
For example if /dev/sda1 was mounted on /data, then the command to change the ownership to your username would be something like:
sudo chown username.groupname /data

Where username is your username and groupname is the group you wish to have access.  If only one person uses the computer then this would likely also be the same as username in many distros.


text:
Q: 'MissingComponentException' with 'CanvasGroup.interactable' in Unity Working with Slider and Button components in Unity 2021.1.1f1.
Beside some other operations, I want to toggle the interactable property of it.
Calling it as an CanvasGroup component, because i want to use the same code for all.
Only the interactable property throws an MissingComponentException.
Here is my shortened code:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class Minigame03Ingredient : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public int ReferenceValue;
    public int Increment;
    public int IncrementDelay;
    private int defaultIncrementDelay;
    public int feedbackValue = 0;
    private CanvasGroup button;
    internal Minigame03Main minigame;
    private bool flowActivated = false;
    private bool flowTriggered = false;
    private int leftIncrementDelay = 0;
    // Start is called before the first frame update
    void Start()
    {
        this.defaultIncrementDelay = this.IncrementDelay;
        this.button = GetComponent<CanvasGroup>();
        if (TryGetComponent(out Slider slider)) {
            slider.maxValue = this.defaultIncrementDelay;
            slider.value = this.defaultIncrementDelay;
        }
        this.button.interactable = false; // Nur zum Test
    }
...
}

And here is the console message from the Unity Editor:
MissingComponentException: There is no 'CanvasGroup' attached to the "waterSlider" game object, but a script is trying to access it.
You probably need to add a CanvasGroup to the game object "waterSlider". Or your script needs to check if the component is attached before using it.
Minigame03Ingredient.Start () (at Assets/_Scripts/Games/Minigame03/Minigame03Ingredient.cs:28)

What's going wrong?

A: When there isn't any component attached which is queried with GetComponent<ComponentType>() method, it returns a null value and doesn't throw any exception.
So, if you do the following:
this.button = GetComponent<CanvasGroup>(); // this.button will be assigned to null.

this.button.interactable = false; // Throws an exception because this.button is null.

This is something like null.some_property, which will throw a null reference exception or a missing reference exception.

A: The solution was to use an Selectable instead of an CanvasGroup here.


text:
Q: Deployment of drools(6.0) rules application in tomcat server I have developed my rules application using drools and would like to deploy it to Tomcat along with my other webapplciation that invokes rules. How do I go ahead with this?
Im using Drools 6.0.

A: You need to download the kie-workbench from here
http://download.jboss.org/drools/release/6.0.1.Final/kie-drools-wb-distribution-6.0.1.Final.zip
and then put the tomcat war inside tomcat/webapps


text:
Q: Centering Nav Bar with Dropdown I am having problems centering my navigation bar with a dropdown menu. I want to center the bar, and the dropdown underneath it. I have tried to use a regular unordered list, and now a table to center the dropdown part. I have seen examples of code working, but when I implement it into my nav bar it does not work with the dropdown. I am wanting to have the nav bar be a fluid width, not a set width, as I can get a set width to kind of work. Any help?
HTML:

@charset "utf-8";

/* CSS Document */

#navbar {
  position: relative;
  top: 100px;
  left: 150px;
  margin: 0;
  padding: 0;
  width: 800px;
  margin: 0 auto;
}
#navbar li {
  list-style: none;
  float: left;
}
#navbar li a {
  display: block;
  padding: 3px 8px;
  text-transform: uppercase;
  text-decoration: none;
  color: #999;
  font-weight: bold;
}
#navbar li a:hover {
  color: #000;
}
#navbar li ul {
  display: none;
}
#navbar li:hover ul,
#navbar li.hover ul {
  position: absolute;
  display: inline;
  left: 15px;
  width: 300px;
  margin: 0;
  padding: 0;
  text-align: center;
}
#navbar li:hover li,
#navbar li.hover li {
  float: center;
}
#navbar li:hover li a,
#navbar li.hover li a {
  color: #999;
}
#navbar li li a:hover {
  color: #000;
}

Home

Services

          Spraying

          Combining

          Planting

          Drilling

          Strip Tillage

          Tillage

Packages

About Us

Contact Us

A:
I want to center the bar, and the dropdown underneath it.

Then, you have to remove the left property on the #navbar. Otherwise, it is good.
You put the dropdown ul in absolute position with a 100% width.

I am wanting to have the nav bar be a fluid width, not a set width, as
  I can get a set width to kind of work.

Also, it is :hover state. .hover means the class "hover".
See this working example


text:
Q: Github-Jenkins Trigger issue with slave I have a jenkins instance which has a windows slave machine attached. I also have a job running which resides in github and I have the trigger - "Build when a change is pushed to GitHub" set.
as I push a change to github, there is no build triggered on jenkins. I check and see that the payload does get tranferred to jenkins in the "Github hook log" but I get the following error:
 Started on Sep 18, 2014 3:57:06 PM
Using strategy: Default
[poll] Last Built Revision: Revision ce6a183e834a3e31afa0eb83a4418b0619c8642b (origin/master)
 > "C:\Program Files (x86)\Git\cmd\git.exe" ls-remote -h https://xx/xx/xx master # timeout=10
FATAL: hudson.plugins.git.GitException: Error performing command: "C:\Program Files (x86)\Git\cmd\git.exe" ls-remote -h https://xx/xx/xx master
hudson.util.IOException2: hudson.plugins.git.GitException: Error performing command: "C:\Program Files (x86)\Git\cmd\git.exe" ls-remote -h https://xx/xx/xx master
    at hudson.plugins.git.GitSCM.compareRemoteRevisionWith(GitSCM.java:462)
    at hudson.scm.SCM._compareRemoteRevisionWith(SCM.java:357)
    at hudson.scm.SCM.poll(SCM.java:374)
    at hudson.model.AbstractProject._poll(AbstractProject.java:1428)
    at hudson.model.AbstractProject.poll(AbstractProject.java:1331)
    at com.cloudbees.jenkins.GitHubPushTrigger$1.runPolling(GitHubPushTrigger.java:73)
    at com.cloudbees.jenkins.GitHubPushTrigger$1.run(GitHubPushTrigger.java:98)
    at hudson.util.SequentialExecutionQueue$QueueEntry.run(SequentialExecutionQueue.java:118)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: hudson.plugins.git.GitException: Error performing command: "C:\Program Files (x86)\Git\cmd\git.exe" ls-remote -h https://xx/xx/xx master
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1444)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1225)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1138)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1129)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.getHeadRev(CliGitAPIImpl.java:2059)
    at hudson.plugins.git.GitSCM.compareRemoteRevisionWithImpl(GitSCM.java:495)
    at hudson.plugins.git.GitSCM.compareRemoteRevisionWith(GitSCM.java:460)
    ... 13 more
Caused by: java.io.IOException: Cannot run program ""C:\Program Files (x86)\Git\cmd\git.exe"": error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
    at hudson.Proc$LocalProc.<init>(Proc.java:244)
    at hudson.Proc$LocalProc.<init>(Proc.java:216)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:780)
    at hudson.Launcher$ProcStarter.start(Launcher.java:360)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1433)
    ... 19 more
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
    at java.lang.ProcessImpl.start(ProcessImpl.java:130)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1022)
    ... 24 more

Basically complains about not being able to run the command C:\Program Files (x86)\Git\cmd\git.exe" ls-remote -h https://xx/xx/xx master
But as I manually go into my slave machine and run the command, it works fine.
Please note that
 1. I have made the adjustment where jenkins slave service logs in  as admin so that it has all permissions.
 2. My default jenkins server is a linux box and the slave machine is a windows box. Obviously both have different git executable path. So I am wondering if jenkins runs this command on my linux box for some reason.
I do have the project setup to run on the windows slave box only and that works fine as it builds fine(so it is able to find the git executable for the job)
Any pointers?
Also does anyone know how github plugin for jenkins works with slave machines(does it look for git in the slave or does it go to where jenkins resides, as that might be the source, though have no idea what the solution for that weird case would be?)

A: I tried a work around of adding the "Force polling using workspace" as an "Additional behaviour" in my git SCM definition of the windows job.This solves my issue - not the best way but effective.
If the poll runs on the Linux node (the master) but somehow decides it needs to use the Windows git configuration to poll the master, that might cause the Linux master to attempt to execute git from the Windows git location, instead of the Linux git location(which is what is happening in my project). That would be a bug, and I was surprised at this bug, since there are many installations of Jenkins git which use a wide mix of Linux and Windows slaves.
I'm was not aware of such a bug, but since the "Force polling using workspace" resolved the problem for you, it may hint that is an area for more investigation.


text:
Q: Automator rename finder item date and time I want to use automator to create a project folder with a Automator service, but i like to add the month and year (with two decimals) not the day, month and whole year.
want i can creatie is item_29022014 but i like to create a file named: 'item_0214' where the first two numbers (02) are the month and the last two numbers (14) are the last to numbers of the current year(2014).
Can i download some add-on for automator? Or do i need a custom script for this?

A: Check the answer found here
https://apple.stackexchange.com/questions/52535/clean-up-file-names-using-automator
I changed the bash script code to include the date code.
shopt -s extglob
dcode=`date '+%m%y'`
for f in "$@"; do
   f1="${f%.*}"
   f2="${f##*.}"
   if [ "$f2" == "$f1" ] ; then
       echo "$f" "${f1}_${dcode}"
   else
       echo "$f" "${f1}_${dcode}.${f2}"
   fi
done

The code will should work even with files that do not have extensions.
Replace the commands echo with mv to actually get the code to do anything.
Hope that helped.


text:
Q: Problema para envio SPED-REINF c# Caros amigos,
Estou tentando enviar um xml para homologação para o SEFAZ referente a codigo R-1000 do SPED-REINF, consegui ajuda para os metodos necessarios aqui com os amigos da lista de discução. Mas estou com o problema que nao sei comno resolver, todo arquivo que tento enviar me retorna.
O servidor remoto retornou um erro: (500) Erro Interno do Servidor.
Detalhes subjacentes:
Falha no processamento. Favor tentar novamente. Identificador : 3033699826
o xml que estou enviando e o que segue:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sped="http://sped.fazenda.gov.br/">
<soap:Header />
<soap:Body>
    <REINF xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_01_01">
        <loteEventos>
            <evento id="ID1">
                <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_02_00">
                    <evtInfoContri id="ID1000000032343842018011517062000001">
                        <ideEvento>
                            <tpAmb>1</tpAmb>
                            <procEmi>1</procEmi>
                            <verProc>1.0</verProc>
                        </ideEvento>
                        <ideContri>
                            <tpInsc>1</tpInsc>
                            <nrInsc>03234384</nrInsc>
                        </ideContri>
                        <infoContri>
                            <inclusao>
                                <idePeriodo>
                                    <iniValid>2018-01</iniValid>
                                </idePeriodo>
                                <infoCadastro>
                                    <classTrib>13</classTrib>
                                    <indEscrituracao>1</indEscrituracao>
                                    <indDesoneracao>0</indDesoneracao>
                                    <indAcordoIsenMulta>0</indAcordoIsenMulta>
                                    <indSitPJ>0</indSitPJ>
                                    <contato>
                                        <nmCtt>LUCAS VALFRIDO COSTA.</nmCtt>
                                        <cpfCtt>21513643991</cpfCtt>
                                        <foneFixo>(042)32195250</foneFixo>
                                        <email>uniprime@uniprimecamposgerais.com.br</email>
                                    </contato>
                                </infoCadastro>
                            </inclusao>
                        </infoContri>
                    </evtInfoContri>
                    <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                        <SignedInfo>
                            <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                            <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
                            <Reference URI="#ID1000000032343842018011517062000001">
                                <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                </Transforms>
                                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                <DigestValue>ffcLduYaxHryR1/P1I4/uvgD+8GFKSsN5zEn4aX/AaU=</DigestValue>
                            </Reference>
                        </SignedInfo>
                        <SignatureValue>NDwAI/SzB4E65rL3TecWRPNisXdaCXfPHnyHXO1VQ3Pp5MUoLq9XhrNQRdlFRVdhEsr7ZYtY7VrfCO/Ty++r5I9Nj4xYZFBSoKBLFSVkOW2RCOpeh3oV4MxY4Zb71wQScFPVsNbv1gHBkP5NhX9y8ZBknAmmtOFG79dMhCB1kHQXdX6a95gur3x2spviNOi/1RIvzK8s1MheilOXBYAKIlC0kfp7UQnkgjWoq/XK3LToHRuyMhhGQjcmG4S48B0ogAgScSClBzyP0s5eALFSNm+K6QTSJHIoB7lkNpilCZHW8zHkvi+BzY6EsoDAskf/wWsB1DwnxjFG8uoqrEteVQ==</SignatureValue>
                        <KeyInfo>
                            <X509Data>
                                <X509Certificate>MIIICjCCBfKgAwIBAgIQKmzokwPdnLVj3xB2tj4cszANBgkqhkiG9w0BAQsFADCBgDELMAkGA1UEBhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEkMCIGA1UEAxMbQUMgSW5zdGl0dXRvIEZlbmFjb24gUkZCIEczMB4XDTE3MTEwNzE2NDY0OFoXDTIwMTEwNjE2NDY0OFowgeMxCzAJBgNVBAYTAkJSMRMwEQYDVQQKDApJQ1AtQnJhc2lsMTYwNAYDVQQLDC1TZWNyZXRhcmlhIGRhIFJlY2VpdGEgRmVkZXJhbCBkbyBCcmFzaWwgLSBSRkIxFTATBgNVBAsMDFJGQiBlLUNQRiBBMzEUMBIGA1UECwwLKEVNIEJSQU5DTykxLTArBgNVBAsMJEF1dGVudGljYWRvIHBvciBBUiBJbnN0aXR1dG8gRmVuYWNvbjErMCkGA1UEAwwiR0VTU0lDQSBCRU5JQ0lPIEZFTElQRTowNzM0NjU4Nzk2MDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANvoCrBmtQL11Q9U9yav5tKyxy4d2l5fh3guKUTR7D3jLvCJfZ4lRBUDcRBs5NfX7TER4g4FQWSHHgus7I8/8Amwzk4F0ZjY5P8XxaK5dlyOjlqrflNQPTC/ZfemS78oi7jWZk+Hla1TZ3dxDAOfIPXSZLzP1OvBCtYTdb0z0Y/l/9wJmKpD3AnsoGGaGyO4cK1KJwS2vtZ1eRlrwYeJjJoLHaqhKVtdAlo1pMoHlxpc8grXZV4eX1ZUkpgFDUZR72q9cvgZStBNMe+z6sLH8eaqF7dDauo2MYlBVlo4A3udgrH0XgMDFqM/VmAtQ50ily1oCTA+jVkRTetzZ46CI6kCAwEAAaOCAxkwggMVMIGjBgNVHREEgZswgZigOAYFYEwBAwGgLwQtMTkwNzE5OTAwNzM0NjU4Nzk2MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwoBcGBWBMAQMGoA4EDDAwMDAwMDAwMDAwMKAeBgVgTAEDBaAVBBMwMDAwMDAwMDAwMDAwMDAwMDAwgSNnZXNzaWNhLjQ4MDFAdW5pcHJpbWVjZW50cmFsLmNvbS5icjAJBgNVHRMEAjAAMB8GA1UdIwQYMBaAFCbHlD16h35/S3iKhz3gz7XOqbDaMIGGBgNVHSAEfzB9MHsGBmBMAQIDITBxMG8GCCsGAQUFBwIBFmNodHRwOi8vaWNwLWJyYXNpbC5hY2ZlbmFjb24uY29tLmJyL3JlcG9zaXRvcmlvL2RwYy9BQy1JbnN0aXR1dG8tRmVuYWNvbi1SRkIvRFBDX0FDX0lGZW5hY29uX1JGQi5wZGYwgcoGA1UdHwSBwjCBvzBeoFygWoZYaHR0cDovL2ljcC1icmFzaWwuYWNmZW5hY29uLmNvbS5ici9yZXBvc2l0b3Jpby9sY3IvQUNJbnN0aXR1dG9GZW5hY29uUkZCRzMvTGF0ZXN0Q1JMLmNybDBdoFugWYZXaHR0cDovL2ljcC1icmFzaWwub3V0cmFsY3IuY29tLmJyL3JlcG9zaXRvcmlvL2xjci9BQ0luc3RpdHV0b0ZlbmFjb25SRkJHMy9MYXRlc3RDUkwuY3JsMA4GA1UdDwEB/wQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwgbsGCCsGAQUFBwEBBIGuMIGrMGYGCCsGAQUFBzAChlpodHRwOi8vaWNwLWJyYXNpbC5hY2ZlbmFjb24uY29tLmJyL3JlcG9zaXRvcmlvL2NlcnRpZmljYWRvcy9BQ19JbnN0aXR1dG9fRmVuYWNvbl9SRkJHMy5wN2MwQQYIKwYBBQUHMAGGNWh0dHA6Ly9vY3NwLWFjLWluc3RpdHV0by1mZW5hY29uLXJmYi5jZXJ0aXNpZ24uY29tLmJyMA0GCSqGSIb3DQEBCwUAA4ICAQApm2ZReXj58EXKCwPuLFoIRfuT9N/wY0imzW1CQcNgApp8I5JhVKLwndYKVqFG1VXMLtxoDKJqiiD5FdnPjh06StKdY/AhKJ52jbRxfJw9cfVFnFR1mDmcLC+fKodBnYFExtc1R8IeGBNScc+1TraoKGvDR3eiJMzj9od1r7ltOyZalkvl7m902Ib5l2h/ciwMdel4RJ/vLhvyEyG2btXgQ5oTvIAMkTL+GdIJ9ijnW5I2esXrb6OEZQYnfB5YWjWzfbOqftmqojaspsyc9Ure7BOcOb6Wmwzf+5FCESrOlR9ipfnbtTqGJsbDQPzIxHKDvKdZcOXVbnNDXIVxoMYAYq1Qji+NoysuUza6FK044UAN72thYlHfGcc6WY2FaTJnfVVcMBzwkoNpNwf7j2FUdmEzh/7fXkuKlDMcL3ie6mRZhtODKxYs+MJM7AVycj/G/u669SMa92qKN/adpjf+AieYISkvx1NWmK2WttV0JMFZQiJSqUN//FwOXKkQgR+hQI2fhaSiwltd8gqQgUIfItFdniM3CwdWtcz517o9DsB3E3+WTPUsrhR2tgpseZf0mro5tvrRuR2Zh6t8XxGGts/hOVLZw3hJNjI88KBIoRAHjKswQq/nb3uQIxXRa7HMHQqJYp/7C07VzTmMur8GedmqUorI8OVsRS92Ytl1og==</X509Certificate>
                            </X509Data>
                        </KeyInfo>
                    </Signature>
                </Reinf>
            </evento>
        </loteEventos>
    </REINF>
</soap:Body>

E o processo para envio e o seguinte:
    public string TransmitirDireto(string FilePath)
    {
        XmlDocument arquivoXML = new XmlDocument();
        arquivoXML.Load(FilePath.Trim());

        XmlTextWriter xmlWriter = new XmlTextWriter(FilePath, System.Text.Encoding.UTF8);
        xmlWriter.Formatting = Formatting.Indented;
        arquivoXML.Save(xmlWriter);
        //xmlWriter.Dispose();
        xmlWriter.Close();
        xmlWriter = null;

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.URL);
        //request.Headers.Add("SOAPAction", string.Format("\"{0}{1}\"", XMLNS, METODO));
        request.Headers.Add("SOAPAction", @"https://preprodefdreinf.receita.fazenda.gov.br/RecepcaoLoteReinf.svc");
                                        //  https://preprodefdreinf.receita.fazenda.gov.br/RecepcaoLoteReinf.svc
        request.ContentType = "text/xml;charset=\"utf-8\"";
        request.Accept = "text/xml";
        request.Method = "POST";
        //  request.Proxy = proxy;

        if (this.Certificado != null)
            request.ClientCertificates.Add(this.Certificado);
        if (this.TimeOutEmSegundos > 0)
            request.Timeout = this.TimeOutEmSegundos * 1000;

        this.UltimaRequisicao = arquivoXML.InnerXml;
        try
        {

            using (Stream stream = request.GetRequestStream())
            {
                using (StreamWriter stmw = new StreamWriter(stream))
                {
                    stmw.Write(arquivoXML.InnerXml);
                }
            }
        }
        catch (Exception wex)
        {
            throw new Exception(wex.Message);
        }

        try
        {
            WebResponse webresponse = request.GetResponse();
            HttpWebResponse response = (HttpWebResponse)webresponse;
            //if(response.StatusCode == HttpStatusCode.OK)
            using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
            {
                string result = responseReader.ReadToEnd();
                return result;
            }
        }
        catch (WebException wex)
        {
            string mensagemSubjacente = ObterMensagemSubjacente(wex);
            string msg = string.Format("{1}\r\n{0}\r\n Detalhes subjacentes: \r\n{2}",
                System.Environment.NewLine, wex.Message, mensagemSubjacente);
            throw new ExcecaoComunicacaoREINF(msg, wex, arquivoXML.InnerXml);
            //  throw new Exception(wex.Message);
        }
        catch (Exception ex)
        {
            throw new ExcecaoComunicacaoREINF(ex.Message, ex, arquivoXML.InnerXml);
        }
    }

    private static string ObterMensagemSubjacente(WebException wex)
    {
        //TODO rever
        if (wex.Response == null)
            return wex.Message;

        string mensagemSubjacente = string.Empty;
        using (Stream s = wex.Response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(s);
            mensagemSubjacente = reader.ReadToEnd();

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(mensagemSubjacente);
                XmlNodeList fault = xml.GetElementsByTagName("faultstring");
                if (fault != null && fault.Count > 0)
                {
                    mensagemSubjacente = fault[0].InnerText;
                }
            }
            catch (Exception ex)
            {
                return mensagemSubjacente;
            }
        }
        return mensagemSubjacente;
    }

Se alguem puder me ajudar, ficarei muito grato.

A: Você está informando <tpAmb>1</tpAmb> no XML, mas, o tipo de ambiente para o ambiente de produção restrita (ambiente de testes) deve ser 2. O tipo de ambiente 1 só deve ser usado no ambiente de produção (oficial), que ainda não está liberado para ninguém (só será liberado a partir de maio/2018, mas somente para as empresas que tiveram faturamento maior que R$ 78 milhões no ano de 2016).
Use então <tpAmb>2</tpAmb> no seu XML, e tente novamente.


text:
Q: Detecting $\eta^3$ in stunted projective spaces. Consider the stunted complex projective space $\mathbb{C}P^{n+2}_n:=\mathbb{C}P^{n+2}/\mathbb{C}P^{n-1}$ which is a three-cell complex of the form
$$\mathbb{C}P^{n+2}_n\simeq S^{2n}\cup_{\alpha_n} e^{2n+2}\cup_{\beta_n} e^{2n+4}.$$
I am interested in knowing the attaching maps $\alpha_n$ and $\beta_n$.
To begin we note that the cohomology $H^*\mathbb{C}P^{n+2}_n=\mathbb{Z}\{x^n,x^{n+1},x^{n+2}\}$ is free on three classes which correspond via the collapse map $\mathbb{C}P^{n+2}\rightarrow \mathbb{C}P^{n+2}_n$ with the top three powers of the canonical generator $x\in H^2\mathbb{C}P^{n+2}$. This makes it easy to calculate Steenrod squares in $H^*\mathbb{C}P^{n+2}_n$, and in particular we find that $Sq^2x^n=n\cdot x^{n+1}$, which tells us that
$$\alpha_n\simeq\begin{cases}\ast&n\equiv 0\mod 2\\\eta_{2n}&n\equiv 1\mod2\end{cases}$$
since the Hopf map $\eta_{2n}$ is detected by $Sq^2$.
It is now the even case that really interests me so I will assume from here on out that $n$ is even and also that $n>2$, so that we will be working in the stable range. Moreover I happen to only be interested in $2$-local data, and for this reason all spaces and groups will be localised at the prime $2$ in the following.
Then under these assumptions we have
$$\mathbb{C}P^{n+2}_n\simeq (S^{2n}\vee S^{2n+2})\cup_{\beta_n} e^{2n+4}$$
and $\beta_n$ identifies as an element of $\pi_{2n+3}S^{2n}\oplus\pi_{2n+3}S^{2n+2}$ since there are no Whitehead products in these dimensions. We know from the previous calculation that $\beta_n$ attaches non-trivially to $S^{2n+2}$ by the Hopf map $\eta_{2n+2}$, so recalling that $\pi_{2n+3}S^{2n}\cong\mathbb{Z}_8$ is stable and generated by the element $\nu_{2n}$ it must be that
$$\beta_n=a\cdot \nu_{2n}+\eta_{2n+2}:S^{2n+3}\rightarrow S^{2n}\vee S^{2n+2}$$
for some mod $8$ integer $a$.
Now $Sq^4$ detects $\nu_{2n}$, and with a little work we can calculate the action of $Sq^4$ on $H^*\mathbb{C}P^{n+2}_n$, finding that
$$Sq^4x^n=\begin{cases}0&n\equiv 0,1\mod 4\\
x^{2n+2}&n\equiv {2,3}\mod 4\end{cases}.$$
It follows from this that $a$ is odd when $n\equiv2\mod 4$, and this sorts out $\beta_n$ completely in these cases (we already have that $n$ is even). Therefore let us add the assumption that $n\equiv 0\mod 4$. Then there are essentially three choices for $a$. Namely $a=0,2$ or $4$.

For which even values of $n>2$ does $a=0,2,4$?

Now Adams has constructed stable secondary cohomology operations $\varphi_{0,2}$ based on the Adem relation $Sq^4Sq^1+(Sq^2Sq^1)Sq^2+Sq^1Sq^4=0$ and proved that these operations detect $2\cdot\nu$. For instance $\varphi_{0,2}(x^4)=x^6$ with no intederminacy, and this sorts out $\beta_4=2\cdot\nu+\eta$. However I am not sure of exactly how to evaluate these operations on the higher classes in $H^*\mathbb{C}P^{n+2}$. I have constructed a rudimentary Cartan formula for the operation, but am struggling to deal with the indeterminancy. Moreover, this operation will still leave undecided the cases when it vanishes, since it cannot distinguish $a=0$ and $a=4$.
I am aware of a tertiary cohomology operation capable of detecting $\eta^3=4\cdot\nu$, but I have no idea how to evaluate it on $\mathbb{C}P^{n+2}_n$ for large $n$.
I believe all this must be well known and must appear in a textbook or paper somewhere, but if it does I am not sure where. Any help tracking down reliable references would be very welcome.

A: This is calculated in

Mosher, Robert E.
  Some stable homotopy of complex projective space.
  Topology 7, 1968, 179–193.

Specifically, in Proposition 5.2 (proved in section 9), Mosher shows in particular when $n$ is even that the attaching map of the top cell in $\mathbb{C}P^{n+2}/\mathbb{C}P^{n-1}$ is $$\eta + \lambda \nu \in \pi_{2n+3}(S^{2n+2}) \oplus \pi_{2n+3}(S^{2n})$$ where $$\lambda = \begin{cases} 0, & n \equiv 0 \pmod{8}, \\ 1, & n \equiv 2 \pmod{4}, \\ 2, & n \equiv 4 \pmod{8}. \end{cases}$$


text:
Q: How does psycopg2's connection_factory work? Can someone explain what psycopg2's connection_factory is and how to use it?
I've been looking at a project's code that connects to postgres via the connection_factory and I am at a lost. I have looked at the docs, https://www.psycopg.org/docs/module.html, but all it tells me is:
Using the connection_factory parameter a different class or connections factory can be specified. It should be a callable object taking a dsn string argument.

Looking at the cursor factories and connection becomes overwhelming and I don't even know if it is still related to the connection_factory.
Below is the code that I am looking at:
class PsycoConnection(psycopg2.extensions.connection):
    def lobject(*args, **kwargs):
        pass

Somewhere in another class the above class gets called as follows:
result = psycopg2.connect(
                connection_factory=PsycoConnection,
                **connection_info)

Normally when I use psycopg2 to connect to a database I simple do something like below:
result = psycopg2.connect("host=127.0.0.1 port=5433 dbname=yugabyte sslmode=prefer")

I know the connection_info is not any different to "host=127.0.0.1 port=5433 dbname=yugabyte sslmode=prefer" except it's a dict. So my question is what is this PsycoConnection passed to connection_factory? To me the PsycoConnection class isn't even doing anything since the only code is pass. Thank you.


text:
Q: Java, how to merge smaller classes via 1 big class? Imagine having the following classes:
Head
Torso
Hands
Legs

that I would like to keep but link them via a new class Human. This is what their codes look like:
package myEntities;

public class Head {

    private float headSize;

    Head(float headSize) {
        this.headSize = headSize;
    }

    public static void main(String[] args) { }

    public float[] getHeadSize() {
        return headSize;
    }
}

repeated the same for the other 3 parts except for the name. If I wanted to make a human class, how would it look like? I'm thinking something like this but this seems too repetitive:
package myEntities;

public class Human {

    private Head headObject = new Head(variable1);
    private Torso torsoObject = new Torso(variable2);
    private Leg rightLegObject = new Leg(variable3);

    Human(float variable1, float variable2, float variable3) {

    }

    public static void main(String[] args) { }

And this way gives an error of not being able to resolve variable1 and the rest of the variables.

A: First, in your human class, the constructor should be a Human constructor (not a Zombie - Zombie could be a superclass, a subclass, or a completely separate class)
public class Human {

    Human(float variable1, float variable2, float variable3) {

    }
}

Second, you need to declare the object members like you are doing, but initialize them in your constructor
Human {
    private Head headObject;
    private Torso torsoObject;
    private Leg rightLegObject;

    public Human (float variable1, float variable2, float variable3) {
      headObject = new Head(variable1);
      torsoObject = new Torso(variable2);
      rightLegObject = new Leg(variable3);
   }
}


text:
Q: Josephus Algorithm I was reading the algorithm for the Josephus Problem.
I came across the following algorithm :
int josephusIteration(int n,int k) {
    int a=1;
    for(int i=1;i<=n;i++) {
        a=(a+k-1)%i+1;
    }
    return a;
}

I couldn't understand its logic. Suppose n=5 and k=2.
i=1, a=1
i=2, a=1
i=3, a=3
i=4, a=1
i=5, a=3

Can anybody explain this by giving an example?

A: If n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives.
I have read your code but I would like to suggest a recursive solution below which is easier to understand.
// this function returns the position of the person alive
int josephus(int n, int k)
{
  if (n == 1)
    return 1;
  else
    /* The position returned by josephus(n - 1, k) is adjusted because the
       recursive call josephus(n - 1, k) considers the original position
       k%n + 1 as position 1 */
    return (josephus(n - 1, k) + k-1) % n + 1;
}

After the first person (kth from begining) is killed, n-1 persons are left. So we call josephus(n – 1, k) to get the position with n-1 persons.
But the position returned by josephus(n – 1, k) will consider it again from the position 1. So we add k-1 to it and take its modulus with n as there are n elements and add 1 to make the position 1-indexed rather than 0-indexed.
Reference: http://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/

A: It might help to look at how the formula a = (a + k - 1) % i + 1; is derived. We can do that by starting with the recursive call in unrealsoul007's answer.
return (josephus(n - 1, k) + k-1) % n + 1;

That can be rewritten as:
j = josephus(n - 1, k);
return (j + k-1) % n + 1;

which can be rewritten as:
j = josephus(n - 1, k);
pos = (j + k-1) % n + 1;
return pos;

The second line can now be rewritten to the original formula we were trying to derive, except in this case we have % n, but in the original we had % i. This is because as we make recursive calls n is decreasing, but as those recursive calls return n is increasing again (like i in the loop version).
The reason we need to do the % operation is because when we get to the end of the circle, we need to start over back at the beginning. The reason we add 1 is because we don't want to return the position of the person just eliminated. We want to return the position of the next person, where we start counting again in the next iteration. When n-1 people have been eliminated, that position is the last person remaining, so it's the final return value.


text:
Q: Visual edit jquery knob I have a problem with the visual adaptation of the script. I would like to number in the middle looks like the one in the picture. Where is a different color and a % character in the end.

How I can edit it. I must do it on jquery.knob.js or on some other file like css?

A: I don't think you can add a % symbol at the end of the count.
However, you can change the color code of the count by using the inputColor parameter.
Initialize the plugin as  -
$(".cs_knob").knob({
//other parameters-----
inputColor : '#34EB40', //Color of the count text
});

Below is a visual edit fiddle for the jQuery knob where you can play with all configurations -
http://bitconfig.com/jquery-knob/bitconfig_jquery_knob.html


text:
Q: Существуют ли какие-то затраты на преобразование объектов? С преобразованием значимого типа в объект и обратно все понятно — там появляются доп. операции на упаковку/распаковку.
А есть ли какие-то затраты при преобразовании объектов между дочерним типом и базовым типом?

A: Неявные преобразования
Неявные преобразования проверяются компилятором и после компиляции уже не существуют, соответственно, дополнительных затрат не требуют.
Это можно проверить, прочитав IL-код после компиляции:
Код на C#:
class A{}
class B : A{}
...
B b = new B();
A a = new A();
A target;
target = b;
Console.WriteLine(target);
target = a;
Console.WriteLine(target);

Сгенерерированный IL:
IL_0001:  newobj     instance void B::.ctor()                             //new B()
IL_0006:  stloc.0                                                         //b =
IL_0007:  newobj     instance void A::.ctor()                             //new A()
IL_000c:  stloc.1                                                         //a =
IL_000d:  ldloc.0
IL_000e:  stloc.2
IL_000f:  ldloc.2
IL_0010:  call       void [mscorlib]System.Console::WriteLine(object)
IL_0015:  nop
IL_0016:  ldloc.1
IL_0017:  stloc.2
IL_0018:  ldloc.2
IL_0019:  call       void [mscorlib]System.Console::WriteLine(object)

Как видно, в обоих случаях генерируется пара инструкций ldloc (загрузка переменной в стек) и stloc (выгрузка из стека в переменную). Никаких дополнительных телодвижений при преобразовании типа не выполняется.
Аналогично, если Вы вызываете метод вида: A a = someClass.generateA(), то среда выполнения не проверяет реальный тип объекта, который вернулся из A, ожидая, что компилятор уже выполнил проверку соответствия типов.
Явные преобразования
Явные преобразования генерируют дополнительные инструкции, которые требуют определенных затрат. Приведение типа — инструкцию castclass, преобразования через as и is — isinst. Обе эти инструкции описаны в спецификации CLI.
Соответственно, код на C#:
A a = new B();
Console.WriteLine((B) a);
Console.WriteLine(a as B);
Console.WriteLine(a is B);

будет преобразован в следующий IL:
IL_0001:  newobj     instance void B::.ctor()
IL_0006:  stloc.0
IL_0007:  ldloc.0
IL_0008:  castclass  B
IL_000d:  call       void [mscorlib]System.Console::WriteLine(object)
IL_0012:  nop
IL_0013:  ldloc.0
IL_0014:  isinst     B
IL_0019:  call       void [mscorlib]System.Console::WriteLine(object)
IL_001e:  nop
IL_001f:  ldloc.0
IL_0020:  isinst     B
IL_0025:  ldnull
IL_0026:  cgt.un
IL_0028:  call       void [mscorlib]System.Console::WriteLine(bool)

Если типы не сходятся, то castclass сгенерирует исключение, что несколько более затратно. Соответственно, если вероятность этого высока, то лучше применять as чем cast. В случае когда типы сходятся ощутимой разницы быть не должно.
Обе инструкции применяются очень часто, работают быстро и крайне оптимизированы. Навряд ли приведение типа будет узким местом в Вашем коде, поэтому в большинстве случаев важно писать то приведение, которое имеет больше смысла и лучше читается.
Достаточно обширное обсуждение разницы as vs cast на английском Stack Overflow: Casting vs using the 'as' keyword in the CLR


text:
Q: How to print sub matrix in python? Is there any short way in python to print sub matrix of a bigger matrix like this not using for loop?
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

sub1 = matrix[1:2][1:2]
>>>desired answer: [[6,7][10,11]]
1   2  3   4
5  *6  7*  8
9  *10 11* 12
13  14  15 16

sub2 = matrix[2][1:3]
>>>desired answer: [[7,11,15]]
1   2  3  4
5   6  *7* 8
9  10 *11* 12
13 14 *15* 16

extra: for the latter example, how to return it in reverse format not using reverse()? ie: [15,11,7] or [16,15,14],

A: For lists of lists, you can get your desired result like this:
>>> [s[1:3] for s in matrix[1:3]]
[[6, 7], [10, 11]]
>>>
>>> [s[2:3] for s in matrix[1:4]]
[[7], [11], [15]]
>>>

Note that the latter is a vertical slice, so each element is wrapped in its own list.  Also note that this is Python indexing, so the second limit in a range specifier is one higher than the last index in the slice.


text:
Q: How to count the number of ads on a website I've been looking around but can't find anything. Is it possible to scrape and identify the use of ads (and presumably count them for any given site?
As an example this page has 13 ads.
I'm currently using BeautifulSoup to obtain the page
            headers = {'Content-Type':'application/json'}
            url = requests.get("https://www.worthofweb.com/website-value/wikipedia.com/")
            response = requests.request(method="GET", url=url, headers=headers, timeout=5)
            response.raise_for_status()

            soup = BeautifulSoup(response.text, "html.parser")

The problem is parsing the page.

A: You can consider to analyze every element in the DOM and check for standard ad sizes. Here's a list:
https://www.creatopy.com/blog/banner-standard-sizes/
Briefly, get the width/height from the element's style, and see if it matches a standard ad unit size. If so, we can argue it's an ad (false positives possible though).


text:
Q: Resetting/Clearing a global array of pointers to structs I'm new to C and I'm having a bit of a problem resetting or clearing a global array of pointers to structs.
I need to receive a file (or more) and read it's lines in two cycles.
while reading it I need to create a table of symbols(labels basically), and then use it to create more data (exporting the location of the labels to files writing it in hexadecimal values).
The problem I am having is when I'm reading two files. The first file is read fine and all the values are correct, but when it tries to read the second file the values in the table(array) I created are still there even though I free'd them.
I have this declared in a header file: (SIZE being 30)
typedef struct symbol{
unsigned action :1;
unsigned external :1;
int address;
char label[SIZE];
unsigned data_flag :1;
} symbol ;

symbol *symbol_Table[SIZE] ;

An example of adding a new symbol: (this sits in the reading function)
new_symbol =  malloc(sizeof(symbol));
strcpy(new_symbol->label, temp);
new_symbol->external = 0;
new_symbol->address = DC - tok_count;
new_symbol->action = 0;
new_symbol->data_flag = 1;
add_symbol(new_symbol);
free(new_symbol);

The adding function, in a different file: (UPDATE)
if(count == SIZE){
    **/*realloc the array size, increase it*/**
}

if(count < SIZE){
    symbol_Table[count] = malloc(sizeof(symbol));
    symbol_Table[count]->action = new_symbol->action;
    symbol_Table[count]->external = new_symbol->external;
    symbol_Table[count]->address = new_symbol->address;
    strcpy(symbol_Table[count]->label, new_symbol->label);
    symbol_Table[count]->data_flag = new_symbol->data_flag;

    /*printf("count: %d\n", count);*/
    return ++count;
}

return count;

And the freeing of the symbols at the end of the reading loop: (UPDATE)
int i;
for(i = 0; i < count ; i++){
    free(symbol_Table[i]);
    symbol_Table[i] = NULL;
}

this is the correct output after the first loop on the first file:
action: no | extern: yes | address: 0 | label L3 | data: no
action: no | extern: yes | address: 0 | label W | data: no
action: yes | extern: no | address: 100 | label MAIN | data: no
action: yes | extern: no | address: 106 | label LOOP | data: no
action: yes | extern: no | address: 119 | label END | data: no
action: no | extern: no | address: 0 | label STR | data: yes
action: no | extern: no | address: 7 | label LENGTH | data: yes
action: no | extern: no | address: 10 | label K | data: yes

and the faulty output after the first loop of the second file: (UPDATE)
action: yes | extern: no | address: 100 | label MAIN | data: yes
action: no | extern: yes | address: 0 | label W | data: yes
action: yes | extern: no | address: 108 | label LOOP | data: yes
action: no | extern: no | address: 0 | label STR | data: yes
action: no | extern: no | address: 3 | label K | data: yes

should be:
action: yes | extern: no | address: 100 | label MAIN | data: no
action: no | extern: yes | address: 0 | label W | data: no
action: yes | extern: no | address: 108 | label LOOP | data: no
action: no | extern: no | address: 0 | label STR | data: yes
action: no | extern: no | address: 3 | label K | data: yes

A few questions:

*

*Is there a way to clean the list after I used it? and then reusing the same list for new values? and avoiding the memory leak.

*Is this idea with arrays just a waste of space, should I try using linked lists instead? I fear that I will have to write my whole project again, and time is not on my side..

(AFTER UPDATE)

*How can I Reallocate more memory to increase the size of the array when I reach its end?

Apologies if I misused a term, I'm studying C in a different language.

A: Even though you are freeing your structs, your data is not immediately overwritten since the heap allocator isn't required to; it just makes a note that the space you freed is available. You should go one step further, and set each index of your array to NULL after freeing them. That will actually remove them from your array.
Now, I would be cautious when using an array. You have specified a size, but you aren't enforcing it in your add function.
If you swap your array over to use dynamic memory by using malloc, and you reach the size constraint later in the program, you can allocate more space using realloc (which would basically allow you to implement an ArrayList without disturbing the rest of your program's implementation).
To initially allocate space for your array, try:
symbol **symbol_Table = (symbol *) malloc(sizeof(symbol *) * SIZE);

Note: malloc can only be called from inside a method. So, at the top of your file, you can declare your variable:
symbol **symbol_Table;

Then, before using it, you should define it in your main() method:
symbol_Table = (symbol **) malloc(sizeof(symbol **) * SIZE);

Note the notation in the malloc statement - you need to multiply the size of
the array with the size of a symbol pointer, because malloc takes the number of bytes that are to be allocated. sizeof(symbol *) gives you the size of a single symbol pointer.
Also: in order to use realloc, the initial allocation of symbol_Table should be something returned by malloc / calloc / realloc, or NULL.
If you're just trying to pop the reallocation into your if-statement, try:
static size_t current_size = SIZE;

if(count == current_size) {
  current_size = current_size << 1;
  symbol_Table = (symbol *)realloc(symbol_table, sizeof(symbol *) * current_size);
}

if(count < current_size) {
  // ... the rest of the code continues here

The bit about current_size << 1 is a bitshift left - it effectively multiplies current_size by two.
Static variables retain their values between function calls. So, if I change it when I call the function one time, the next time I call the function, the variable will have the value I set in the previous call. The reason for the static variable is that the value of current_size should be saved between calls if you increase the size of your array, and that you have to store the size of the array somewhere. The best place to store it is in the one function where the real size of the array is important - the only place where it will be upscaled. A global variable would work just as well though.

To free the symbol table at the end:
int i;
for(i = 0; i < count ; i++){
  if(symbol_Table[i] != NULL) // Important - we cannot free NULL
  {
    free(symbol_Table[i]);
    symbol_Table[i] = NULL;
  }
}
count = 0; // Important - if we are deleting everything in the array, we
           // need to make sure we reset the count for our next delete
           // operation

A: Your problem is (IMO) that SIZE is a constant. If you make it variable you could resize the symbol table when needed.
The cleanest way is to store the array of pointers together with the size(s) in some envelope-structure, like in:

struct symbol{
        unsigned action :1;
        unsigned external :1;
        unsigned data_flag :1;
        int address;
        char label[SIZE];
        } symbol ;

struct symtab{
        unsigned size;
        unsigned used;
        struct symbol **table; /* used as an array of pointers */
        };

        /* global: for fun */
struct symtab thetab = {0,0,NULL};

int resize_the_thing(struct symtab *sp, unsigned new_size)
{
struct symbol **newtable;

        /* Note: realloc takes care of copying, too ...*/
newtable = realloc (sp->table, new_size * sizeof sp->table[0]);

if (!newtable) { /* handle error */
        return -1;
        }

sp->table = newtable;
        /* TODO: you need to check the case new_size < size here, too */
sp->size = new_size;
return 0; /* no_error */
}

/* typical usage: */

if (thetab.used >= thetab.size && resize_the_thing( &thetab, 12345)) {
        /* report error */
        }

thetab.table[thetab.used++] = new_symbol(...);


text:
Q: How to access json object am keep getting undefined error? I have tried to parse json and iterates it. After some nesting i was not able to get the object. it keeps saying undefined. Can anybody tell me how to access this.
 $.each( data[widget_val[0]][j],function(key,value){
            alert(data[widget_val[0]][j][key]); //getting output
        alert(data[widget_val[0]][j]['Type']);  //getting undefined
       });

my json
({'Encounter Date  ':"06/09/2008 ", 'Description  ':"new patient ", 'Type  ':"Note ", 'Status  ':"ARC ", 'Provider  ':"Brady, Roseann "})

so i am getting alert for each key even for 'Type'.But when i gave it as seprately as string i am getting undefined error. can any body tell why. What is the way to access it?

A: Try
alert(data[widget_val[0]][j]['Type  '])

with spaces instead of
alert(data[widget_val[0]][j]['Type'])

because you are trying access undefined variable 'Type'


text:
Q: Automorphism(Galois groups) and galois theory I've been stuck on two last parts for two different questions, can someone please help me with these.
The first question is:
Let $\sigma\in Aut(L/\mathbb{Q})$, where $L$ is some subfield of $\mathbb{C}$, such that $\sigma:L\rightarrow L$  and $\sigma(\alpha)=\bar\alpha$. The first part of the question asks to show that $\sigma$ has order $2\iff L\not\subset \mathbb{R}$. By order does it mean, the minimum number of times I need to repeatedly call the function $\sigma$ on $\alpha$ till I arrive with output $\alpha$. If this is the case, then $\sigma(\alpha)=\alpha\neq\alpha$, however $\sigma(\sigma(\alpha))=\sigma(\bar\alpha)=\alpha$. So order is equal to 2. If I am right, then could someone help me word this correctly.
The second half of the first question is:
Let $F=L^{<\sigma>}$, show that $[L:F]=1$ or $2$, according to whether $L\subset\mathbb{R}$ or $L\not\subset\mathbb{R}$.
Where $L^{<\sigma>}:=${$\alpha\in L|\sigma_i(\alpha)=\alpha\space\space\forall\sigma\in <\sigma>$}
Is it okay for me to assume that $<\sigma>=${$\sigma, \space\sigma\circ\sigma$=$I$}, where $I$ is the identity map. Are there any elements in $<\sigma>$ that I'm missing out. Since $\sigma\circ\sigma$ will always map any $\alpha$ back to $\alpha$, so we only need to find the set of all $\alpha$, for which $\sigma(\alpha)=\alpha$.
When $L\subset\mathbb{R}\implies \sigma(\alpha)=\bar\alpha = \alpha$. It follows that $F=L$, hence $[L:F]=1$.
When $L\not\subset\mathbb{R}$, $\exists l\in L$, such that $l\in\mathbb{C}/\mathbb{R}$. This is where I'm completely stumped, can I somehow use the fact that $\sigma$ has order $2$ from the previous part, to show that $[L:K]=2$.
The Second question I'm struggling with is:
Let $\sigma (\alpha)=\bar\alpha$. I need to show that $\mathbb{Q}(\zeta)^{<\sigma>}=\mathbb{Q}(\zeta + 1/\zeta)$. That is, I need to show that $\forall\alpha\in\mathbb{Q}(\zeta + 1/\zeta)$, $\sigma_i(\alpha)=\alpha$  $\forall\sigma_i\in<\sigma>$, where $\zeta$ is the primitive $p^{th}$ root of unity and $p$ is an odd prime. From the previous questions I had proved that $\mathbb{Q}(\zeta)/\mathbb{Q}$ is a galois extension. Also, I had proved that the function $\mu:(\mathbb{Z}/p\mathbb{Z})^*\rightarrow Aut(\mathbb{Q}(\zeta)/\mathbb{Q})$, defined as $\mu(\bar a)(\zeta)=\zeta^a$. Can I use the two previous results to answer this question.


text:
Q: Getting point geometry by clicking at the map within QGIS plugin From QGIS 3 Plugin Tutorial I need the example for getting a point geometry from clicking at the map.
So I have a file point_tool.py:
from qgis.gui import QgsMapTool, QgsMapToolEmitPoint
from PyQt5.QtCore import pyqtSignal

class PointTool(QgsMapToolEmitPoint):
    canvasClicked = pyqtSignal('QgsPointXY')

    def __init__(self, canvas):
        super(self, QgsMapTool).__init__(self, canvas)

    def canvasReleaseEvent(self, event):
        point_canvas_crs = event.mapPoint()

        self.canvasClicked.emit(point_canvas_crs)

And in my plugin:
from .point_tool import PointTool

...
def addFachdatum(self):
   self.mapTool = PointTool(self.iface.mapCanvas())
   self.iface.mapCanvas().setMapTool(self.mapTool)
   self.mapTool.canvasClicked.connect(self.onMapClick)

def onMapClick(point):
   logging.warning('onMapClick: '+point.asWkt())

But in QGIS I get the following error:
2021-11-18T12:21:46     WARNING    Traceback (most recent call last):
File "C:/Users/sschmidt/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\gga_importer\gga_importer.py", line 420, in addFachdatum
    self.mapTool = PointTool(self.iface.mapCanvas())
File "C:/Users/sschmidt/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\gga_importer\point_tool.py", line 9, in __init__
    super(self, QgsMapTool).__init__(self, canvas)
TypeError: super() argument 1 must be type, not PointTool

But I don't understand the problem, because it is Python37 and PointTool is derived from QgsMapToolEmitPoint and this is QObject. Who can help please?

A: Change
super(self, QgsMapTool).__init__(self, canvas)

to
super(QgsMapTool, self).__init__(canvas)


text:
Q: Assign a method when selecting annotation view I try to call a method when the annotation view (and only the annotation view) is clicked.
- (void)mapView:(MKMapView *)m didSelectAnnotationView:(MKAnnotationView *)view {

            [self openDetailView];

}

But what i noticed, is that this method (openDetailView) is called only when i select the PIN, means before the annotation view gets displayed. How can i fire that method on callout click? Thanx in advance.

A: By adding button with arrow instead of callout:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    if ([annotation isMemberOfClass:[MKUserLocation class]]) {
        return nil;
    }
    MKPinAnnotationView *v =[[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ku"] autorelease];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    button.frame = CGRectMake(0, 0, 24, 24);
    Shop *shop = [(ShopAnnotation *)annotation myShop];
    button.tag = [shop.ID intValue];
    [button addTarget:self action:@selector(callOutPressed:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"map_arr_right.png"] forState:UIControlStateNormal];

    v.rightCalloutAccessoryView = button;
    v.canShowCallout = YES;
    return v;
}

- (void) callOutPressed:(id)sender {

    NSLog(@"callout pressed");
}


text:
Q: $\sigma$ finite measure. Assume $\mu$ is a $\sigma$-finite measure on  $(\Omega,\mathcal{F})$, i.e. exist finite $A_n\in\mathcal{F}$ such that $\bigcup A_n=\Omega,\mu(A_n)<\infty$.
$\mathcal{P}$ is a $\pi$-system with $\sigma(\mathcal P)=\mathcal  F$, can we find such $A_n\in\mathcal P$? (Is $\mu$ a $\sigma$-finite measure on  $\mathcal{P}$?)

This problem is from "the uniqueness of measure extension":
If $\nu_1,\nu_2$ are two measure that agree on $\mathcal{P}$, then they agree on $\sigma(\mathcal{P})$ under the condition that $\nu_i$ is $\sigma$-finite measure on $\mathcal{P}$.
I wonder if it can be replaced by $\sigma$-finite measure on  $\mathcal{F}=\sigma(\mathcal P)$. I got stuck on the final step on the original proof. (Refer to Durrett http://www.math.duke.edu/~rtd/PTE/PTE4_1.pdf page 361 thm A1.5)

A: Let $\nu_1$ be Lebesgue measure on $\mathbb{R}$ and $\nu_2=2\nu_1$. These are both $\sigma$ finite on the Borel sets ${\cal B}(\mathbb{R})$ and $\nu_1=\nu_2$ on
${\cal P}=\{(-\infty, x]: x\in \mathbb{R}\}$, which generates ${\cal B}(\mathbb{R})$.