text:
Q: Posftix+Dovecot emails not delivered I have Debian 9 + Postfix + Dovecot installed following the manual at https://postfix-configuration.readthedocs.io/en/latest/
I have added my domain (say, mydomain.com) + 1 mailbox (mb@mydomain.com) + 1 alias (test@mydomain.com).
However, when trying to send an email from mb@mydomain.com to test@mydomain.com it doesn't appear in the mailbox folder although the Postfix logs show that it got sent successfully although there are no Dovecot logs.
The Dovecot configuration file 10-mail.conf contains this for the mail path:
mail_location = maildir:/var/mail/vmail/%d/%n/Maildir

and Postfix config file main.cf contains this:
home_mailbox = Maildir/
virtual_mailbox_base = /var/mail/vmail/

and nothing new appears within the /var/mail/vmail/mydomain.com/mb/Maildir directory and its sub-directories (/cur and /new).
Please advise whether any additional configuration needs to be done.
Thank you.
This is the content of main.cf:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2

# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mail.mydomain.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydomain = mydomain.com
myorigin = /etc/mailname
mydestination = $myhostname, mydomain.com, localhost.com, , localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
relay_domains = mydomain.com
home_mailbox = Maildir/
mailbox_command =
virtual_mailbox_base = /var/mail/vmail/

# Allow authenticated users to send email, and use Dovecot to authenticate them. Tells Postfix to use Dovecot for authentication
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
smtpd_sasl_type = dovecot
smtp_sasl_type = dovecot

virtual_mailbox_domains = mysql:/etc/postfix/sql/mysql_virtual_domains_maps.cf
virtual_mailbox_maps = mysql:/etc/postfix/sql/mysql_virtual_mailbox_maps.cf
virtual_alias_maps = mysql:/etc/postfix/sql/mysql_virtual_alias_maps.cf

## Path to the Postfix auth socket
smtpd_sasl_path = private/auth
smtp_sasl_path = private/auth

## Tells Postfix to let people send email if they've authenticated to the server.
## Otherwise they can only send if they're logged in (SSH)
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtp_sasl_security_options = noanonymous
smtpd_sasl_local_domain = $myhostname

header_checks = regexp:/etc/postfix/header_checks
mime_header_checks = regexp:/etc/postfix/header_checks

and here is the content of master.cf:
#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd -v
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
submission inet n       -       y       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_recipient_restrictions=permit_sasl_authenticated,reject
  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}

dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}

A: I found out that the emails are saved in the /home/mb/Maildir instead so i just added a symbolic link /home/mb/Maildir to the /var/mail/vmail/mydomain.com/mb/Maildir


text:
Q: How to use dynamic programming through Levenshtein algorithm (in Javascript) I'm trying to understand dynamic programming through Levenshtein algorithm, but I have been stuck on this for a few hours now.  I know my attempt at the following problem is the 'brute force' one. How would I use "dynamic programming" to change my approach? I'm pretty lost....

Problem: Given two strings, s and t, with lengths of n and m, create a
  function that returns one of the following strings: "insert C" if
  string t can be obtained from s by inserting character C "delete C"
  (same logic as above) "swap c d" if string t can be obtained from
  string s by swapping two adjacent characters (c and d) which appear in
  that order in the original string.  "Nothing" if no operation is
  needed "impossible" if none of the above works ie LevenShtein distance is greater than 1.

Here is my brute force attempt. the "tuple" variable is misnamed as I originally wanted to push the indices and values to the matrix but got stuck on that.
function levenshtein(str1, str2) {
  var m = str1.length,
    n = str2.length,
    d = [],
    i, j,
    vals = [],
    vals2 = [];

  for (i = 0; i <= m ; i++) {

    var tuple = [str1[i]];
    //console.log(tuple);
    // console.log(tuple);
    d[i] = [i];
    // console.log(str1[i]);
    vals.push(tuple);

  }
    vals = [].concat.apply([], vals);
    vals = vals.filter(function(n){ return n; });
    console.log(vals);

  for (j = 0; j <= n; j++) {
    d[0][j] = j;
    var tuple2 = [str2[j]];
    // console.log(tuple2);
    vals2.push(tuple2);
    // console.log(vals2);
  }

  vals2 = [].concat.apply([], vals2);
    vals2 = vals2.filter(function(n){ return n ;});
    console.log(vals2);
  for (j = 1; j <= n; j++) {
    for (i = 1; i <= m; i++) {
      if (str1[i - 1] == str2[j - 1]) d[i][j] = d[i - 1][j - 1];
      else d[i][j] = Math.min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1]) + 1;
    }
  }
  var val = d[m][n];

  // console.log(d);
  if(val > 1){
    return "IMPOSSIBLE";
  }
  if(val === 0){
    return "NOTHING";
  }
  //console.log(d);
  if(val === 1){
    //find the missing element between the vals

        //return "INSERT " + missing element
    //find the extra element
        //return "DELETE + " extra element

    //find the out of place element and swap with another
  }

}

console.log(levenshtein("kitten", "mitten"));
// console.log(levenshtein("stop", "tops"));

// console.log(levenshtein("blahblah", "blahblah"));

A: The problem as described cannot be optimized using dynamic programming because it only involves a single decision, not a series of decisions.
Note that the problem specifically states that you should return "impossible" when the Levenshtein distance is greater than 1, i.e., the strings can't be made equal through a single operation. You need to be searching for a sequence of zero or more operations that cumulatively result in the optimal solution if you want to apply dynamic programming. (This is what the dynamic programming wikipedia article is talking about when it says you need "optimal substructure" and "overlapping subproblems" for dynamic programming to be applicable.)
If you change the problem to calculate the full edit distance between two strings, then you can optimize using dynamic programming because you can reuse the result of choosing to do certain operations at a particular location in the string in order to reduce the complexity of the search.

Your current solution looks a bit overly complex for the given problem. Below a simpler approach you can study. This solution takes advantage of the fact that you know you can only do at most one operation, and you can infer which operation to attempt based off the difference between the lengths of the two strings. We also know that it only makes sense to try the given operation at the point where the two strings differ, rather than at every position.

function lev(s, t) {
    // Strings are equal
    if (s == t) return "nothing"
    // Find difference in string lengths
    var delta = s.length - t.length
    // Explode strings into arrays
    var arrS = s.split("")
    var arrT = t.split("")
    // Try swapping
    if (delta == 0) {
        for (var i=0; i<s.length; i++) {
            if (arrS[i] != arrT[i]) {
                var tmp = arrS[i]
                arrS[i] = arrS[i+1]
                arrS[i+1] = tmp
                if (arrS.join("") == t) {
                    return "swap " + arrS[i+1] + " " + arrS[i]
                }
                else break
            }
        }
    }
    // Try deleting
    else if (delta == 1) {
        for (var i=0; i<s.length; i++) {
            if (arrS[i] != arrT[i]) {
                var c = arrS.splice(i, 1)[0]
                if (arrS.join("") == t) {
                    return "delete " + c
                }
                else break
            }
        }
    }
    // Try inserting
    else if (delta == -1) {
        for (var i=0; i<t.length; i++) {
            if (arrS[i] != arrT[i]) {
                arrS.splice(i, 0, arrT[i])
                if (arrS.join("") == t) {
                    return "insert " + arrS[i]
                }
                else break
            }
        }
    }
    // Strings are too different
    return "impossible"
}

// output helper
function out(msg) { $("body").append($("<div/>").text(msg)) }

// tests
out(lev("kitten", "mitten"))
out(lev("kitten", "kitten"))
out(lev("kitten", "kitetn"))
out(lev("kiten", "kitten"))
out(lev("kitten", "kittn"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: laravel querying multiple classes and or tables How do I query more than two tables. What I want to do is have a list of products queryed by a genre and then query productvariations - where a product variation has a producttype_id = $producttype->id
Route::get('browse/{producttype_slug}/{genre_slug}', array(
    'as' => 'products.viewbygenre',
    function($productype_slug, $genre_slug)
    {
        $producttype = ProductTypes::where('slug', '=', $productype_slug)->firstOrFail();

        $genre = GenreTypes::where('slug', '=', $genre_slug)->firstOrFail();

        // error below
        $products = Product::with(array('ProductVariations', 'GenreTypes'))
         ->where('genre', '=', $genre->id)->get();

        return View::make('products.viewbygenre')->with(compact('productvariations', 'genre', 'producttype'));

}))->where('producttype_slug', '[A-Za-z\-]+')->where('genre_slug', '[A-Za-z\-]+');

products class
class Product extends \Eloquent {
    protected $table = "products";
    protected $fillable = ['keywords', 'description', 'title', 'slug', 'release_date', 'clip'];

    public function productvariations() {
        return $this->hasMany("ProductVariations");
    }

    public function variations() {
        $variations = $this->productvariations()->get();
        return $variations;
    }

    public function genres() {
        return $this->belongsToMany('GenreTypes', 'product_genretypes', 'product_id', 'genretype_id')->withTimestamps();
    }

}

A: I didn't quite understand the issue so I will just refer to this bit:
// error below
$products = Product::with(array('ProductVariations', 'GenreTypes'))
         ->where('genre', '=', $genre->id)->get();

I believe you cannot use a where clause this way on a 'with' array. I am not 100% sure if this works when you have more than one parameter in your with method but this is worth trying:
$products = \Product::with(array('ProductVariations', 'GenreTypes' => function ($query)
    {
        // Note I think you also had a mistake in your column name
        // (genre should be genretype_id?)
        // Also ... not sure how you are getting the $genre->id variable
        // as I cannot see the the $genre object / collection in this method you provided !
        $query->where('genretype_id', '=', $genre->id);
    }))->get();

Let us know how you get on.


text:
Q: HttpWebRequest doesn't work: unexpected error occurred on a receive TLS is TLS 1.3, Linux server.
Cipher: TLS_AES_256_GCM_SHA384
error: unexpected error occurred on a receive
'''
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.DefaultConnectionLimit = 9999;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)12288;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://example.com/oauth/token?grant_type=password&username=aptk0012&password=9875322");
            request.Method = "POST";
            request.ContentType = "application/json";
            string post_data = "Basic VV9mZ.....";
            request.Headers.Add("Authorization", post_data);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string result = reader.ReadToEnd();

'''
But Postman does it.
Pls help me here!!!
full error detail is here:
'''See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.ComponentModel.Win32Exception: The client and server cannot communicate, because they do not possess a common algorithm
   at System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)
   at System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)
   at System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)
   at System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)
   at System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
   at System.Net.TlsStream.CallProcessAuthentication(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.ConnectStream.WriteHeaders(Boolean async)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.GetResponse()
   at WindowsFormsApplication1.Form1.ND_Get_Token(String username, String password, LabelControl lbMessage, Boolean is_show_msg) in C:\Users\orgil\OneDrive\Documents\Visual Studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 512
   at WindowsFormsApplication1.Form1.btGetEMDToken_Click(Object sender, EventArgs e) in C:\Users\orgil\OneDrive\Documents\Visual Studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 488

'''


text:
Q: While using cloud firestore .get() doc.exists always remains undefined eventhough the document exists this is the code:
the collection name is"usernames" and documents have a field known as "userName" and i am limitting the data retrieved to 1. i have exactly one document that matches the query and using console logs i verified that data is being retrieved but still everytime snapshot.exists gives me an undefined
db.collection("usernames").where("userName", "==", userName.toString()).limit(1).get()
    .then(snapshot => {
        if(snapshot.exists)
            window.alert("Username already exists");
        else{
            window.alert("Username added");
            db.collection("usernames").add({
                profilePic: "",
                userName: userName

            })

            db.collection("users").add({
                age: age,
                email: email,
                firstName: fname,
                lastName: lname,
                mobileNo: mobileNo,
                password: password,
                userName: userName

            })
            .then( user => dispatch(addNewUser(user)))
            .catch(error => dispatch(addUserFailed(error)));
        }
    })
    .catch(error => dispatch(addUserFailed(error)));

snapshot.exists always is undefined even though the documents are read

A: In your code, snapshot is a QuerySnapshot object, which is a container for 0 or more DocumentSnapshot objects resulting from the query.  The linked API documentation suggests that there is no attribute "exists" on a QuerySnapshot.  Only DocumentSnapshot has an exists property, but that's not what you have here.
Even if you are expecting exactly one document from the query, you still should check the QuerySnapshot to make sure it contains the one document you're looking for.  You could do this by checking the size() of the results:
.then(querySnapshot => {
    if (querySnapshot.size() > 0) {
        const docSnapshot = querySnapshot.docs[0];
    }
    else {
        // decide what you want to do if no results
    }


text:
Q: Closing a python DDE 'Conversation', and terminating server? OK, DDE is ridiculously ancient technology, but, I'm stuck with it for the moment.
In python 2.7 I'm able to start a DDE server, and create conversations to collect data from the 3rd party application, however, I can't figure out how to gracefully terminate the conversation/server.
The DDE module is compiled (it is 'dde.pyd'), so I can't look inside
When I run 'help(dde)', after importing DDE (and win32ui), I don't see any functions for closing things down.
Can anyone offer me any help?


text:
Q: Kivy Issue - Unable to get a Window, abort Problem:
I am tyring to run kivy for the first time for my python 3.9 project but I get the following error:
Python : 3.9
OS: Windows 10
Installation Method:
python -m pip install --upgrade pip wheel setuptools
python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew
python -m pip install kivy.deps.gstreamer
python -m pip install kivy.deps.angle
python -m pip install kivy

Error:
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

[INFO ] [Logger ] Record log in C:\Users\User.kivy\logs\kivy_21-09-18_23.txt
[INFO ] [deps ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO ] [deps ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO ] [deps ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO ] [deps ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO ] [Kivy ] v2.0.0
[INFO ] [Kivy ] Installed at "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\kivy_init_.py"
[INFO ] [Python ] v3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)]
[INFO ] [Python ] Interpreter at "C:\Users\User\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe"
[INFO ] [Factory ] 186 symbols loaded
[INFO ] [Image ] Providers: img_tex, img_dds (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Window ] Unable to find any valuable Window provider. Please enable debug logging (e.g. add -d if running from the command line, or change the log level in the config) and re-run your app to identify potential causes
sdl2 - ImportError: DLL load failed while importing window_sdl2: The specified module could not be found.
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\kivy\core_init.py", line 58, in core_select_lib
mod = import(name='{2}.{0}.{1}'.format(
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\kivy\core\window\window_sdl2.py", line 27, in
from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App ] Unable to get a Window, abort.

Code:
from kivy.app import App

class TheLabApp(App):
   pass

TheLabApp().run()

A: Ok so I have fixed it:
I dont know how it worked but I just reinstalled python 3.9 and kivy 2.0.0 and then it worked
Code to uninstall kivy:
python -m pip unisntall kivy
python -m pip uninstall kivy.deps.angle
python -m pip uninstall kivy.deps.sdl2
python -m pip uninstall kivy.deps.glew
python -m pip uninstall kivy.deps.gstreamer

Code to reinstall it:
pip install kivy
pip install kivy.deps.angle
pip install kivy.deps.sdl2
pip install kivy.deps.glew
pip install kivy.deps.gstreamer


text:
Q: Divergence in Spherical & Cylindrical Polar co-ordinates derivation I am attempting to understand how to derive $\vec{\nabla}.\vec{F}$ in both cylindrical and spherical polar co-ordinates.
I understand that in a Cartesian system we say:
$$\vec{\nabla}\vec{F}=\frac{\partial{F}}{\partial{x}}\hat{x}+\frac{\partial{F}}{\partial{y}}\hat{y}+\frac{\partial{F}}{\partial{z}}\hat{z}.$$
In principle, it would be straightforward to 'translate' the vector derivitive into $r,\theta,\phi$ notation by the chain rule:
$$\frac{\partial{F}}{\partial{x}}=\frac{\partial{F}}{\partial{r}}\left(\frac{\partial{r}}{\partial{x}}\right)+\frac{\partial{F}}{\partial{\theta}}\left(\frac{\partial{\theta}}{\partial{x}}\right)+\frac{\partial{F}}{\partial{\phi}}\left(\frac{\partial{\phi}}{\partial{x}}\right).$$
However, I understand this would take a very long time to derive via this method. The text-book that I am using states the above (Introduction to Electrodynamics- Griffiths), but it then suddenly jumps to the following with no explanation:
$$\vec{\nabla}\vec{F}=\frac{\partial{F}}{\partial{r}}\hat{r}+\frac{1}{r}\frac{\partial{F}}{\partial{\theta}}\hat{\theta}+\frac{1}{rsin\theta}\frac{\partial{F}}{\partial{\phi}}\hat{\phi}.$$
My intuition tells me (which is obviously wrong) that the above should simply be:
$$\vec{\nabla}\vec{F}=\frac{\partial{F}}{\partial{r}}\hat{r}+\frac{\partial{F}}{\partial{\theta}}\hat{\theta}+\frac{\partial{F}}{\partial{\phi}}\hat{\phi}.$$
As the gradient is the rate of change of F within each 'dimension'. I vaguely remember my lecturer saying that we can derive it simply due to unit consistency, but I have no clue why I am wrong, and from here, how to get to divergence and even curl.
If anyone can let me know, that'd be great, I am assuming it is a reasonably similar answer for cylindrical polars also. Thanks in advance.


text:
Q: Internal error in debugger Can anyone help me with this error in Visual Studio 2015? When I put a breakpoint, on debug I receive this error(from the picture) and after that vshost32 stop working.
enter image description here
Edit: that post doesn't have a correct answer. The error is still there. I try all the answers from suggested post.


text:
Q: How to selectively log call stack I'm pulling my hair out trying to understand android objects' lifecycles and debugging my code. After having read hundreds of questions on lifecycles of Activitys, Fragments and Services, I've come to the conclusion that confusion is the natural state of affairs for most Android developers in this area, which comforts me to some degree.
I have wrapped android's Log.x() functions in my version, LOG.x() which accepts additional arguments so I can filter what is logged based on flags, but I would like to extend it further so I can examine real-time call graphs.
At the moment, I must have hundreds of LOG.x() calls at the beginning of methods. This, with the flags, has helped me a great deal. But it still falls a bit short:
It would be nice if I could see a real-time hierarchical tree/list of (filtered) calls.
I'm amazed I haven't seen anything like this! Are there any tools which do it?
If not, what would be a good way of writing this? I think calling Log.x() is now falling short, it's obviously not meant for this. I was thinking of writing an eclipse plugin, and using System.out's println() calls or similar to get data to it. But this would become an enormous amount of work.
Then there's the matter of actually determining which methods called which methods and so on.
Any advice would be great
Thanks

A: There is such a thing as printStackTrace(), and it can be used virtually everywhere:
 public static void printStack() {
    Throwable throw = new Throwable();
    throw.printStackTrace();
 }

Also, I think what you're thinking of is a non-interactive debugger. There wasn't a need for one, since we have the interactive ones.


text:
Q: JSF2 h:message is not displayed in its specific field I want to display messages next to h:inputText fields but they just won't show there but are displayed in a field for global messages instead.
The message fields are bound to a inputText by a binding tag but when i call them with getClientId() in my backing bean the returned id seems to be wrong. I think this causes the messages to be displayed in a global field.
This can be viewed in the linked image below.

My page:
<a4j:outputPanel id="editPanel">
        <a4j:queue requestDelay="300" ignoreDupResponses="true" />

                Kostenstelle
                <h:inputText id="kst" inputType="text" placeholder=""
                        value="#{kostenstellenBean.kst}" label="Kostenstelle"
                        maxlength="5" binding="#{kostenstellenBean.kstInput}">
                        <a4j:ajax event="keyup" render="buttonPanel kstMessage" />
                    </h:inputText>
                <h:message id="kstMessage" for="kst" />

                Bezeichnung
                <h:inputText id="bezeichnung" inputType="text"
                        placeholder="" value="#{kostenstellenBean.bezeichnung}"
                        label="Bezeichnung" maxlength="20"
                        binding="#{kostenstellenBean.bezeichnungInput}">
                        <a4j:ajax event="keyup" render="buttonPanel bezeichnungMessage" />
                    </h:inputText>
                <h:message id="bezeichnungMessage" for="bezeichnung" />

                BA
                <h:inputText id="ba" inputType="text" placeholder=""
                        value="#{kostenstellenBean.ba}" label="BA" maxlength="3"
                        binding="#{kostenstellenBean.baInput}">
                        <a4j:ajax event="keyup" render="buttonPanel baMessage" />
                    </h:inputText>
                <h:message id="baMessage" for="ba" />

                BK
                <h:inputText id="bk" inputType="text" placeholder=""
                        value="#{kostenstellenBean.bk}" label="BK" maxlength="3"
                        binding="#{kostenstellenBean.bkInput}">
                        <a4j:ajax event="keyup" render="buttonPanel bkMessage" />
                    </h:inputText>
                <h:message id="bkMessage" for="bk" />

                BL
                <h:inputText id="bl" inputType="text" placeholder=""
                        value="#{kostenstellenBean.bl}" label="BL" maxlength="3"
                        binding="#{kostenstellenBean.blInput}">
                        <a4j:ajax event="keyup" render="buttonPanel blMessage" />
                    </h:inputText>
                <h:message id="blMessage" for="bl" />

        <rich:panel id="buttonPanel">
            <bwf:commandButton id="save" value="Speichern"
                disabled="#{!kostenstellenBean.validateData()}">
                <rich:componentControl target="confirmation_save" operation="show" />
            </bwf:commandButton>
            <bwf:commandButton id="edit" value="Ändern"
                disabled="#{!kostenstellenBean.rowSelected or !kostenstellenBean.validData}">
                <rich:componentControl target="confirmation_edit" operation="show" />
            </bwf:commandButton>
            <bwf:commandButton id="delete" value="Löschen"
                disabled="#{!kostenstellenBean.rowSelected}">
                <rich:componentControl target="confirmation_delete"
                    operation="show" />
            </bwf:commandButton>
            <h:messages />
        </rich:panel>
    </a4j:outputPanel>

And my validation method in the backing bean:
public boolean validateData() {
    boolean valid = true;
    String message;
    FacesContext context = FacesContext.getCurrentInstance();
    if (kst == 0) {
        message = "Kostenstelle ungültig! ";
        context.addMessage(kstInput.getClientId(), new FacesMessage(message
                + kstInput.getClientId()));
        valid = false;
    }
    if (bezeichnung == null || bezeichnung.isEmpty()) {
        message = "Bezeichnung muss vorhanden sein!";
        context.addMessage(bezeichnungInput.getClientId(),
                new FacesMessage(message));
        valid = false;
    }
    if (ba + bk + bl != 100) {
        message = "Die Summe aller Verteilungsschlüssel muss 100 ergeben! ";
        context.addMessage(baInput.getClientId(), new FacesMessage(message));
        valid = false;
    }
    validData = valid;
    return valid;
}

All those input fields change the command buttons availability depending on their input. If it is not valid, the command buttons should be disabled. This works so far.
The problem is that the messages invoked in the backing bean are not displayed next to the input fields which I address by their binding and getClientId() but in the field for global messages under the command buttons (This field should be removed when all messages are displayed properly.).
Hopefully someone could point out a mistake I made or tell me the flaws in my logic.

A: I fixed the problem by trying a different approach.
Now I'm using the required attribute for the first two input fields which simply should not be empty, resulting in the error messages being displayed in the specified message fields.
For the other three input fields a method in the backing bean checks if their sum equals 100 and if not just displays a global message.


text:
Q: Word VBA - Returning the bookmark by finding Text I'm trying to write some VBA with a Microsoft Word Document that will search for a text string within itself, and once it has found it, will return the preceding bookmark name.
I currently have the below code;
Public Sub FindDocument()

Dim wrdThis As Document
Dim strSearch As String
Dim myRange As Range
Dim lngBookMark As Long
Dim lngHeadingName As Long
Dim varBookmarks As Variant
Dim i As Integer

Set wrdThis = ThisDocument
Set myRange = wrdThis.Content

strSearch = "ID: VTER"

varBookmarks = wrdThis.GetCrossReferenceItems(wdRefTypeBookmark)

myRange.Find.Execute FindText:=strSearch, Forward:=True
If myRange.Find.Found = True Then
    lngBookMark = myRange.BookmarkID
    MsgBox "Search text found in bookmark " & varBookmarks(lngBookMark)
End If

End Sub

I can't seem to get the code to return a unique identifier for the preceding bookmark as the text I am searching for will be found between 2 bookmarks.
Any help would be greatly appreciated.

A: The only way, really, to pick up bookmarks is to query them from a Range. In your case, you need the Range from the Found range backwards. Simplest would simply be to set the Range back to the start of the Document, then pick up the last bookmark. The following code sample, based on your original, illustrates this.
Note that I've changed ThisDocument to ActiveDocument. ThisDocument is the document object in which your VBA code resides. I'm assuming you want the code to run on whichever document is currently being worked on? In that case, ActiveDocument is correct.
Sub FindThenPrevBookmark()
    Dim wrdThis As Document
    Dim strSearch As String
    Dim myRange As Range, rngToStart As word.Range
    Dim bkm As word.Bookmark
    'Dim lngBookMark As Long
    'Dim lngHeadingName As Long
    'Dim varBookmarks As Variant
    'Dim i As Integer

    Set wrdThis = ActiveDocument
    Set myRange = wrdThis.content

    strSearch = "Home"

    'Ensure that Execute and Found are performed on the same FIND
    With myRange.Find
        .Execute findText:=strSearch, Forward:=True
        If .found = True Then
            'Always use DUPLICATE to "copy" a Range object!
            Set rngToStart = myRange.Duplicate
            rngToStart.Start = wrdThis.content.Start
            If rngToStart.Bookmarks.Count > 0 Then
                Set bkm = rngToStart.Bookmarks(rngToStart.Bookmarks.Count)
                MsgBox "Search text found in bookmark " & bkm.Name
            End If
        End If
    End With
End Sub


text:
Q: RecyclerView and OnItemClick: No value passed for parameter 'click' in Fragment I'm trying to implement an OnClick listener for specific items in a recyclerview. I've done it before with activities, but now I want to do this in a fragment and I've run into a problem. I'm getting the error No value passed for parameter 'click'. This is the line of code that gives that error:
recyclerAdapterAbstract = abstractList.let {AbstractAdapter(requireActivity(),it)}

This the only error Android Studio is currently showing me. The logcat doesn't show any error. Only the Build Output shows what's wrong and it's exactly what I said earlier
Fragment Class
  @Suppress("UNREACHABLE_CODE")
class AbstractWallpapers: Fragment(), PurchasesUpdatedListener, AbstractAdapter.OnItemClickListenerAbstract {

    private lateinit var subscribeAbstract: Button

    private var billingClient: BillingClient? = null

    lateinit var recyclerView: RecyclerView
    lateinit var abstractList: ArrayList<Abstract>

    private var recyclerAdapterAbstract: AbstractAdapter? = null
    private var myRef3: DatabaseReference? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_abstract_wallpaper, container, false)

        recyclerView = requireActivity().findViewById(R.id.abstract_recyclerView)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.abstract_recyclerView)

        val layoutManager = GridLayoutManager(requireContext(), 2)

        recyclerView.layoutManager = layoutManager
        recyclerView.setHasFixedSize(true)

        myRef3 = FirebaseDatabase.getInstance().reference
        abstractList = ArrayList()
        ClearAll()
        GetDataFromFirebase()

        subscribeAbstract = view.findViewById(R.id.abstract_subscribe_btn)

        subscribeAbstract.setOnClickListener {
            subscribeAbstract()

        }

        //Establish connection to billing client
        //check subscription status from google play store cache
        //to check if item is already Subscribed or subscription is not renewed and cancelled
        billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
        billingClient!!.startConnection(object : BillingClientStateListener {

            override fun onBillingSetupFinished(billingResult: BillingResult) {
                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    val queryPurchase = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)

                    val queryPurchases = queryPurchase.purchasesList
                    if (queryPurchases != null && queryPurchases.size > 0) {
                        handlePurchases(queryPurchases)

                    } else {

                        saveSubscribeValueToPref(false)
                    }
                }
            }

            override fun onBillingServiceDisconnected() {
                Toast.makeText(requireActivity(), "Service Disconnected", Toast.LENGTH_SHORT).show()
            }
        })

        //item subscribed
        if (subscribeValueFromPref) {
            subscribeAbstract.visibility = View.GONE

        } else {
            subscribeAbstract.visibility = View.VISIBLE

        }
    }

    // Code relating to my Firebase storage
    @SuppressLint("NotifyDataSetChanged")
    private fun GetDataFromFirebase() {

        val query: Query = myRef3!!.child("Abstract")

        query.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {

                for (dataSnapshot: DataSnapshot in snapshot.children) {
                    val abstract = Abstract()

                    abstract.abstract = dataSnapshot.child("abstract").value.toString()
                    abstractList.add(abstract)}

                recyclerAdapterAbstract = abstractList.let {AbstractAdapter(requireActivity(),it)}

                recyclerView.adapter = recyclerAdapterAbstract
                recyclerAdapterAbstract!!.notifyDataSetChanged()
            }

            override fun onCancelled(error: DatabaseError) {}
        })
        if (recyclerAdapterAbstract != null) recyclerAdapterAbstract!!.notifyDataSetChanged()
    }

    private fun ClearAll() {
        abstractList.clear()
        abstractList = ArrayList()
    }

    private val preferenceObject: SharedPreferences
        get() = requireActivity().getSharedPreferences(PREF_FILE, 0)

    private val preferenceEditObject: SharedPreferences.Editor
        get() {
            val pref = requireActivity().getSharedPreferences(PREF_FILE, 0)
            return pref.edit()
        }

    private val subscribeValueFromPref: Boolean
        get() = preferenceObject.getBoolean(SUBSCRIBE_KEY, false)

    private fun saveSubscribeValueToPref(value: Boolean) {
        preferenceEditObject.putBoolean(SUBSCRIBE_KEY, value).commit()
    }

    //initiate purchase on button click
    fun subscribeAbstract() {
        //check if service is already connected
        if (billingClient!!.isReady) {
            initiatePurchase()
        } else {
            billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
            billingClient!!.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                        initiatePurchase()
                    } else {
                        Toast.makeText(requireActivity(), "Error " + billingResult.debugMessage, Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onBillingServiceDisconnected() {
                    Toast.makeText(requireActivity(), "Service Disconnected ", Toast.LENGTH_SHORT).show()
                }
            })
        }
    }

    private fun initiatePurchase() {
        val skuList: MutableList<String> = ArrayList()
        skuList.add(ITEM_SKU_SUBSCRIBE)
        val params = SkuDetailsParams.newBuilder()
        params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS)
        val billingResult = billingClient!!.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS)
        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
            billingClient!!.querySkuDetailsAsync(params.build()
            ) { billingResult, skuDetailsList ->
                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    if (skuDetailsList != null && skuDetailsList.size > 0) {
                        val flowParams = BillingFlowParams.newBuilder()
                            .setSkuDetails(skuDetailsList[0])
                            .build()
                        billingClient!!.launchBillingFlow(requireActivity(), flowParams)
                    } else {
                        //try to add subscription item "sub_example" in google play console
                        Toast.makeText(requireActivity(), "Item not Found", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(requireActivity(),
                        " Error " + billingResult.debugMessage, Toast.LENGTH_SHORT).show()
                }
            }
        } else {
            Toast.makeText(requireActivity(),
                "Sorry Subscription not Supported. Please Update Play Store", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onPurchasesUpdated(billingResult: BillingResult, purchases: List<Purchase>?) {
        //if item subscribed
        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
            handlePurchases(purchases)
        }
        else if (billingResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
            val queryAlreadyPurchasesResult = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)
            val alreadyPurchases = queryAlreadyPurchasesResult.purchasesList
            alreadyPurchases?.let { handlePurchases(it) }
        }
        else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
            Toast.makeText(requireActivity(), "Purchase Canceled", Toast.LENGTH_SHORT).show()
        }
        else {
            Toast.makeText(requireActivity(), "Error " + billingResult.debugMessage, Toast.LENGTH_SHORT).show()
        }
    }

    fun handlePurchases(purchases: List<Purchase>) {
        for (purchase in purchases) {
            //if item is purchased
            if (ITEM_SKU_SUBSCRIBE == purchase.sku && purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
                if (!verifyValidSignature(purchase.originalJson, purchase.signature)) {
                    // Invalid purchase
                    // show error to user
                    Toast.makeText(requireActivity(), "Error : invalid Purchase", Toast.LENGTH_SHORT).show()
                    return
                }
                // else purchase is valid
                //if item is purchased and not acknowledged
                if (!purchase.isAcknowledged) {
                    val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchase.purchaseToken)
                        .build()
                    billingClient!!.acknowledgePurchase(acknowledgePurchaseParams, ackPurchase)
                } else {
                    // Grant entitlement to the user on item purchase
                    // restart activity
                    if (!subscribeValueFromPref) {
                        saveSubscribeValueToPref(true)
                        Toast.makeText(requireActivity(), "Item Purchased", Toast.LENGTH_SHORT).show()
                        recreate(requireActivity())
                    }
                }
            } else if (ITEM_SKU_SUBSCRIBE == purchase.sku && purchase.purchaseState == Purchase.PurchaseState.PENDING) {
                Toast.makeText(requireActivity(),
                    "Purchase is Pending. Please complete Transaction", Toast.LENGTH_SHORT).show()
            } else if (ITEM_SKU_SUBSCRIBE == purchase.sku && purchase.purchaseState == Purchase.PurchaseState.UNSPECIFIED_STATE) {
                saveSubscribeValueToPref(false)
                subscribeAbstract.visibility = View.VISIBLE
                Toast.makeText(requireActivity(), "Purchase Status Unknown", Toast.LENGTH_SHORT).show()
            }
        }
    }

    var ackPurchase = AcknowledgePurchaseResponseListener { billingResult ->
        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
            //if purchase is acknowledged
            // Grant entitlement to the user. and restart activity
            saveSubscribeValueToPref(true)
            recreate(requireActivity())
        }
    }

    /**
     * Verifies that the purchase was signed correctly for this developer's public key.
     *
     * Note: It's strongly recommended to perform such check on your backend since hackers can
     * replace this method with "constant true" if they decompile/rebuild your app.
     *
     */
    private fun verifyValidSignature(signedData: String, signature: String): Boolean {
        return try {
            // To get key go to Developer Console > Select your app > Development Tools > Services & APIs.
            val base64Key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhBlajrk5nNjpRTPJjDtGxgtgAeKijz3Wc0KrRKKSCxxsViHl7DhsI+sUZfk4Y1jxSg4/3W1uRo/0UASM77XfJIq34bK9KYgoSAGYSuH8Z+4fK/MrPz7dHhsljkAi4GZkv8x9VhZdDdpn2GSHVFaxs8c+HBOFp9aWAErHrQhi9/7fYf39pQSTC3WkVcy9xNDZxiiKTfDN3dyEvS0XQ617ZJwqDuRdkU5Aw9+R8r+oXyURV/ekgCQkWfCUaTp/jWdySOIcR87Bde24lQAXbvJaL5uAYI4zPwO4sIP1AbXLuDtv3N2rFVmP/1cML/NHDcfI5FOoStz88jzJU26Ngpqu1QIDAQAB"
            Security.verifyPurchase(base64Key, signedData, signature)
        } catch (e: IOException) {
            false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (billingClient != null) {
            billingClient!!.endConnection()
        }
    }

    companion object {
        const val PREF_FILE = "MyPref"
        const val SUBSCRIBE_KEY = "subscribe"
        const val ITEM_SKU_SUBSCRIBE = "abstract_wallpapers"
    }

    override fun onItemClick(item: String) {

    }
}

Adapter class
 class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>, private val click: OnItemClickListenerAbstract ) :
    RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {

     interface OnItemClickListenerAbstract{
         fun onItemClick(item:String)
     }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
        return ViewHolder(view)

    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Glide.with(mContext)
            .load(abstractList[position].abstract)
            .into(holder.imageView)

        holder.imageView.setOnClickListener {
            val intent = Intent(mContext, AbstractPreview::class.java)
            intent.putExtra("abstract", abstractList[position].abstract.toString())
            Toast.makeText(mContext, "Fullscreen view", Toast.LENGTH_SHORT).show()
            mContext.startActivity(intent)

        }

        holder.downloadBtn.setOnClickListener {
            abstractList.get(position).abstract?.let { it1 -> click.onItemClick(it1) }
        }
    }

    override fun getItemCount(): Int {
        return abstractList.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.abstractImageView)
        val downloadBtn: Button = itemView.findViewById(R.id.abstractDownloadBtn)

    }

    companion object
}

A: You have 3 parameters for the class AbstractAdapter
 class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>, private val click: OnItemClickListenerAbstract )

but you are instantiating the object with only two parameters
AbstractAdapter(requireActivity(),it)

It's expecting the third parameter for the clickListener
AbstractAdapter(requireActivity(),it,this)

(send the Fragment as the third param)


text:
Q: Uploading videos to specific Google account through YouTube API After hours of searching, i've did'nt found a solution yet.
The most relevant post i've found is : Youtube API : Service account
According to this part of the Google documentation : here
That i've read is that YT API did not support Service Accounts, so i've found no other solution yet.
There is any way to uploading videos to specific Google (YT) account, without ask the users of my service to log to their Google account ? The fact is that I want to any users on my website can upload some videos in private mode to my Youtube account, but google, when creating the client though this portion of code :
$client = new Google_Client();
$key = file_get_contents("some/path/to/".KEY_FILE);
$client->setClientId(CLIENT_ID);
     $client->setAssertionCredentials(
          new Google_AssertionCredentials(
              SERVICE_ACCOUNT_NAME,
              array('https://www.googleapis.com/auth/youtube'),
                $key
          )
     );
$client->setRedirectUri('some_url');
$client->setDeveloperKey('some_DEV_KEY');

request to my user to get logged in with his own Google account...
Any way to bypass this login request by enter my own credentials in the code ?
Sorry for not-so-good english, and thank you.

A: Eric , It  is possible to do that if you use the  browser upload API ( V2 ) https://developers.google.com/youtube/2.0/developers_guide_protocol_browser_based_uploading . However it doesn't fully support CORS which means you can't show a progress bar and you must use iframes to handle the browser redirect.
  Youtube fixed the CORS issue in V3 but they don't support browser based uploading anymore so they suck and you have to choose either to proxy the video upload through your server(I do this) or ask the user login with their google account. I think they did it on purpose to promote the plus service. After they 'fixed it' ( took about a year ) a guy @jeff showed a demo using  google plus to login ! what a joke !

A: It is by design that you can't easily do what you're wanting; you don't want to be liable for what other people upload through your app into your account. The best way to accomplish what you're after is to use something like Youtube Direct Lite -- users will upload videos into their own accounts with their own credentials, but it automatically will tie those videos into a playlist that you run off your own app (and it even gives you review capabilities over whether those videos should be included).
You can also roll your own solution that accomplishes the same kind of approach. Trust me ... at some point you'll be grateful that you can't just let anyone upload into your personal account!

A: Here's the solution : use ClientLogin authentication.
That allow us to specify our YT credentials through this line :
$httpClient = Zend_Gdata_ClientLogin::getHttpClient($youtubeEmail, $youtubePassword, 'youtube');

NB : The third parameter is the "id" of the service we want to connect to
I know ClientLogin is deprecated but this solution work. If there is any solution more secure and clean, let me know :)
Have a nice day


text:
Q: Jquery radio button preventDefault on click event, if ajax fails I have radio buttons. Ajax request executed on click and returns response. success variable receives result(true or false). What I need is to make radio checked only if ajax is successfull. But it marked checked before ajax is called.
$('input[type="radio"]').on('click',function (e){
    var success = callAjax();
    if (!success)
       e.preventDefault();
});

Upd.
The reason to use preventDefault is to leave previous radio button checked. Not just uncheck current.

A: Use $(this).prop("checked",false); to check the radio button when ajax is return true.
Following code may help you..
$('input[type="radio"]').on('click',function (e){
    var success = callAjax();;
    if (!success){
        e.preventDefault();
        $(this).prop("checked",false);
    }
});

For Live Demo Please Check the JSFIDDLE

A: $('input[type="radio"]').on('click',function (e){
    var success = callAjax();
    if (!success){
       $(this).prop('checked', false);
    }

});

A: All AJAX requests are run asynchronously, it means that you will not get a response right after your AJAX request is executed.
You would need to change your code a bit to make it work:
$('input[type="radio"]').on('click',function (e){
    var _this = this;
    var currentState = $(this).prop("checked");
    callAjax(function(success) {
        if (!success)
             $(_this).prop("checked", !currentState);
    });
});

And you should change your callAjax method to receive a callback function as parameter and call then request is complete with success parameter.
I hope you got an idea!

A: You can check/uncheck your checkbox using:
$("#chkBox").attr('checked', false); //uncheck
$("#chkBox").attr('checked', true); //check


text:
Q: Why Does Raising PropertyChanged events from a timer cause an COMException? I'm developing a Universal Windows Platform app using XAML that runs on a Raspberry Pi under Windows 10 IoT Core. The app drives a temperature sensor that's on the I2C bus. The sensor class is MLX90614Thermometer. The sensor uses a DispatcherTimer to take readings every 100 milliseconds (approx) and updates a moving average. When the value of the moving average changes by more than a specified threshold, the sensor raises a ValueChanged event and provides the new value in the event args.
In my ViewModel class, TemperatureSensorViewModel, I subscribe to the sensor's ValueChanged event and use it to update bound properties named Ambient, Channel1 and Channel2. These properties are bound to text blocks in the XAML UI. Here is the event handler:
    void HandleSensorValueChanged(object sender, SensorValueChangedEventArgs e)
    {
        switch (e.Channel)
        {
            case 0:
                Ambient = e.Value;
                break;
            case 1:
                Channel1 = e.Value;
                break;
            case 2:
                Channel2 = e.Value;
                break;
        }
    }

...and here is a sample data binding for Ambient...
    <TextBlock x:Name="Ambient"  Grid.Row="1" Text="{Binding Path=Ambient}" Style="{StaticResource FieldValueStyle}" />

I'm using the MVVM Light Toolkit, so my properties are implemented like this (only Ambient shown, but the others are identical except in name):
    public double Ambient
    {
        get { return ambientTemperature; }
        private set { Set(nameof(Ambient), ref ambientTemperature, value); }
    }

The MVVM Light Toolkit provides the Set() method, which automatically raises the PropertyChanged notification for the property being set.
This works correctly if I read a single sample from the sensor in response to a button press. As soon as I enable the automatic sampling mode (which is timer based) though, it starts throwing COMExceptions. So this must be some kind of threading issue related to the timer.
Now, if I understand correctly, the runtime is supposed to marshal PropertyChanged notifications onto the UI thread automatically; and that does seem to be the case from looking at the stack trace. However, I eventually get a COMException. Ugh.

System.Runtime.InteropServices.COMException (0x8001010E): The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
   at System.Runtime.InteropServices.WindowsRuntime.PropertyChangedEventArgsMarshaler.ConvertToNative(PropertyChangedEventArgs managedArgs)
   at System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e)
   at GalaSoft.MvvmLight.ObservableObject.RaisePropertyChanged(String propertyName)
   at GalaSoft.MvvmLight.ViewModelBase.RaisePropertyChanged[T](String propertyName, T oldValue, T newValue, Boolean broadcast)
   at GalaSoft.MvvmLight.ViewModelBase.Set[T](String propertyName, T& field, T newValue, Boolean broadcast)
   at TA.UWP.Devices.Samples.ViewModel.TemperatureSensorViewModel.set_Channel1(Double value)
   at TA.UWP.Devices.Samples.ViewModel.TemperatureSensorViewModel.HandleSensorValueChanged(Object sender, SensorValueChangedEventArgs e)
   at TA.UWP.Devices.MLX90614Thermometer.RaiseValueChanged(UInt32 channel, Double value)
   at TA.UWP.Devices.MLX90614Thermometer.SampleAllChannels()
   at TA.UWP.Devices.MLX90614Thermometer.b__37_0()
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at TA.UWP.Devices.MLX90614Thermometer.d__37.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at TA.UWP.Devices.MLX90614Thermometer.d__38.MoveNext()

WAT? I don't understand what's happening here. Can anyone see what the problem might be?

A: After further research,  think I can answer my own question...
It seems that I made an invalid assumption about PropertyChanged events being marshalled to the UI thread automatically. I read that in a few places in articles about WPF, but as @Clemens pointed out in a comment, this is not WPF we are talking about, it is the Universal Windows Platform, which is a derivative of the Windows Runtime (WinRT).

*

*Key Learning: XAML in UWP ≠ WPF. You can't rely on WPF documentation when considering Universal Windows Apps.

Then I found this question which has similarities to mine, specifically that the poster has made my mistake of assuming that he's dealing with WPF. The accepted answer led me to this other question regarding the MVVM Light Toolkit's DispatcherHelper class, which can be used to marshal any code onto the dispatcher thread.
So, it seems that I have to do my own thread marshalling (I really hate this aspect of Windows programming, I wish Microsoft would make a thread-safe UI technology!).
So I have updated my properties to use this pattern:
    public double Ambient
    {
        get { return ambientTemperature; }
        private set
        {
            ambientTemperature = value;
            DispatcherHelper.CheckBeginInvokeOnUI(() => RaisePropertyChanged());
        }
    }

This now appears to work as expected.
I think a lot of people are going to fall into this quagmire so I am leaving this answer here in the hope that people will find it when they need it.

A: I don't think the runtime does any sort of marshalling for PropertyChanged events, which is admittedly a bit irritating.
You probably want to do something like:
public double Ambient
{
    get { return ambientTemperature; }
    private set
    {
        Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                Set(nameof(Ambient), ref ambientTemperature, value);
            });
    }
}

to make this happen on the UI thread.


text:
Q: A particular exact sequence of vector spaces using full rank linear maps let $V_a,V_b,V_c$ and $V_d$ be vector spaces where $$\dim(V_a) = n-1$$ $$\dim(V_b)=n$$ $$\dim(V_c)=n$$ $$\dim(V_d)=n+1$$
Let the following all be full rank linear maps:
$$\gamma_{ab}: V_a \rightarrow V_b$$
$$\gamma_{ac}: V_a \rightarrow V_c$$
$$\gamma_{bd}: V_b \rightarrow V_d$$
$$\gamma_{cd}: V_c \rightarrow V_d$$
Furthermore, say that the following sequence is exact: (sorry I don't know how to make the mappings ABOVE the arrows...)
$$V_a \overset{(\gamma_{ab},\gamma_{ac})}{\longrightarrow} V_b \oplus V_c \overset{\gamma_{ba}-\gamma_{ca}}{\longrightarrow} V_d$$

I would like to learn more about this situation in any way possible. Here are some things that I believe can be said (please correct me if I'm wrong):
The dimensions of $V_b$ and $V_c$ are both one higher than the dimension of $V_a$; thus, since $\gamma_{ab}$ and $\gamma_{ac}$ are full rank maps, they inject $V_a$ into $V_b$ and $V_c$ respectively; thus $im(\gamma_{ab}) \cong V_a$ and $im(\gamma_{ac}) \cong V_a$.
By the isomorphism theorem, we have $\frac{V_b \oplus V_c}{\ker(\gamma_{ca}-\gamma_{ba})} \cong im(\gamma_{ba}-\gamma_{ca}) < V_d$
Since this sequence is exact, we have that $\ker(\gamma_{ca}-\gamma_{ba}) \cong im(\gamma_{ab},\gamma_{ac})$. Although in general when invoking the isomorphism theorem with respect to some algebraic structure, $A \cong B$ and $C \cong D$ does not imply that $\frac{A}{C} \cong \frac{B}{D}$, in our situation, since isomorphism classes of vector spaces are completely determined by dimension, we can conclude that:
$$\frac{V_b \oplus V_c}{V_a \oplus V_a} \cong \frac{V_b \oplus V_c}{im(\gamma_{ab},\gamma_{ac}) } \cong \frac{V_b \oplus V_c}{\ker(\gamma_{ca}-\gamma_{ba})} \cong im(\gamma_{ba}-\gamma_{ca}) < V_d$$
Now,
$$\dim\left(\frac{V_b \oplus V_c}{V_a \oplus V_a}\right)=\dim(V_b)+\dim(V_c)-2\dim(V_a)=n+1+n+1-2n=2$$ and thus $\dim(im(\gamma_{ba}-\gamma_{ca}))=2$.
Is all of this true? What else that can (or can't) be said?
I know this is a pretty open ended questions, but it seems my open ended questions on this site get some really insightful answers... Sometimes you don't know what you are looking for until you find it!
Thanks


text:
Q: Property 'spring.cloud.config.server.git.privateKey' is not a valid private key Sort of stuck on above. although i see there are questions asked on same topic, and have tried them but still no resort.
stack im using -> mac(mojave), Intellij, jdk8, generated key using puttygen on mac itself and looks like this, this is only for my local springboot config server.
i have tried 2 ways:
spring.cloud.config.server.git.private-key=-----BEGIN RSA PRIVATE KEY-----\n
MIIEowIBAAKCAQEAssBl7ZADFHBZrSnDPVhClH9HFzCaEPKEaO3MX7H5uBMTEL59\n
CLRguWdCQJnvv2L6vSLyBb9ds05DHEzE2OqkU5VzYX4CCrU7t1ktZmy3cwyNc0g0\n
ijJMInd47KG57Pi6nzpN/bVsLNiwRO3PZ7wUxgeQT6vh5euhBbTlvrFRbNMZm0Rf\n
....
..
,,,
F5vNwcngKk/tFFwX2XooikGliOCxHU66/KOckbNXqOaLBc+QlNsB\n
-----END RSA PRIVATE KEY-----
gives error:

APPLICATION FAILED TO START

Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.cloud.config.server.git' to org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentProperties failed:
Reason: Property 'spring.cloud.config.server.git.privateKey' is not a valid private key

2) spring.cloud.config.server.git.private-key=~/.ssh/temp/id_rsa
spring.cloud.config.server.git.ignore-local-ssh-settings=true
and still get the same error as i shared above.
3) there was a SO question where solution talked, that the key might not be created right.
Now i have using the same key for my normal development & been using it fine for a year & have the pub added to my bitbucket repo and it works fine. its our own repo(not git hub) i normally work fine with the key in ~/.ssh/id_rsa. So i created RSA private key from ~/.ssh/id_rsa file into a temp directory and using the same for the config server APP.
4) in the known hosts file, there are about 7 entries 1 of them is the bitbucket server. and its ssh-rsa.
was wondering if there a step-by-step guide or some sample someone can help me with please ?

A: Maybe this will help, user 'introtj' commented here https://github.com/spring-cloud/spring-cloud-config/issues/1392 and this helped me.
JGit requires RSA keys in PEM format. Below is an example ssh-keygen (from openssh) command that will generate a key in the corect format:

ssh-keygen -m PEM -t rsa -b 4096

Update 22-Apr-2021
So today I decided to switch from yml to properties and of course had the same error as above. I knew the key was good because it was working fine in the YAML format. After 2 hours of trial and error I managed to get it working:
spring.cloud.config.server.git.private-key= \
-----BEGIN RSA PRIVATE KEY-----\n\
your_key_here_your_key_here_you\n\
your_key_here_your_key_here_you\n\
your_key_here_your_key_here_you\n\
your_key_here_your_key_here_you\n\
your_key_here_your_key_here_you\n\
-----END RSA PRIVATE KEY-----\n

I am using spring boot 2.4.5 and spring cloud 2020.0.02
Let me know if it is working for you this solution.

A: Just add |
spring.cloud.config.server.git.private-key= |
                               ----BEGIN RSA PRIVATE KEY-----
                               MIIEpQIBAAKCAQEA3Tz2mr7SZiAMfQyuvBjM9Oi..
                               RK+Lh9x5eJPo5CAZ3/ANBE0sTK0ZsDGMak2m1g7..
                               wnLe4nOb7/eEJbDPkk05ShhBrJGBKKxb8n104o/..
                               5A13wiLitEO7nco2WfyYkQzaxCw0AwzlkVHiIyC..
                               -----END RSA PRIVATE KEY-----


text:
Q: Fetching records from SQLite with date field saved as text in android Hiii Freinds
I have an serious issue in android.I am using SQlite as my DB. In my application i am storing date as text field as sqlite don't have date datatype.In the report section i am taking from and to date from user fetching records from sqlite as below,
select * from Table2 where TDate >= '2013-1-1' and TDate <='2013-3-1'

The problem is that above query runs correct ,but when I use date with month higher than 10 eg.'2013-10-1' or '2013-11-1' or '2013-12-1' it was not fetching any records please help
Thankx In adv.

A: You must use one of the supported date formats such as yyyy-mm-dd so that the string comparison come out right.
(In a string, 1 < 9, therefore 10 < 9.)


text:
Q: Eloquent has query I have this error :
in_array() expects parameter 2 to be array, object given (View: C:\wamp64\www\partie2-exo\resources\views\index.blade.php)

Here is the line in question :
{!! link_to_route('poll.edit', 'Modifier', [$poll->id], ['class' => 'btn btn-warning btn-block' . (in_array($poll->question, $polls_voted)? ' disabled' : '')]) !!}

This error comes from the PollRepository :
$polls_voted = Poll::has('answers')->get();

The values of "polls_voted" should be the questions for which there were votes.

A: $polls_voted in your case is a Collection. An easy fix for this would be to pluck() all the questions and convert it to an array with toArray().
{!! link_to_route('poll.edit', 'Modifier', [$poll->id], ['class' => 'btn btn-warning btn-block' . (in_array($poll->question, $polls_voted->pluck('question')->toArray()) ? ' disabled' : '')]) !!}

A: IN_ARRAY() accept parameter 2 to be array. The passed array should be non-assosiative like this  $arr = ["one","two","three"]

A: When you use the Eloquent Builder, you get an object. That is'nt an array, so in_array won't work. Instead of that, you can use toArray() to change it into an array. Like these 2 examples
$user = App\User::with('roles')->first();

return $user->toArray();

$users = App\User::all();

return $users->toArray();

https://laravel.com/docs/5.7/eloquent-serialization


text:
Q: javascript reflection library Is there any library for reflection in javascript?
I need to list all global variables, functions or list all variables of an object. I'm dealing with a tool which allows javascript and html, but there is no any debugger there.
Thanks

A: It's probably easier than you're expecting.  Take a look at http://www.codeproject.com/Articles/24549/How-to-Inspect-a-JavaScript-Object which shows the for(member in object) { } syntax


text:
Q: how to invoke a method on a value change of a variable? I want invoke VoiceSearch() method when a value of my keyword(string variable) change.
private void VoiceSearch()
    {
        try
        {
            query.Append(keyword);

            Browser.Navigate(query.ToString());

        }
        catch (Exception)
        {
            throw;
        }
    }

solution
private string _keyword
public string keyword
{
  get
  {
    return _keyword;
  }
  set
  {
    _keyword=value;
    VoiceSearch();
  }
}

A: Simplest way to do this is implement keyword as a property:
private string _keyword
public string keyword
{
  get
  {
    return _keyword;
  }
  set
  {
    _keyword=value;
    VoiceSearch();
  }
}

Here, _keyword is what is referred to as a "backing variable". There are interfaces such as INotifyPropertyChanged which are very commonly used in databinding that are worth looking into, but in your case, the minimum code you have to write is this example.

A: Either declare keyword as a property and invoke VoiceSearch in the setter or create a special method for setting the keyword and invoke VoiceSearch from it when called.
Property
private string keyword;
public string Keyword
{
    get { return keyword; }
    set { keyword = value; VoiceSearch(); }
}

Method
public void SetKeyword(string value)
{
    keyword = value;
    VoiceSearch();
}

Assuming that keyword is actually string. These two options still leaves you with a chance to change the variable and not call VoiceSearch().

A: You should look into INotifyPropertyChanged. Instead of variable I would suggest to use property. See a MSDN example below:
using System.ComponentModel;

namespace SDKSample
{
  // This class implements INotifyPropertyChanged
  // to support one-way and two-way bindings
  // (such that the UI element updates when the source
  // has been changed dynamically)
  public class Person : INotifyPropertyChanged
  {
      private string name;
      // Declare the event
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }

      public Person(string value)
      {
          this.name = value;
      }

      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              // Call OnPropertyChanged whenever the property is updated
              OnPropertyChanged("PersonName");
          }
      }

      // Create the OnPropertyChanged method to raise the event
      protected void OnPropertyChanged(string name)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(name));
          }
      }
  }
}


text:
Q: Getting google sheet dropdown values of a cell with sheet api using javascript I am trying to get all the values from a dropdown list of a cell in google sheet
google sheet dropdown screenshot
however in the json return that i am getting from the sheet api, I only get the selected value and not the list of all the values of the dropdown. How can i the whole list?
the ajax code is:

"GET",
  "https://sheets.googleapis.com/v4/spreadsheets/"+sheetId+"/values/Sheet1?key="+apiKey+""

json return screenshot

A: That's the expected outcome. Sheets API only fetches values which are currently visible on the cells. There is no way to get the hidden whole list. Check Reading and Writing for more info.


text:
Q: How do I write a Linux sosreport plugin? How do I write a Linux sosreport plugin? I have been looking at python code that creates a plugin for the linux sosreport command. But I have not been able to find a link on the internet that describes how to write and implement a plugin for the sosreport. Can anyone point me in the right direction?

A: The second result when I googled "implement a plugin for the sosreport" is this tutorial.
If this isn't what you are looking for, then you should be more specific: mention what you have tried and what specific problem you are having. Questions should show at least a basic amount of research / effort.


text:
Q: Android WebView - Works in browser but not WebView I am attempting to create an Android game in Javascript, then I planned on putting it into a WebView. The problem is, although my game works 100% in the default Android browser, running it in a WebView seems to break it somehow. I've looked through all of my code and cannot for the life of me figure out what the issue is.
I used this game as the "codebase" for my own game, and it faces the same issue.
It loads perfectly in the default Android browser but when you put it into a WebView it will no longer play. Simply copy the above link into a webview and see for yourself.
Note I do have Javascript enabled and the webview is functioning properly.
Perhaps the cache manifest?

A: Have you tried Phonegap? You have all the hard work done and works out of the box.


text:
Q: How can I change App.xaml build action from Application Definition to Page I want make mutex, so I tried change App.xaml build action from AppDefinition To Page, then vs2019 said below:
An error has occurred while saving the edited properties listed below:
    Build Action
One or more values are invalid. Cannot add 'App.xaml' to the project, because the path is explicitly excluded from the project (C:\Program Files\dotnet\sdk\3.1.100-preview8-013656\Sdks\Microsoft.NET.Sdk.WindowsDesktop\targets\Microsoft.NET.Sdk.WindowsDesktop.targets (57,5)).

I tried commented out, but then my app doesn't work.
How can I change build action?

A: If you target .NET Core you should implement your custom Main method as usual and then edit the .csproj file to include a <StartupObject> element that specifies the type where your custom Main method is defined instead of changing the build action of App.xaml:
<PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <Version>1.0.5</Version>
    <StartupObject>WpfCoreApp1.MyProgramClass</StartupObject>
</PropertyGroup>


text:
Q: wsdl not showing XML-WCF When calling service url https://example.com/TestService.svc I am getting the below 2 URLs but when I am trying to click on WSDL then it is not working.
WSDL URLs
http://example.com/TestService.svc?wsdl -- NOT WORKING
http://example.com/TestService.svc?singleWsdl -- NOT WORKING
Manually change http to https
https://example.com/TestService.svc?wsdl -- WORKING
https://example.com/TestService.svc?singleWsdl -- WORKING
Client Config

  <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
</client>
<behaviors>
  <serviceBehaviors>
    <clear/>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />

Main Service Config
<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <clear />
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
  <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0">
  <serviceActivations>
    <clear />
    <add factory="DataServicesHost.UnityServiceHostFactory" relativeAddress="TestService.svc" service="TestService.Service" />
  </serviceActivations>
</serviceHostingEnvironment>

Service Consuming
var customHeader = new MessageHeader<Security>(security);
            var tempHeader = customHeader.GetUntypedHeader("Security", "http://tempuri.org/");

            var client = new ServiceClient();

            using (var scope = new OperationContextScope(client.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(tempHeader);
                objDataRequest = client.DataRequest("test");

            }

A: From the above configuration, we can infer that it belongs to the client-side. However, the WSDL feature of the WCF service is set up on the server-side. It is controlled by the ServiceMetadata section.
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

Therefore, if we want to have the HTTP protocol of WSDL feature working, we need to enable it on the server-side and apply the service behavior in the service section(the endpoint should be within the service section instead of  client section).
<system.serviceModel>
    <services>
      <service name="WcfService3.Service1" behaviorConfiguration="sb">
        <endpoint address="" binding="basicHttpBinding" contract="WcfService3.IService1"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="sb">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
</behaviors>

Feel free to let me know if there is anything I can help with.


text:
Q: How to install Go Firebase Admin SDK v3.10.0 on Go 1.10.7? I know I know... We have 2022 and the current version of Go Firebase Admin SDK is V4.8.0 and GO is 1.18.1 so versions for SDK v3.10.0 and 1.10.7 for GO are very outdated but I can't use the newest though I'd love to :/
I need to create a small script that will fetch some data from the local database, and send it periodically to Firestore. That database is running on Windows XP 32bit (I agree that this is crazy, but there are running 2 "custom" programs - XP only - without any updates to newer versions :/ )
I tried to run there a Go Firebase Admin SDK v4.7.1 on Go 1.12.17 and the program runs but with an error panic: Failed to find GetFileInformationByHandleEx procedure in kernel32.dll... so I decided to try the last Go version with XP support 1.10 with the last Go Firebase Admin SDK v3.10.0 (Release Notes) which supports Go 1.10.
And I am able to build some simple base Go program, but I have no idea how to install a Go Firebase Admin SDK v3 version :/ I try go get firebase.google.com/go it try to install version v4 which is incompatible, but when I try go get firebase.google.com/go@v3 (how it is described in docs) I receive package firebase.google.com/go@v3: firebase.google.com/go@v3: invalid import path: malformed import path "firebase.google.com/go@v3": invalid char '@' error.
Do you have any idea how can I install Go Firebase Admin SDK v3.10.0 on Go 1.10.7?
Or do u see any options to read/write data to Firestore from XP in a simpler way instead of creating a simple SDK with Firestore REST API?
Thanks!


text:
Q: Concurrency Violation in NHibernate( c#) example For quite some time , I was reading about the optimistic concurrency in NHibernate. If what i understood was correct then the below sample should hold good.
Consider two transactions T1 and T2.

*

*When T1 and T2 are done simultaneously , the state(DB entries) gets updated with the values of the most latest update.(T1 or T2).

Though it seems to be conceptually sound , how do i simulate this for the purpose of understanding and integration testing.?
Can someone help me with a sample c# code.?
Thanks ,
vijay

A: Conceptually :

*

*use 2 threads for performing T1 and 2; and a shared lock to synchronize access

*thread1 acquires lock and performs T1

*thread2 acquires the same lock and performs T2

*one of the transactions will fail with Optimistic Concurrency Exception

A: Now after a lot of googling , i have found out a fairly simple way to do that .The following are the steps to reproduce this.

*

*Have a Thread.Sleep() between the Get() and Update() methods, for only one user(process 1 ).

*When process 1 is running , start process 2 which doesnt encounter the Thread.Sleep() and completes the update before the process 1 does .

*Now process 2 has modified the data in the data base, now when process 1 tries to update the data, NHibernate throws a stale object exception.
Please refer the following code snippet.
public void Update(int empid)
    {
        Employee person = this.dalService.GetByEntityId(empid);
        person.Name = "Process 1";

        // At this point , Update the Person table  manually using raw sql query
        // such as this 'Update Person Set Name = 'Process 2'where empid = @empid;

        // When the update is performed , it is expected to throw the exception , as the in memory data
        // is different from the one in database.
        if (username.equals("Bob"))
        {
            Thread.Sleep(50000);
            // If this is a website, have the above condition, so that it is simulated only for one user.
        }

        this.dalService.Update(person);
    }


text:
Q: OneupUploaderBundle relation between 2 entities I'm new on stackoverflow and I hope you can help me.
I use OneupUploaderBundle on symfony2 and it's working I can upload multiple images and I can persist them in my database.
But now I would like to upload multiple images for one 'Annonce' for exemple so, I have 2 entities
Annonce
namespace TestBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Annonce
 *
 * @ORM\Table(name="annonce")
 * @ORM\Entity(repositoryClass="TestBundle\Repository\AnnonceRepository")
 */
class Annonce
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255)
     */
    private $titre;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titre
     *
     * @param string $titre
     * @return Annonce
     */
    public function setTitre($titre)
    {
        $this->titre = $titre;

        return $this;
    }

    /**
     * Get titre
     *
     * @return string
     */
    public function getTitre()
    {
        return $this->titre;
    }
}

And my Entity Image
namespace TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Image
 *
 * @ORM\Table(name="image")
 * @ORM\Entity(repositoryClass="TestBundle\Repository\ImageRepository")
 */
class Image
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Image
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @ORM\ManyToOne(targetEntity="TestBundle\Entity\Annonce")
     * @ORM\JoinColumn(nullable=false)
     */
    private $annonce;

    /**
     * Set annonce
     *
     * @param \TestBundle\Entity\Annonce $annonce
     * @return Image
     */
    public function setAnnonce(\TestBundle\Entity\Annonce $annonce)
    {
        $this->annonce = $annonce;

        return $this;
    }

    /**
     * Get annonce
     *
     * @return \TestBundle\Entity\Annonce
     */
    public function getAnnonce()
    {
        return $this->annonce;
    }
}

My EventListener
namespace TestBundle\EventListener;

use Doctrine\Common\Persistence\ObjectManager;
use Oneup\UploaderBundle\Event\PostPersistEvent;
use TestBundle\Entity\Annonce;
use TestBundle\Entity\Image;

class UploadListener
{
    /**
     * @var ObjectManager
     */
    private $em;

    public function __construct(ObjectManager $em)
    {
        $this->em = $em;
    }

    public function onUpload(PostPersistEvent $event)
    {
        $file = $event->getFile();

        $annonce = new Annonce();
        $image = new Image();
        /* TEST */
        $annonce->setTitre("I'am a title");
        $this->em->persist($annonce);

        $image->setName($file->getFilename());
        $image->setAnnonce($annonce);

        $this->em->persist($image);
        $this->em->flush();

        $response = $event->getResponse();
        $response['files'] = [
            'name' => $file->getFilename(),
            'size' => $file->getSize()
        ];
    }

The problem is, when I upload many images, I have the same number of row in Annonce as in Image.
Someone can help me please :)


text:
Q: How to SUM of SUMS of fields with same value in MYSQL I have these table: I need to "SUM" all the VALUES with the same KEY1 & KEY2 WHEN KEY3 = X
| KEY1 | VALUE1 | KEY2 | VALUE2 | KEY3 |
|   1  |   9    |   2  |   2    |   x  |
|   1  |   10   |   2  |   3    |   x  |
|   2  |   5    |   1  |   8    |   x  |
|   2  |   5    |   1  |   9    |   y  |

SELECT key1 as k1, key2 as k2 FROM table1 WHERE key3 = x

For each result of these query I need to do:
SELECT
COALESCE(SUM(case when key1 = k1 then totalamount1 else 0   end),0) +
COALESCE(SUM(case when key2 = k2 then totalamount2 else 0   end),0) as total
FROM table1
WHERE key3 = x

Y need these output:
      Total
id 1:  27
id 2:  10

How I can join thes two query?
Thanks!

A: The easiest way is to "unpivot" your table:
SELECT
  Key,
  SUM(Value) AS Total
FROM (
  SELECT Key3, Key1 AS Key, Value1 AS Value FROM Table1
  UNION ALL SELECT Key3, Key2, Value2 FROM Table1
) NormTable
WHERE Key3 = 'x'
GROUP BY Key

You could also move the WHERE Key3 = 'x' into each of the union queries. That would be faster, but more error prone because you'll need to change it in each query if you need a different Key3 value. Your call on that one.

A: Here's one way to get the result:
SELECT IF(i.i,t.key1,t.key2) AS `id`
     , SUM(IF(i.i,t.value1,t.value2)) AS `Total`
  FROM table1 t
 CROSS
  JOIN (SELECT 0 AS i UNION ALL SELECT 1) i
 WHERE t.key3 = 'x'
 GROUP
    BY IF(i.i,t.key1,t.key2)

SQL Fiddle demo here: http://sqlfiddle.com/#!2/d7599f/1

The "trick" I used is to get two sets of rows, by performing a cross join of table1 with a set containing exactly two rows; those two rows can be distinguished from each other with a conditional test.
Since the value of i.i will either be 1 or 0, that means it will evaluate to TRUE and FALSE as a conditional test within an IF function.
We can extract (key1, value1) from one set of rows, and extract (key2,value2) from the other set, essentially, creating a result set like this:
| i | keyN | valueN |
| 1 |   1  |   9    |
| 1 |   1  |   10   |
| 1 |   2  |   5    |
| 0 |   2  |   2    |
| 0 |   2  |   3    |
| 0 |   1  |   8    |

Now, it's just a matter of doing a SUM(valueN) GROUP BY keyN

The query above could be rewritten in (more portable) SQL-92 style:
SELECT CASE WHEN i.i = 1 THEN t.key1 ELSE t.key2 END AS `id`
     , SUM(CASE WHEN i.i = 1 THEN t.value1 ELSE t.value2) AS `Total`
  FROM table1 t
 CROSS
  JOIN (SELECT 0 AS i UNION ALL SELECT 1) i
 WHERE t.key3 = 'x'
 GROUP
    BY CASE WHEN i.i = 1 THEN t.key1 ELSE t.key2 END AS `id`

(For Oracle, we'd need to add FROM DUAL on each select in the inline view aliased as i.)


text:
Q: Cannot use PagerSlidingTabStrip as library project in eclipse I want to include PagerSlidingTabStrip in my application project. But I cannot. After I added PagerSlidingTabStrip library project to my application project, I found that I cannot use it so I checked my project properties->android. The Library project I just added show "X" red mark.
Here is step I used to include PagerSlidingTabStrip
Import PagerSlidingTabStrip to eclipse

*

*File->Import->Existing Android code into Workspace

*click browse and navigated to ..\PagerSlidingTabStrip-master\library

*then changed the project name to "Lib_PagerSlidingTabStrip"

*finish

*now I have PagerSlidingTabStrip in my workspace.

Include PagerSlidingTabStrip to my application project

*

*Right click on my project name -> properties->android

*in library section add Lib_PagerSlidingTabStrip

*then click ok

and here is a picture of properties->android

Why is this happen? Did I do something wrong?

A: OK now I know what cause me the problem. this is because my
eclipse workspace is in drive D:
but library project is in drive C:

So when import library into eclipse make sure you check "Copy projects into workspace" and finish. Then re-add library project to application project again.


text:
Q: C# Listview column tag I need to get the sender tag from the colums in a ListView, how can I do this?
I mean something like this:
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
   if((string)(sender as ColumnHeader).Tag == "...")
   {
      /*mycode*/
   }
}

A: Look for ColumnClickEventArgs.Column which returns zero-based index of the column that is clicked.
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{

   if(e.Column >=0 && ListView1.Columns[e.Column].Tag == "...")
   {
      /*mycode*/
   }
}

A: The sender of the event is ListView. You should use e.Column which is the index of clicked column and find the column object, then get the value from tag
private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
    var column = listView1.Columns[e.Column];
    var tag = column.Tag as string;
    if(tag == "something")
    {
        //...
    }
}


text:
Q: Failed with exception Connection lost (32109) when an Android app subscribes events from IBM IoT platform I am trying to subscribe events from IBM IoT platform.
The example I tested is from an IBM blog: https://www.ibm.com/developerworks/library/iot-mobile-phone-iot-device-bluemix-apps-trs/. In this link, the codes can be downloaded.
With this example, the Android app can successfully connect and publish events to the IBM IoT platform, but when I tried "subscribe", I always receive the error "Connection lost". What causes this problem? Thank you!
The relevant codes are:
public IMqttToken subscribeToEvent(String deviceType, String deviceId, String event, String format, int qos, Object userContext, IMqttActionListener listener) throws MqttException {
    String eventTopic = "iot-2/type/" + deviceType + "/id/" + deviceId + "/evt/" + event + "/fmt/"+format;
    return subscribe(eventTopic, qos, userContext, listener);
}

public static void subscribeEvent(Context context,String event) {
    Log.v(TAG, ".subscribeEvent() entered")

    try {
        MyIoTActionListener listener = new MyIoTActionListener(context, Constants.ActionStateStatus.SUBSCRIBE);
        IoTClient iotClient = IoTClient.getInstance(context);
        String deviceType = "Android";
        String deviceId = "...";
        iotClient.subscribeToEvent(deviceType, deviceId, event, "json", 0, context,listener);

    } catch (MqttException e) {
        Log.d(TAG, ".SubscribeEvent() received exception on SubscribeEvent()");
    }
}

The connection URL is:
String connectionURI = "tcp://" + this.getOrganization() + ".messaging.internetofthings.ibmcloud.com:1883";

ssl somehow cannot work.

A: This problem has been solved.
Two concepts have to be clarified: device client and application client.
A device client can only publish events and subscribe commands. In the question, I subscribe events with a device client, the IoT platform cannot response and returns the error "Connection Lost". The correct way to code is:
    public IMqttToken subscribeToCommand(String command, String format, int qos, Object userContext, IMqttActionListener listener) throws MqttException {
        String commandTopic = getCommandTopic(command, format);
        return subscribe(commandTopic, qos, userContext, listener);
    }

public static String getCommandTopic(String command, String format) {
        return "iot-2/cmd/" + command + "/fmt/json";
    }

public static void subscribeCommand(Context context, String command) {
        try {
            MyIoTActionListener listener = new MyIoTActionListener(context, Constants.ActionStateStatus.SUBSCRIBE);
            IoTClient iotClient = IoTClient.getInstance(context);

        iotClient.subscribeToCommand(command, "json", 0, context,listener);
    } catch (MqttException e) {
        Log.d(TAG, ".SubscribeCommand() received exception on SubscribeEvent()");
    }
}

The example provided by IBM contains functions like subscribeEvent and publishCommand for a device client. These functions make me confused.
If you want to publish commands and subscribe events, an application client need to be created. The method to create an application client is:
import com.ibm.iotf.client.app.ApplicationClient;

Properties appProperties = new Properties();
appProperties.put("id",applicationId);
appProperties.put("Organization-ID",organizationId);
appProperties.put("Authentication-Method","apikey");
appProperties.put("API-Key",apiKey);
appProperties.put("Authentication-Token",token);

appClient = new ApplicationClient(appProperties);

appClient.connect();

See more about application client at https://github.com/ibm-watson-iot/iot-java/blob/master/src/main/java/com/ibm/iotf/client/app/ApplicationClient.java