text:
Q: sendmail - sendmail using relay (Why it doesn't work?) I am trying to configure configure sendmail to use a relay. I've tried several procedures, but I don't know why it doesn't work since the same relay is used by other services and it works.
Below is the installation procedure I am using.
What can I do to diagnose what happens? What could be wrong?
Thanks!

Installation and configuration
Run the following to update and install...
yum -y update
yum -y install sendmail-cf
yum -y install m4
yum -y install cyrus-sasl-plain

Create directory for storing authentication files...
mkdir /etc/mail/authinfo
chmod 700 /etc/mail/authinfo

Create a auth file...
TIP: The file may have any name like "smtp-auth".
read -r -d '' FILE_CONTENT << 'HEREDOC'
BEGIN
AuthInfo:smtp.my_domain.com.br "U:root" "I:my_user@my_domain.com.br" "P:my_password"

END
HEREDOC
echo -n "${FILE_CONTENT:6:-3}" > "/etc/mail/authinfo/smtp-auth"

Create a hash map file of above created auth file...
enter code heremakemap hash /etc/mail/authinfo/smtp-auth < /etc/mail/authinfo/smtp-auth
Configure Sendmail with SMART_HOST...
Add following configuration lines into your "sendmail.mc" configuration file immediately before "MAILER(smtp)dnl" line...
vi /etc/mail/sendmail.mc

Content...
define(`SMART_HOST', `smtp.my_domain.com.br')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo', `hash -o /etc/mail/authinfo/smtp-auth.db')dnl
MASQUERADE_AS(my_domain.com.br)dnl
FEATURE(masquerade_envelope)dnl
FEATURE(masquerade_entire_domain)dnl
MASQUERADE_DOMAIN(my_domain.com.br)dnl

Re-build sendmail's configuration...
make -C /etc/mail

Enable and start the sendmail service...
systemctl enable sendmail.service
systemctl restart sendmail.service

Test and output
[root@localhost ~]# read -r -d '' EMAIL_CONTENT << 'HEREDOC'
> BEGIN
> From: my_user@my_domain.com.br
> To: recipient@recipient_domain.com
> Subject: Fail2ban test
>
> Fail2ban test
>
> END
> HEREDOC
[root@localhost ~]# echo -n "${EMAIL_CONTENT:6:-3}" | sendmail -Am -d60.5 -v recipient@recipient_domain.com
map_lookup(dequote, root, %0=root) => NOT FOUND (0)
map_lookup(host, recipient_app.com, %0=recipient_app.com) => recipient_app.com. (0)
map_lookup(mailertable, recipient_app.com, %0=recipient_app.com) => NOT FOUND (0)
map_lookup(mailertable, .com, %0=.com, %1=recipient_app, %2=recipient_app) => NOT FOUND (0)
map_lookup(mailertable, ., %0=., %1=recipient_app.com) => NOT FOUND (0)
recipient@recipient_domain.com... Connecting to smtp.my_domain.com.br port 587 via relay...
220 a2-smithers5.uhserver.com ESMTP
>>> EHLO localhost.localdomain
250-a2-smithers5.uhserver.com
250-PIPELINING
250-SIZE 41943040
250-VRFY
250-ETRN
250-AUTH LOGIN PLAIN LOGIN PLAIN
250-AUTH=LOGIN PLAIN LOGIN PLAIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
map_lookup(macro, {TLS_Name}, %0={TLS_Name}, %1=smtp.my_domain.com.br) =>  (0)
map_lookup(access, TLS_Srv:smtp.my_domain.com.br, %0=TLS_Srv:smtp.my_domain.com.br) => NOT FOUND (0)
map_lookup(access, TLS_Srv:my_domain.com.br, %0=TLS_Srv:my_domain.com.br) => NOT FOUND (0)
map_lookup(access, TLS_Srv:com.br, %0=TLS_Srv:com.br) => NOT FOUND (0)
map_lookup(access, TLS_Srv:br, %0=TLS_Srv:br) => NOT FOUND (0)
map_lookup(access, TLS_Srv:200.147.36.31, %0=TLS_Srv:200.147.36.31) => NOT FOUND (0)
map_lookup(access, TLS_Srv:200.147.36, %0=TLS_Srv:200.147.36) => NOT FOUND (0)
map_lookup(access, TLS_Srv:200.147, %0=TLS_Srv:200.147) => NOT FOUND (0)
map_lookup(access, TLS_Srv:200, %0=TLS_Srv:200) => NOT FOUND (0)
map_lookup(access, TLS_Srv:, %0=TLS_Srv:) => NOT FOUND (0)
map_lookup(authinfo, AuthInfo:smtp.my_domain.com.br, %0=AuthInfo:smtp.my_domain.com.br) => NOT FOUND (0)
map_lookup(authinfo, AuthInfo:200.147.36.31, %0=AuthInfo:200.147.36.31) => NOT FOUND (0)
map_lookup(authinfo, AuthInfo:, %0=AuthInfo:) => "U:my_user@my_domain.com.br" "I:my_user@my_domain.com.br" "P:brlight2012" "M:PLAIN" (0)
>>> AUTH PLAIN YWRtaW5AbGlnaHRiYXNlLmNvbS5icgBhZG1pbkBsaWdodGJhc2UuY29tLmJyAGJybGlnaHQyMDEy
235 2.7.0 Authentication successful
>>> MAIL From:<root@localhost.localdomain> SIZE=97 AUTH=root@localhost.localdomain
550 5.7.1 Envio nao autorizado - Verifique o MX e/ou SPF do seu dominio
map_lookup(dequote, root, %0=root) => NOT FOUND (0)
map_lookup(dequote, root, %0=root) => NOT FOUND (0)
map_lookup(dequote, MAILER-DAEMON, %0=MAILER-DAEMON) => NOT FOUND (0)
map_lookup(host, my_domain.com.br, %0=my_domain.com.br) => my_domain.com.br. (0)
map_lookup(host, recipient_app.com, %0=recipient_app.com) => recipient_app.com. (0)
root... Connecting to local...
root... Sent
Closing connection to smtp.my_domain.com.br
>>> QUIT

NOTE: The "my_user@my_domain.com.br" account is able to send email to the "recipient@recipient_domain.com" account from its webmail.
ERROR: "550 5.7.1 Envio nao autorizado - Verifique o MX e/ou SPF do seu dominio" (portuguese)/"550 5.7.1 Unauthorized sending - Check your domain's MX and/or SPF" (english).

A: *

*mc files expects `x' quotes [fixed in revised version of the question]

*
*

*You have deployed standard recommendation to forbid sending "plain text" (unencrypted) password over unencrypted SMTP connections [p flag in confAUTH_OPTIONS].

*Your smart host offers only plaintext authentication [see AUTH lines in EHLO reply] but it does not offer upgrading to encrypted connection [no STARTTLS in  EHLO reply].

*Effectively your configuration forbids to send unencrypted password over unencrypted SMTP connection but your smart host offers no other option.

A: The error...

"550 5.7.1 Envio nao autorizado - Verifique o MX e/ou SPF do seu
  dominio" (portuguese)/"550 5.7.1 Unauthorized sending - Check your
  domain's MX and/or SPF" (english)

... happens because the SMTP service in use by us requires that the "envelope sender" be the same as the effective "sender".
To address this issue we need to build a genericstable database to map the input sender address to the desired address.
In our case, create the file "/etc/mail/genericstable" with the entry root           my_user@my_domain.com.br and add the entry FEATURE(genericstable',hash -o /etc/mail/genericstable.db')dnl in the "/etc/mail/sendmail.mc" file.
For a better understanding, below is the complete procedure.

Sendmail - Installation and configuration
Run the following to update and install dependencies...
yum -y update
yum -y install sendmail-cf
yum -y install m4
yum -y install cyrus-sasl-plain

Create an auth file...
read -r -d '' FILE_CONTENT << 'HEREDOC'
BEGIN
AuthInfo:smtp.my_domain.com.br "U:root" "I:my_user@my_domain.com.br" "P:my_password"

END
HEREDOC
echo -n "${FILE_CONTENT:6:-3}" > "/etc/mail/authinfo"

Building a "genericstable" database to map the input sender address to the desired address ("envelope sender").
Create the "genericstable" file...
read -r -d '' FILE_CONTENT << 'HEREDOC'
BEGIN
root           my_user@my_domain.com.br

END
HEREDOC
echo -n "${FILE_CONTENT:6:-3}" > "/etc/mail/genericstable"

Configure Sendmail with "SMART_HOST".
Add following configuration lines into your "sendmail.mc" configuration file immediately before "MAILER(smtp)dnl" line...
vi /etc/mail/sendmail.mc

Content...
define(`SMART_HOST', `smtp.my_domain.com.br')dnl
define(`RELAY_MAILER_ARGS', `TCP $h 587')dnl
define(`ESMTP_MAILER_ARGS', `TCP $h 587')dnl
define(`confAUTH_OPTIONS', `A p')dnl
TRUST_AUTH_MECH(`EXTERNAL DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo', `hash -o /etc/mail/authinfo/smtp-auth.db')dnl
MASQUERADE_AS(my_domain.com.br)dnl
FEATURE(masquerade_envelope)dnl
FEATURE(masquerade_entire_domain)dnl
MASQUERADE_DOMAIN(my_domain.com.br)dnl
FEATURE(`genericstable',`hash -o /etc/mail/genericstable.db')dnl

Re-build sendmail's configuration...
make -C /etc/mail

Enable and start the sendmail service...
systemctl enable sendmail.service
systemctl restart sendmail.service

Test your configuration
read -r -d '' EMAIL_CONTENT << 'HEREDOC'
BEGIN
From: my_user@my_domain.com.br
To: recipient@recipient_domain.com
Subject: Fail2ban test

Fail2ban test

END
HEREDOC
echo -n "${EMAIL_CONTENT:6:-3}" | sendmail -Am -d60.5 -v recipient@recipient_domain.com

[Refs.: http://blog.achinthagunasekara.com/2015/08/how-to-configure-sendmail-to-work-with.html , https://access.redhat.com/discussions/2959431 , https://docs.cloud.oracle.com/iaas/Content/Email/Reference/sendmail.htm , https://serverfault.com/a/574118/276753 , https://serverfault.com/a/839476/276753 , https://superuser.com/a/1448009/195840 , https://tecadmin.net/sendmail-to-relay-emails-through-gmail-stmp/ , https://www.bonusbits.com/wiki/HowTo:Configure_SendMail_to_Use_SMTP_Relay , https://www.sitepoint.com/community/t/email-mx-records-vs-spf-records/7947 ]

Further question/Plus: Why use Sendmail with relay?

The biggest problem with sendmail is that a lot of spammers like to
  use it to blast out emails without needing a domain name, so it gets
  rejected frequently. If you have a SMTP you can relay through that
  will help matters a bit.

[Ref.:  https://support.nagios.com/forum/viewtopic.php?f=7&t=28246 ]


text:
Q: Jquery slide from right I have this box i want to bump or slide in from the right.
How do i do this?
My code is:
$(window).load(function(){
    setTimeout(function(){
       $('.popin-window').delay(1000).fadeIn(2000);
    });
});

I need the delay

A: Here you just use, fade action, so the block just appears, if you want it to slide from the right, try this:
Into your css file, do this:
.popin-window {
    position: absolute;
    right: -250 /* right value */
}

And your javascript will be like this:
$(window).load(function(){
    setTimeout(function(){
       $('.popin-window').delay(1000).animate({right: 0}, 2000);
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: rails datetime in separate fields I may have over-complicated what I need to do but this is what I now have.
I have a jobs controller that has 2 fields
starts_at as DATETIME
end_time as DATETIME

I save the event_date in a form using a
calendar_date_select :starts_at ,:time => false

I save the date time as
time_select :starts_at, {:twelve_hour => true}

This saves the Event date i.e 12/26/2009  and the start time as 7:00 pm
I need to also save the event end_time without having to re-enter the date, just the time
time_select :end_time, {:twelve_hour => true}

If i just use the above, the time is correct but the date dafaults to 01/01/2000
How do I save the date with the same date from starts_at?

A: In your controller, if the :end_time is nil, set it to the :starts_at variable like so:
object.end_time = object.starts_at unless not object.end_time.nil?

You may be able to shorten the end to
object.end_time = object.starts_at unless object.end_time.present?

but I'm not sure which version of Rails you are using and what the default implementation of .present? does for dates.

A: You could do this in the model or controller, but isn't it possible that an event will start late at night and end on the following day? To allow for this possibility I'd recommend having two calendar_date_selects and auto-assigning the ending date when the starting date is chosen (so the second calendar_date_select will rarely be used).
If you really don't want two calendars, maybe use a hidden field for the ending date that follows the start date.
I wouldn't enforce this same-date rule below the interface level unless you're absolutely sure different start and end dates will never occur.


text:
Q: Android SimpleCursorAdapter and Database Update I just started with Android development and love it so far. To get
some experience, I am writing a little todo application. In my
database I have a state for a todo item, represented as int. I use a
checkbox in a list view to represent this state. To bind the data to
the view, I use a subclass of SimpleCursorAdapter. I add an
onClickListener to the checkbox that updates the state in the database
for the used list item. The problem is, if I use the following code,
the list is screwed up in the display (many items will be checked):
@Override
public View getView(final int pos, View inView, ViewGroup parent) {
  View view = inView;
  if (view == null) {
    LayoutInflater inflater = (LayoutInflater) context
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.toodoolist_item, null);
  }
  cursor.moveToPosition(pos);
  ...

  checkBox.setOnClickListener(new OnClickListener() {

     @Override
     public void onClick(View v) {
        int state = 0;
        if (checkBox.isChecked()) {
        titleView.setPaintFlags(titleView.getPaintFlags()
            | Paint.STRIKE_THRU_TEXT_FLAG);
        titleView.setEnabled(false);
        state = 1;
     } else {
        titleView.setPaintFlags(titleView.getPaintFlags()
            ^ Paint.STRIKE_THRU_TEXT_FLAG);
        titleView.setEnabled(true);
     }

     ContentValues values = new ContentValues();
     values.put(TooDooTable.STATE, state);
     context.getContentResolver()
        .update(ContentUris.withAppendedId(
     TooDooTable.CONTENT_URI, id), values, null, null);
     cursor.requery();
  }
}

My current workaround is to use the inflater every time, even if the
inView is not null:
 @Override
 public View getView(final int pos, View inView, ViewGroup parent) {
   View view = inView;
   LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   view = inflater.inflate(R.layout.toodoolist_item, null);
  ...

This works, but I don't understand why I have to do this hack.
What would be the best practice to update the database in a
CurserAdapter and get the changes reflected immediately in the view?
Thanks
Kai

A: Use notifyDataSetChanged instead of requery, and maybe use invalidate on the view if the previous method don't do anything.


text:
Q: I am getting this error "The instance member 'widget' can't be accessed in an initializer." Flutter/Dart This is my code :
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class viewLossEvent extends StatefulWidget {
  String code,

  viewLossEvent(
      {this.code});

  @override
  State<viewLossEvent> createState() => _viewLossEventState();
}

class _viewLossEventState extends State<viewLossEvent> {

  int _selectedIndex = 0;

  void _navigateBottomBar(int index){
    setState(() {
      _selectedIndex = index;
    });
  }

  final List<Widget> _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];

the error that I am getting :
"The instance member 'widget' can't be accessed in an initializer."

I am getting the error right here :

can anyone help solve this and kindly explain why this is happening.
Thank You!

A: You cannot initialize a property by using widget.code. You should use initState instead :
List<Widget> _pages = [];

void initState() {
  super.initState();
  _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];
}

A: Always prefer using getters instead fields because Flutter re-uses your state instance across the widget lifecycle and if you keep track the old object references you can face weird and hard to track bugs.
So use instead:
  List<Widget> get _pages => [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];

This also best fits the Flutter state management principles.
As you can see this getter will create a new instance of your Container widget every time you access the _pages field, this prevent us from accessing widgets that are not even in the screen anymore, and this approach has no performance issues since it just re-create the widget configuration.
In your case you can also fix the error by using the late modifier  (Not recommended due the reasons mentioned above):
  late final List<Widget> _pages = [
    Container(
      child: Text(
          '${widget.code}'
      ),
    ),
  ];


text:
Q: hosintg WCF rest services in .net webforms app I have a traditional .net web application with .aspx pages and code behind files...
I want to use some jquery on the UI and wanted to ass json services to connect things like grids from jquery-easyui. I have seen some bad options like using .aspx pages to return json content type and standalone wcf samples but I want to host the services in IIS because the application is on a hosted online provider.
what is the simplest method that would be good practice to use for this and how do I implement it in VS2012 and my local IIS hosted site plus th production internet site?

A: You can use Web.Api to create rest services and host them as part of your website.
Have a look here for a complete tutorial : http://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api.

A: You can also include WCF services directly into your web application and configure them so they will return and receive JSON.
They look like this :
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class YourServiceDoesJSON
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public ReturnTypeThatWillBeTransformedIntoJSON GetWhatever(string parameterIfYouNeed)
    {
        // do something
        return new ReturnTypeThatWillBeTransformedIntoJSON();
    }

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    public SomethingElse PostWhatever()
    {
            ...
    }
}

The config file for this service looks like this :
<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="WebApp.Folder.YourServiceDoesJSONAspNetAjaxBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MetadataBehaviors" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
      <service name="WebApp.Folder.YourServiceDoesJSON" behaviorConfiguration="MetadataBehaviors">

        <endpoint address="" behaviorConfiguration="WebApp.Folder.YourServiceDoesJSONAspNetAjaxBehavior"
          binding="webHttpBinding" contract="WebApp.Folder.YourServiceDoesJSON" />
      </service>
    </services>

Note: this is how I did before I knew it was so easy to turn a web application into MVC; see my previous answer ;)


text:
Q: Android Jtwitter, authentication issues Hello I am having difficulty using the JTwitter functions to authenticate with my twitter application. I always get a "TwitterException"
Here is my method
OAuthSignpostClient oauthClient = new OAuthSignpostClient(consumerKey,
            privateKey, "oob");

a) I don't know what the "oob" value SHOULD be, it is the "callbackURL" and in my application on twitter it says "callBack URL: none"  so I have tried putting "none", "None", and null  where "oob" with no differing results.
then the rest is boilerplate
 Intent i = new Intent(Intent.ACTION_VIEW,
    Uri.parse(oauthClient.authorizeUrl().toString()));
    startActivity(i);
    // get the pin
    String v = oauthClient.askUser("Please enter the verification PIN from Twitter");
    oauthClient.setAuthorizationCode(v);
    // Store the authorisation token details for future use
    String[] accessToken = oauthClient.getAccessToken();
    // Next time we can use new OAuthSignpostClient(OAUTH_KEY, OAUTH_SECRET,
    //        accessToken[0], accessToken[1]) to avoid authenticating again.

    EditText twitterText = (EditText)findViewById(R.id.twitterText);
    twitterText.getText();

    // Make a Twitter object
    Twitter twitter = new Twitter(null, oauthClient);
    // Print Daniel Winterstein's status
    //System.out.println(twitter.getStatus("winterstein"));
    // Set my status
    twitter.setStatus(twitterText.getText());

at this point, I'm simply not sure on how to make this work. Wish I could be more verbose about it, but it has something to do with the authentication. Online things I've seen haven't been helpful

A: Try this as your callback url:
OAuthSignpostClient oauthClient =
    new OAuthSignpostClient(consumerKey, privateKey, "callback://twitter");

Remember! After:
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));

Do the following
override onResume() to get the verification code
protected void onResume() {
    super.onResume();
    if (this.getIntent()!=null && this.getIntent().getData()!=null){
        Uri uri = this.getIntent().getData();
        if (uri != null && uri.toString().startsWith("callback://twitter")) {
            //Do whatever you want
            //usually use uri.getQueryParameter(someString);
            //test what could be someString using Log.v("",uri.toString());
            //you want the Authorization code which is a couple of numbers
            //so you could use oauthClient.setAuthorizationCode(v);
            //and finally initialise Twitter
        }
    }
}

You can use uri.getQueryParameterNames() to get the parameter String names.

@BobVork
I'd just like to add that you'll need to have a callback URL set in the Settings tab for your Twitter app (on twitter.com).
It doesn't even matter what you put in the field, but if it's empty, callback urls will not work.

A: I'm not sure that's the problem, but it seems like you never set the user name for the twitter object.

A: Well, I don't know how it is with the Jtwitter API and I don't know enough Java at this point to really understand the inner workings of this code, but have you tried, instead of NULL or None, to try ? instead. That is the callback used with the restful API when making calls from Javascript. Try it out.


text:
Q: How do I have a functioning all button with a SimpleListFilter I have a django admin that I am trying to change my default filter for. I have the filter displaying the data I want as default but my all button is not functioning correctly because I am returning a specific queryset when the value is None. Is there a way to have a functioning all button without changing the 'All' value?
class EmailFilter(admin.SimpleListFilter):
    title = _('email category')

    parameter_name = 'email_category'

    def lookups(self, request, model_admin):
        return (
            (10, _('Forwarded')),
            (8, _('Spam')),
        )

    def queryset(self, request, queryset):
        if self.value() is not None:
            return queryset.filter(email_category=self.value())
        return queryset

class myAdmin(VersionAdmin):
    list_filter = (EmailFilter)

A: class EmailFilter(admin.SimpleListFilter):
   title = _('email category')

   parameter_name = 'email_category'

   def lookups(self, request, model_admin):
       return (
           (None, _('Forwarded')),
           (8, _('Spam')),
           ('all', _('All')),
       )

   def queryset(self, request, queryset):
       if not self.value():
           return queryset.filter(email_category=10)  # forwarded if None which it will be by default
       elif self.value() == 'all':
           return queryset
       else:
           return queryset.filter(email_category=self.value())


text:
Q: how to read db format file in pyspark? df_chinook = spark.read.format('jdbc').load("/content/datasets/chinook.db")

here is my code I try to load db base into pyspark dataframe, but have (error like this
IllegalArgumentException: requirement failed: Option 'url' is required.)
what I have to do?

A: Loading data from a JDBC source
jdbcDF = spark.read \
    .format("jdbc") \
    .option("url", "jdbc:postgresql:dbserver") \
    .option("dbtable", "schema.tablename") \
    .option("user", "username") \
    .option("password", "password") \
    .load()

The JDBC URL of the form jdbc:subprotocol:subname to connect to. The source-specific connection properties may be specified in the URL.
e.g. jdbc:postgresql://localhost/test?user=fred&password=secret
More data-sources examples here

A: Does this answer help you?
You could try with
from pyspark.sql import SQLContext

SQLContext.read.jdbc(url="...", table="baz", properties=properties)


text:
Q: how to make emulator running prossesor AMD I am getting the following error when running the emulator like this:
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please Ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!

And here I use AMD processors, is there any solution ?

A: Intel HAXM only runs on certain Intel processors that support Virtualization and ND bit. There are other alternative emulators to the built in one - like GenyMotion


text:
Q: Django 2: how to force a foreignkey in admin interface I am new to Django and Python. Let's say I am building an app to manage devices used by users in companies. I have multiple companies, with multiple users and rooms in each.
Rooms and users are always linked to a company.
A device can be linked to:

*

*An user ("Joe's iPhone", "Anna's Laptop")

*A room ("Conference Room's Computer")

A device is always linked to a company.
So, I can have a device, that is linked to a company only.
So here's my code :
models.py:
class Company(models.Model):
    name=models.CharField(max_length=50)

class User(models.Model):
    name=models.CharField(max_length=50)
    company=models.ForeignKey('Company', on_delete=models.CASCADE)

class Room(models.Model):
    name=models.CharField(max_length=50)
    company=models.ForeignKey('Company', on_delete=models.CASCADE)

class Device(models.Model):
    company=models.ForeignKey('Company', on_delete=models.CASCADE)
    user=models.ForeignKey('User', on_delete=models.CASCADE,  blank=True, null=True)
     room=models.ForeignKey('Room', on_delete=models.CASCADE,  blank=True, null=True)

admin.py:
class DevicesInline(admin.TabularInline):
    model = Device
    extra = 0
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field == "Company":
            kwargs['queryset'] = ## Here I don't know ##
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

class UserAdmin(admin.ModelAdmin):
    inlines = [DeviceInline]

What I want is pretty simple : when I am editing a user (or a room), I want to be able to add a device for it. But the field Company has to be filled with the company for the user or room, and it can't be modified. That's all :)
PS: I don't know if the device needs to be linked to the company if it's already linked to a user or room ? That's a whole other question.

A: In Django , to mark a field required you must add the the kwarg blank blank=False to the field , as well as adding null=False to enforce the relation on the database.
In your case if you want to force the user to add a company:
class User(models.Model):
    name=models.CharField(max_length=50)
    company=models.ForeignKey('Company',blank=False,null=False, on_delete=models.CASCADE)

class Room(models.Model):
    name=models.CharField(max_length=50)
    company=models.ForeignKey('Company',blank=False,null=False, on_delete=models.CASCADE)

Moreover,no need to add Company as ForeignKey inside the Device model,your data will not be accurate , suppose that the device is linked to CompanyA while the device room is linked to CompanyB...
With respect to making the Company a readonly field, have a look at this answer.
class MyModelAdmin(admin.ModelAdmin):

    def get_readonly_fields(self, request, obj=None):
        if obj: # editing an existing object
            return self.readonly_fields + ('field1', 'field2')
        return self.readonly_fields

A: I did not have time this week to work on this, but I tought about it.
A device will be linked to a company, a user or a room. It has to be linked to one of them. So if a device is linked to a user, as user are linked to a company, therefore the device is linked to the company of the user.
Now I just have to do something inside the model to say that a device must have a company, a user or a room. I don't know how I will do that yet.


text:
Q: How can I add a check if a signature is entered using jquery validation and signature_pad? I'm using jquery.validate.js to validate multiple fields in my form along with smizek's signature_pad. I want to validate if something is drawn on the html canvas (signature pad) at the same time all the other input fields are validated.
Unfortunately, adding a function to the jquery validation submithandler to check if the canvas has a signature is not sufficient because this only triggers once all other required fields are satisfied. I can add methods to jquery validator, but I'm pretty sure those only work on validating the content of inputs—not a canvas.
I can check if the signature exists with "signaturePad.isEmpty()". Ideally, there would be a way to add a function like this that happens concurrently with any validation:
    var errorExists = false;
    if( signaturePad.isEmpty()){
      if (errorExists == false){
        $( "#signature-pad" ).append( "
A signature is required
" );
        errorExists = true;
      }
    }else if( !signaturePad.isEmpty()) {
      if (errorExists == true){
        $('#sig-error').remove();
      }
    }

...and only continue on to actually submit the form if both the jquery validation and the signature are satisfied.
Is there a way to have a function trigger at the same time other validation happens—not after? How can I stop the form from submitting unless both my conditions are met—not just the jquery validation?

A: In the jquery validation submithandler, return false if the signature is not filled:
    if( signaturePad.isEmpty()){
            console.log('it is empty');
            return false;
        }

This prevents the form from being submit if there is no signature.
To show an error message for a missing signature like the rest of the jquery validation error messages, bind a function to the submit input's click:
    $('#submit_form').click(function(){
      if( signaturePad.isEmpty()){
        if (errorExists === false){
          $( "#signature-pad" ).append( "
A signature is required
" );
          errorExists = true;
        }
      }else if( !signaturePad.isEmpty()) {
        if (errorExists === true){
          $('#sig-error').remove();
          errorExists = false;
        }
      }
    });

Declare your variable somewhere:
var errorExists = false;

A: I made a hidden field with a custom validation to handle this.
JavaScript to set the hidden field's value to a base64 encoded signature.

Signature Pad HTML

                <canvas id="canvas" width="611" height="150"></canvas>

                <button class="button clear" data-action="clear" type="button">Clear</button>

                  Sign above

Form HTML
<input data-rule-signature="true" id="signature" name="signature" type="hidden">

Custom validation code added to jquery-validate-additional-methods.js (download link is on that page)
jQuery.validator.addMethod("signature", function(value, element, options) {
    if( signaturePad.isEmpty()){
            return false;
        }
    return true;
}, "Your signature is required");


text:
Q: stripeToken is not being returned to my form I have my Stripe integration setup correctly, because it does return an error This customer has no attached payment source which is a Stripe error indicating that the form is not returning sufficient payment info.
This is my subscriptions.js.coffee:
stripeResponseHandler = (status, response) ->
  $form = $('#payment-form')
  if response.error
    #Show the errors on the form
    $form.find('.payment-errors').text response.error.message
    $form.find('button').prop 'disabled', false
  else
    # response contains id and card, which contains additional card details
    token = response.id
    #Insert the token into the form so it gets submitted to the server
    $form.append $('<input type="hidden" name="stripeToken" />').val(token)
    # and submit
    $form.get(0).submit()
  return

jQuery ($) ->
  $('payment-form').submit (event) ->
    $form = $(this)
    $form.find('button').attr 'disabled', true
    Stripe.card.createToken $form, stripeResponseHandler
    false
  return

This is my form at new.html.erb:
<% unless @subscription.errors.blank? %>
  <%= @subscription.errors.full_messages.to_sentence %>
<% end %>

Subcribing to <%= @plan.name %>

<%= form_for @subscription, html: {id: 'payment-form'} do |f| %>
  <input type="hidden" name="plan_id", value="<%= @plan.id %>" />

      Email Address
      <input type="email" size="20" name="email_address" />

      Card Number
      <input type="text" size="20" data-stripe="number" />

      CVC
      <input type="text" size="4" data-stripe="cvc" />

      Expiration (MM/YYYY)
      <input type="text" size="2" data-stripe="exp-month" />

     /
    <input type="text" size="4" data-stripe="exp-year" />

  <button type="submit">Pay Now</button>
<% end %>

This is the SubscriptionsController#Create:
  def create
    @plan = Plan.find(params[:plan_id])
    @subscription = CreateSubscription.call(
      @plan,
      params[:email_address],
      params[:stripeToken]
    )
    if @subscription.errors.blank?
      flash[:notice] = "Thank you for your purchase! Please click the link in the email we just sent you to get started."
      redirect_to authenticated_root_path
    else
      render :new
    end
  end

The above calls this app/services/create_subscription.rb:
class CreateSubscription
  def self.call(plan, email_address, token)
    user, raw_token = CreateUser.call(email_address)

    subscription = Subscription.new(
      plan: plan,
      user: user
    )

    begin
      stripe_sub = nil
      if user.stripe_customer_id.blank?
        binding.pry
        customer = Stripe::Customer.create(
          source: token,
          email: user.email,
          plan: plan.stripe_id
        )

        user.stripe_customer_id = customer.id
        user.save!
        stripe_sub = customer.subscriptions.first
      else
        customer = Stripe::Customer.retrieve(user.stripe_customer_id)
        stripe_sub = customer.subscriptions.create(
          plan: plan.stripe_id
        )
      end

      subscription.stripe_id = stripe_sub.id

      subscription.save!
    rescue Stripe::StripeError => e
      subscription.errors[:base] << e.message
    end

    subscription
  end
end

The reason I know that the form is not receiving the stripeToken is because when I use binding.pry in that create and did this:
00:52:31 web.1              |     14: def create
00:52:31 web.1              |     15:   @plan = Plan.find(params[:plan_id])
00:52:31 web.1              |  => 16:   binding.pry
00:52:31 web.1              |     17:   @subscription = CreateSubscription.call(
00:52:31 web.1              |     18:     @plan,
00:52:31 web.1              |     19:     params[:email_address],
00:52:31 web.1              |     20:     params[:stripeToken]
00:52:31 web.1              |     21:   )
00:52:31 web.1              |     22:   if @subscription.errors.blank?
00:52:31 web.1              |     23:     flash[:notice] = "Thank you for your purchase! Please click the link in the email we just sent you to get started."
00:52:31 web.1              |     24:     redirect_to authenticated_root_path
00:52:31 web.1              |     25:   else
00:52:31 web.1              |     26:     render :new
00:52:31 web.1              |     27:   end
00:52:31 web.1              |     28: end
00:52:31 web.1              |
[1] pry(#<SubscriptionsController>)> params
00:52:37 web.1              | => {"utf8"=>"✓", "plan_id"=>"1", "email_address"=>"someuser@test.com", "action"=>"create", "controller"=>"subscriptions"}

Notice that there is no params[:stripeToken].
Also, when I try the binding.pry in my create_subscription.rb service, this is what I get:
00:52:41 web.1              |     10:     begin
00:52:41 web.1              |     11:       stripe_sub = nil
00:52:41 web.1              |     12:       if user.stripe_customer_id.blank?
00:52:41 web.1              |  => 13:         binding.pry
00:52:41 web.1              |     14:         customer = Stripe::Customer.create(
00:52:41 web.1              |     15:           source: token,
00:52:41 web.1              |     16:           email: user.email,
00:52:41 web.1              |     17:           plan: plan.stripe_id
00:52:41 web.1              |     18:         )
00:52:41 web.1              |
[1] pry(CreateSubscription)> token
00:52:44 web.1              | => nil

What could be causing this and how do I fix it?

A: As it turns out, my issue was a dumb mistake.
Notice in my CoffeeScript I have this:
jQuery ($) ->
  $('payment-form').submit (event) ->
    $form = $(this)
    $form.find('button').attr 'disabled', true
    Stripe.card.createToken $form, stripeResponseHandler
    false
  return

The issue is in the form selector. I didn't add the # to the ID of the form.
So once I changed this line:
  $('payment-form').submit (event) ->

To this:
  $('#payment-form').submit (event) ->

It works like a charm.
DOH! Faceslap


text:
Q: Get javascript var from webview to android var I am trying get a var from a webview but I only can modify like this:
browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';");

but I need get any js var like this :
String myAndroidvar = browser.loadUrl("javascript:var x = document.getElementById('login').value");

but this syntax is incorrect, I need the correct method.

A: You have to add a javaScriptInterface to you webview. See this blog for a decent description.
You can also get stuff from javascript by calling an interface function you defined using:
web.loadUrl("javascript: window.jsinterface.getValue(document.getElementById('login').value)");


text:
Q: I can't catch specific browser logged errors from an AJAX call. Is catching these even possible? I'm trying to break an AJAX call in as many ways as I can to anticipate many specific errors. Using the error callback in jQuery ajax, doesn't give me specific enough information compared to what the browser logs (which I would like to catch). I would receive the same generic information (status of 0 with a statusText of "error") for these two errors from Chrome in the error callback:

*

*No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'some url' is therefore not allowed access. The response had HTTP status code 503.

*GET http://google.com/ net::ERR_INTERNET_DISCONNECTED
Right now my code is similar to the answer in how can i handle multiple ajax errors in jquery. I would like it to address more specific errors, but I suspect it's not possible to catch the specific errors the browser logs.
Is it even possible to catch these errors?
Note: Wrapping the call in a try-catch does not work either. Using vanilla XHR doesn't provide specific error information either.

A: That answer refers to handling the .status object, which will only contain a number. If you want to handle error messages, use the .responseText, and either JSON.parse() it or use indexOf() to check on the exceptions you want to use. You can also use the thrownError string:
$.ajax({
  ...
  error: function(xhr, ajaxOptions, thrownError) {
      console.log("thrownError: " + thrownError);
  }
});


text:
Q: Как сделать что бы звук не накладывался на себя? Unity, C# Я пытаюсь сделать, что бы звук проигрывался при нажатии на кнопку, но оно начинается только тогда когда я уже отпускаю кнопку, если сделаю что звук проигрывался при скорости больше одного оно начинает проигрывать бесконечно и накладывается на себя. Как я могу сделать что бы звук играл при нажатии на кнопку и не накладывался на себя?
   using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveUI : MonoBehaviour
{
    float speed = 4.5f;

    Rigidbody2D rb;

    bool FacingRight = true;

    int directionInput;

    public float jumpForce = 6f;

    public bool onGround;
    public Transform GroundCheck;
    public float checkRadius = 0.5f;
    public LayerMask Ground;
    public LayerMask Hitbox;
    public GameObject KnopkaDown;
    public AudioSource footstep1;
    public AudioSource footstep2;

    Animator anim;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    void Update()
    {
        rb.velocity = new Vector2(speed * directionInput, rb.velocity.y);

        if (directionInput < 0 && FacingRight)
        {
            Flip();
        }
        else if (directionInput > 0 && !FacingRight)
        {
            Flip();
        }
        if (directionInput == 0)
        {
            anim.SetBool("Run", false);

        }
        else
        {
            anim.SetBool("Run", true);
            footstep1.Play();   //here
        }
        if (onGround == false)
        {
            anim.SetBool("Jump", true);
            anim.SetBool("Run", false);
        }
        else
        {
            anim.SetBool("Jump", false);
        }

        CheckingGround();

        Physics2D.IgnoreLayerCollision(9, 14);
        Physics2D.IgnoreLayerCollision(14, 9);

        Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.left) * 2f, Color.yellow);
        RaycastHit2D hitLeft = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.left), 2f, Hitbox);
        //RayRight
        Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.right) * 2f, Color.yellow);
        RaycastHit2D hitRight = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.right), 2f, Hitbox);

        if(hitLeft)
        {
            KnopkaDown.SetActive(true);
        }
        else
        {
            KnopkaDown.SetActive(false);
        }

        if(hitRight)
        {
            KnopkaDown.SetActive(true);
        }
        else
        {
            KnopkaDown.SetActive(false);
        }

        if (directionInput >= 0)
        {

        }
    }
    public void Move(int ImputAxis)
    {
        directionInput = ImputAxis;
    }
    void Flip()
    {
        FacingRight = !FacingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }

    public void Jump()
    {
        if (onGround)
        {
            rb.AddForce(Vector2.up * jumpForce);
        }
    }

    void CheckingGround()
    {
        onGround = Physics2D.OverlapCircle(GroundCheck.position, checkRadius, Ground);
    }

    public void Down()
    {
        Physics2D.IgnoreLayerCollision(8, 9, true);
        Invoke("IgnoreLayerOff", 1f);
    }

    void IgnoreLayerOff()
    {
        Physics2D.IgnoreLayerCollision(8, 9, false);
    }

}


text:
Q: Why `kill %jobnumber` not working on stopped jobs? I'm running few tasks side by side on an ubuntu 18 LTS. So I'm switching between these jobs by running
# command &
# fg
# fg -

(Also) use of Ctrl+z sometimes to send running job to background.
Say I have 3 jobs in my list
# jobs
[1]+  Stopped                 nano /etc/nginx/site-available/blog.conf
[2]   Stopped                 top
[3]-  Stopped                 nano script.sh

I can successfully switch between these, but when I run kill command on these, jobs still showing in the list, none gets killed, I wonder why?
# kill %1

I list again, and jobs are still there.
# jobs
[1]+  Stopped                 nano /etc/nginx/site-available/blog.conf
[2]   Stopped                 top
[3]-  Stopped                 nano script.sh


text:
Q: ElasticSearch cannot open . Only showing authentication panel for entering username and password I have a problem in my elasticsearch.
I downloaded from https://www.elastic.co/downloads/elasticsearch. I couldn't open the page.
I only see a pop-up menu for an authentication (username and password) when I use https://localhost:9200/ . Do you have any idea how to fix it?
Here is the screenshot shown below.

When I go to localhost:9200 in Postman , I get this error messsage shown below.
{
    "error": {
        "root_cause": [
            {
                "type": "security_exception",
                "reason": "unable to authenticate with provided credentials and anonymous access is not allowed for this request",
                "additional_unsuccessful_credentials": "oauth2 token: invalid token",
                "header": {
                    "WWW-Authenticate": [
                        "Basic realm=\"security\" charset=\"UTF-8\"",
                        "ApiKey"
                    ]
                }
            }
        ],
        "type": "security_exception",
        "reason": "unable to authenticate with provided credentials and anonymous access is not allowed for this request",
        "additional_unsuccessful_credentials": "oauth2 token: invalid token",
        "header": {
            "WWW-Authenticate": [
                "Basic realm=\"security\" charset=\"UTF-8\"",
                "ApiKey"
            ]
        }
    },
    "status": 401
}

A: Elasticsearch latest version(8.0) comes with basic security, hence you see the pop-up for authentication, you need to provide the username(elastic which is reserved name) and it's password (printed on Elasticsearch logs when you start the service).


text:
Q: SceneBuilder won't load my custom control which references another custom control via FXML I have created an FXML-based custom control, which in turn references another FXML-based custom control. They all work just fine when I load them in eclipse, but when I try to import them into SceneBuilder, the outer control (the one containing the other one) does not get imported properly.
Here is a dramatically simplified example:
Widget.java:
package example;

import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.fxml.FXMLLoader;
import javafx.scene.layout.Pane;

public class Widget extends Pane{

    public Widget() {

        Logger logger = Logger.getLogger(Widget.class.getName());

        try {
            FXMLLoader loader= new FXMLLoader(Widget.class.getResource("Widget.fxml"));
            Pane pane = loader.load();
            this.getChildren().add(pane);
        }
        catch(Exception e) {
            logger.log(Level.SEVERE, "Failed to load Widget", e);
        }
    }
}

Widget.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.control.Label?>
<?import example.SubWidget?>

<FlowPane  xmlns:fx="http://javafx.com/fxml/1" >
   <children>
       <Label text="Widget"/>
      <SubWidget></SubWidget>
   </children>
</FlowPane>

SubWidget.java:
package example;

import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.fxml.FXMLLoader;
import javafx.scene.layout.Pane;

public class SubWidget extends Pane{

    public SubWidget() {

        Logger logger = Logger.getLogger(SubWidget.class.getName());

        try {
            FXMLLoader loader= new FXMLLoader(SubWidget.class.getResource("SubWidget.fxml"));
            Pane pane = loader.load();

            this.getChildren().add(pane);
        }
        catch(Exception e) {
            logger.log(Level.SEVERE, "Failed to load SubWidget", e);
        }
    }
}

SubWidget.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.FlowPane?>
<?import javafx.scene.control.Label?>

<FlowPane  xmlns:fx="http://javafx.com/fxml/1" >
   <children>
       <Label text="Subwidget"/>
   </children>
</FlowPane>

I export these to a jar and attempt to import them via SceneBuilder's jar import functionality. When I do so, SubWidget gets imported and looks just fine. Widget will also show up as a control, but it will be completely empty.
When I check the log files I see that it is due to the FXML loader not being able to find the SubWidget class file:
Oct 29, 2020 4:28:30 PM example.Widget <init>
SEVERE: Failed to load Widget
javafx.fxml.LoadException:
file:/C:/Users/nate/AppData/Roaming/Scene%20Builder/Library/TestFxControl.jar!/example/Widget.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2848)
    at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
    at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at example.Widget.<init>(Widget.java:27)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.reflect.misc.ReflectUtil.newInstance(Unknown Source)
    at javafx.fxml.FXMLLoader$InstanceDeclarationElement.constructValue(FXMLLoader.java:1009)
    at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:746)
    at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2707)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2527)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2425)
    at com.oracle.javafx.scenebuilder.kit.library.util.JarExplorer.instantiateWithFXMLLoader(JarExplorer.java:110)
    at com.oracle.javafx.scenebuilder.kit.library.util.JarExplorer.exploreEntry(JarExplorer.java:160)
    at com.oracle.javafx.scenebuilder.kit.library.util.JarExplorer.explore(JarExplorer.java:70)
    at com.oracle.javafx.scenebuilder.kit.library.user.LibraryFolderWatcher.exploreAndUpdateLibrary(LibraryFolderWatcher.java:325)
    at com.oracle.javafx.scenebuilder.kit.library.user.LibraryFolderWatcher.runDiscovery(LibraryFolderWatcher.java:138)
    at com.oracle.javafx.scenebuilder.kit.library.user.LibraryFolderWatcher.run(LibraryFolderWatcher.java:92)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: example.SubWidget
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
    at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
    ... 24 more

It appears to me that the FXML loader is using a classloader which doesn't include other custom components, which is odd because if I bypassed the FXML in the Widget class and made it:
public class Widget extends FlowPane{

    public Widget() {

        this.getChildren().addAll(new Label("Widget"), new SubWidget());
    }
}

Then it loads just fine in SceneBuilder. So it appears that the ClassLoader that actually loads Widget and the one that the FXMLLoader uses are not the same.
This could possibly be related to this unanswered question, though they aren't exactly the same thing.

A: I had the same issue and created a work around that is not pretty but works.
Create a jar that contains blank classes for the controls you can not load into Scene Builder, e.g:
package com.junglefinance.gui.controls;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class CategoryTextField extends TextField {
    @FXML private TextField textField;
    public CategoryTextField() {
    }
 }

Make sure the package matches the package of your target control.
Load this jar into Scene Builder.  This will allow Scene Builder to generate your FXML ready to load into your program.  When it is loaded it will pick up your target control rather than the dummy as the import is (in this case)
<?import com.junglefinance.gui.controls.CategoryTextField?>

Note the package.


text:
Q: PicklingError when using mock to check function is called I'm having trouble testing that a method is called using mock -- as a simple example, let's say that the method is os.getcwd. I want to test that my own function, pickle_wdir, is calling os.getcwd as intended. However, the function I am testing pickles the value returned by os.getcwd, which results in an error.
Here's a simple example to reproduce the error.
os_ex.py:
import os
import pickle

def pickle_wdir(filename):
    dir = os.getcwd()
    with open(filename, 'wb') as handle:
        pickle.dump(dir, handle)

test_os_ex.py:
from unittest import TestCase
from unittest.mock import patch
from os_ex import pickle_wdir

class TestPickleWdir(TestCase):
    def test_os_called(self):
        fname = 'dir.pickle'
        with patch('os_ex.os') as mocked_obj:
            pickle_wdir(fname)
            mocked_obj.getcwd.assert_called()

The error message returned is
_pickle.PicklingError: Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock.
How can I test that os.getcwd is called without getting this PicklingError?

A: You need to mock os.getcwd(), open() and pickle.dump() methods. You can use unittest.mock.patch as context manager to do this.
E.g.
os_ex.py:
import os
import pickle

def pickle_wdir(filename):
    dir = os.getcwd()
    with open(filename, 'wb') as handle:
        pickle.dump(dir, handle)

test_os_ex.py:
import unittest
from unittest.mock import patch, mock_open
from os_ex import pickle_wdir

class TestOsEx(unittest.TestCase):
    def test_pickle_wdir(self):
        fname = 'dir.pickle'
        m = mock_open(read_data='mocked data')
        with patch('os_ex.os') as mocked_obj, patch('builtins.open', m) as mocked_open, patch('pickle.dump') as mocked_dump:
            mocked_obj.getcwd.return_value = '/root'
            pickle_wdir(fname)
            mocked_obj.getcwd.assert_called()
            m.assert_called_with(fname, 'wb')
            handle = mocked_open()
            mocked_dump.assert_called_with('/root', handle)

if __name__ == '__main__':
    unittest.main()

unit test results with 100% coverage:
.
----------------------------------------------------------------------
Ran 1 test in 0.012s

OK
Name                                       Stmts   Miss  Cover   Missing
------------------------------------------------------------------------
src/stackoverflow/60627827/os_ex.py            6      0   100%
src/stackoverflow/60627827/test_os_ex.py      17      0   100%
------------------------------------------------------------------------
TOTAL                                         23      0   100%


text:
Q: std::set::insert, how bad can I hint? I'm doing lots and lots of inserts of std::pair<int, int> into a std::set, and it's taking longer than I'd like. When I wrote the code I figured I'd look at using the hint iterator form of insert later if it turned out to be a bottleneck; well, now it's profiled and it is a bottleneck. So I want to use the iterator hint.
However, I'm not always going to know a good position to insert my pairs. I typically insert them in batches (a batch in this case is on the order of 0.01% of the total input size, duplicates included) of increasing set-order, but when a batch is inserted, I do not know where the next one should start. How is the hint used? Does insert do something like a binary search from the suggested position? How bad would it be to use a bad hint, typically?

A: I suggest just reading what the compiler reads: the header file for #include <set>. On my system (GNU libstdc++ 4.5.1) I can read the following self-explanatory text:
  /**
   *  @brief Attempts to insert an element into the %set.
   *  @param  position  An iterator that serves as a hint as to where the
   *                    element should be inserted.
   *  @param  x  Element to be inserted.
   *  @return  An iterator that points to the element with key of @a x (may
   *           or may not be the element passed in).
   *
   *  This function is not concerned about whether the insertion took place,
   *  and thus does not return a boolean like the single-argument insert()
   *  does.  Note that the first parameter is only a hint and can
   *  potentially improve the performance of the insertion process.  A bad
   *  hint would cause no gains in efficiency.
   *
   *  For more on @a hinting, see:
   *  http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt07ch17.html
   *
   *  Insertion requires logarithmic time (if the hint is not taken).
   */
  iterator
  insert(iterator __position, const value_type& __x)
  { return _M_t._M_insert_unique_(__position, __x); }

Takeaway:

*

*A bad hint would cause no gains in efficiency

*Insertion is O(log n)

*You can read even more about insertion hints in the GNU libstdc++ manual.

A: If you check the file bits/stl_tree.h (in GNU libstdc++), you'll find that the _M_insert_unique member function with a hint argument looks one node to the left of the hint, then one node to the right, then defaults to calling the ordinary insert routine.
It calls key_compare at least once (if the set is not empty) and at most three times. Going from one node to the next or previous is a matter of following a pointer since (IIRC) std::set and friends are threaded trees.
So, how bad a bad hint is depends on the comparison routine, and on whether your std::set's allocator packs nodes close in memory.

A: A hint is good if it is the right hint - the position to use for an insert. Works if you insert objects sequentially, for example.
If the hint is not correct, it has no effect and you get a non-hinted insert.

A: If you're building the set all at once before you use it, you can use a vector instead and sort it before you use it. You can use the binary_search, lower_bound, upper_bound, and equal_range algorithms on a sorted vector for fast lookups. You can also use merge or inplace_merge to combine sorted vectors, and set_difference, set_intersection, and set_union to do other common set operations.


text:
Q: Cap a pyspark column by condition on other column? I have a Pyspark dataframe
x1 x2
12 4
8 5
13 2

I would like to cap x1 = 10 for the rows with x2 < 5, something like:
if x2 < 5:
  if x1 > 10:
    x1 = 10

How could I do that for Pyspark?
Many thanks

A: this is the base logic:
https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.when
from pyspark.sql.functions import when

df = spark.createDataFrame([(12, 4), (8, 5), (13, 2)]).toDF("x1", "x2")

df\
.withColumn("logic", when(df.x2 < 5, 10)\
            .otherwise(when(df.x1 > 10, 10)))\
.show()

+---+---+-----+
| x1| x2|logic|
+---+---+-----+
| 12|  4|   10|
|  8|  5| null|
| 13|  2|   10|
+---+---+-----+

// other logic

from pyspark.sql.functions import when, lit

df\
.withColumn("logic", when((df.x2 < 5) & (df.x1 > 10), lit(10))\
            .otherwise(df.x1))\
.show()

+---+---+-----+
| x1| x2|logic|
+---+---+-----+
| 12|  4|   10|
|  8|  5|    8|
| 13|  2|   10|
+---+---+-----+


text:
Q: sql - what does '^\d+\D+$' mean in regexp I came through an expression -
select * from table where regexp_like(field, '^\d+\D+$');

I'm sure of what the expression does, but please can someone explain what '^\d+\D+$' refers to exactly?
Thanks.

A: ^ beginning of string
\d single digit
+ one or more occurrences of preceding
\D nondigit character
+ one or more occurrences
$ end of string
So, it means one or more digits followed by one or more nondigits, and that should be the whole string, not a substring.


text:
Q: Java Calling function from other class async I have a problem. I am trying to call a method from another class async. Here is the function I am trying to call:
public class CandlestickDriver {

    public void run(String market, String coin, String period, boolean once, boolean firstRun) {

    }

}

And in my MainClass, I have the following code:
CompletableFuture.supplyAsync(CandlestickDriver::run);

But that gives me the error:

The type CandlestickDriver does not define run() that is applicable
here

I also don't see a way how I can pass the paramters to that class, so how can I fix this. It's important that I can use some kind of chaining, because when that method is done, I need to call another method, so I found the command .thenApply(), but also for that I need to pass paramters.
How can I fix my error and pass parameters?
UPDATE
I tried the following:
CompletableFuture.supplyAsync(() -> new CandlestickDriver.run("USDT", "BTC", "1d", once, firstRun));

But that give me an error on supplyAsync : The method supplyAsync(Supplier<U>) in the type CompletableFuture is not applicable for the arguments (() -> {})
And I also get an error on CandlestickDriver.run: CandlestickDriver.run cannot be resolved to a type
How can I fix this?

A: Here's a full example of how to call supplyAsync in the way you're attempting.  I used a class with fewer arguments, but it should indicate what you need to do.
package com.com;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class QuickExample {

   private static final class Runner {
       public void run(String arg) {
           try {
               // Emulate long running task.

               TimeUnit.SECONDS.sleep(3L);
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
           System.out.println(arg);
       }
   }

   public static void main(String[] args) throws ExecutionException, InterruptedException {
       // Have an instance of your class
       final Runner runner = new Runner();

       // runAsync is also an option if you don't care about any output.
       final CompletableFuture<Object> future = CompletableFuture.supplyAsync(() -> {
           // Invoke your runner
           runner.run("woof");

           // supplyAsync expects a Callable, which returns a value.
           // Assuming you don't care about the output here, you can just
           // return anything.  This will only affect the generic-type of
           // the returned CompletableFuture<...>.
           return null;
       });

       // Get the result to ensure that it's happened before exiting your
       // program.
       future.get();
   }
}

A: You have a syntax related issue immediately, which is new CandlestickDriver.run. This needs to be new CandlestickDriver().run as you're instantiating a new object.
Also, CompletableFuture#supplyAsync takes a Supplier<U> as input, and you're passing Supplier<void>, but void isn't a type that can be supplied. Since this function doesn't return anything, you don't need to supplyAsync, but rather runAsync.
CompletableFuture.runAsync(() -> new CandlestickDriver().run("", "", "", false, false));

A: Check this out, the given information is not complete clear. But propably this is what you try to do.
public class CandlestickDriver implements Supplier<String> , Runnable {

public CandlestickDriver(String market, String coin, String period, boolean once, boolean firstRun)  {

    //store parameter into fields
}

@Override
public String get() {
    return "Get it first";
}

@Override
public void run() {

System.out.println("Run..");

}

}
        CandlestickDriver candlestickDriver = new CandlestickDriver("USDT", "BTC", "1d", true, true);
    CompletableFuture.supplyAsync(candlestickDriver::get).thenRunAsync(candlestickDriver);


text:
Q: How to install HttpCanary Certificate on Android 11 Without Root i want to install the CA certificate which required to use HttpCanary, but my phone says that i can't install in app also i don't know where the CA file that i install. So it needs root to solve that problem. Is there an any way to install without root? Thank You for your answers, sorry for may bad english.

A: Android 11 (or at least my LineageOS 18.1) is a pain, since all certificates must be installed directly from the Settings App, but HttpCanary doesn't give you the raw certificate file.
I found a Chinese post and followed it with the help of Google Translator.
this is the CA file, you can name it HttpCanary.pem and install the it directly from [Settings > Security > Encryption & Credentials > Install a certificate > CA certificate] but the certificate will only be User Trusted, to make it System Trusted you WILL need root access.
[ROOT REQUIRED FOR THE FOLLOWING STEPS]

To install the certificate and make it System Trusted + make HttpCanary detect it, all you need to do is run these commands using ADB from a computer (The connected phone must have USB Debugging turned on):
adb shell
su
mount -o rw,remount /
cp -f /data/data/com.guoshi.httpcanary/cache/HttpCanary.pem /system/etc/security/cacerts/87bc3517.0
chmod 644 /system/etc/security/cacerts/87bc3517.0
touch /data/data/com.guoshi.httpcanary/cache/HttpCanary.jks
chmod 600 /data/data/com.guoshi.httpcanary/cache/HttpCanary.jks


text:
Q: How can I load query from SQLite database into tableview in ios 7 ( xcode 5.1.1 )? I have an SQLite database named "BookDataBase.sqlite" with two columns : Category , Name .
It contains categories for books and some book names for each category .
I have a table view controller connected to class "CategoryTableViewController" which is a subclass of "UITableViewController" .
I want the table view to display the result for a query from the database where only the categories are displayed .
I have tried this code but it didn't work for me .
CategoryTableViewController.m  :
#import "CategoryTableViewController.h"
#import <sqlite3.h>

@interface CategoryTableViewController ()

@end

sqlite3 *BookDatabase;
NSString *databasepath;
const char *filepath;
NSString *querySQL;
const char *query_stmt;
sqlite3_stmt *statement;
NSMutableDictionary *BookRecord;
NSUserDefaults *BookData;
NSMutableArray *BookArray;

@implementation CategoryTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated {

    databasepath = [[NSBundle mainBundle]pathForResource:@"BookDatabase" ofType:@"sqlite"];
    filepath = [databasepath UTF8String];

    if (sqlite3_open(filepath, &BookDatabase) == SQLITE_OK) {

        querySQL = @"SELECT Category FROM BookTable Group By Categoy" ;
        query_stmt = [querySQL UTF8String];

        if (sqlite3_prepare_v2(BookDatabase, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {

                BookRecord =[[NSMutableDictionary alloc] initWithCapacity:sqlite3_column_count(statement)];

                for (int i=0; i<sqlite3_column_count(statement); i++) {

                    NSString *ColName = [[NSString alloc] initWithUTF8String:sqlite3_column_name(statement, i)];
                    NSString *ColVal = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_value(statement, i)];

                    [BookRecord setObject:ColVal forKey:ColName];
                }

                [BookArray addObject:BookRecord];

            }

             sqlite3_finalize(statement);

        }

        sqlite3_close(BookDatabase);

    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [BookArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CategoryTableViewCell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    int row = [indexPath row];

    cell.textLabel.text = [BookArray[row] objectForKey:@"Category"];

    return cell;
}

@end

I have already added the libsqlite3 framework.
The database file is located in the app folder :
https://dl-web.dropbox.com/get/Screen%20Shot%202014-08-15%20at%207.18.22%20PM.png?_subject_uid=104745578&w=AADDzW343bbSsnQ9wko1dFQ3yQes8N5tY9hJmEDb3qnwNw
The type for the table view prototype cell is set to basic and the cell identifier is "CategoryTableViewCell".
The name of the table in the database is "BookTable".
Can someone please help me fix this?
Feel free to rewrite my entire code if needed < but please keep in mind that it's a subcalass of "UITableViewController".
Thanks .

A: I FINALLY FOUND IT
Turns out I didn't add the database file to the main bundle .
I didn't know I should do that .


text:
Q: How to perform CCA with block design in R Following example and data are completely fabricated:
Suppose I am studying grooming behaviour in apes. I have four cages, 8 apes in each (4 females +  males). For 24 hours I did an observations with aim to record the number of events when females were grooming males.

I would like to know, whether I can explain the variability of grooming events [grooming]  with these 5 characteristics of males [m_char] (x1, x2,...x5).

My approach was to perform CCA (a.k.a. canonical correspondence analysis) as following:
library(vegan)
my.cca <- cca(grooming ~ x1 + x2 + x3 + x4 + x5,
              data = m_char,
              scale = TRUE)

and test this model by anova to obtain p-values for factors
anova(my.cca, by="terms", permutations=1000)

# Permutation test for cca under reduced model
# Terms added sequentially (first to last)
# Permutation: free
# Number of permutations: 1000
#
# Model: cca(formula = grooming ~ x1 + x2 + x3 + x4 + x5,
#            data = m_char, scale = TRUE)
#          Df ChiSquare      F   Pr(>F)
# x1        1    0.5327 1.1054 0.718282
# x2        1    0.6216 1.2899 0.359640
# x3        1    0.6341 1.3159 0.314685
# x4        1    0.6739 1.3984 0.191808
# x5        1    0.8782 1.8225 0.008991 **
# Residual 10    4.8188
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Although, x5 seems to have significant effect on grooming, when I look on plot...
plot(my.cca)

...apes from one cage seems to strongly group together.
I think that the structure of my data causes a problem to cca analysis, because, when you look on table with numbers of interactions...

...only zeros in yellow squares are "true" zeros (i.e. there is no interactions between apes), the rest of zeros outside yellow squares are just a consequence of being in different cage.

Is it possible to somehow tell the CCA to ignore "false zeros"? How to
  incorporate such data structure appropriately? My main aim is to find
  whether one or multiple characteristics of males can be used to
  explain the grooming rates.

Thank you very much for any suggestion!

"grooming" example data:
AF1 <- c(3,7,2,0,rep(0, times = 12))
AF2 <- c(8,0,0,3,rep(0, times = 12))
AF3 <- c(0,2,0,0,rep(0, times = 12))
AF4 <- c(4,0,1,0,rep(0, times = 12))
AF4 <- c(4,0,1,0,rep(0, times = 12))
BF1 <- c(rep(0, times = 4),4,1,5,0,rep(0, times = 8))
BF2 <- c(rep(0, times = 4),3,0,0,1,rep(0, times = 8))
BF3 <- c(rep(0, times = 4),0,2,0,0,rep(0, times = 8))
BF4 <- c(rep(0, times = 4),0,0,7,0,rep(0, times = 8))
CF1 <- c(rep(0, times = 8),4,0,4,0,rep(0, times = 4))
CF2 <- c(rep(0, times = 8),2,0,0,0,rep(0, times = 4))
CF3 <- c(rep(0, times = 8),0,3,0,4,rep(0, times = 4))
CF4 <- c(rep(0, times = 8),0,0,9,0,rep(0, times = 4))
DF1 <- c(rep(0, times = 12),0,2,0,0)
DF2 <- c(rep(0, times = 12),6,0,0,1)
DF3 <- c(rep(0, times = 12),0,0,1,0)
DF4 <- c(rep(0, times = 12),4,0,1,0)

male_id <- c("AM1", "AM2", "AM3", "AM4",
             "BM1", "BM2", "BM3", "BM4",
             "CM1", "CM2", "CM3", "CM4",
             "DM1", "DM2", "DM3", "DM4")

grooming <- data.frame(AF1,AF2,AF3,AF4,
                       BF1,BF2,BF3,BF4,
                       CF1,CF2,CF3,CF4,
                       DF1,DF2,DF3,DF4)
rownames(grooming) <- male_id

"m_char" example data:
x1 <- c(2,5,3,1,8,1,1,6,2,3,5,1,1,6,6,7)
x2 <- c(4,9,1,3,2,1,9,4,3,1,9,2,9,1,4,3)
x3 <- c(1,2,5,4,4,4,5,2,2,1,1,1,2,5,5,9)
x4 <- c(4,1,1,8,8,6,6,6,6,8,1,6,2,2,1,1)
x5 <- c(1,7,3,3,4,1,5,1,3,8,4,8,8,5,9,9)

m_char <- data.frame(x1, x2, x3, x4, x5)
rownames(m_char) <- male_id

A: I believe the issue is that the permutation test you are using is too liberal; it assumes a Null hypothesis in which all observations are exchangeable. From what you say, observations within a cage are exchangeable, but are not exchangeable between cages.
To use the more restrictive null in the permutation test we can use a restricted permutation design, in which we ask vegan to only permute observations within cages and never between cages. This is most easily done using a blocking factor.
Create the blocking factor:
m_char <- transform(m_char,
                    cage = factor(substring(rownames(m_char), 1, 1)))

Next, define the restricted permutation design (the defaults for how() mean we get randomisation within the levels of the factor passed to blocks)
ctrl <- how(nperm = 1000, blocks = m_char$cage)

Now fit the model and remove the between-cage variation, which is also required for these analyses with blocks
my.cca <- cca(grooming ~ x1 + x2 + x3 + x4 + x5 + Condition(cage),
              data = m_char)

Now do the restricted permutation test
set.seed(10)
anova(my.cca, by = "terms", permutations = ctrl)

This produces:
> anova(my.cca, by = "terms", permutations = ctrl)
Permutation test for cca under reduced model
Terms added sequentially (first to last)
Blocks:  m_char$cage
Permutation: free
Number of permutations: 1000

Model: cca(formula = grooming ~ x1 + x2 + x3 + x4 + x5 + Condition(cage), data = m_char)
         Df ChiSquare      F  Pr(>F)
x1        1   0.52470 1.4119 0.15185
x2        1   0.60901 1.6388 0.03397 *
x3        1   0.21703 0.5840 0.96503
x4        1   0.36739 0.9886 0.36563
x5        1   0.83984 2.2600 0.03497 *
Residual  7   2.60129
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

And the triplot shows different behaviour to that you obtained

Does this make sense now?


text:
Q: Python Selenium: How to select the drop down menu with highlighted feature I am trying to select the drop down menu. Selenium can control Chrome to click the drop down list and the list shows the options. However, it fails to select and click the options. Is it because the drop down list has a feature when the cursor point to the text and the text will be highlighted. The class name will be changed.
Here is the code:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)

url = 'https://system.arthuronline.co.uk/genieliew1/dashboards/index'
driver.get(url)
wait = WebDriverWait(driver, 20)

wait.until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.ID, 'password'))).send_keys("")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()

url = 'https://system.arthuronline.co.uk/genieliew1/units/view/377225/filter:Transaction-_statement:property-owner;Transaction-_payeeEntityId:149280;Transaction-unit_id:377225;Transaction-_order:default;/page:1#tab-transactions-7322b9'
driver.get(url)

#Click the drop down menu
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()

This is the error:
---------------------------------------------------------------------------
ElementClickInterceptedException          Traceback (most recent call last)
<ipython-input-26-3afc38e2a733> in <module>
     25 #Click the drop down menu
     26 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@id='s2id__statement']"))).click()
---> 27 WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[contains(.,'Property Owner Statement')]"))).click()

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in click(self)
     91     def click(self) -> None:
     92         """Clicks the element."""
---> 93         self._execute(Command.CLICK_ELEMENT)
     94
     95     def submit(self):

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in _execute(self, command, params)
    408             params = {}
    409         params["id"] = self._id
--> 410         return self._parent.execute(command, params)
    411
    412     def find_element(self, by=By.ID, value=None) -> WebElement:

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    442         response = self.command_executor.execute(driver_command, params)
    443         if response:
--> 444             self.error_handler.check_response(response)
    445             response["value"] = self._unwrap_value(response.get("value", None))
    446             return response

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    247                 alert_text = value["alert"].get("text")
    248             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 249         raise exception_class(message, screen, stacktrace)

ElementClickInterceptedException: Message: element click intercepted: Element
...
 is not clickable at point (1280, 646). Other element would receive the click:

  (Session info: chrome=108.0.5359.124)
Stacktrace:
0   chromedriver                        0x00000001055fff38 chromedriver + 4910904
1   chromedriver                        0x000000010557fa03 chromedriver + 4385283
2   chromedriver                        0x00000001051c4747 chromedriver + 472903
3   chromedriver                        0x0000000105212588 chromedriver + 791944
4   chromedriver                        0x000000010520f9ec chromedriver + 780780
5   chromedriver                        0x000000010520c671 chromedriver + 767601
6   chromedriver                        0x000000010520b18b chromedriver + 762251
7   chromedriver                        0x00000001051fbac3 chromedriver + 699075
8   chromedriver                        0x000000010522f112 chromedriver + 909586
9   chromedriver                        0x00000001051fb0ed chromedriver + 696557
10  chromedriver                        0x000000010522f2ce chromedriver + 910030
11  chromedriver                        0x000000010524a28e chromedriver + 1020558
12  chromedriver                        0x000000010522eee3 chromedriver + 909027
13  chromedriver                        0x00000001051f930c chromedriver + 688908
14  chromedriver                        0x00000001051fa88e chromedriver + 694414
15  chromedriver                        0x00000001055cd1de chromedriver + 4702686
16  chromedriver                        0x00000001055d1b19 chromedriver + 4721433
17  chromedriver                        0x00000001055d928e chromedriver + 4752014
18  chromedriver                        0x00000001055d291a chromedriver + 4725018
19  chromedriver                        0x00000001055a6b02 chromedriver + 4545282
20  chromedriver                        0x00000001055f1888 chromedriver + 4851848
21  chromedriver                        0x00000001055f1a05 chromedriver + 4852229
22  chromedriver                        0x0000000105607e5f chromedriver + 4943455
23  libsystem_pthread.dylib             0x00007fff6bdeb109 _pthread_start + 148
24  libsystem_pthread.dylib             0x00007fff6bde6b8b thread_start + 15[!

enter image description here]1


text:
Q: Does large use of signals and slots affect application performance? The question is just done for educational purpose:
Does the use of 30-50 or more pairs of signals and slots between two object (for example two threads) affect the application performance, runtime or response times?

A: First of all, you should probably not put any slots in QThreads. QThreads aren't really meant to be derived from other than by reimplementing the run method and private methods (not signals!).
A QThread is conceptually a thread controller, not a thread itself. In most cases you should deal with QObjects. Start a thread, then move the object instance to that thread. That's the only way you'll get slots working correctly in the thread. Moving the thread instance (it is QObject-derived!) to the thread is a hack and bad style. Don't do that in spite of uninformed forum posts telling otherwise.
As to the rest of your question: a signal-slot call does not have to locate anything nor validate much. The "location" and "validation" is done when the connection is established. The main steps done at the time of the call are:

*

*Locking a signal-slot mutex from a pool.

*Iterating through the connection list.

*Performing the calls using either direct or queued calls.
Common Cost
Any signal-slot call always starts as a direct call in the signal's implementation generated by moc. An array of pointers-to-arguments of the signal is constructed on the stack. The arguments are not copied.
The signal then calls QMetaObject::activate, where the connection list mutex is acquired, and the list of connected slots is iterated, placing the call for each slot.
Direct Connections
Not much is done there, the slot is called by either directly calling QObject::qt_static_metacall obtained at the time the connection was established, or QObject::qt_metacall if the QMetaObject::connect was used to setup the connection. The latter allows dynamic creation of signals and slots.
Queued Connections
The arguments have to marshalled and copied, since the call has to be stored in an event queue and the signal must return. This is done by allocating an array of pointers to copies, and copy-consting each argument on the heap. The code to do that is really no-frills plain old C.
The queuing of the call is done within queued_activate. This is where the copy-construction is done.
The overhead of a queued call is always at least one heap allocation of QMetaCallEvent. If the call has any arguments, then a pointers-to-arguments array is allocated, and an extra allocation is done for each argument. For a call with n arguments, the cost given as a C expression is (n ? 2+n : 1) allocations. A return value for blocking calls is counter as an argument. Arguably, this aspect of Qt could be optimized down to one allocation for everything, but in real life it'd only matter if you're calling trivial methods.
Benchmark Results
Even a direct (non-queued) signal-slot call has a measurable overhead, but you have to choose your battles. Ease of architecting the code vs. performance. You do measure performance of your final application and identify bottlenecks, do you? If you do, you're likely to see that in real-life applications, signal-slot overheads play no role.
The only time signal-slot mechanism has significant overhead is if you're calling trivial functions. Say, if you'd call the trivial slot in the code below. It's a complete, stand-alone benchmark, so feel free to run it and see for yourself. The results on my machine were:
Warming up the caches...
trivial direct call took 3ms
nonTrivial direct call took 376ms
trivial direct signal-slot call took 158ms, 5166% longer than direct call.
nonTrivial direct signal-slot call took 548ms, 45% longer than direct call.
trivial queued signal-slot call took 2474ms, 1465% longer than direct signal-slot and 82366% longer than direct call.
nonTrivial queued signal-slot call took 2474ms, 416% longer than direct signal-slot and 653% longer than direct call.

What should be noted, perhaps, is that concatenating strings is quite fast :)
Note that I'm doing the calls via a function pointer, this is to prevent the compiler from optimizing out the direct calls to the addition function.
//main.cpp
#include <cstdio>
#include <QCoreApplication>
#include <QObject>
#include <QTimer>
#include <QElapsedTimer>
#include <QTextStream>

static const int n = 1000000;

class Test : public QObject
{
    Q_OBJECT
public slots:
    void trivial(int*, int, int);
    void nonTrivial(QString*, const QString&, const QString&);
signals:
    void trivialSignalD(int*, int, int);
    void nonTrivialSignalD(QString*, const QString&, const QString &);
    void trivialSignalQ(int*, int, int);
    void nonTrivialSignalQ(QString*, const QString&, const QString &);
private slots:
    void run();
private:
    void benchmark(bool timed);
    void testTrivial(void (Test::*)(int*,int,int));
    void testNonTrivial(void (Test::*)(QString*,const QString&, const QString&));
public:
    Test();
};

Test::Test()
{
    connect(this, SIGNAL(trivialSignalD(int*,int,int)),
            SLOT(trivial(int*,int,int)), Qt::DirectConnection);
    connect(this, SIGNAL(nonTrivialSignalD(QString*,QString,QString)),
            SLOT(nonTrivial(QString*,QString,QString)), Qt::DirectConnection);
    connect(this, SIGNAL(trivialSignalQ(int*,int,int)),
            SLOT(trivial(int*,int,int)), Qt::QueuedConnection);
    connect(this, SIGNAL(nonTrivialSignalQ(QString*,QString,QString)),
            SLOT(nonTrivial(QString*,QString,QString)), Qt::QueuedConnection);
    QTimer::singleShot(100, this, SLOT(run()));
}

void Test::run()
{
    // warm up the caches
    benchmark(false);
    // do the benchmark
    benchmark(true);
}

void Test::trivial(int * c, int a, int b)
{
    *c = a + b;
}

void Test::nonTrivial(QString * c, const QString & a, const QString & b)
{
    *c = a + b;
}

void Test::testTrivial(void (Test::* method)(int*,int,int))
{
    static int c;
    int a = 1, b = 2;
    for (int i = 0; i < n; ++i) {
        (this->*method)(&c, a, b);
    }
}

void Test::testNonTrivial(void (Test::* method)(QString*, const QString&, const QString&))
{
    static QString c;
    QString a(500, 'a');
    QString b(500, 'b');
    for (int i = 0; i < n; ++i) {
        (this->*method)(&c, a, b);
    }
}

static int pct(int a, int b)
{
    return (100.0*a/b) - 100.0;
}

void Test::benchmark(bool timed)
{
    const QEventLoop::ProcessEventsFlags evFlags =
            QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers;
    QTextStream out(stdout);
    QElapsedTimer timer;
    quint64 t, nt, td, ntd, ts, nts;

    if (!timed) out << "Warming up the caches..." << endl;

    timer.start();
    testTrivial(&Test::trivial);
    t = timer.elapsed();
    if (timed) out << "trivial direct call took " << t << "ms" << endl;

    timer.start();
    testNonTrivial(&Test::nonTrivial);
    nt = timer.elapsed();
    if (timed) out << "nonTrivial direct call took " << nt << "ms" << endl;

    QCoreApplication::processEvents(evFlags);

    timer.start();
    testTrivial(&Test::trivialSignalD);
    QCoreApplication::processEvents(evFlags);
    td = timer.elapsed();
    if (timed) {
        out << "trivial direct signal-slot call took " << td << "ms, "
               << pct(td, t) << "% longer than direct call." << endl;
    }

    timer.start();
    testNonTrivial(&Test::nonTrivialSignalD);
    QCoreApplication::processEvents(evFlags);
    ntd = timer.elapsed();
    if (timed) {
        out << "nonTrivial direct signal-slot call took " << ntd << "ms, "
               << pct(ntd, nt) << "% longer than direct call." << endl;
    }

    timer.start();
    testTrivial(&Test::trivialSignalQ);
    QCoreApplication::processEvents(evFlags);
    ts = timer.elapsed();
    if (timed) {
        out << "trivial queued signal-slot call took " << ts << "ms, "
               << pct(ts, td) << "% longer than direct signal-slot and "
               << pct(ts, t) << "% longer than direct call." << endl;
    }

    timer.start();
    testNonTrivial(&Test::nonTrivialSignalQ);
    QCoreApplication::processEvents(evFlags);
    nts = timer.elapsed();
    if (timed) {
        out << "nonTrivial queued signal-slot call took " << nts << "ms, "
               << pct(nts, ntd) << "% longer than direct signal-slot and "
               << pct(nts, nt) << "% longer than direct call." << endl;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Test t;
    return a.exec();
}

#include "main.moc"

A: Ofcourse they affect application performance, mainly due to the time spent over locating the connection object+ validating the slot object state n so .But the simplicity and flexibility of the signals and slots mechanism is well worth the overhead.Plus one of the major advantage of signal-slot mechanism is they are type=safe allowing communication between objects, irrespective of type of object unlike callbacks.
Compared to callbacks, signals and slots are slightly slower because of the increased flexibility they provide, although the difference for real applications is insignificant. In general, emitting a signal that is connected to some slots, is approximately ten times slower than calling the receivers directly, with non-virtual function calls. This is the overhead required to locate the connection object, to safely iterate over all connections (i.e. checking that subsequent receivers have not been destroyed during the emission), and to marshall any parameters in a generic fashion. While ten non-virtual function calls may sound like a lot, it's much less overhead than any new or delete operation, for example. As soon as you perform a string, vector or list operation that behind the scene requires new or delete, the signals and slots overhead is only responsible for a very small
proportion of the complete function call costs.
Source:Signals and Slots


text: Q: How to convert a .nfo file to .fff I have an nfo file that I want to convert to HTML using https://github.com/imazen/folioxml. However, it requires .fff files. Does anyone know of a way to convert to fff from nfo? Also, if anyone has suggestions for a better way to do this, I am all ears. Thanks!


text:
Q: Uncaught TypeError: Converting circular structure to JSON using JSON.stringfy inside Jquery.each I created this code to send user invites by websocket but It doesn't work and shows this error:

Uncaught TypeError: Converting circular structure to JSON

$.each(formAttibutes, function(index, formAttribute){
    if (formAttribute[0].value !== 0) {
        if (formAttribute[1].value !== 0) {
            var friend = {
                "name": formAttribute[0],
                "description": formAttribute[1],
            };
            socket.send(JSON.stringify(friend));
        }
    }
});

Oh gosh I'm sleepy, sorry. As you said infinity reference (replace formAttribute[1] >> formAttribute[1].value) thanks!

A: I think you are looking to have a JSON stringified object containing the values in those elements (and not the elements themselves). For that, you can do:
...

var friend = {
    "name": formAttribute[0].value,
    "description": formAttribute[1].value
};
socket.send(JSON.stringify(friend));

...

Note: The above is assuming formAttribute[0] and formAttribute[1] are DOMElements. If they are jQuery objects, you should use .val() instead.


text:
Q: How to find specific files in folders and do an operation in case they exist I am having some difficulty doing a basic script in sh shell.
What I want to do is simple though:
I want to do a sh script (can also be csh) that looks through a number of folders and for each folder that contains the files I am interested in, it should do a specific operation of pasting the corresponding filename into a sh script with rdseed commands.
The script I wrote in sh shell and doesn't work is:
for dir in EV*
do
    echo $dir
    cd $dir
    if [ -f GEFLE* = true ];
    then
        set dataless = gur_ini_dataless.seed
        for file GEFLE*
        do
            echo "rdseed -d -o 2 -f "$file " -g " $dataless >> runmseed2ahGEFLE.sh
        done
    else
       echo "File does not exists"
    fi
    sleep 0.5
    cd ..
done

Does anyone know a solution?

A: Please try this... I'm adding some comments to the lines...
#!/bin/sh

for dir in EV*
do
    echo $dir
    cd $dir
    if [ -f GEFLE* ]   # true if at least one FILE named "GEFLE*" exists
    then
        dataless=gur_ini_dataless.seed   # no `set`, no spaces
        for file in GEFLE* # will match all FILES/DIRS/... that start with "GEFLE"
        do
            echo "rdseed -d -o 2 -f $file -g $dataless" >> runmseed2ahGEFLE.sh  # vars are substituted in double quoted strings
        done
    else
       echo "File does not exists"
    fi
    cd ..
done

Please note this will only look one level deep into the directories. If you need some resursion you should better use something like
for dir in `find . -type d -name 'EV*'`; do
    # ...
done

The way I had put this is:
for f in `find EV* -name GEFLE* -type f`; do
    echo "rdseed -d -o 2 -f ./$f -g gur_ini_dataless.seed >> ./`dirname $f`/runmseed2ahGEFLE.sh"
done


text:
Q: Trying to convert input to list I'm trying to take input from user for 2 points and output the distance.
I'm getting stuck on converting the input to a list for the output.
I might be thinking about it the wrong way, any help to get me in the right direction is appreciated.
import math
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = p1.split(',')
x2y2 = p2.split(',')
distance = math.sqrt( ((x1y1[0]-x2y2[0])**2)+((x1y1[1]-x2y2[1])**2) )

print(distance)

A: You can use a list comprehension to translate the inputs into ints and then do a destructuring assignment to assign them to two different variables:
from math import sqrt

[x1, y1] = [int(n) for n in input("please enter x1 and y1: ").split()]
[x2, y2] = [int(n) for n in input("please enter x2 and y2: ").split()]

print(f"Distance: {sqrt((x1-x2)**2+(y1-y2)**2)}")

A: Convert each element to int first:
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = [int(x) for x in p1.split(',')]
x2y2 = [int(y) for y in p2.split(',')]

A: This could help:
from math import sqrt
xi, yi = [int(i) for i in input().split()]
xf, yf = [int(i) for i in input().split()]
print(math.sqrt((xf-xi)**2 + (yf-yi)**2))

A: import math
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = [int(num) for num in p1.split(',')]
x2y2 = [int(num) for num in p2.split(',')]
distance = math.sqrt( ((x1y1[0]-x2y2[0])**2)+((x1y1[1]-x2y2[1])**2) )

print(distance)

Str should be converted to int.

A: You can use map() to easily convert to int
import math
p1 = input("please enter x1 and y1: ")
p2 = input("please enter x2 and y2: ")

x1y1 = list(map(int, p1.split(',')))
x2y2 = list(map(int, p2.split(',')))

distance = math.sqrt( ((x1y1[0]-x2y2[0])**2)+((x1y1[1]-x2y2[1])**2) )

print(distance)


text:
Q: Laravel hasManyThrough joining on wrong ID I have a relation
   public function followers(){
           return $this->hasManyThrough('App\User','App\Follow','owner_id','follower_id);
   }

Its not working though.  It says...
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.follower_id' in 'on clause'

Which is obvious.  Because it should be joining on the ID on the users table.
But if I change it to
public function followers(){
       return $this->hasManyThrough('App\User','App\Follow','owner_id','id);

}
It returns a collection, but its joining the user ID, with the App\Follow ID.
So its returning user #1.  Connected to App\Follow #1.
I want it to be returning user #42  Connected to App\Follow #1.  (follower_id is 42 in this example)
What am I doing wrong?