text:
Q: Get feature importance from trained Vertex AI Tabular regression model using Python I am working with models trained using the Tabular automl of Vertex in GCP.
Training and batch predictions work fine. I am truing to use the feature importance in visualizations and trying to get to them from within python.
I can get to the model:
client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
name = client.model_path(project=project, location='us-central1', model=modelnum)
response = client.get_model(name=name)

But I can not figure out how to get the trained model's feature importance's that were generated in the training pipeline. I can see them on the model page but can't access them from python.

A: To get details on the "Evaluate" page, you need to use list_model_evaluations(). This will return google.cloud.aiplatform_v1.services.model_service.pagers.ListModelEvaluationsPager that contains the values you see on "Evaluate" page. Since you mentioned you want to get the feature importance, you need to loop through the said object and get model_explanation. See code below:
from google.cloud import aiplatform_v1 as aiplatform

api_endpoint = 'us-central1-aiplatform.googleapis.com'
client_options = {"api_endpoint": api_endpoint} # api_endpoint is required for client_options
client_model = aiplatform.services.model_service.ModelServiceClient(client_options=client_options)
project_id = 'your-project-id'
location = 'us-central1'
model_id = '9999999999999'

model_name = f'projects/{project_id}/locations/{location}/models/{model_id}'
list_eval_request = aiplatform.types.ListModelEvaluationsRequest(parent=model_name)
list_eval = client_model.list_model_evaluations(request=list_eval_request)
for val in list_eval:
    print(val.model_explanation)

For the testing, I used Google's sample data (gs://cloud-ml-tables-data/bank-marketing.csv).
Response from the code:
mean_attributions {
  feature_attributions {
    struct_value {
      fields {
        key: "Age"
        value {
          number_value: 0.027145349596062344
        }
      }
      fields {
        key: "Balance"
        value {
          number_value: 0.009469658279914696
        }
      }
      fields {
        key: "Campaign"
        value {
          number_value: 0.009621628534664564
        }
      }
      fields {
        key: "Contact"
        value {
          number_value: 0.006477007587775141
        }
      }
      fields {
        key: "Day"
        value {
          number_value: 0.013976069802316006
        }
      }
      fields {
        key: "Default"
        value {
          number_value: 1.528606850783311e-08
        }
      }
      fields {
        key: "Duration"
        value {
          number_value: 0.1395725763431482
        }
      }
      fields {
        key: "Education"
        value {
          number_value: 0.007015091678270283
        }
      }
      fields {
        key: "Housing"
        value {
          number_value: 0.055101036115872845
        }
      }
      fields {
        key: "Job"
        value {
          number_value: 0.021222775094579954
        }
      }
      fields {
        key: "Loan"
        value {
          number_value: 0.002048753814978598
        }
      }
      fields {
        key: "MaritalStatus"
        value {
          number_value: 0.005709941134721149
        }
      }
      fields {
        key: "Month"
        value {
          number_value: 0.12325089337437695
        }
      }
      fields {
        key: "PDays"
        value {
          number_value: 0.023952343173674555
        }
      }
      fields {
        key: "POutcome"
        value {
          number_value: 0.06695149606670256
        }
      }
      fields {
        key: "Previous"
        value {
          number_value: 0.03921166116430856
        }
      }
    }
  }
}

From "Evaluate" page:

EDIT: 20210920
I used my regressions model and get the data using aiplatform library. Still I got the attribute model_explanation. I'm using google-cloud-aiplatform==1.4.3 for the library version.
Code used:
from google.cloud import aiplatform

api_endpoint = 'us-central1-aiplatform.googleapis.com'
client_options = {"api_endpoint": api_endpoint}
client_model = aiplatform.gapic.ModelServiceClient(client_options=client_options)
#client_model = aiplatform.services.model_service.ModelServiceClient(client_options=client_options)

project_id = 'your-project-id'
location = 'us-central1'
model_id = '999999999'

model_name = f'projects/{project_id}/locations/{location}/models/{model_id}'
list_eval = client_model.list_model_evaluations(parent=model_name)
print(list_eval)

Full JSON response:
ListModelEvaluationsPager<model_evaluations {
  name: "projects/xxxxxxx/locations/us-central1/models/99999999/evaluations/8888888"
  metrics_schema_uri: "gs://google-cloud-aiplatform/schema/modelevaluation/regression_metrics_1.0.0.yaml"
  metrics {
    struct_value {
      fields {
        key: "meanAbsoluteError"
        value {
          number_value: 0.1303236
        }
      }
      fields {
        key: "meanAbsolutePercentageError"
        value {
          number_value: 9.991856
        }
      }
      fields {
        key: "rSquared"
        value {
          number_value: 0.39691383
        }
      }
      fields {
        key: "rootMeanSquaredError"
        value {
          number_value: 0.24697715
        }
      }
      fields {
        key: "rootMeanSquaredLogError"
        value {
          number_value: 0.10037828
        }
      }
    }
  }
  create_time {
    seconds: 1632106497
    nanos: 416614000
  }
  model_explanation {
    mean_attributions {
      feature_attributions {
        struct_value {
          fields {
            key: "Age"
            value {
              number_value: 0.033690840005874634
            }
          }
          fields {
            key: "Balance"
            value {
              number_value: 0.021756498143076897
            }
          }
          fields {
            key: "Campaign"
            value {
              number_value: 0.03156016394495964
            }
          }
          fields {
            key: "Contact"
            value {
              number_value: 0.09849491715431213
            }
          }
          fields {
            key: "Day"
            value {
              number_value: 0.08989512920379639
            }
          }
          fields {
            key: "Default"
            value {
              number_value: 0.00012870959471911192
            }
          }
          fields {
            key: "Duration"
            value {
              number_value: 0.3097792863845825
            }
          }
          fields {
            key: "Education"
            value {
              number_value: 0.01789841242134571
            }
          }
          fields {
            key: "Housing"
            value {
              number_value: 0.05525226518511772
            }
          }
          fields {
            key: "Job"
            value {
              number_value: 0.010000345297157764
            }
          }
          fields {
            key: "Loan"
            value {
              number_value: 0.00856288243085146
            }
          }
          fields {
            key: "MaritalStatus"
            value {
              number_value: 0.01715957187116146
            }
          }
          fields {
            key: "Month"
            value {
              number_value: 0.22002224624156952
            }
          }
          fields {
            key: "PDays"
            value {
              number_value: 0.026749607175588608
            }
          }
          fields {
            key: "POutcome"
            value {
              number_value: 0.05268073454499245
            }
          }
          fields {
            key: "Previous"
            value {
              number_value: 0.00636840146034956
            }
          }
        }
      }
    }
  }
}
>

From "Evaluate" page:


text:
Q: Как в последнем методе реализовать проверку? public class RegistrationActivity extends Activity {

boolean number;
boolean name;
boolean Email;

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

public void BackToLogin(View view)
{
Intent BackToLogin = new Intent(RegistrationActivity.this, LoginActivity.class);
startActivity(BackToLogin);
}

private boolean CheckPhoneNumber()
{
TextView hint = (TextView)findViewById(R.id.NumberTextView);
EditText checkPhoneNumber = (EditText)findViewById(R.id.Number);
String phoneNumber = checkPhoneNumber.getText().toString();
if (phoneNumber.length()<8 || phoneNumber.length()>20)
{
    hint.setText("You enter wrong phone number. Try again");
    checkPhoneNumber.setText("");
    return number = false;
}
else
{
    return number = true;
}
}
private boolean CheckEmail()
{
TextView Hint = (TextView)findViewById(R.id.EmailTextView);
EditText checkEmail = (EditText)findViewById(R.id.Email);
String email = checkEmail.getText().toString();
if (email.matches("@") & email.matches("."))
{
    Email = true;
    return Email;
}
else
{
    Email = false;
    Hint.setText("You enter wrong E-mail. It must contains symbol '@' and '.'");
    return Email;
}
}
private boolean CheckName()
{
TextView Hint = (TextView)findViewById(R.id.NameTextView);
EditText checkName = (EditText)findViewById(R.id.Name);
String Name = checkName.getText().toString();
if (Name.length()<3)
{
    Hint.setText("Your name must contains more than 3 symbols");
    name = false;
    return name;
}
else
{
    name = true;
    return name;
}
}
public void GiftActivity(View view)
{
TextView Hint = (TextView)findViewById(R.id.Hint);

if (name == false && Email == false && number == false)
{
    Hint.setText("You enter something wrong. Please, check again.");
}
else
{
    Intent GiftActivity = new Intent(RegistrationActivity.this, GiftHomeActivity.class);
    startActivity(GiftActivity);
}
}

A: 1.
if (name == false && Email == false && number == false)

В этом месте логичнее использовать оператор || (или). У вас ошибка покажется только если все три переменные false.
2.
Hint = (TextView)findViewById(R.id.Hint);

Такие вещи лучше делать в onCreate методе

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to concatenate strings String outputFile = String.Format("{0}\t{1}\t{2}\t{3}\r\n", x.url, x.company, x.country, x.vendor,);

if (client.cf.is_cis == true)
{
    outputFile = String.Format("{0}\r\n", x.cis);
}

if (client.cf.is_firmographic == true)
{
    outputFile = String.Format("{0}\t{1}\r\n", x.revenue, x.employee);
}

writerCustomerTxt.Write(outputFile);

I have a set of strings that I am trying to output, but obviously with the code above, the output is being overrided if any of the if statements are true. I believe that string concatenation is the solution to this issue. What would be the most efficient way to do this?

A: It's a bit difficult to get exactly what you are asking, but using a StringBuilder to build up your string, this will work:
StringBuilder builder = new StringBuilder();

builder.AppendFormat("{0}\t{1}\t{2}\t{3}\r\n",
    x.url, x.company, x.country, x.vendor);

if (client.cf.is_cis == true)
{
    builder.AppendFormat("{0}\r\n",
        x.cis);
}

if (client.cf.is_firmographic == true)
{
    builder.AppendFormat("{0}\t{1}\r\n",
        x.revenue, x.employee);
}

writerCustomerTxt.Write(builder.ToString());

A: The simplest way of concatenating a string is by using the += operator:
String outputFile = String.Format("{0}\t{1}\t{2}\t{3}\r\n", x.url, x.company, x.country, x.vendor);

if (client.cf.is_cis == true)
{
    outputFile += String.Format("{0}\r\n", x.cis);
}

if (client.cf.is_firmographic == true)
{
    outputFile += String.Format("{0}\t{1}\r\n", x.revenue, x.employee);
}

writerCustomerTxt.Write(outputFile);

By the way, if you are not passing any argument over here, then you can remove the ,:
String.Format("{0}\t{1}\t{2}\t{3}\r\n", x.url, x.company, x.country, x.vendor, );
                                                                             ^^^


text:
Q: PytelegramBotApi нужна помощь с просмотренными новостями Делаю телеграм бота с помощью библиотеки pytelegrambotapi. Сделал Кнопки и Приветствие, а также кнопку Новости.
Можно ли так сделать, чтобы пользователь, прочитавший все новости, при очередном нажатии увидел бы сообщение "Для вас новостей нет!"
Как это сделать?

A: print(bot.get_me())

news_count = 4  # количество новостей
press_news_count = {}  # словарь с id и количеством нажатий на кнопку Новости

@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardMarkup(True)
    markup.row('Новости')
    bot.send_message(message.chat.id, 'Привет', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def func(message):
    if message.text == 'Новости':
        if message.chat.id in press_news_count:  # если id есть в словаре
            if press_news_count[message.chat.id]['press'] < news_count:  # кол-во нажатий у id меньше кол-ва новостей
                press_news_count.update({message.chat.id: {'press': press_news_count[message.chat.id]['press'] + 1}})  # +1 к нажатию
                bot.send_message(message.chat.id, 'Вы нажали на кнопку новости')
            else:
                bot.send_message(message.chat.id, 'новостей нет')
        else:
            press_news_count.update({message.chat.id: {'press': 1}})  # если id нет в словаре, запись первого нажатия
            bot.send_message(message.chat.id, 'Вы нажали на кнопку новости')
        print(press_news_count)

bot.polling(none_stop=True, interval=0)

>>>
{id: {'press': 1}}
{id: {'press': 2}}
{id: {'press': 3}}
{id: {'press': 4}}
{id: {'press': 4}}


text:
Q: Laravel one to one polymorphic relationship returns null I'm facing issue in one to one polymorphic relationship in laravel 6.0.
I have 2 Model CategoryModel and SeoModel(Polymorphic model with one to one relationship)
Below is a snippet from controller where i try to add category and its seo's.
        $info=[];
        $query = [
            'name' => 'name',
            'description' => 'description',
            'parent_id' => NULL,
            'status' => 1,
            'image' => NULL,
            'sort_order' => 1,
        ];
        // dd($query);

        $info["category"]= new CategoryModel;
        $info["seo"] = new SeoModel;

        $info['category']->fill($query);
        $info['category']->save();

        $seo_query = [
            'meta_title' => 'meta_title',
            'meta_description' => 'meta_description',
            'meta_keyword' => 'meta_keyword',
            'seoable_id' => $info['category']->getKey(),
            'seoable_type' => CategoryModel::class,
        ];

        // dd($seo_query);

        $info['category']->seo()->create($seo_query);
        $info['category_id']= $info['category']->getKey();

        return $info;

SeoModel Path : App/Models/Seo/SeoModel
class SeoModel extends Model
{
    use SoftDeletes, ModelTrait;

    protected $table = 'seo';
    protected $primaryKey = 'id';
    protected $fillable = ['meta_title', 'meta_description', 'meta_keyword', 'seoable_id', 'seoable_type'];
    protected $dates = ['deleted_at'];
    public $incrementing = false;

    public function seoable()
    {
        return $this->morphTo();
    }

}

CategoryModel Path : App/Models/Category/CategoryModel
namespace App\Models\Category;

use App\Models\Seo\SeoModel;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;

class CategoryModel extends Model
{
    use SoftDeletes, ModelTrait;

    protected $table = 'category';
    protected $primaryKey = 'category_id';
    protected $fillable = ['name', 'description', 'parent_id', 'status', 'image', 'sort_order'];
    protected $dates = ['deleted_at'];
    protected $with = ['seo'];

    protected $appends = ['image_url'];
    protected $file_directory = "categories/";

    public function getImageUrlAttribute() {
        return $this->resolveFileUrl($this->attributes['image']);
    }

    public function seo(){
        return $this->morphOne(SeoModel::class, 'seoable');
    }
}

Thanks in Advance


text:
Q: Attempt to read form field value throwns keyerror when used with jQuery datepicker I am new to Django framework and am running into the following issue.  Any help to resolve the issue will be much appreciated.
Background:
I am using the jQuery datePicker to gather date input. I am able to see the calendar show up on the (Appointment) form and select a date from the calendar. However, once submitted, attempt to extract the selected date, in the post processing function, throws a keyerror.
I don't know if this has anything to do with the fact that I didn't manually enter "perfDate", but rather made a selection on the calendar.
The Django debugs show that the POST data as shown here-
enter image description here
Following are my form, template and views files:
forms.py:
class DateInput(forms.DateInput):
    input_type = 'date'

class AppointmentForm(forms.Form):
    class Meta:
        model = Appointment
        widgets = {
            'perfDate': forms.DateInput(attrs={'class':'datepicker'}),
        }

datePicker.html:
<!doctype html>

... JS code...

        <form action="/users/makeReservation/" method="post">
            {% csrf_token %}

Desired date:

        <input name="perfDate" type="text" id="id_date">

            <input type="submit" value="Reserve" />
        </form>

views.py:
def makeReservation(request):
    if request.method == 'POST':
        aptForm = AppointmentForm(request.POST)
        # Have we been provided with a valid form?
        if aptForm.is_valid():
            aptDate = aptForm.cleaned_data['perfDate'])
            ...
        else:
            # The supplied form contained errors - just print them to the terminal.
            print(form.errors)
    else:
        aptForm = AppointmentForm(request.POST)
        return render(request, 'datePicker.html', {'form' : aptForm})

Thanks,
/Baktha Muralidharan


text:
Q: Multiple MouseGetPos coordinates I am trying to figure out how to have an AutoHotKey script save different coordinates through MouseGetPos on different hotkeys at the same time, without one overwriting the other.
I want to make a loop performing some sequence of events. Say at one point I want it to execute the first coordinate that I saved before or during the loop (but before the action), and then I want the script to execute the other coordinate at a later point in the loop.
I want the coordinates to be able to be preset (instead of pressing Hotkey1 before the action of hotkey1 and consequently hotkey2 after hotkey1 to ensure one is not overwritten).
An example of this would be:
If one hotkey saves one coordinate:
hotkey1::
MouseGetPos, posx, posy,

// If inserted into a loop, it would be:
MouseMove, %posx%, %posy%,

One hotkey saves another coordinate:
hotkey2::
MouseGetPos, posx1, posy1,

// In loop:
MouseMove, %posx1%, %posy1%,

If inputted into a random loop
#SingleInstance Force
SendMode Input
#MaxThreadsPerHotkey, 2
#NoEnv
#Persistent
SetWorkingDir %A_ScriptDir%
SetTitleMatchMode, 3
SetMouseDelay, -1

Process, Priority, , H
SetKeyDelay, -1, -1
SetDefaultMouseSpeed, 0

SetKeyDelay, 0, 10, Play
SetMouseDelay, 10, Play

CoordMode, Mouse, Screen

hotkey1::
MouseGetPos, posx, posy,
return

hotkey2::
MouseGetPos, posx1, posy1,
return

Toggle=0
f::
Toggle := !Toggle
Loop
{
 If Toggle
   {
    Send {a}
    sleep 100
    MouseMove, %posx%, %posy%, // Say I want it to move to bottom left corner
    Send {LButton}
    sleep 100

            If !Toggle
                Break

    MouseMove, %posx1%, %posy1%, // Say this coordinate would be top-right corner
    Send {LButton}
    sleep 100
    Send {c}
   }
}
return

q::ExitApp

If I trigger hotkey1 and hotkey2 in that order, hotkey1 would get saved then overwritten by hotkey2, making hotkey1 the same coordinate as hotkey2. I would want 2 separately saved coordinates.
Do I do that by having one script trigger another script or can this be done in a single script?


text:
Q: Dynamically calculate how many months have passed - SQL Server I am trying to calculate how many months ago the date field was
I have a table
CREATE TABLE Date(
Date Date
);

INSERT INTO Date (Date)
VALUES ('05-01-18'),
('04-01-18'),
('03-01-18'),
('02-01-18'),
('01-01-18'),
('12-01-17'),
('11-01-17');

And a query
SELECT Date ,
MONTH(Date),
CASE WHEN MONTH(Date) = MONTH(GETDATE()) Then 'Current Month'
WHEN MONTH(Date) = MONTH(GETDATE()) -1 Then '1 Month Ago'
WHEN MONTH(Date) = MONTH(GETDATE()) -2 Then '2 Month Ago'
ELSE 'n/a' END AS [Months Ago]
FROM Date

Which gives me the correct result:
|       Date |    |    Months Ago |
|------------|----|---------------|
| 2018-05-01 |  5 | Current Month |
| 2018-04-01 |  4 |   1 Month Ago |
| 2018-03-01 |  3 |   2 Month Ago |
| 2018-02-01 |  2 |           n/a |
| 2018-01-01 |  1 |           n/a |
| 2017-12-01 | 12 |           n/a |
| 2017-11-01 | 11 |           n/a |

But is there anyway to create this dynamically instead of keep having to write case expressions. So if anyone add's more dates in the future this will just work without having to add more cases?

A: You exactly want datediff():
select datediff(month, date, getdate()) as num_months_ago

datediff() counts the number of month boundaries between two dates.  So, Dec 31 is "one month before" Jan 1.  This appears to be the behavior that you want.
I don't see an advantage to putting this in a string format.

A: In case you do want this to have a string format:
SELECT D.[Date],
       DATEPART(MONTH,D.[Date]) AS [Month],
       CASE WHEN V.DD = 0 THEN 'Current Month'
            WHEN V.DD = 1 THEN  '1 Month Ago'
            ELSE CONVERT(varchar(4), V.DD) + ' Months ago' END AS MonthsAgo
FROM [Date] D
     CROSS APPLY (VALUES(DATEDIFF(MONTH, D.[Date], GETDATE()))) V(DD);

I, however, agree with Gordon, SQL Server isn't really the palce to do that type of formatting. :)


text:
Q: menukeys package breaks SyncTeX for \input files? Including the menukeys package breaks SyncTeX's inverse search for content included by \input.
MWE:
mwe.tex:
\documentclass{article}

\usepackage{menukeys}

\begin{document}

Hello World.

\input{input.tex}

\end{document}

input.tex:
Bonjour Le Monde.

Double-clicking the Hello World on the PDF takes me to mwe.tex, but double-clicking Bonjour Le Monde results in a message "No synchronization info at this position". I expected it to take me to input.tex.
System:

*

*OS: Windows 10

*LaTeX compiler: TeXworks 0.6.6, using pdfLaTeX.

*PDF Viewer: SumatraPDF 3.3.3 64-bit.

*TeX Editor: Notepad++ 8.1.9.2 32-bit

(I prefer to use TeXworks for compiling the TeX only. I'm not bothered about forward search.)
I'm aware that several people have raised similar issues with SyncTeX and \input files, such as Synctex fails for input files. Related to fancyhdr + graphicx?. However, the most recent post says it's resolved. A \clearpage fixes the issue but this doesn't always result in a pleasing document.
Is there more up-to-date information on resolving this? Should I consider raising an issue, and if so, where? SyncTeX?
Thanks!

A: It breaks for me as soon as I add an immediate xform (something that the fadings libary of pgf does too):
\documentclass{article}

\setbox0\hbox{A}
\immediate\pdfxform0
\begin{document}

Hello World.

\input{input1.tex}

\end{document}

This gives a synctex file with beside other this here
Output:pdf
Magnification:1000
Unit:1
X Offset:0
Y Offset:0
Content:
x0,0:491521,447828 %<------ from the xform
!1346

Imho the marked part confuses sumatra.
I added an issue here https://github.com/jlaurens/synctex/issues/44
I have some doubts pgf really has to use \immediate\pdfxform resources, imho simply \pdfxform resources should work too. So another solution could be to ask pgf to change that in the relevant driver files.


text:
Q: Kerberos authentication in macOS Sierra system settings Situation
We configured a macOS Sierra machine for Kerberos authentication by:

*

*Adding an appropriate /etc/krb5.conf for our organization

*Adding the following lines at the beginning of /etc/pam.d/authorization
auth optional pam_krb5.so use_first_pass use_kcminit default_principal
auth sufficient pam_krb5.so use_first_pass default_principal
We further configured the machine for LDAP directory usage by creating a custom LDAP binding in the directory services app:

*

*Users record maps to inetOrgPerson

*Attribute mappings:

*

*AuthenticationAuthority -> uid

*EMailAddress -> mail

*FirstName -> givenName

*NFSHomeDirectory -> #/Users/$uid$

*PhoneNumber -> telephoneNumber

*PrimaryGroupID -> gidNumber

*RealName  -> displayName

*RecordName -> uid

*UniqueID  -> uidNumber

*UserShell -> loginShell
This gives us a working network login that authenticates against Kerberos and LDAP.
Problem
When network users want to change their screen saver timeout, the user authentication in the system settings does not work. The user name is greyed out and the password is not accepted. There is no visible indication about the problem source in the log files.
When you use the unlock symbol (lower left corner) for the system settings, the (non-network) admin account is accepted, but the subsequent behavior remains the same.
Adding the lines above to /etc/pam.d/screensaver does not solve the problem.
Is there any /etc/pam.d configuration file that is responsible for the system settings authentication dialog in macOS Sierra?
Is there a way to get more logging information from PAM in macOS Sierra?

A: Not sure what this has to do with SSO?
The pam.d settings you have listed above allow the renewal of the kerberos ticket when unlocking the screensaver, that's it.
Do you have profiles installed that are stopping the change.
I applied a profile that requires the screen saver to start after 10 minutes of activity. Even if you unlock the preference panel you cannot make the change.
If your local admin cannot make the change it would probably be a security profile that has been set.
If you change or remove the profile and then the admin can change the screensaver then you should be good.


text:
Q: rotate large table ajax I have a very large table (that overflows the content div) and because it's dynamic it can contain at least 20 columns.
Anyway, the problem is that I'm obliged to put this table in a "tight" div.
And, the idea is to avoid the overflow and, to display elegantly all the columns so that it can rotate horizontally (a slide from left to right and possibly with "previous" and "forward" buttons).
Is there a ready script to help developping that?
Thank you very much,
Regards.

A: You could set it up so that it can be scrolled horizontally within the alloted div:
<div style="width: 100%; overflow-x: auto">
  <table> [ really wide table data ] </table>
</div>

This would result in the table to be contained in a horizontally scrollable div. It would only look good if the table is not taller vertically than the window height (that  is it can fit in the window vertically without needing to be scrolled)


text:
Q: Wildcard redirects on .htaccess I am trying to create some redirect rules with wildcards but it seens that is not working.
Redirect 301 ^/nl//producten/(.*)/(.*) https://www.mysite.eu/lighting/$1/$2
Redirect 301 ^/fr//producten/(.*)/(.*) https://www.mysite.eu/fr/lighting/$1/$2
Redirect 301 ^/de//producten/(.*)/(.*) https://www.mysite.eu/de/lighting/$1/$2
Redirect 301 ^/en//producten/(.*)/(.*) https://www.mysite.eu/en/lighting/$1/$2

i want to redirect all producten to lighting.
Any ideea why this is not working ?

A: Check this modified rules on the top of your .htaccess file
RewriteEngine on

RewriteRule ^nl\/\/producten\/(.*)\/(.*)$ https://www.mysite.eu/lighting/$1/$2  [R=301,L]
RewriteRule ^(.*)\/\/producten\/(.*)\/(.*)$ https://www.mysite.eu/$1/lighting/$2/$3   [R=301,L]


text:
Q: how to decorate the selenium WebDriver class? I want to add some functionality to the WebDriver class. I've tried to use the pattern decorator. I think it's the best in this situation for add functionalities to WebDriver class without change it.
This my code :
public abstract class DriverExtends extends RemoteWebDriver {

   protected Log logger = LogFactory.getLog(getClass());
   protected RemoteWebDriver rwd;
   protected final int SLEEP = 10;

   public DriverExtends(RemoteWebDriver driver) {
         rwd = driver;
   }

   /**
   * Determines whether an element is present on the page.
   * @param by The search item.
   * @param log if true, logs a message in the log in the absence of the element. False otherwise.
   * @return true if the element is present, false otherwise.
   */
   public boolean isElementPresent(By by, boolean log) {
         try{
                (new WebDriverWait(rwd, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(by));
                return true;
         } catch(NoSuchElementException e) {
                if(log) {
                       logger.warn("L'élément est absent : "+ e.getMessage());
                }
                return false;
         }
   }

   /**
   * Allows click on a submenu hide default.
   * @param by The link to click. Example (By.linkText ("Search"));
   */
   public void loadMenu(By by) {
         rwd.findElement(By.id("bouton_menu")).click();
         ((JavascriptExecutor)rwd).executeScript("$(\".menu2\").show()");
         rwd.findElement(by).click();
   }
}

FirefoxDriverExtends.class
public class FirefoxDriverExtends extends DriverExtends {

       public FirefoxDriverExtends (FirefoxDriver driver) {
             super(driver);
       }

}

My test case :
public class CreatePeople extends DefaultTestCaseWithParam<PersonLoaded> {

   @Override
   public boolean test(DriverExtends driver, PersonLoaded p) throws InterruptedException, TimeoutException {
         System.out.println("CreatePeople.test() - " + p);
         driver.loadMenu(By.linkText("Recherche"));
         (new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("idform:nom_input"))).sendKeys(p.getPrenom());
         driver.findElement(By.id("idform:datenaiss_input")).sendKeys(p.getDateNaiss());
         new Select(driver.findElement(By.id("idform:paysRR"))).selectByValue("Danemark");
         (new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.elementToBeClickable(By.id("idform:villeRR"))).sendKeys("COPENHAGUE");
         driver.findElement(By.id("idform:rechercherRes")).click();
         (new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("idform:creerRes"))).click();
         new Select((new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("People:selecGestio")))).selectByVisibleText("SELENIUM-UN SELENIUM");
         driver.findElement(By.id("People:adresse")).sendKeys("01 rue du test");
         driver.findElement(By.id("People:telT")).sendKeys("0102030405");
         new Select(driver.findElement(By.id("People:posS"))).selectByVisibleText("someText");
         new Select((new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("People:categAD")))).selectByVisibleText("someText");
         new Select(driver.findElement(By.id("People:autoEmploi"))).selectByVisibleText("Armée de l'air");
         new Select((new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("People:categP")))).selectByVisibleText("someText");
         new Select(driver.findElement(By.id("People:precMili"))).selectByVisibleText("De carrière");
         new Select((new WebDriverWait(driver, SLEEP)).until(ExpectedConditions.presenceOfElementLocated(By.id("People:categH")))).selectByVisibleText("someText");
         driver.findElement(By.id("id=People:date_debut-service_input")).click();
         driver.findElement(By.linkText("1")).click();
         return true;
   }
}

And this the error i get :
uild info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39'
System info: host: 'UCFC4DD43D730B', ip: '36.138.1.237', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_25'
Driver info: driver.version: RemoteWebDriver
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
Build info: version: '2.41.0', revision: '3192d8a6c4449dc285928ba024779344f5423c58', time: '2014-03-27 11:29:39'
System info: host: 'UCFC4DD43D730B', ip: '36.138.1.237', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_25'
Driver info: driver.version: RemoteWebDriver
       at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:589)
-Start of the timer for "Test 4 - selenium.tests.testsuites.TestSuitePeople.testCreatePeople"
09/04/2014 15:10:00 (DbUnit.java:173)  [INFO ]: Désactivation des contraintes
       at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:610)
       at org.openqa.selenium.remote.RemoteWebDriver.getScreenshotAs(RemoteWebDriver.java:320)
       at selenium.utils.jUnit.SeleniumTestWatcher.failed(SeleniumTestWatcher.java:68)
       at org.junit.rules.TestWatchman$1.evaluate(TestWatchman.java:51)
       at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
       at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
       at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
       at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
       at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
       at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
       at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
       at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
       at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
       at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
       at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
       at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
       at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
       at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
       at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
       at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
       at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
       at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException
       at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:568)
       ... 22 more

It's the first time i use the decorator pattern. So what i've missed? :)

A: i assume, the issue is with initialization of RemoteWebDriver. You cannot inject the firefox driver to RWD object rather specify the capabilities. Check this doc.

A: Ok, i've found how to do this. This is the solution. In decorator pattern you must map all method of decorated object with the decorator object.
First we can see that RemoteWebDriver.class is the super class of all webDriver objects. So to decorate RemoteWebDriver we must create class that implement all of RemoteWebDriver's interfaces.
public abstract class DriverCustom implements WebDriver, JavascriptExecutor,
FindsById, FindsByClassName, FindsByLinkText, FindsByName,
FindsByCssSelector, FindsByTagName, FindsByXPath,
HasInputDevices, HasCapabilities, TakesScreenshot {

    //Our decorated object
protected RemoteWebDriver rwd;

public DriverCustom(RemoteWebDriver driver) {
    rwd = driver;
}

// custom methods to add to the decorator. Must be public.

}

Next we need to implements this decorator with our browser implementation. Let's go with firefox example. In this class we need to map all methods to the corresponding FirefoxDriver class
public class FirefoxDriverCustom extends DriverCustom {

    // Add decorated object to decorator
public FirefoxDriverCustom(FirefoxDriver driver) {
    super(driver);
}

@Override
public void get(String url) {
    rwd.get(url);
}

@Override
public String getCurrentUrl() {
    return rwd.getCurrentUrl();
}

@Override
public String getTitle() {
    return rwd.getTitle();
}

@Override
public List<WebElement> findElements(By by) {
    return rwd.findElements(by);
}

@Override
public WebElement findElement(By by) {
    return rwd.findElement(by);
}

@Override
public String getPageSource() {
    return rwd.getPageSource();
}

@Override
public void close() {
    rwd.close();

}

@Override
public void quit() {
    rwd.close();

}

@Override
public Set<String> getWindowHandles() {
    return rwd.getWindowHandles();
}

@Override
public String getWindowHandle() {
    return rwd.getWindowHandle();
}

@Override
public TargetLocator switchTo() {
    return rwd.switchTo();
}

@Override
public Navigation navigate() {
    return rwd.navigate();
}

@Override
public Options manage() {
    return rwd.manage();
}

@Override
public Object executeScript(String script, Object... args) {
    return rwd.executeScript(script, args);
}

@Override
public Object executeAsyncScript(String script, Object... args) {
    return rwd.executeAsyncScript(script, args);
}

@Override
public WebElement findElementById(String using) {
    return rwd.findElementById(using);
}

@Override
public List<WebElement> findElementsById(String using) {
    return rwd.findElementsById(using);
}

@Override
public WebElement findElementByClassName(String using) {
    return rwd.findElementByClassName(using);
}

@Override
public List<WebElement> findElementsByClassName(String using) {
    return rwd.findElementsByClassName(using);
}

@Override
public WebElement findElementByLinkText(String using) {
    return rwd.findElementByLinkText(using);
}

@Override
public List<WebElement> findElementsByLinkText(String using) {
    return rwd.findElementsByLinkText(using);
}

@Override
public WebElement findElementByPartialLinkText(String using) {
    return rwd.findElementByPartialLinkText(using);
}

@Override
public List<WebElement> findElementsByPartialLinkText(String using) {
    return rwd.findElementsByPartialLinkText(using);
}

@Override
public WebElement findElementByName(String using) {
    return rwd.findElementByName(using);
}

@Override
public List<WebElement> findElementsByName(String using) {
    return findElementsByName(using);
}

@Override
public WebElement findElementByCssSelector(String using) {
    return rwd.findElementByCssSelector(using);
}

@Override
public List<WebElement> findElementsByCssSelector(String using) {
    return rwd.findElementsByCssSelector(using);
}

@Override
public WebElement findElementByTagName(String using) {
    return rwd.findElementByTagName(using);
}

@Override
public List<WebElement> findElementsByTagName(String using) {
    return rwd.findElementsByTagName(using);
}

@Override
public WebElement findElementByXPath(String using) {
    return rwd.findElementByXPath(using);
}

@Override
public List<WebElement> findElementsByXPath(String using) {
    return rwd.findElementsByXPath(using);
}

@Override
public Keyboard getKeyboard() {
    return rwd.getKeyboard();
}

@Override
public Mouse getMouse() {
    return rwd.getMouse();
}

@Override
public Capabilities getCapabilities() {
    return rwd.getCapabilities();
}

@Override
public <X> X getScreenshotAs(OutputType<X> target)
        throws WebDriverException {
    return rwd.getScreenshotAs(target);
}

// We can also add some specific firefox's methods to our decorator class.

}


text:
Q: AttributeError: module 'sqlalchemy' has no attribute '__all__' In my GitHub CI I get errors like the one below since today:
File "/home/runner/.local/lib/python3.8/site-packages/fb4/login_bp.py", line 12, in <module>
    from fb4.sqldb import db
  File "/home/runner/.local/lib/python3.8/site-packages/fb4/sqldb.py", line 8, in <module>
    db = SQLAlchemy()
  File "/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 758, in __init__
    _include_sqlalchemy(self, query_class)
  File "/home/runner/.local/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 112, in _include_sqlalchemy
    for key in module.__all__:
AttributeError: module 'sqlalchemy' has no attribute '__all__'

CRITICAL: Exiting due to uncaught exception <class 'ImportError'>

without being aware of any significant commit that might cause this.
My local tests and my Jenkins CI still work.
I changed the matrix to stick to python 3.8 instead of also trying 3.9, 3.10 and 3.11 also taking into account that a similar problem in python 3.9 AttributeError: module 'posix' has no attribute '__all__' was due to missing 3.9 support.
How can the above error could be debugged and mitigated?
My assumption is that the problem is in the setup/environment or some strange behaviour change of GitHub actions, Python, pip or the test environment or whatever.
I am a committer of the projects involved which are:

*

*https://github.com/WolfgangFahl/pyOnlineSpreadSheetEditing
and potentially

*https://github.com/WolfgangFahl/pyFlaskBootstrap4
Update:
After following the suggestions by @snakecharmerb the logs
Now show a version conflict
RROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
The conflict is caused by:
    The user requested Flask~=2.0.2
    bootstrap-flask 1.8.0 depends on Flask
    flask-dropzone 1.6.0 depends on Flask
    flask-login 0.6.2 depends on Flask>=1.0.4
    flask-httpauth 1.0.0 depends on Flask
    flask-sqlalchemy 3.0.2 depends on Flask>=2.2

Which is interesting since i am trying to avoid the ~ notation ... and indeed it was  a typo ... let's see whether the fix to upgrade Flask-SQLAlchemy>=3.0.2 works now.
I have accepted the answer after setting the version as suggested.
There are followup problems but the question is answered.

A: I have solved this problem by adding a specific version of SQLAlchemy to my requirement before flask-SQLAlchemy.  Example:
Flask==2.1.3
SQLAlchemy==1.4 (new one)
flask-restx==0.5.1

I noticed that pip was installing the 2.0 version

A: It seems the .__all__ attribute has been removed in the recently released SQLAlchemy 2.0.  You may need to pin the SQLAlchemy version in your config somehow. Or ensure that you are using Flask-SQLAlchemy 3.0.2 or later, as this issue suggests that version has the required fix.


text:
Q: Transistors basic question, Voltage is confusing me
you can't go sticking a voltage across the base-emitter terminals,
  because an enormous current will flow if the base is more positive
  than the emitter by more than about 0.6 to 0.8 volt.

Base being more positive, is it saying that base has more holes ? And what does it mean that base is 0.6 volt more positive ? It also says: Vb= Ve+Vbe, the concept of voltage is really bothering me here, is this equation saying the voltage needed across base for current to flow throught it is equal to voltage across emitter plus the voltage drop from base to emitter ? What does this even mean ? These are probably very dumb questions but I'm really frustrated because anything I have read for the past 10 hours won't explain it in a more basic way.

A: They're not dumb questions but the concept isn't too difficult to understand.
A few notes:

*

*The base emitter junction appears as a diode.

*In forward conduction at moderate currents about 0.7 V is dropped across the junction.

*The base current rises exponentially with the base-emitter voltage so we need to limit this applied voltage.

simulate this circuit – Schematic created using CircuitLab
Figure 1. Various NPN transistor arrangements.
In (a) there is no current limiter on the base. We can turn the transistor on by applying about half a volt or more to it but slight variations in voltage will cause large variations in the current through R1. This makes it very difficult to control. If the base voltage rises too much the transistor will be destroyed.
In (b) we have added a current limiting resistor to the base. Now we can apply, for example, 5 V to NODE1 and with a 1k resistor be sure that a maximum of almost 5 mA will flow into the base.
In (c) we can apply a voltage to NODE1 and current will flow into the base turning on the transistor. Current will flow through R3 causing a voltage drop across it and the emitter voltage will rise to about 0.7 V below that of NODE1.
(a) and (b) are common emitter mode as their emitters are connected to a fixed voltage. (c) is a common collector arrangement and is also called an "emitter follower" as the emitter voltage follows the base voltage (with the 0.7 V drop).
To answer your questions:

Base being more positive, is it saying that base has more holes?

No. And thinking of holes and electrons doesn't help much. Just think of voltages and currents.

And what does it mean that base is 0.6 volt more positive?

Explained above.

It also says: Vb = Ve+Vbe.

It's just saying that when you're calculating voltages at any point in the circuits above you can reckon that the base voltage will be 0.6 or 0.7 V above the emitter voltage (when current is flowing into the base).

Figure 2. Horowitz and Hill, The Art of Electronics. "Transistor Man" looks at the current at the base, and adjust the current at the collector so as to be a multiple of the base current.
The image of Figure 2 may help a little.

A: This can simply be reduced to your usual voltage/circuit analysis problem. There's no need to think about electrons/holes.
Rearranging the equation Vb = Ve + Vbe would be Vbe = Vb - Ve, which is your typical voltage equation and applies to almost anything, not just the base-emitter voltage of a transistor.
This equation tells you that the voltage difference between the base and emitter must equal the voltage at the base (in reference to ground) minus the voltage at the emitter (in reference to ground) Typically, Vbe in a BJT is a fixed voltage around 0.6V - 0.8V when operating in the forward active region (which is the usual assumption when first learning about BJT transistors)
For example, let's say that your emitter is directly connected to ground (Ve = 0V). Assuming the transistor is operating in the forward-active region, Vbe = 0.6V. Plugging into the voltage equation you have gives you Vb = 0.6

A:
you can't go sticking a voltage across the base-emitter terminals, because an enormous current will flow if the base is more positive than the emitter by more than about 0.6 to 0.8 volt.

The relation between \$I_C\$ and \$V_{BE}\$ is known as the Ebers-Moll equation, and is given \$I_C=I_S .e^{\frac{V_{BE}}{V_T}}.\$ In this equation \$I_S\$ is the saturation current of the particular transistor (e.g. for 2N3904 it's \$ \approx10^{-14}\$). \$V_{BE}\$ is the voltage across the base-emitter junction. For silicon BJTs this value is between \$0.6\$ to \$0.8\$ Volts but for germanium transistors it can be as low as \$0.3V\$. \$V_T\$ is given by \$\frac{k(T+273^{\circ}C)}{q}\$, where \$k\$ is the Boltzman's constant and q the electron charge. T is the temperature and is give in unit of Celsius. At room temperature it's about \$25mV\$ but it increases as temperature goes up.
According to the Ebers-Moll equation, \$V_{BE}\$ can be written \$ V_{BE}=V_T. \ln \frac{I_C}{I_S}\$. In this equation \$V_T\$ has a positive tempco but the stronger temperature dependence of \$I_S(T)\$, which appears in the denominator of the logarithmic term, almost dominates and causes an overall \$- \frac{2.1mV}{\ ^oC}\$ change in \$V_{BE}\$ (for a fixed collector current). This suggests that the base-emitter voltage \$V_{BE}\$ increases \$60mV\$ per decade of collector current, or the collector current doubles for each \$18mV\$ change in \$V_{BE}\$. The Ebers-Moll equation also suggests that at \$V_{BE}\$ fixed the collector current doubles for an \$8 ^oC\$ rise.
So a small change in \$V_{BE}\$ causes an enormous change in the collector current. This is why it says you can't stick a voltage across the base-emitter junction and be happy with that.


text:
Q: need idea on strtok function? hi friends am reading the data from the file and delimiting the value with the help of ','.
input file:
shankar,kumar,ooty
ravi,,cbe

code:
while ( fgets ( mem_buf, sizeof mem_buf, infile ) != NULL )
{
item = strtok(mem_buf,delims);
printf("1 val:%s",item);
item = strtok(NULL,delims);
printf("2 val:%s",item);
item = strtok(NULL,delims);
printf("3 val:%s",item);
}

for the above input file output like:
1:shankar 2:kumar 3:ooty
1:ravi 2:cbe 3:

but i need output like,
1:shankar 2:kumar 3:ooty
1:ravi 2: 3:cbe

because in the input file for the second row middle data is null? could you please help me on this?
i know this happens because no space between ,, in the second row of input file?please tell me any other alternative way? or i should for alter the input file before it read?

A: There's nothing stopping you from coding up your own strtok-like function:
#include <stdio.h>
#include <string.h>

static char *myStrTok (char *s, int c) {
    static char *nextS = NULL;  // Holds modified delimiter.
    static int done = 1;        // Flag to indicate all done.

    // Initial case.
    if (s != NULL) {
        // Return NULL for empty string.
        if (*s == '\0') { done = 1; return NULL; }

        // Find next delimiter.
        nextS = s;
        while ((*nextS != c) && (*nextS != '\0')) nextS++;
        done = (*nextS == '\0');
        *nextS = '\0';
        return s;
    }

    // Subsequent cases.
    if (done) return NULL;

    // Put delimiter back and find next one.
    *nextS++ = c;
    s = nextS;
    while ((*nextS != c) && (*nextS != '\0')) nextS++;
    done = (*nextS == '\0');
    *nextS = '\0';
    return s;
}

static int prt (char *s) {
    char *s2 = myStrTok (s, ','); printf ("1: [%s]\n", s2);
    s2 = myStrTok (NULL, ',');    printf ("2: [%s]\n", s2);
    s2 = myStrTok (NULL, ',');    printf ("3: [%s]\n", s2);
    s2 = myStrTok (NULL, ',');    if (s2 != NULL) printf ("4: [%s]\n", s2);
    printf ("==========\n");
}

int main (void) {
    char x[] = "shankar,kumar,ooty"; char y[] = "ravi,,cbe";
    prt (x); prt (y);
    printf ("[%s] [%s]\n", x, y);
    return 0;
}

This outputs:
1: [shankar]
2: [kumar]
3: [ooty]
==========
1: [ravi]
2: []
3: [cbe]
==========
[shankar,kumar,ooty] [ravi,,cbe]

as you desire. It only handles a single character for the separator but that appears to be adequate in this case.

A: From the manpage: "A  sequence  of  two  or  more  contiguous delimiter characters in the
       parsed string is considered to be a single delimiter.  Delimiter characters  at  the  start  or end of the string are ignored.  Put another
       way: the tokens returned by strtok() are always nonempty strings."
So if you must use strtok, you will have to modify the input first somehow.

A: You could check the length of each item to make sure it's not 0.
Better yet, combine this with looping each line (example) so that you're not limited to three values.

A: If strtok cannot do the job you want, you can code up your own parser, something along the lines of:
#include <stdio.h>
#include <string.h>

static int prt (char *s) {
    char *s2;
    s2 = strchr (s, ','); printf ("1: [%*.*s]\n", s2-s, s2-s, s); s = s2 + 1;
    s2 = strchr (s, ','); printf ("2: [%*.*s]\n", s2-s, s2-s, s); s = s2 + 1;
    printf ("3: [%s]\n", s);
    printf ("==========\n");
}

int main (void) {
    char x[] = "shankar,kumar,ooty"; char y[] = "ravi,,cbe";
    prt (x2); prt (y2);
    return 0;
}

That little sample shows you the difference between a strtok solution and a manual strchr solution, the output being:
1: [shankar]
2: [kumar]
3: [ooty]
==========
1: [ravi]
2: []
3: [cbe]
==========

You'll need to watch out for cases where you don't have enough delimiters (or too many) but that should be a minor modification.

A: Here's a technique that I shamelessly copied from Rob Pike:
void print_tokens(char *s)
{
    char *p, *last;

    last = s;

    for (p = strchr(s, ','); p; p=strchr(p+1, ',')){
            *p = 0;
            puts(last);
            *p = ',';
            last = p+1;
    }
    puts(last);
}

I didn't test the above code, so there may be some minor flaws. The main idea should be clear, though.


text:
Q: Highlight Current Page after Page Loads Help needed...I have this navigation bar

OVERVIEW

 DETAILS

QUESTIONS

REVIEWS

 <input type="submit" name="answer-save" id=" answer-save" value="Save" class="save-btn" style="width:100px;">

<input type="submit" name="answer-save1" id=" answer-save1" value="Save" class="save-btn" style="width:100px;">

There are quite a few submit buttons which saves the edited input of the page. Eg, change of name or adds a comment etc. When the page loads after saving/editing, the url changes. [ start?ertrer%sdsde%srerte becomes start?someother%^url but the page remains the same] How do I keep the class as current when the page loads ?
I had used this script but as the url changes when the page loads script is pointless now.
var url = window.location.href;
// passes on every "a" tag
$("#nav a").each(function() {
        // checks if its the same on the address bar
    if(url == (this.href)) {
        $(this).closest("li").addClass("current");
    }
});

Help ????

A: Modify your markup like so to include the query string value:

OVERVIEW

 DETAILS

Then add a line of script, something like this:
$(document).ready(function () {
    $("ul#menu li[data-qs=" + location.search.replace("?", "") + "]").addClass("current");
});


text:
Q: Is that possible to give admin access to normal user and restrict to edit profile? Our project is running on secured environment. So we add IP to profile to restrict access outside of the organization. Its strictly followed in production org. But when we give dev sandbox access to developer we give admin permission to them. Some people edit the IP of admin profile and try to access outside of the organization.
So we are thinking to give admin request but not to give permission on edit IP in profile. Will that possible. ?
i am trying to change the standard user to admin user by adding permission set and system permission in profile.
Any Idea or suggestion ?

A: Refer the documentation - Set Trusted IP Ranges for Your Organization.
As you cannot change permissions on Standard profile, Try cloning the required standard profile and disable appropriate permissions mentioned below.

*

*To view network access:

*

*Login Challenge Enabled

*To change network access:

*

*Manage IP Addresses
Note: One catch is, Restricted admins can still login as some other administrator and enable it back. To avoid that, disable login as for those users.


text:
Q: Use shared variables in charts My Crystal Report has 5 groups:

*

*DirectoryID

*RID

*QID

*GroupID

*FormID
I have few columns  QuestionType,IsMarkedasNA,OriginalScore,QuestionMaxScore,QuestionMinScore.

I have score calculation based on below formula at FormID Level.
SUM(OriginalScore) - SUM(QuestionMinScore) / SUM(QuestionMaxScore) - SUM(QuestionMinScore)

I need the Maximum, Minimum, Median, and Average of the scores for different formIDs at the GroupID level. Shared Variables calculate it accordingly. Subreport charts display these values.
One more Chart which at QID level needs to compare the Maximum scores of different GroupID levels. I can only get the last FormID Max(Value), but I need all the max(Value)s from all forms.


text:
Q: QwtPlotBarChart - how to get labels to match midpoint of bars I am using QwtPlotBarChart to draw a histogram. I have set the chart up so that there is zero spacing between bars, and my xBottom axis has the real range of the data.
Samples are set on the chart using a QVector of QPointF, with the x values corresponding to the midpoints of the bins.
A QwtPlotPicker hovering over the bars shows that they start and end at the actual start and ends of the bins.
However, I am having trouble getting the ticks where the labels are drawn to show up in the correct place along the x axis. I am using a custom scaledraw, similar to the distrowatch example. I have an additional couple of parameters, namely the minimum value of the data range, and the bin size. My label index code looks like this:
virtual QwtText label( double value ) const
{
    QwtText lbl;

    //const int index = qRound( value );
    const int index = (int)(value-_min_val)/_bin_size;
    if ( index >= 0 && index < d_labels.size() )
    {
        lbl = d_labels[ index ];
    }

    return lbl;
}

This seems to be ok; my labels show the min and max values of each bin and a nearly in the right place.
I have tried to set the tick positions as follows:
QwtScaleDiv div = _plot->axisScaleDiv(QwtPlot::xBottom);
div.setTicks(QwtScaleDiv::MajorTick, x_data.toList());
_plot->setAxisScaleDiv(QwtPlot::xBottom, div);

here x_data is the vector of bin midpoints used to plot the data. The axis range is set using:
double half_bin = bin_size / 2.0;
_plot->setAxisScale(QwtPlot::xBottom, x_data.first() - half_bin, x_data.last() + half_bin, bin_size);

Any ideas what I'm missing? Depending on the number of bins, the ticks (and subsequently the labels) will occasionally line up with the mid point of the bins (or at least most of them), but as I change the bin count, the ticks will become more or less offset from the center of the bin.


text:
Q: Looking for a query solution I need help with a query solution
table: roomclimate

id
time
deviceId
temperature
humidity

1
2021-12-22 15:49:31
1
23.5
50

2
2021-12-22 15:49:31
2
10.5
50

3
2021-12-22 15:59:31
1
23.5
56

4
2021-12-22 15:59:31
2
10.7
57

and now i want to group the values like this

time
dev_1_temp
dev_1_humi
dev_2_temp
dev_2_humi

2021-12-22 15:49:31
23.5
50
10.5
50

2021-12-22 15:59:31
23.5
56
10.7
57

A: So, this is working.. but is there an better Solution?
SELECT
    `time`,

    MAX(IF(`deviceId`=1,ROUND(`temperature`,1),NULL)) AS dev_1_temp,
    MAX(IF(`deviceId`=1,`humidity`,NULL)) AS dev_1_humi,
    MAX(IF(`deviceId`=2,ROUND(`temperature`,1),NULL)) AS dev_2_temp,
    MAX(IF(`deviceId`=2,`humidity`,NULL)) AS dev_2_humi

FROM tbl_klima
GROUP BY `time` DESC

A: Try this:
SELECT
    base.time,
    dev1.temperature, dev1.humidity,
    dev2.temperature, dev2.humidity
FROM roomclimate AS base
LEFT JOIN roomclimate AS dev1
    ON dev1.time = base.time AND dev1.deviceId = 1
LEFT JOIN roomclimate AS dev2
    ON dev2.time = base.time AND dev2.deviceId = 2
ORDER BY base.time DESC

I hope that you have an index on time.


text:
Q: Can not use session in model that is declared in controller I can not use session variable in model that I have declared in controler.
this is the code. I have declare this session in dataOperate controller.
 $this->session->set_userdata('newrecord','new');

I use above session in model dataOperateModel
if($this->session->userdata('newrecode')){
       echo $this->session->userdata('newrecode');

       }

But it prints nothing. I have loaded session in autoload CodeIgniter. I cleared all session and tried again. but no luck. but when I use print_r($this->session->all_userdata()); I can see newrecord session variable and other session variables. what has happend here.

A: You misspelled newrecord twice in your model. It says newrecode so if you copied this straight from your code editor you have found your problem.


text:
Q: JSX not rendering to DOM Nothing is being rendered to the DOM. It might be something to do with the multiple map loops though this is just a guess. Had a search around but couldn't find anything of use for my problem.
I have changed all forEach loops to map. I have console logged everything from each map and all outputs are correct. I have even tried with a simple "Hello, world!" using h1 tag but to no avail.
import React, { Fragment } from "react";
import { Query } from "react-apollo";
import { Link } from "react-router-dom";
import FilterWidget from "./FilterWidget";
import { Bar } from 'react-chartjs-2';
import ChartWidget from "./ChartWidget";
import "./ProjectsWidget.css";
import { BarChart } from 'react-easy-chart';
import getChartsData from '../../graphql/types/dashboards/getChartData'
import { VictoryChart, VictoryBar, VictoryTheme } from 'victory'

const ProjectWidget = (props) => {

    const projectName = props.match.params.ProjectName
    const dashboardName = props.match.params.dashboardName

    return (
        <Query query={getChartsData(projectName, dashboardName)}>
            {({ loading, error, data }) => {
                if (loading) return null;
                if (error) return `Error! ${error}`;
                return Object.values(data).map(element => {
                    console.log(element)
                    return element.map(item => {
                        console.log(item)
                        item.map(valueData => {
                            console.log(valueData)
                            return (

                                    <FilterWidget />

Time allocated outside of active sprint

                                            <VictoryChart theme={VictoryTheme.material} domainPadding={1}>
                                                <VictoryBar style={{ data: { fill: "#ff00aa" } }} data={valueData.Chart.data} />
                                            </VictoryChart>

                                    <Link to="/projects" className="btn btn-secondary">
                                        Back
                                    </Link>

                            );
                        })
                    })
                });
            }}
        </Query>
    );
}

export default ProjectWidget;

I expect all elements to be rendered to the DOM.

A: You have to change
return element.map(item => {
    console.log(item)
    item.map(valueData => {

to
return element.map(item => {
    console.log(item)
    return item.map(valueData => {


text:
Q: Additive primes The product of two integers is always an integer. However, the quotient of two integers is not always an integer. This simple fact leads directly to concepts such as "divisibility", "divisors" and "factors", and ultimately to the "prime numbers". Famously, every positive integer can be uniquely written as a product of prime factors. (Unique if you write the factors in ascending order, anyway.)
This whole structure results from the fact that not every quotient has a solution in the integers. If we consider the set of rational numbers instead, suddenly all these interesting properties disappear. (Unless we continue to treat the integers as a "special" subset of the rationals. If we treat all rationals equally, then every quotient is possible, and there's no special structure to see.)
The sum of two integers is always an integer. However, the difference of two integers is also always an integer. So here there is no analogue of the "prime numbers"; there is no unique way of writing an integer as a sum. For a positive integer $n$, there are $n+1$ different ordered pairs of integers who's sum is $n$. And if we allow negative integers, then for every $n$ there are infinity different sums that produce $n$, of an infinite range of lengths.
The rationals have no interesting prime structure, but if we restrict ourselves to just the integers, then such a structure appears. My question: Is there some subset of the integers that we can restrict ourselves to such that a similar structure appears for addition?

A: Yes, these are called Numerical Monoids, aka Numerical Semigroups. Here is a slide deck that, while having a bit of a silly title, contains a good undergraduate-level overview of them.
What is interesting, though, is that in most numerical monoids, factorization is not unique!  For example, if we consider the set $$M=\langle 2,3 \rangle := \{0,2,3,4,5,...\}=\{2m + 3n \,\vert\,m,n\in \mathbb{N}\cup\{0\}\}$$
Then 2 and 3 are both irreducible (in that they can't be "broken down" any more under addition), but we have $$2+2+2=3+3,$$ and hence two ways to write 6 as a sum of irreducible elements in $M$.
So, your question actually is a segue way into the factorization theory of (commutative, cancellative) monoids and integral domains; check out my other answer on the topic for a further description and links to resources.


text:
Q: How to dynamically add LinearLayout on Android? I have an array of length n, I now need to create n number of LinearLayouts and add different stuffs on each of them.
How can it be done dynamically?

A: LinearLayout lLayout = new LinearLayout(context);
parentWidget.addView(lLayout);

A: The easiest way is to create a layout in xml and inflate it using
LayoutInflater.from(context).inflate(R.layout.my_linear_layout);
You may also want to setId() your added views so you can access them easily later on.

A: I solved it using RelativeLayout which I found a little easier to work with. Yes of-course like the guys pointed out above I used setId(). Here is the code I implemented:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);

    //Parent RelativeLayout
    parentLayout = new RelativeLayout(this);
    parentLayout.setBackgroundColor(Color.WHITE);
    params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    parentLayout.setLayoutParams(params);
    sv.addView(parentLayout);

    final String[] comList = getCommunication();
    int listLength=0;
    try{
    listLength= comList.length/3;
    }catch(Exception e){System.out.println(e);System.exit(0);}

    childLayout= new RelativeLayout[listLength] ;
    TextView[] tvName  = new TextView[listLength];
    TextView[] tvDate  =new TextView[listLength];
    TextView[] tvMsg =new TextView[listLength];

    for(int i =0;i<listLength;i++){
        try{

        childLayout[i] = new RelativeLayout(this);
        childLayout[i].setPadding(5, 5, 5, 5);
        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 75);
        if(i==0){params.addRule(RelativeLayout.BELOW);}
        else{params.addRule(RelativeLayout.BELOW,i);}
        childLayout[i].setId(i+1);
        childLayout[i].setClickable(true);
        childLayout[i].setLayoutParams(params);
        childLayout[i].setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {

                //Create the intent
                  Intent i = new Intent("ACTIIVTY");
                   startActivity(i);
            }
        });

        tvName[i] = new TextView(this);
        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        tvName[i].setLayoutParams(params);
        childLayout[i].addView(tvName[i]);
        if(comList[i*3].length()>24){
            String name = comList[i*3].substring(0,24)+"...";
            tvName[i].setText(name);
        }else{
            tvName[i].setText(comList[i*3]);
        }
        tvName[i].setId(listLength+1+i);
        tvName[i].setTextSize(12);
        tvName[i].setTextColor(Color.BLACK);

        tvDate[i] = new TextView(this);
        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        tvDate[i].setLayoutParams(params);
        childLayout[i].addView(tvDate[i]);
        tvDate[i].setTextSize(11);
        tvDate[i].setTextColor(Color.BLUE);
        tvDate[i].setText(comList[i*3+1]);

        tvMsg[i] = new TextView(this);
        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, listLength+1+i);
        tvMsg[i].setLayoutParams(params);
        childLayout[i].addView(tvMsg[i]);
        tvMsg[i].setTextSize(11);
        tvMsg[i].setTextColor(Color.GRAY);
        if(comList[i*3+2].length()>96){
            String msg = comList[i*3+2].substring(0,96)+"...";
            tvMsg[i].setText(msg);
        }else{
            tvMsg[i].setText(comList[i*3+2]);
        }

        parentLayout.addView(childLayout[i]);

        }catch(Exception e){System.out.println("Errrorrrrr");}
    }

    setContentView(sv);
}


text:
Q: Bib sorting without author This is what one of my sources looks like
@misc{Madlena11,
Author={Chavala Madlena},
Publisher={Guardian},
Title = {Telecomix: tech support for the Arab spring},
url = {http://www.guardian.co.uk/technology/2011/jul/07/telecomix-arab-spring}
}

However, sometimes I have a source that doesn't have an Author such as:
@misc{RT12,
%Author={},
Publisher={RT TV Network},
Title = {Anti-ACTA day: Angry crowds take action},
url = {http://rt.com/news/acta-protests-rallies-europe-089/}
}

My problem is when the Author is not listed it doesn't sort by Publisher or even display the publisher in the references, nor the URL. How can I fix this?

A: Use the key field:
@misc{RT12,
key={some string reflecting how you wish the entry alphabetized},
Publisher={RT TV Network},
Title = {Anti-ACTA day: Angry crowds take action},
url = {http://rt.com/news/acta-protests-rallies-europe-089/}
}

Assuming you want the entry to be sorted as "RT TV Network", then use
key={RT TV Network}

The url field is used only if the bibliography style knows about it. For example, with
\usepackage[numeric]{natbib}
\bibliographystyle{plainnat}

then URLs are showed. And the contents of key will be used in place of the author.
Example
\begin{filecontents*}{\jobname.bib}
@misc{Madlena11,
Author={Chavala Madlena},
Publisher={Guardian},
Title = {Telecomix: tech support for the {Arab} spring},
url = {http://www.guardian.co.uk/technology/2011/jul/07/telecomix-arab-spring}
}

@misc{RT12,
key={aaaa},
Publisher={RT TV Network},
Title = {{Anti}-{ACTA} day: {Angry} crowds take action},
url = {http://rt.com/news/acta-protests-rallies-europe-089/}
}

\end{filecontents*}

\documentclass{article}

\usepackage[numbers]{natbib}
\usepackage{url}

\begin{document}
\cite{Madlena11}, \cite{RT12}

\bibliographystyle{plainnat}
\bibliography{\jobname}
\end{document}

The filecontents* is just for having the .bib file inside the source. Note also the braces to force capitalization.

A: Another option (especially if you don't like having the key field displayed at the beginning of your entry (or at all) or have to customize each bibliographic entry to use key instead of publisher) is to customize the BST file.  Since your provided code has natbib using plainnat, you can find plainnat.bst in your TeX repository and place a local copy with a different name (like plainnat-copy.bst) into your working directory.  There are four steps in modifying your local copy of plainnat-copy.bst:  First, update the misc function to account for your usage of publisher instead of howpublished.  Second, update the presort function to sort by publisher when there is no author.  Third, write the rule for how to sort by publisher.  Fourth, have your TeX file use your newly customized BST file.
Note:  I am using the 2007 version of plainnat.bst, which is the latest as of this posting in 2022.

*

*In your local copy of plainnat-copy.bst, search for the misc function and replace all instances of howpublished with publisher.  I show the new version here:

FUNCTION {misc}
{ output.bibitem
  format.authors output
  author format.key output
  title publisher new.block.checkb
  format.title output
  publisher new.block.checka
  publisher output
  format.date output
  format.issn output
  format.url output
  new.block
  note output
  fin.entry
  empty.misc.check
}

*Search for the presort function (starts with FUNCTION {presort}).  As you work here, note that the language in the BST file implements a postfix notation.  We'll focus just on this portion from the middle of the function:

        { type$ "manual" =
            'author.organization.sort
            'author.sort
          if$
        }

Perhaps you'll recognize that this is the innermost of a set of nested if statements that apply different sorting rules to different bibliographic entry types and that there is not yet a branch for the misc type.  By default, when the algorithm gets to this innermost if, the test type$ "manual" = returns false (because your entry is a misc not a manual) so the algorithm skips the next (first) option and applies the author.sort rule to all misc entries.  We'll modify this second option to insert the next deeper level in these nested if statements to establish a branch specific to misc entries.
        { type$ "manual" =
            'author.organization.sort
            { type$ "misc" =
              author empty$
              and
                'publisher.sort
                'author.sort
                if$
            }
          if$
        }

For anchoring, take note that the first two lines and the last two lines are the same in the original version and this modified version; I replaced only the middle line with the new code for the misc type.  The new logic is as follows:  If the entry is not a manual type, then the algorithm proceeds to the second line following, which is the next deeper level in the nested if statements.  Then it tests whether the type is misc and has no author; if both of these are true, then it will apply the publisher.sort rule (which we'll write in step 3 below); else it will apply the author.sort rule, so that all other entries are not affected by this change.

*For the publisher.sort function, paste the following code into your plainnat-copy.bst right above the presort function that you just modified so that this publisher.sort function is between editor.organization.sort and presort functions:

FUNCTION {publisher.sort}
{ publisher empty$
    { key empty$
        { "to sort, need author, publisher, or key in " cite$ * warning$
          ""
        }
        { key sortify }
      if$
    }
    { "The " #4 publisher chop.word sortify }
  if$
}

*In your TeX file, you'll need to change this line to account for your newly customized file:  \bibliographystyle{plainnat-copy}.  Here's the MWE:

\begin{filecontents*}{\jobname.bib}
@misc{Madlena11,
Author={Chavala Madlena},
Publisher={Guardian},
Title = {Telecomix: tech support for the {Arab} spring},
url = {http://www.guardian.co.uk/technology/2011/jul/07/telecomix-arab-spring}
}

@misc{RT12,
Publisher={RT TV Network},
Title = {{Anti}-{ACTA} day: {Angry} crowds take action},
url = {http://rt.com/news/acta-protests-rallies-europe-089/}
}

\end{filecontents*}

\documentclass{article}

\usepackage[numbers]{natbib}
\usepackage{url}

\begin{document}
\cite{Madlena11}, \cite{RT12}

\bibliographystyle{plainnat-copy}
\bibliography{\jobname}
\end{document}

Here's the output:


text:
Q: Xamarin Forms: How to parse an .epub file? I am using EpubReader.Cross NuGet Package for reading epub files. For this, I have added a sample .epub book file to my main project and set the Build Action to EmbedResource. As per the document I try to parse the title, author, and coverImage details like below. But details are not correct, please have a look at the below code.
My Code
string fileName = "content.epub";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{fileName}");
EpubBook epubBook = EpubReader.ReadBook(stream);
// Book's title
string title = epubBook.Title;
Debug.WriteLine("title:>>"+title);
// Book's authors (comma separated list)
string author = epubBook.Author;
Debug.WriteLine("author:>>" + author);
// Book's authors (list of authors names)
List<string> authors = epubBook.AuthorList;
Debug.WriteLine("authors:>>" + authors.Count);
// Book's cover image (null if there is no cover)
byte[] coverImage = epubBook.CoverImage;
Debug.WriteLine("coverImage:>>" + coverImage);

Output
[0:] title:>>be023aa39d417e1493850a0b9de6220c
[0:] author:>>Unknown
[0:] authors:>>1
[0:] coverImage:>>

I think the issue is with reading the .epub file added on the project. My .epub file generated by converting a .opf file, is that cause the issue?

A: In your case , the issue wasn't caused by your code or the plugin  .  An EPUB file is a digital ebook saved in the EPUB format, an open XML-based format for digital books and publications.
Some ePUB file doesn't contain the complete information when been created . You could firstly check it in your computer
In Windows , it can been opened by Adobe Digital Editions or Microsoft Edge .
In MacOS , it can been opened by Apple Pages or Apple Books .


text:
Q: Convert a Radio to a Select I've made my own FieldRenderer like this:
class BootstrapRadioFieldRenderer(ChoiceFieldRenderer):
    outer_html = '{content}'
    inner_html = '
{choice_value}{sub_widgets}
'
    choice_input_class = RadioChoiceInput

class BootstrapRadioSelect(RendererMixin, Select):
    renderer = BootstrapRadioFieldRenderer
    _empty_value = ''

As you can see it's based on RadioChoiceInput which outputs a Radio element. I'd like to change it to output a simple "Select" element. How to do this?
(Of course I've tried to change RadioChoiceInput by Select and I get __init__() takes at most 3 arguments (6 given))

A: I dont know what was wrong with me... because the answer was so simple.
I didnt have to touch my model. In all my forms I had things like this:
a = _(u'Statut:')
statut = forms.TypedChoiceField(
    label=a, required=False,
    choices=[(k, Personne.TAB_STATUT[k])
             for k in Personne.TAB_STATUT],
    widget=BootstrapRadioSelect(attrs={
        'title': a,
    }),
    error_messages=e)

I just had to change them: "back to classical":
statut = forms.CharField(
    label=a, required=False,
    widget=forms.Select(attrs={
        'title': a,
        'class': 'form-control'},
        choices=[(k, Personne.TAB_STATUT[k])
                 for k in Personne.TAB_STATUT],),
    error_messages=e)

And it worked like a charm.

A: The ChoiceFieldRenderer  is meant to be

An object used by RadioSelect to enable customization of radio widgets.

however, it does not seem to be useful for customizing a Select widget.
To do that, I suggest you subclass the Select widget and override it's render method, as described in docs.
Alternatively, if you really want to, you can probably define your own SelectRenderer which would in turn iterate over self.choices of the widget and render them as you intend.
This would be useful if you need more flexibility when defining other subclasses of the widget (where only rendering is modified); I can image other Django users would also benefit of such generic "rendering customization", so feel free to discuss this feature in the django-developers mailing list.


text:
Q: Using PasswordResetForm in Django My problem is: when I submit the form it falls into the else: block below that I have defined in my view.
What I'm trying to accomplish: allow a user to reset their password using the django 1.5 built in PasswordResetForm functionality in django auth
Views.py
def UserResetPassword(request):
    form = UserForgotPasswordForm(None, request.POST)
    if request.method == 'POST':
        if form.is_valid():
            form.save(from_email='admin@thedomain.com',email_template_name='mysite/reuse/forgotpassword.html', use_https=False,token_generator=default_token_generator, html_email_template_name=None)
        else:
            return HttpResponse("Are you sure you entered that correctly?")

    return render(request, 'mysite/reuse/forgotpassword.html', {
        'form':form
    })

Upon submitting the form it outputs: Are you sure you entered that correctly? (e.g. the value being sent from the else: condition
What am I doing wrong here?

A: I see a couple of issues:
def UserResetPassword(request):
    form = UserForgotPasswordForm(request.POST or None) #data=is request.POST or None
    if request.method == 'POST':
        if form.is_valid():
            form.save(from_email = 'admin@thedomain.com', email_template_name= 'mysite/reuse/forgotpassword.html', use_https = False, token_generator = default_token_generator, html_email_template_name=None)

    return render(request, 'mysite/reuse/forgotpassword.html', {
        'form':form
    })

Also, get rid of the else part. You want to be able to see what the error is. render() would show the errors.
In the forms,
fields = ("email")

should be
fields = ("email", )

Also, you should be using PasswordChangeForm if you want a form that lets a user change his/her password by entering their old password.


text:
Q: Error, Higher Kinded types Scala: type arguments do not conform. type T's bounds are stricter than type T's declared bounds Here is a simple experiment in Scala REPL:
scala> trait A; trait B extends A; trait C extends B
defined trait A
defined trait B
defined trait C

scala> trait TC[T]
defined trait TC

scala> trait TC2[T <: B]
defined trait TC2

scala> class Test[TC[T]]
warning: there was one feature warning; re-run with -feature for details
defined class Test

scala> new Test[TC]
res1: Test[TC] = Test@6f195bc3

scala> new Test[TC2]

<console>:11: error: kinds of the type arguments (TC2) do not conform to the expected kinds of the type parameters (type TC) in class Test.
TC2's type parameters do not match type TC's expected parameters:
type T (in trait TC2)'s bounds <: B are stricter than type T's declared bounds >: Nothing <: Any
       val res2 =
           ^
<console>:12: error: kinds of the type arguments (TC2) do not conform to the expected kinds of the type parameters (type TC) in class Test.
TC2's type parameters do not match type TC's expected parameters:
type T (in trait TC2)'s bounds <: B are stricter than type T's declared bounds >: Nothing <: Any
              new Test[TC2]
                  ^

Question 1:
How can these error messages be explained based on the Scala Language Specification ?
In other words, which sections of the SLS explain these error messages ?
Question 2:, how can these error messages be explained in simple terms (not based on SLS) ?
Phrasing the previous question in the compiler's words:
why is it a problem that TC2's type parameters do not match type TC's expected parameters, i.e. type T (in trait TC2)'s bounds <: B are stricter than type T's declared bounds >: Nothing ?
Is there any book or article where the reasoning behind this error message is explained ?
Perhaps somewhere in Pierce's TAPL book ?

A: As I note in a comment above, the TC in the type parameter list of Test (and in the error message) is not the TC that you defined a couple of lines earlier—it's a new type constructor parameter that shadows the trait TC.
(As a side note, I'd strongly suggest not shadowing type parameters. Shadowing variables at the value level can be confusing enough, but shadowing type parameters is almost always a recipe for confusion.)
Type constructor parameters are discussed in section 4.4 of the spec. From that section:

A type constructor parameter adds a nested type parameter clause to
  the type parameter... The above scoping restrictions are generalized
  to the case of nested type parameter clauses, which declare
  higher-order type parameters. Higher-order type parameters (the type
  parameters of a type parameter t) are only visible in their
  immediately surrounding parameter clause (possibly including clauses
  at a deeper nesting level) and in the bounds of t.

Your T here is one of these higher-order type parameters. It can be bounded (like any other type parameter), but it's not. This is what causes the error: you're trying to provide a type constructor that constrains its type parameter (TC2) as the value of a type constructor parameter that doesn't share the constraint (that in fact doesn't have any constraints at all).
To get an intuitive sense of why this is a problem, consider the following trait:
trait Foo[X[_]] {
  def create[A]: X[A]
}

This is a perfectly reasonable thing to write—I could create an instance for example like this:
object ListFoo extends Foo[List] {
  def create[A]: List[A] = Nil
}

Now suppose I have a type constructor with a constraint:
trait MyIntOptionThingy[A <: Option[Int]]

The compiler prohibits me from instantiating a Foo[MyIntOptionThingy] because the type parameter of MyIntOptionThingy is constrained more strictly than the type parameter of the X in Foo's type parameter list. If you think about it this makes sense: how would I be able to define create for any A, when the only As that would work for MyIntOptionThingy are Some[Int], None.type, and Option[Int]?

A: For the sake of completeness I cite some possibly relevant parts of SLS:

About conformance of type constructors from SLS 3.5.2 :


text:
Q: Sending a data from tabhost child activity to parent activity I want to pass the data from child activity to parent activity in a tabhost and fire an onclick event for a button from tabHost parent activity
As a result I could send the data from parent activity (data from TabActivity1+ data from TabActivity2) to some new activity.

Schematically i have represented the scenario below::

How to achieve this ??

A: To call any method from the parent activity use this code:
((PARENT_CLASS_NAME)getParent()).METHOD_NAME();

Hope this is what you want!


text:
Q: Took a practice technical interview online,,, what am I missing? I am preparing for interviewing for jobs soon, and took a practice technical test. I did pretty well on the problems, except for this one...
The premise of the problem is this: Given an array, find the maximum difference for sequential subsets of the array of size "n". Example
input = [6,8,4,5,3,1,7], n=3
[6,8,4] = the biggest diff = 4 (8-4)
[8,4,5] = the biggest diff = 4 (8-4)
[4,5,3] = 2
[5,3,1] = 4
[3,1,7] = 6
Final return from function:6

The limits of inputs were something like :the length of array will be less than 100k, n will be less than the length of array. The function must finish within 2 seconds.
I initially wrote this in python, but only received 3/6 correct test cases, 3 failed due to time limits, so I rewrote in C hoping for better performance.
int i,j;
int maxdiff = 0;
int localmax,localmin,localdiff;
for (i=0;i<v_length-d+1;i++){
    localmax = v[i];
    localmin = v[i];
    localdiff = 0;
    for(j=0;j<d;j++){
        if(v[j+i] > localmax){
            localmax = v[j+i];
        }
        if(v[j+i] < localmin){
            localmin = v[j+i];
        }
    }
    localdiff = localmax-localmin;
    if(localdiff > maxdiff){
        maxdiff = localdiff;
    }
}
return maxdiff;

I tried running this, but to the same results. 3/6 correct, 3/6 failed due to runtime.
Am I missing something here? I realize that I loop over each value in the array ArraySize-n times, I can somehow visualize in my mind that it is possible to loop through the array only once, but cannot seem to figure out how.
Any advice?
Thanks!

A: you can do this in O(nlogn) using one min heap and one max heap for the subset.
during traversing the array remove fist element from heaps and add new element

A: The easiest way to solve questions involving sequential subsequences of a long input sequence is to use a (single-ended) queue, at least conceptually. (In the case where the input is a vector, rather than a stream, it's not actually necessary to store the queue, but the algorithm is often clearer if the queue is made explicit.)
In this case, the solution requires finding the largest difference between the max and the min of the queue. If we want an O(1) solution, we need a queue for which the operations push_back, pop_front, min and max are all O(1).
The first thing to note is that if we were looking for a stack with that property (where pop_front is replaced with pop_back), the solution is trivial: whenever we push a new value, we compute the new min and max, and push them along with the new value. When we pop a value, we also pop the associated min and max, and the min and max remaining on the top of the stack are again correct.
How do we translate that to a queue? The answer is that we need to implement the queue using a stack. Or more accurately, using two stacks. This is the so-called "banker's queue", which provides an amortized O(1) (functional) queue using two (functional) stacks.
It's a simple trick: one of the stacks -- the front stack -- is used for pushing, and the other stack -- the back stack -- is used for popping. The front of the queue is kept in the front stack, and the back of the queue is kept in reverse order on the back stack, so that the top of the back stack is the first element in the queue. This works fine until the back stack is empty and we need to pop the first element. At that point, we simply pop the elements from the front stack one at a time, and push each one onto the back stack. Once we've done that, the front stack is empty, and the top of the back stack is what was the last element in the front stack, which was the first element of the queue, as desired.
It's clear that the above implementation is amortized O(1) because every element is pushed once onto each stack (and popped once from each stack). It's not actually O(1) on each operation, of course: every once in a while a pop_front will take quite a long time. But the average always works out right. (Pushes, on the other hand, are always O(1).)
So we can make a min-max queue out of two min-max stacks, and the use that to solve the maximum range problem.
With that outline, it's easy to find some optimizations. First, we can store both stacks in the same array, and if we store the back stack backwards and contiguous with the front stack, then we only need to keep track of the position of the boundary between the two stacks, and the operation of popping the front stack and pushing that value onto the back stack consists of simply moving the boundary pointer. (In the case of min-max stacks, we need to compute the mins and maxes, though.) That leads to a simple circular buffer implementation, which is a common queue solution.
Furthermore, in the case of a moving window, the size of the queue is known, so we don't have to deal with dynamic resizing. And, in the case that the input is a vector, we don't need to actually push elements onto the front stack, since the elements are at a known place in the input and we don't need the stack min/max values in the front stack.
I hope all that is sufficient to explain this C++ implementation:
#include <algorithm>
#include <vector>

using std::min;
using std::max;

struct minmax { int min; int max; };

int maxrange(const std::vector<int>& v, int n) {
  int sz = v.size();
  n = min(n, sz);
  if (n <= 1) return 0;
  // The stack only needs n - 2 elements. So this could be adjusted.
  minmax* stack = new minmax[n];
  int loback, hiback, lofront, hifront;
  int maxrange = 0;
  for (int s = n - 1, m = 0; s < sz; ++s, --m) {
    if (m == 0) {
      lofront = hifront = v[s];
      loback = hiback = v[s - 1];
      for (int i = 2; i < n; ++i) {
        stack[i - 2] = minmax{loback, hiback};
        loback = min(loback, v[s - i]);
        hiback = max(hiback, v[s - i]);
      }
      m = n - 1;
    } else {
      lofront = min(lofront, v[s]);
      hifront = max(hifront, v[s]);
      loback = stack[m-1].min;
      hiback = stack[m-1].max;
    }
    maxrange = max(maxrange, max(hifront, hiback) - min(lofront, loback));
  }
  delete[] stack;
  return maxrange;
}

A: Input:
int inp[]={...},n=...;

*

*create int index array for the input
const int N=sizeof(inp)/sizeof(inp[0]);
int ix[N];
for (int i=0;i<N;i++) ix[i]=i;

*index sort inp[N] in ix[N] ascending (keep inp[N] unchanged)

*

*so for any i={0,1,2,...,N-2} is (inp[ix[i]]<=inp[ix[i+1]])==true

*this can be done in O(N*log(N))

*now any subset of size 1<n<=N starting from int i0=0,1,2,...N-n is done like this:
int i1=i0+n-1; // valid indexes for subset are i0<=i<=i1;
int min=0,max=0;
for (i=  0;i< N;i++) if ((ix[i]>=i0)&&(ix[i]<=i1)) { min=inp[ix[i]]; break; }
for (i=N-1;i>=0;i--) if ((ix[i]>=i0)&&(ix[i]<=i1)) { max=inp[ix[i]]; break; }
int diff=max-min;

*cycle bullet 3 through all locations

*

*and find the max diff ...

[notes]

*

*this is faster for bigger n but slower for smaller n

*so the best would be to use your approach and this according to n size treshold


text:
Q: Managing storage for Virtual Machines in Red Hat Enterprise Virtualization (RHEV) I am using RHEV and I have created two virtual machines. These have too little disk space, how can I edit the disk space of these machines? I cannot find the option anywhere.

A: You can create new volumes of desired capacity and simply attach them to VM through RHEV Manager WebUI.


text:
Q: java.lang.ClassNotFoundException: Didn't find class after update library After I change the Google Play Service Liblibrary my application can't run.
When I start it's appear error like this and I tried to fix by google it but still can't fix.
Anybody can explain me on the log bellow:
06-10 20:45:13.116: E/AndroidRuntime(18582): FATAL EXCEPTION: main
06-10 20:45:13.116: E/AndroidRuntime(18582): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kidsgame.kidsmath/com.kidsgame.kidsmath.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.kidsgame.kidsmath.MainActivity" on path: /data/app/com.kidsgame.kidsmath-2.apk
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2171)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread.access$700(ActivityThread.java:150)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.os.Looper.loop(Looper.java:137)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread.main(ActivityThread.java:5283)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at java.lang.reflect.Method.invokeNative(Native Method)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at java.lang.reflect.Method.invoke(Method.java:511)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at dalvik.system.NativeStart.main(Native Method)
06-10 20:45:13.116: E/AndroidRuntime(18582): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.kidsgame.kidsmath.MainActivity" on path: /data/app/com.kidsgame.kidsmath-2.apk
06-10 20:45:13.116: E/AndroidRuntime(18582):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.Instrumentation.newActivity(Instrumentation.java:1071)
06-10 20:45:13.116: E/AndroidRuntime(18582):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
06-10 20:45:13.116: E/AndroidRuntime(18582):    ... 11 more

A: Try going to Project -> Properties -> Java Build Path -> Order & Export and ensure Android Private Libraries are checked for your project and for all other library projects you are using. Clean all projects afterwards and see what happens. Taken from here.

A: At this line:
06-10 20:45:13.116: E/AndroidRuntime(18582): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.kidsgame.kidsmath.MainActivity" on path: /data/app/com.kidsgame.kidsmath-2.apk

It looks like you've moved the file location of your mainactivity.java or aren't importing a class you need. Try going to your class file and hitting ctrl+shift+o to import anything you are missing, then clean the project


text:
Q: solving Can't open perl script "all_gen_cmf_image": No such file or directory error i work on image copy move forgery detection field. i downloaded GRIP dataset form https://www.grip.unina.it/, there is some modification needed for the images and can be done with perl functions downloaded with the dataset. it is the first time for me to work with .pl functions. i downloaded the program form this website  https://platform.activestate.com/create-project?language=perl, and followed the setup steps.
now i have two problems: the first one, when i tried to run the function this error appeared "Can't open perl script "all_gen_cmf_image": No such file or directory", i have added the scripts directory using cd.
the second problem i don't know what he mean with this line "update the "vole" variable in the configuration file db_configs.pl, it should point to your vole binary of CMFD framework." in reedme file.
can any one helping me solving this problem?

A: Perl doesn't automatically try the .pl extension when you pass it the name of a script on the command line.[1] So, it fails because there isn't a script named "all_gen_cmf_image"; it's actually named "all_gen_cmf_image.pl". To run all_gen_cmf_image.pl you have to include the .pl part of the extension. Assuming you are in the scripts folder, the following should work:
perl all_gen_cmf_image.pl

or in the parent directory:
perl scripts/all_gen_cmf_image.pl

*

*However, when Perl runs a use Module; statement, perl automatically adds .pm on the end and replaces any :: in the module name with a slash.