text:
Q: batch file permutation to output to textfile results i want a simple batch file that will display the permutations to a text file, after asking the user to input the following:
How many numbers for Permutation?: example say 6
----clear screen-----
Enter 1st number for Permutation:
Enter range: example 1-32          (Note the "-" is the delimiter used for spaces)
----clear screen-----
Enter 2nd number for Permutation:
Enter range: example 3-24          (Note the "-" is the delimiter used for spaces)
----clear screen-----
Enter 3rd number for Permutation:
Enter range: example 2-16          (Note the "-" is the delimiter used for spaces)
----clear screen-----
And so on..........
note: the textfile permutation results should be delimited like 5-25-6-15-22-8

A: Try like this :
@echo off&cls
setlocal enabledelayedexpansion
set $Liste=
set /p "$PNumber=Number of permutation ? : "
for /l %%a in (1,1,%$Pnumber%) do (
  set /p "$Value=Enter Permutation Number [ %%a ] : "
  set $Liste=!$Liste!-!$Value!)
echo !$Liste:~1!>output.txt


text:
Q: WooCommerce: separate login page and registration page I use the WooCommerce plugin 2.0.13. On my account page there are login and register sections, both on the same page. I want them separate.
I edit form_login.php to create two files: form_login.php for login and form_register.php for registration.
In the new form_login.php I provide a link to form_registration.php as follows:
 register

In my theme's function.php file, I added the following code.
/*//  Separate login form and registration form */
add_action('woocommerce_before_my_account', 'load_registration_form', 2);
function load_registration_form() {
    if (isset($_GET['action']) == 'register') {
        woocommerce_get_template('myaccount/form-registration.php');
    }
}

But this doesn't work. What's going wrong? Is what I am doing completely wrong?

A: You can create a copy of the WooCommerce form-login.php and name it form-register.php. The form-login.php is located in /woocommerce/templates/myaccount/ folder.
Then in the form-login.php you can create a link to the form-register.php using this code:
 register

Next you need to modify your themes function.php file by adding the following code:
<?php
    /* Separate login form and registration form */
    add_action('woocommerce_before_customer_login_form', 'load_registration_form', 2);
    function load_registration_form() {
      if (isset($_GET['action']) == 'register') {
        woocommerce_get_template('myaccount/form-registration.php');
      }
    }

A: /* shortcode for Register */
add_shortcode( 'wc_reg_form', 'registration_form' );

        function registration_form() {
           if ( is_admin() ) return;
           if ( is_user_logged_in() ) return;
           ob_start();

           do_action( 'woocommerce_before_customer_login_form' );

           ?>
              <form method="post" class="woocommerce-form woocommerce-form-register register" <?php do_action( 'woocommerce_register_form_tag' ); ?> >

                 <?php do_action( 'woocommerce_register_form_start' ); ?>

                 <?php if ( 'no' === get_option( 'woocommerce_registration_generate_username' ) ) : ?>

                       <?php esc_html_e( 'Username', 'woocommerce' ); ?> *
                       <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="username" id="reg_username" autocomplete="username" value="<?php echo ( ! empty( $_POST['username'] ) ) ? esc_attr( wp_unslash( $_POST['username'] ) ) : ''; ?>" /><?php // @codingStandardsIgnoreLine ?>

                 <?php endif; ?>

                    <?php esc_html_e( 'Email address', 'woocommerce' ); ?> *
                    <input type="email" class="woocommerce-Input woocommerce-Input--text input-text" name="email" id="reg_email" autocomplete="email" value="<?php echo ( ! empty( $_POST['email'] ) ) ? esc_attr( wp_unslash( $_POST['email'] ) ) : ''; ?>" />

                 <?php if ( 'no' === get_option( 'woocommerce_registration_generate_password' ) ) : ?>

                       <?php esc_html_e( 'Password', 'woocommerce' ); ?> *
                       <input type="password" class="woocommerce-Input woocommerce-Input--text input-text" name="password" id="reg_password" autocomplete="new-password" />

                 <?php else : ?>

<?php esc_html_e( 'A password will be sent to your email address.', 'woocommerce' ); ?>

                 <?php endif; ?>

                 <?php do_action( 'woocommerce_register_form' ); ?>

                    <?php wp_nonce_field( 'woocommerce-register', 'woocommerce-register-nonce' ); ?>
                    <button type="submit" class="woocommerce-Button woocommerce-button button woocommerce-form-register__submit" name="register" value="<?php esc_attr_e( 'Register', 'woocommerce' ); ?>"><?php esc_html_e( 'Register', 'woocommerce' ); ?></button>

                 <?php do_action( 'woocommerce_register_form_end' ); ?>

              </form>

           <?php

           return ob_get_clean();
        }
    /* login shortcode */
    add_shortcode( 'wc_login_form', 'login_form' );

    function login_form() {
       if ( is_admin() ) return;
       if ( is_user_logged_in() ) return;
       ob_start();
       woocommerce_login_form( array( 'redirect' => 'https://custom.url' ) );
       return ob_get_clean();
    }

A: You created a file named form_register.php and you are calling form_registration.php. This is the main  issue.
The method woocommerce_get_template is also outdated now, use wc_get_template instead.
After making a copy of your form-login.php, make sure to comment this line in form-register.php:
do_action( 'woocommerce_before_customer_login_form' );

Otherwise you will be inside an infinite loop using the filter woocommerce_before_customer_login_form.

A: The hook that you are using is wrong. It won't be executed as the user is not logged in.
You should be using woocommerce_before_customer_login_form.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Notation for the Covariant Derivative of a smooth section in the direction of a tangent vector X So I am trying to convince myself of a proof found in lecture concerning the curvature matrix. The idea is I have a theorem stating that:
For X,Y $\in \mathfrak X(M)$ (space of smooth vector fields on M). Then:
$$R(X,Y) = [\nabla_X,\nabla_Y]-\nabla_{[X,Y]} $$
In order to do this we need the definition of the induced linear map R given (in our course) by the curvature matrix:
$$R(X,Y)|_U (s) = \Omega^i_{\; j}(X,Y)|_U s^j$$
Where $s=(s^1, \dots, s^n)$ are smooth sections over a local trivialization $(U,\Phi_U)$. In our lecture we have that:
$$\Omega = dA + A \wedge A$$
and
$$A^i_{\;j} = \Gamma^i_{\; jk}dx^k$$
Where we use that A is the connection matrix, and the gammas are the connection coefficients (here A is written in terms of a local trivialization). The problem I have is when it comes down to doing the work to show that each side is equal, I come upon the quantity
$$\nabla_X s = \langle \nabla s , X \rangle$$
in the notes. The covariant derivative of the smooth section is given by
$$\nabla s |_U =(\frac{\partial s^i}{\partial x^k} + \Gamma^i_{\; jk}s^j )dx^k\otimes \frac{\partial}{\partial u^i}$$
where $u=(u^1, \dots,u^n)$ are the coordinates over the local trivialization. When I look at the quantity in angled brackets, the physicist in me wants to assume an inner product, but I am unsure how to treat that object or what it is. I read a passage in Chern, Chen, Lam "Lectures on Differential Geometry" where the author asserts that the angled bracket quantity "...represents the pairing between TM and T*M." and gives no real clue how to find it, at least in notation that I am use to. If anyone can provide a little insight I would be thankful. If anyone needs further explanation of the notation I use in lecture feel free to ask.

A: Turns out the expression I was looking for, after some discussion with the person that provides the lecture, is given by:
$$ \langle \nabla s , X \rangle = (\frac{ds^i}{dt} + \Gamma^i_{\;jk}s^j X^k(t) )\frac{\partial}{\partial u^i} $$

A: this is a directly definition of Riemannian connection or named Levi-Civita connection !
see wiki :

*

*en.wikipedia.org/wiki/Riemannian_connection_on_a_surface

*en.wikipedia.org/wiki/Levi-Civita_connection

and i also find two paper for you :

*

*http://www.math.uiuc.edu/~kapovich/481-07/riem.pdf

*http://www.cis.upenn.edu/~cis610/cis61008Riem-conn.pdf


text:
Q: Finding jar with given class by name in SBT? While debugging a very difficult classpath problem, I dumped SBT compile classpath. What I need to find is what jar file (in classpath) a class name belongs to.
Is this do-able in SBT? Or is there a mechanism in Scala that can help?

A: -verbose:class in Java is the approach "to display the information about classes being loaded by JVM.". I haven't used it with Scala, but it could work since JVM's involved after all.
Use -verbose:class with javaOptions in SBT and then parse the output.


text:
Q: How to parse HTTP response? I'm trying to build a script to run in Google Sheets to automatically pull my bank account balance into the sheet. I'm using Plaid to get the account information. I've pulled the information using UrlFetchApp. I'm stuck trying to figure out how to parse the returned text for the available balance information.
I've tried to use an old XML method to parse it, but quite frankly I don't think I'm even close to figuring out this problem.
function myFunction() {
  //HTTP Request
  var avail_balance = [];
  var data = {
    "client_id": "5bf874c39bb5dc0012b1be13",
    "secret" : "Redacted",
    "access_token" : "Redacted"
  };
  var payload = JSON.stringify(data);
  var options = {
    "method" : "POST",
    "contentType" : "application/json",
    "payload" : payload
  };
  var url = "https://development.plaid.com/accounts/balance/get";
  var response = UrlFetchApp.fetch(url, options);

  //Parse HTML

 //return avail_balance
 return avail_balance
}

A: The docs for Plaid API say this under API protocols

The Plaid API uses POST requests to communicate and HTTP response
  codes to indicate status and errors. All responses come in standard
  JSON

Plaid API documentation
You should only use XmlService to parse XML, not JSON. JSON is a standard notation for objects, not just in JavaScript but in many other languages as well so the name is a bit confusing.
Calling UrlFetchApp.fetch() will return an HttpResponse object that you can then parse to JSON (if, in fact, it's a valid JSON - if not, try logging the response first via Logger.log(response))
var responseString = resonse.getContentText();
var data = JSON.parse(responseString);

UrlFetchApp methods

A: Checked the documentation for the Plaid service and it appears that the response payload is formatted as JSON. So I'm not sure why you'd need to parse the response as HTML.
Try using JSON.parse() on the response instead and then referencing the appropriate property as detailed in the documentation.


text:
Q: Generate a large number of HEX I am trying to generate all 16^16,
but there are a few problems. Mainly memory.
I tried to generate them in python like this:
for y in range (0, 16**16):
    print '0x%0*X' % (16,y)

This gives me:

OverflowError: range() result has too many items

If I use sys.maxint I get a MemoryError.
To be more precise, I want to generate all combinations of HEX in length of 16, i.e:
0000000000000000
0000000000000001
0000000000000002
...
FFFFFFFFFFFFFFFF

Also, how do I calculate the approximate time it will take me to generate them?
I am open to the use of any programming language as long as I can save them to an output file.

A: Well... 16^16 = 1.8446744e+19, so lets say you could calculate 10 values per nanosecond (that's a 10GHz rate btw). Then it would take you 16^16 / 10 nanoseconds to compute them all, or 58.4 years. Also, if you could somehow compress each value into 1-bit (which is impossible), it would require 2 exabytes of memory to contain those values (16^16/8/2^60).

A: This seems like a very artificial exercise. Is it homework, or is there a reason for generating this list? It will be very long (see other answers)!
Having said that, you should ask yourself: why is this happening? The answer is that in Python 2.x, range produces an actual list. If you want to avoid that, you can:

*

*Use Python 3.x, in which range does not actually make a list, but a special generator-like object.

*Use xrange, which also doesn't actually make a list, but again produces an object.

As for timing, all of the time will be in writing to the file or screen. You can get an estimate by making a somewhat smaller list and then doing some math, but you have to be careful that it's big enough that the time is dominated by writing the lines, and not opening and closing the file.
But you should also ask yourself how big the resultant file will be... You may not like what you find. Perhaps you mean 2^16?


text:
Q: Struggling with OpenLDAP configuration (on AWS EC2) I've been configurating a LDAP server on a linux instance using AWS EC2.
Up to now, I successfully set up LDAP and phpLDAPadmin to work together.
I've created Users and Groups "Organisation Units". I've added users and groups to those "OU"s.
Now I want to grand access to specific parts of my LDAP tree to the "Users" members of a "Group". That's what I wasn't able to configure up to now...
My LDAP tree looks like this:
+--> dc=www,dc=website,dc=com (3)
  ---> cn=admin
  +--> ou=groups (4)
  | ---> cn=admin_users
  | ---> cn=app1_users
  | ---> cn=app2_users
  | ---> cn=basic_users
  +--> ou=users (3)
  | ---> cn=user1
  | ---> cn=user2
  | ---> cn=user3

Let's say that I added user1 + user2 to the "memberUid" list of "app1_users" and user2 + user3 to the "memberUid" list of "app2_users".
I want:

*

*cn=admin have full rights/access to the tree

*app1_users can connect (to phpLDAPadmin) and add new members to the the group itself

*the same for app2_users' users

A connected user (on phpLDAPadmin) should only see the tree (and child substrees) he's part of.
Here are the ACI I tried (but whose were obsiouvly not working):
access to attrs=shadowLastChange
    by self write
    by dn="cn=admin,dc=www,dc=website,dc=com" write
    by * read

access to attrs=userPassword
    by self write
    by dn="cn=admin,dc=www,dc=website,dc=com" write
    by anonymous auth by * none

access to dn.base=""
    by * read

access to dn.subtree="cn=app1_users,ou=groups,dc=www,dc=website,dc=com"
    by group.base="cn=app1_users,dc=www,dc=website,dc=com" write
    by dn.base="cn=admin,dc=www,dc=website,dc=com" write
    by * none

access to dn.subtree="cn=app2_users,ou=groups,dc=www,dc=website,dc=com"
    by group.base="cn=app2_users,dc=www,dc=website,dc=com" write
    by dn.base="cn=admin,dc=www,dc=website,dc=com" write
    by * none

access to *
    by self write
    by dn="cn=admin,dc=www,dc=website,dc=com" write
    by * read

Is there something wrong with my configuration ?

A: If cn=admin,... is your rootDn, it has all the rights there are and shouldn't be addressed in your own access rules.
For group management try:
access to dn.base="cn=app1_users,ou=groups,dc=www,dc=website,dc=com"
    by group.exact="cn=app1_users,dc=www,dc=website,dc=com" write
There's an implicit last rule access to * by * none, so no need for by * none in your own rules.
Generally, add your rules one by one to the list - it's easier to watch the effects that way.


text:
Q: JAXB and inheritance in collection how can I map (via JAXB in java 1.6) Collection to XML and from XML, where
class mapping{
    @XmlElementWrapper(name="list")
    @XmlElement(name="item")
    Collection<A> list;
}

abstract class A{
}

class B extends A{
    public String onlyB;
}

class C extends A{
    public String onlyC;
}

a would like to see XML like this:
<something> (doesnt matter, I'm using it in another structure)
<list>
<item xsi:type="b"><onlyB>b</onlyB></item>
<item xsi:type="c"><onlyC>c</onlyC></item>
</list>
</something>

its working if I have
class mapping{
    @XmlElement(name="item")
    A item;
}

I already tried xmlelementref, but with no success
and I dont want to use @XmlElements({@XmlElement ...}) because other project which are using this can add derived class from A

A: Your mapping appears to be correct.  You need to ensure that the B and C classes are included when you create the JAXBContext.  One way to accomplish this is to use @XmlSeeAlso.
@XmlSeeAlso(B.class, C.class)
abstract class A{
}

Below is an example of using xsi:type to represent inheritance in the domain model with JAXB:

*

*http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html
@XmlElementRef is used when you want to represent inheritance using the XML schema concept of substitution groups:

*

*http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
XmlElements corresponds to the choice structure in XML schema:

*

*http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html

*http://blog.bdoughan.com/2011/04/xml-schema-to-java-xsd-choice.html

FULL EXAMPLE
Below is a complete example:
Mapping
package forum7672121;

import java.util.Collection;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="something")
@XmlAccessorType(XmlAccessType.FIELD)
class Mapping{
    @XmlElementWrapper(name="list")
    @XmlElement(name="item")
    Collection<A> list;
}

A
package forum7672121;

import javax.xml.bind.annotation.XmlSeeAlso;

@XmlSeeAlso({B.class, C.class})
abstract class A{
}

B
package forum7672121;

class B extends A{
    public String onlyB;
}

C
package forum7672121;

class C extends A{
    public String onlyC;
}

Demo
package forum7672121;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Mapping.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum7672121/input.xml");
        Mapping mapping = (Mapping) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(mapping, System.out);
    }

}

input.xml/Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<something>
    <list>
        <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b">
            <onlyB>b</onlyB>
        </item>
        <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="c">
            <onlyC>c</onlyC>
        </item>
    </list>
</something>


text:
Q: Store properties file in map I want to read a usual properties file and put the attribute and his value into a Map object.
Technically, a properties file like
attr1=hello
attr2=java
attr3=world

would dynamically become a map object like this
+-------+-------+
+   K   |   V   +
+-------+-------+
+ attr1 | hello +
+-------+-------+
+ attr2 | java  +
+-------+-------+
+ attr3 | world +
+-------+-------+

In the end, it shouldn't matter what's in the properties file, the whole file will just be saved as a Map.
Is it possible to do that with java.Properties or is a FileReader or an InputStream with special parsing necessary?

A: java.util.Properties also implements of Map.
To load the properties from file, use Properties' load() method with Reader or InputStream.
For instance,
Properties config = new Properties();
try {
    config.load(<this.class>.getResourceAsStream(<property-file-name>)); //example input stream
    //now can access it as a Map instance
    config.get(<Key>);
    config.entrySet();

    //additionally, you can access Properties methods
    config.getProperty(<property-name>);

} catch(...) {
    ...
}

If you want only Map instance, let's say kind of Map<String, String>, need to convert the properties to required map instance by iterating the property names.
Properties config = new Properties();
try {
    config.load(<this.class>.getResourceAsStream(<property-file-name>)); //exampl input stream

    Map<String, String> map = new HashMap<String, String>();
    for (final String name: config.stringPropertyNames())
        map.put(name, config.getProperty(name));

} catch(...) {
    ...
}


text:
Q: If $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, show that $\lim_{n\to\infty} x_n$ exists.
Question: If $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, show that $\lim_{n\to\infty} x_n$ exists.

Solution: Let $(a_m)_{m\ge 1}$ be the series defined by the partial sum $$a_m=\sum_{n=1}^m (x_{n+1}-x_n), \forall m\in\mathbb{N}.$$ Note that by our definition, it follows that $$a_m=x_{m+1}-x_1, \forall m\in\mathbb{N}.$$ Now since it is given that $\sum_{n=1}^\infty|x_{n+1}-x_n|$ converges, implies that the series $(a_m)_{m\ge 1}$ is absolutely convergent, which in turn implies that $(a_m)_{m\ge 1}$ is convergent. From here we can conclude that the sequence $(x_{m+1}-x_1)_{m\ge 1}$ converges, which implies that the sequence $(x_{m+1})_{m\ge 1}$ converges, that is, the sequence $(x_k)_{k\ge 1}$ converges. Hence we are done.
Is this solution correct and rigorous enough and is there any other way to solve this problem (possibly without using absolute convergence)?

A: The solution is correct, the most important step is to derive convergence from absolute convergence,I think this is the most concise solution. For another way, you can prove that $x_{n}$ is a Cauchy sequence by conditions, and then get the conclusion. But I think there is no essential difference between the two solutions.


text:
Q: int argc, const char * argv[] , why we give these input to main Why we give these arguments to main ,searched a lot but couldn't find an answer to clear this doubt.
int main(int argc, const char * argv[])

A: argc represents the number of arguments passed to the main function.
argv[] represents the arguments passed which are separated by space.
Eg:-

$ ./a.out First Second Third

Program Name Is: ./a.out [argv[0]]
Number Of Arguments Passed: 4 [argc value]
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First
argv[2]: Second
argv[3]: Third
Refer here for more information


text:
Q: Runtimeexception: Unable to get androidx.core.content.FileProvider: ClassNotFoundExecption: appears on my Galaxy S8 Hello my dear friends,
I am trying to develop media files to my server with the help of Retrofit and a Fileprovider.
Like the title already describes my situation, am I looking for a solution of the following error. This error let the app crash during the launch while the app runs without issues on other phones. I am trying for a week now to fix this error and tried everything from Multidex integration, writing a new java path for my SDK, checking my permissions and clearing my mobile's cache.
To be honest, I am not really good at understanding the logcat when it comes to files in the background that I have not seen before. Apparently, the app does not find my Fileprovider class. I defined the Fileprovider in my manifest file and wrote a corresponding file_path.xml file. I could not find the need of a specific Java provider.class nor any gradle dependencies to make a fileprovider work.
I am excited what you say to my problem and to my logcat. I appreciate every useful information!
Thank you for reading.
My Logcat:
  java.lang.RuntimeException: Unable to instantiate application com.example.loginandregister.MainActivity: java.lang.ClassCastException: com.example.loginandregister.MainActivity cannot be cast to android.app.Application
        at android.app.LoadedApk.makeApplication(LoadedApk.java:979)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6030)
        at android.app.ActivityThread.-wrap1(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6938)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.ClassCastException: com.example.loginandregister.MainActivity cannot be cast to android.app.Application
        at android.app.Instrumentation.newApplication(Instrumentation.java:1108)
        at android.app.Instrumentation.newApplication(Instrumentation.java:1093)
        at android.app.LoadedApk.makeApplication(LoadedApk.java:973)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6030)
        at android.app.ActivityThread.-wrap1(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6938)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

My Manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.retrofit_uploadmediafiles">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ImageActivity"/>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.retrofit_uploadmediafiles.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>

My Gradle file (I included many dependencies out of desperation ...):
android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.example.retrofit_uploadmediafiles"
        minSdkVersion 23
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.test:runner:1.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.afollestad.material-dialogs:core:0.9.4.5'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'

    implementation "androidx.multidex:multidex:2.0.1"

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.rengwuxian.materialedittext:library:2.1.4'

    implementation group: 'commons-io', name: 'commons-io', version: '2.7'
}

My Main Activity:
public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
    private Button image, video, pdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MultiDex.install(this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        image = findViewById(R.id.image);
        video = findViewById(R.id.video);
        pdf = findViewById(R.id.Pdf);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            image.setEnabled(false);
            video.setEnabled(false);
            pdf.setEnabled(false);
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        } else {
            image.setEnabled(true);
            video.setEnabled(true);
            pdf.setEnabled(true);
        }

        image.setOnClickListener(this);
        video.setOnClickListener(this);
        pdf.setOnClickListener(this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if(requestCode == 0 ) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                image.setEnabled(true);
                video.setEnabled(true);
                pdf.setEnabled(true);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image:
                Intent intent = new Intent(this, ImageActivity.class);
                startActivity(intent);
                break;
            case R.id.video:
                //Intent intent2 = new Intent(this, VideoActivity.class);
                //startActivity(intent2);   I am trying to make the image upload work for now
                break;
            case R.id.Pdf:
                //Intent intent3 = new Intent(this, PdfActivity.class);
                //startActivity(intent3);
                break;
        }
    }

}

I am a little bit overwhelmed by all these different software versions on my phone:
Android version: 8.0.0
Samsung Experience version: 9.0
Knox version:3.0, API level 24
Let me know if you need more information

A: I have solved this problem. I set androidx.core:core:1.8.0 in build.gradle inside defaultConfig.
configurations.all {
    resolutionStrategy {
        force 'androidx.core:core:1.8.0'
    }
}

Then change compileSdkVersion to 32.
Clean project and rebuild project, finally everything be ok.

A: The AppCompat dependency compiles the Fileprovider which is within the androidx.core:core package as its dependency. Therefore remove this line implementation 'androidx.core:core:1.3.0' from your gradle file to see if it works. Because appcompat lib has version 1.1.0 while u still compiled 1.3.0 in your project.


text:
Q: How to read file to variable using cordova-plugin-file I'm using cordova-plugin-file to write a text file. I can get the plugin to populate a <div> on a modal popup. This snippet works perfectly:
function readFile6(fileName){
        var str = '';
        window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir){
        dir.getFile(fileName, {create: false}, function(fileEntry){

            fileEntry.file(function(file){
                var reader = new FileReader();
                reader.onloadend = function (evt) {
                   $(".accordine").html(evt.target.result);
                };
                reader.readAsText(file);

            }, function(error){
                alert("Error: " + error.code);
            });
        }, function(error){
            alert("Error: " + error.code);
        });
}, function(){
    alert("Error");
});

Problem is, I need the content of the file to be returned to the calling function so I can manipulate the data before it is displayed.
I read every tutorial/sample I can find, but none of the examples shows how to do anything with the contents except populate a div or show in console.log().
How can I get the text file's contents as a return value?

A: "Problem is, I need the content of the file to be returned to the calling function so I can manipulate the data before it is displayed." No you don't. You can manipulate the data without getting it as a return value. Suppose you have a function processData which you want to apply to the data. Then just change the reader.onloadend = part to this:
reader.onloadend = function (evt) {
    $(".accordine").html(processData(evt.target.result));
};


text:
Q: How To Exclude System Table When Querying Sys.Tables? I'm running this SQL :
SELECT S.name as Owner, T.name as TableName FROM  sys.tables AS T
JOIN sys.schemas AS S ON S.schema_id = T.schema_id

And the result is:
Owner   TableName
------------------------
dbo         Person
dbo         Customer
dbo         sysdiagrams

sysdiagrams is a system table but showed in result.
Update:
Thanks all for your answers and comments, I'm using Nate Bolam & vmvadivel answers:
SELECT S.name as Owner, T.name as TableName
FROM
  sys.tables AS T
    INNER JOIN sys.schemas AS S ON S.schema_id = T.schema_id
    LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T.[object_id]
WHERE
  T.is_ms_shipped = 0 AND
  (EP.class_desc IS NULL OR (EP.class_desc <>'OBJECT_OR_COLUMN' AND
  EP.[name] <> 'microsoft_database_tools_support'))

A: You can make use of IS_MS_SHIPPED for this. Hope the below script is what you are looking for
SELECT
    S.[name] AS Owner,
    T.[name] AS TableName
FROM
    sys.tables AS T JOIN sys.schemas AS S
    ON S.schema_id = T.schema_id
WHERE
    T.is_ms_shipped = 0
    AND T.[name] <> 'sysdiagrams'

A: SSMS uses an extended property to mark the sysdiagrams table as a sort of pseudo system table.
Try this:
SELECT S.name as Owner, T.name as TableName FROM  sys.tables AS T
INNER JOIN sys.schemas AS S ON S.schema_id = T.schema_id
LEFT JOIN sys.extended_properties AS EP ON EP.major_id = T.[object_id]
WHERE (EP.class_desc IS NULL
OR (EP.class_desc <> 'OBJECT_OR_COLUMN'
    AND EP.[name] <> 'microsoft_database_tools_support'))

A: Would you please try with below query, thanks
SELECT S.name as Owner, T.name as TableName FROM  sys.tables AS T
JOIN sys.schemas AS S ON S.schema_id = T.schema_id
WHERE T.name <> 'sysdiagrams'

A: Just for completeness, I'll give a variation on Nate Bolam's answer
SELECT S.name as Owner, T.name as TableName
FROM  sys.tables AS T
INNER JOIN sys.schemas AS S ON S.schema_id = T.schema_id
WHERE NOT EXISTS (SELECT * FROM sys.extended_properties EP WHERE EP.major_id = T.[object_id] AND EP.name = 'microsoft_database_tools_support')


text:
Q: If I say "car pulled up way too much into the road" what do you understand? I am trying to explain someone this situation. There was a car stopped at intersection but its head was sticking out of the cross walk and into other incoming traffic like this picture.

And I am trying to cross it in front of the car indicated by red arrow. So I was explaining the situation to someone and I said this.
"The car was pulled up too much into the road. If I had to go in front of the car I would have been on the way of other cars."
Are the words in bold font correct to use in this situation? If not how I could have said this more naturally?

A: The car stopped over the line or (an example of more detail) stopped so far over the line that it got in everyone's way would be sensible in British English. We do use pull up to mean stop but it doesn't quite fit here (pull up outside the next house would be fine as an instruction for someone dropping you off, pull up short is fine for stopping too soon).
Other options include simply ...stopped blocking the crossing/crosswalk... and ... so I couldn't (even) walk in front of it.
Your suggestion is comprehensible but not natural.


text:
Q: Uniform continuity of series Let $F= \sum_{j=1}^{\infty} f_j$
where $f_j : [a,b] \to \mathbb R$ are continuous functions and the series is uniformly convergent. Show that $F$ is uniformly continuous.
I'm unsure how to prove this, I first showed that $f_j$ is uniformly continuous since it is continuous on a closed, bounded interval, but then can we deduce that $F$ is also uniformly continuous from this?

A: I would prove first that $F$ is continuous, then only easily deduce it's uniformly continuous on $[a,b]$.  For that first part, it's the very important uniform limit theorem, which you can find in any good analysis book.  If you just want a hint on how to prove this theorem, consider the Cauchy criterion, and the inequality
$$
|f(x) - f(y)| \leq |f(x) - f_{N_\varepsilon}(x)| + |f_{N_\varepsilon}(x) - f_{N_\varepsilon}(y)| + |f(y) - f_{N_\varepsilon}(y)|
$$
for some $N_\varepsilon$ large enough, which does not depend on $x$ or $y$ since the convergence is uniform.
Note: You're using series, I'm using sequences. This doesn't change much by using $F_n = \sum_{j=1}^{n}f_j$, noting that $F$ is the uniform limit of that sequence and taking the argument from there.


text:
Q: problem in run code gives Error: Non-base32 digit found im facing problem while running code below always give "Error: Non-base32 digit found"
i did searched online and fix it by using utf-8 for secret = base64.b32decode(bytes(secret, 'utf-8')) but its not working giving me same error. Any suggestion? i'm using python 3.8
import hmac
import base64
import hashlib
import datetime
import time

#totp
interval=30 #seconds

#otp
digest=hashlib.sha1
digits=6 #number of integers supported?
secret='123456789abcdefg'

#totp
now=datetime.datetime.now()
i=time.mktime(now.timetuple())
timecode=int(i/interval)

#otp
base64_secret = base64.b32decode(secret,casefold=True)
res = []
while timecode != 0:
    res.append(chr(timecode & 0xFF))
    timecode = timecode >> 8
bytestring=''.join(reversed(res)).rjust(8,'\0') #padding=8
hmac_hash = hmac.new(
    base64_secret,
    bytestring,
    digest
).digest()

offset=ord(hmac_hash[19]) & 0xf
code = ((ord(hmac_hash[offset]) & 0x7f) << 24 |
    (ord(hmac_hash[offset + 1]) & 0xff) << 16 |
    (ord(hmac_hash[offset + 2]) & 0xff) << 8  |
    (ord(hmac_hash[offset + 3]) & 0xff))

code = code % 10 ** digits

print (code)

A: The Wikipedia article on base32 says that the most common version of base32 uses as digits the 26 letters in the standard alphabet, together with the digits in the range 2-7. Your code was trying to use as digits the numbers 1,8,9. Those are not base 32 digits, hence the error.
To solve that bug, swap out those 3 digits with letters something like:
secret='234567abcdefghij'

With that change, this bug disappears. Unfortunately, other bugs in your code appear, but that is a separate question.


text:
Q: Which is correct: "anytime" or "any time"? Is it "any time" or "anytime" or are those two things different?

A: Here is the explanation:  "At" is a preposition, so it must be followed by a noun.  The noun in the example is "time."  "Any" is an adjective modifying the noun "time."  It's like "Call me at four o'clock.  Call me at night. Call me at any hour of the day or night."
But "anytime" is an adverb, like "anyhow" or "anyway."  It's like "Call me early" or "Call me occasionally."
So why did the answer indicate that "Call me any time" is also acceptable?  Because using "anytime" is more informal.  The word does not even appear in the Webster's New World Dictionary of 1988.  However, it does appear in the online dictionary (dictionary.reference.com).  Evidently, the use of "anytime" has become more acceptable.

A: One may write

Call me anytime
Call me any time
Call me at any time

but not

*Call me at anytime

because anytime is used as an adverb and not a noun.


text:
Q: Multiple Data Files Read in Python I have Data of different Stocks of various dates
and each stock is stored in different Text Files (not in CSV)
How to Gather up Data in some way into a Single File

A: you can use something like pandas and load each file to a data frame and then merge all of the data frames together, you can find some info here
https://pandas.pydata.org/pandas-docs/stable/io.html

A: If you want to merge all the text files into a single one, use a command type(if linux, use cat). Firstly, cd to the directory your text files in(for example: E:\data).
cd E:\data\
type *.txt > all.csv

and then you can use pandas
df = pd.read_csv("all.csv")
...


text:
Q: Laravel Configuration for web server I developed a website in laravel and uploaded to web server. I uploaded all the files and folders into the root directory and the files of public folder to public_html. Now when I type the URL to my browser the home page works fine but my other routes are showing
Not Found

The requested URL /schedules was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

In the laravel documentation, I found that "Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run."
Is it the reason for this. If yes then how can I do this?

A: Since your new hosting/server is running Apache, make sure you copied .htaccess


text:
Q: UWP: Store file on network USB drive I want my raspberry Pi 3 (Windows IoT) to store a txt file.
The Pi3 is connected to my home LAN network which is operated by my netgear router (manual http://www.downloads.netgear.com/files/GDC/WNDR3700V5/WNDR3700v5_UM_03Sept2015.pdf).
The router also supports to connect a USB drive (called "Ready Share") to store data.
My goal is to let my UWP app running at the Pi3 store the txt at a dedicated folder on the USB drive.
Unfortunately, this is not working:
Windows.Storage.StorageFile sampleFile =
await storageFolder.CreateFileAsync("\\ReadyShare\MyNewFolder\MyTxt.txt",
    Windows.Storage.CreationCollisionOption.ReplaceExisting);

I get an error saying that the path is not existing.
Are there any alternatives?

A: For security reasons you are not allowed to access arbitrary folders. You must first let the user give you permission to do so; this can be done by letting the user point to the folder he wants you application to use (with a FilePicker or similar). The user must do this once, afterwards your application gains permanent access to those files/folders.
See here: https://learn.microsoft.com/en-us/windows/uwp/files/file-access-permissions


text:
Q: Deserializing MongoDB $oid using jackson library I have a very simple POJO that I write to MongoDB. It then returns me JSON that includes the _id property as an $oid object. I'd like to write it into my POJO, but so far have failed. I've seen many people struggle with it and suggesting different solutions, but I have yet to get any of them to work. Probably because nobody provides exact details which libraries they are actually using. There's codehaus.jackson.* there's com.fastxml.jackson., jongo, org.mongo., com.mongo.* etc.
My object looks like this:
package com.blueplanetsoftware.metrics.rest;

import javax.persistence.Id;

import com.fasterxml.jackson.annotation.JsonProperty;

public class MongoObject
{
    @JsonProperty("_id")
    private String _id;

    @JsonProperty("userID")
    private String userID;
    @JsonProperty("appID")
    private String appID;
    @JsonProperty("message")
    private String message = "";
    @JsonProperty("session")
    private String session;

    public MongoObject() {}

    /**
     * @return the id
     */
    @Id
    @JsonProperty("_id")
    public String getId()
    {
        return _id;
    }

    /**
     * @param id the id to set
     */
    @Id
    @JsonProperty("_id")
    public void setId(String id)
    {
        this._id = id;
    }
}

The JSON that I get back looks like this:
{
  "userID" : "aap" ,
  "appID" : "noot" ,
  "message" : "JSON" ,
  "session" : "ea944555b5ea8ea6" ,
  "_id" : { "$oid" : "5245f1063004348555e54815"}
}

when I try to deserialize that JSON into my class with this code:
com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
MongoObject o = mapper.readValue(response, MongoObject.class);

it gives me an exception:
java.lang.AssertionError: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.StringReader@456c1227; line: 1, column: 93] (through reference chain: com.blueplanetsoftware.metrics.rest.MongoObject["_id"])

So how to get the _id / $oid string into my _id property? I'm surprised there's isn't an easy way to do this. At least I haven't found any so far.

A: Have you tried?
@ObjectId @Id
private String id;

I've written a test to see this working:
@Test
public void shouldConvertJSONStringIntoPojo() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    MongoObject actual = mapper.readValue("{\n" +
                                     "        \"userID\" : \"aap\" ,\n" +
                                     "        \"appID\" : \"noot\" ,\n" +
                                     "        \"message\" : \"JSON\" ,\n" +
                                     "        \"session\" : \"ea944555b5ea8ea6\" ,\n" +
                                     "        \"_id\" : { \"$oid\" : \"5245f1063004348555e54815\"}\n" +
                                     "}", MongoObject.class);

    assertThat(actual, equalTo(new MongoObject("5245f1063004348555e54815", "aap", "noot", "JSON", "ea944555b5ea8ea6")));
}

The libraries I'm using for this:
import com.fasterxml.jackson.databind.ObjectMapper; (jackson-databind-2.1.4,jar)
import org.junit.Test;                              (junit-4.11.jar)
import static org.hamcrest.CoreMatchers.equalTo;    (hamcrest-core-1.3.jar)
import static org.junit.Assert.assertThat;          (junit-4.11.jar)

The only changes I've made to your MongoObject posted in the question is adding a constructor that takes all the fields, and hashCode, equals & toString (so I can test it).  If I run that test with that MongoObject, then I get the same error as you:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: java.io.StringReader@7a7ff2aa; line: 5, column: 40] (through reference chain: MongoObject["_id"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:599)

But if I make one small change to your MongoObject:
public class MongoObject
{
    @JsonProperty("_id")
    @org.jongo.marshall.jackson.oid.ObjectId
    private String _id;

    @JsonProperty("userID")
    private String userID;
    @JsonProperty("appID")
    private String appID;
    @JsonProperty("message")
    private String message;
    @JsonProperty("session")
    private String session;

    public MongoObject() {}

//... insert constructors, hashCode, equals and toString just for testing...
}

Then the test passes.


text:
Q: Typography gets pixileted in online version I'm working on this site www.runebs.dk and have problem with the typography. When the site is on my localhost the typography looks fine but when I upload it to the server it gets really pixelated.
I have tried to change the typography but that doesn't work. I might think it could be something in this script underneath because it's only in the divs the script displays, where the typography is pixilated. The typography looks fine on the rest of the site.
Is it because the script prints the content twice or?
Here is the online version http://imgur.com/CzwJiEZ
And here is the local version http://imgur.com/v6jGIRy
I really hope someone in here can point me in the right direction..
the html...

(–)

title text

year text

   description text

the css..
.article-header { display: none;}
 #subHeadline {position:fixed; top:0px; left: 0; margin-left: 22px; padding-top: 64px; height:   auto; width: 600px; z-index:1; }
 #subHeadline .description { display: block; width: 255px; position: relative; margin-top: 28px;}
 #subHeadline .showHide  { display: none; width: 255px; position: relative; margin-top: 28px; cursor: pointer;}
.year {display: block; margin-top: -19px;}

and the jquery...
function toggleInfo () {
 $('.showHide').on('click',function(){
 $(this).toggleClass('active');
 $( '#subHeadline .description' ).slideToggle(200);
 var currentState = $(this).text();
 console.log('state: ', currentState);
 if($(this).hasClass('active')) {
    $('.showHide').empty();
    $(this).text('(+)');
} else {
  $(this).text('(–)');
}
});
}

$(document).ready(function(){

    // firing toggleInfo when doc ready
     toggleInfo();

var $window = $(window);

$window.trigger('scroll'); // init the value

$window.on('scroll', function(){

var pos = $('#subHeadline').offset();
  $('.article-header').each(function(){
      if (pos.top <= $(this).offset().top && pos.top >= $(this).next().offset().top) {
        var desc = $('.description', this).text();
        var title = $('.h3', this).text();
        var year = $('.year', this).text();
        var button = $('.showHide', this).text();
          $('#subHeadline .title').text(title);
          $('#subHeadline .year').text(year);
          $('#subHeadline .description').text(desc);
          $('#subHeadline .showHide').show();
          return;
      }
  });
});


text:
Q: Extract mantissa, exponent and sign data from IEEE-754 double in VBA How to extract mantissa, exponent and sign data from an IEEE-754 64-bit (double) floating-point number in VBA?  Thanks
Edit (after John Coleman comments). Before posting the original question, I have looked around for a solution and could only find how to do it in C (e.g. using structures with bit fields).  Couldn't find anything for VBA.  I have tried using VBA's bit operators (i.e. AND, OR, NOT, XOR) but this does not seem to give the expected result.  For example, 1 expressed in single precision IEEE 32-bit floating-point is represented by
0 01111111 00000000000000000000000
where the first bit is for sign, the next 8 bits are for the (biased) exponent, and the last 23 bits are for the mantissa.  Applying NOT to 1 should return
1 10000000 11111111111111111111111
which is -3.9999998 in decimal, but the following code in VBA returns -2, which is represented by
1 10000000 00000000000000000000000
x = Not 1!
Debug.Print x

I didn't see the point of posting this in my OP.

A: I think I've found the way to do this.  The following function DoubleToBin returns a string of 64 bits representing an IEEE-754 double floating-point number. It uses a VBA "trick" to pass around raw data without using API routines (such as MemCopy (RtlMoveMemory)) by combining LSet with User Defined Types of the same size.  And once we have the bit string we can extract all components from it.
Type TDouble
  Value As Double
End Type

Type TArray
  Value(1 To 8) As Byte
End Type

Function DoubleToArray(DPFloat As Double) As Variant
  Dim A As TDouble
  Dim B As TArray
  A.Value = DPFloat
  LSet B = A
  DoubleToArray = B.Value
End Function

Function DoubleToBin(DPFloat As Double) As String
  Dim ByteArray() As Byte
  Dim BitString As String
  Dim i As Integer
  Dim j As Integer

  ByteArray = DoubleToArray(DPFloat)

  For i = 8 To 1 Step -1
    j = 2 ^ 7
    Do While j >= 1
      If (ByteArray(i) And j) = 0 Then
        BitString = BitString & "0"
      Else
        BitString = BitString & "1"
      End If
      j = j \ 2
    Loop
  Next i

  DoubleToBin = BitString
End Function

How does it work on here - do I now accept my own answer?

A: This is a modification of Confounded's excellent answer. I modified their function to be use the built-in function Hex rather than bit-wise operations to get the to the bit patterns, made it be able to handle both single and double precision flexibly, and return either the results in either hex (the default) or binary:
Type TDouble
  Value As Double
End Type

Type TSingle
  Value As Single
End Type

Type DArray
  Value(1 To 8) As Byte
End Type

Type SArray
  Value(1 To 4) As Byte
End Type

Function DoubleToArray(DPFloat As Double) As Variant
  Dim A As TDouble
  Dim B As DArray
  A.Value = DPFloat
  LSet B = A
  DoubleToArray = B.Value
End Function

Function SingleToArray(SPFloat As Single) As Variant
  Dim A As TSingle
  Dim B As SArray
  A.Value = SPFloat
  LSet B = A
  SingleToArray = B.Value
End Function

Function HexToBin(hDigit As String) As String
    Select Case hDigit
        Case "0": HexToBin = "0000"
        Case "1": HexToBin = "0001"
        Case "2": HexToBin = "0010"
        Case "3": HexToBin = "0011"
        Case "4": HexToBin = "0100"
        Case "5": HexToBin = "0101"
        Case "6": HexToBin = "0110"
        Case "7": HexToBin = "0111"
        Case "8": HexToBin = "1000"
        Case "9": HexToBin = "1001"
        Case "A": HexToBin = "1010"
        Case "B": HexToBin = "1011"
        Case "C": HexToBin = "1100"
        Case "D": HexToBin = "1101"
        Case "E": HexToBin = "1110"
        Case "F": HexToBin = "1111"
    End Select
End Function

Function ByteToString(B As Byte, Optional FullBinary As Boolean = False)
    Dim BitString As String
    BitString = Hex(B)
    If Len(BitString) < 2 Then BitString = "0" & BitString
    If FullBinary Then
        BitString = HexToBin(Mid(BitString, 1, 1)) & HexToBin(Mid(BitString, 2, 1))
    End If
    ByteToString = BitString
End Function

Function FloatToBits(float As Variant, Optional FullBinary As Boolean = False) As String
    Dim ByteArray() As Byte
    Dim BitString As String
    Dim i As Integer, n As Integer
    Dim x As Double, y As Single
    If TypeName(float) = "Double" Then
        n = 8
        x = float
        ByteArray = DoubleToArray(x)
    ElseIf TypeName(float) = "Single" Then
        n = 4
        y = float
        ByteArray = SingleToArray(y)
    Else
        FloatToBits = "Error!"
        Exit Function
    End If

    For i = n To 1 Step -1
        BitString = BitString & ByteToString(ByteArray(i), FullBinary)
    Next i
    FloatToBits = BitString
End Function

Here is a test:
Sub test()
    Dim x As Single, y As Double
    x = Application.WorksheetFunction.Pi()
    y = Application.WorksheetFunction.Pi()

    Debug.Print FloatToBits(x)
    Debug.Print FloatToBits(x, True)
    Debug.Print FloatToBits(y)
    Debug.Print FloatToBits(y, True)
End Sub

Output:
40490FDB
01000000010010010000111111011011
400921FB54442D18
0100000000001001001000011111101101010100010001000010110100011000

When I feed 400921FB54442D18 into this online tool I get back 3.141592653589793, which makes perfect sense.
Somewhat curiously, when I apply this to 10.4 I get
0100000000100100110011001100110011001100110011001100110011001101
which differs in the final place from the example in this excellent article on floats in Excel VBA. Both versions round to 10.4 (to many, many places). I don't quite know what to make of the discrepancy.

A: Partial Answer:
VBA bitwise operators are designed to work with integer or long data. Consider the following:
Sub test()
    Dim x As Single, y As Single
    x = 1#
    y = Not x
    Debug.Print y
    Debug.Print TypeName(Not x)
End Sub

Output:
-2
Long

The first output line is the observed weirdness. The second line is the explanation of this weirdness. Evidently, x is converted to a long before being fed into Not. Interestingly, the following C program also prints -2:
int main(void){
    int x,y;
    x = 1;
    y = ~x;
    printf("%d\n",y);
    return 0;
}

(gcc uses 32 bit ints on my machine, so int here is equivalent to Long in VBA)
It should be possible to obtain what you want, but bitwise operators are not the way to go.

A: This function works for 64 bit double precision format:
Function IEEE754todouble(hexanumber As String) As Double

    If Left(hexanumber, 1) > 7 Then
        sign = 1
    Else
        sign = 0
    End If

    exponent = Val("&H" & (Left(hexanumber, 3))) Mod 2048

    mantissa = 16 ^ 8 * Val("&H" & Mid(hexanumber, 4, 5)) + Val("&H" & Right(hexanumber, 8))
    IEEE754todouble = (-1) ^ sign * 2 ^ (exponent - 1023) * (1 + 2 ^ -52 * mantissa)

End Function

If you need other formats, just change a few numbers in it and it should be alright.
I have put a double calculation in mantissa because the guy didn't want to know about a single Val("&H" & Right(hexanumber, 13)).


text:
Q: How do I modify part of the DOM outside of my Vue.js app such as a  tag? I have a Vue.js app where the main template looks like this:

  <link id="theme" rel="stylesheet" href="foo.css">

I can easily modify anything within #app as part of my Vue.js code, however later I want to modify the #theme from within a Component where a <select> is used to select which theme to use.

A: Made a JSFiddle using material design colors css : https://jsfiddle.net/rk5ytqs3/2/
in data assign theme name, css url
    themes:[
    {color:'blue', url:'https://code.getmdl.io/1.3.0/material.light_blue-light_green.min.css'},
    {color:'orange', url:'https://code.getmdl.io/1.3.0/material.orange-yellow.min.css'},
  {color:'purple', url:'https://code.getmdl.io/1.3.0/material.deep_purple-red.min.css'},
  {color:'pink', url:'https://code.getmdl.io/1.3.0/material.pink-indigo.min.css'},
    ]

use v-for and assign them in to select
<select name="theme" @change="changetheme">
    <option v-for="(theme, index) in themes" :value="index">{{theme.color}}</option>
   </select>

When user selected change theme via method
changetheme(event) {
  let val = event.target.value

  document.querySelector('#theme').href = this.themes[val].url
}

In general, modifying the DOM outside of your app is considered a side effect. As such, this code should be part of your higher-order components.


text:
Q: .NET Identity UserManager.FindAsyc throwing "Invalid column name 'Discriminator'." I created a new .NET Web Application project and choose the Individual User Account Authentication for the template I selected.  By default this sets up the Identity database to be a local database in the App_Data directory.  This worked fine.  But then I needed the AspNet tables for membership to be in my real SQL Server database that holds the rest of my application.  So I changed the DefaultConnection string to point to my local SQL Server database and when I reran the application, EF automatically created those tables in my real database.  So everything seemed good.
Then when I try to Login and it calls UserManager.FindAsync, it gives me the following SqlException: "Invalid column name 'Discriminator'.".  The full StackTrace is below for reference.
I'm using the same ApplicationDbContext and ApplicationUser that come with the default web application templates.
Any ideas for what I am doing wrong?  This is my first time working with .NET Identity.  Is there a different way to make it work with an existing SQL Server database besides just changing the connection string?
Thanks.
Full Stack Trace:
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\r\n   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed)\r\n   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)\r\n   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

A: Two different DbContexts?
The error message could be caused by a database created by a DbContext with a DbSet of type IdentityUser or maybe more likely some entity related to IdentityUser in some way. while the UserManager seems to be using another Context (the ApplicationDbContext?) containing a DbSet of a type inheriting from IdentityUser. When you have a type inheriting from another type in your model entity framework will use/expect a column called discriminator that will contain the type name of the entity that is stored in a particular row.

A: This error would also happen if Self-Hosted WEB API created the Database, and then you tried to access it from ASP.NET MVC site. Both Projects come as default in VS 2013.
As Olav Nybo said, this is probably related to the fact that ASP.NET MVC tries to login as ApplicationUser that inherits from IdentityUser.
The quick fix for me was to generate the database from ASP.NET MVC Web Site.

A: Little late to the party but, what I saw in this is that when extending the IdentityUser, the AspNetUsers table needs your new custom columns for the attributes being used AND a column for the types of IdentityUser.
For example if you are creating a new ApplicationUser : IdentityUser then there will be a new column in the table named Discriminator and it will have a value of ApplicationUser.  This is the case that you are not using Code First and you need to manually apply your database changes.


text:
Q: How to store images in google drive through salesforce Actually my requirement is want to store bulk of images for these we can use document/notes and attachments due to storage constraint i want to use google drive to store the images from visualforce page/salesforce can any one help me how can i achieve this and what are the steps i have to follow.
Thanks in advance,
Chandra.

A: You can use plenty of app exchange apps to save Google Drive.
We use one such app.
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000008amNrEAI
If you gonna go with standard solutions, Summer 15 has provided solution to connect with Google Drive.
https://releasenotes.docs.salesforce.com/en-us/summer15/release-notes/rn_chatter_files_connect_google_drive.htm
http://www.summa.com/blog/salesforce-summer-15-feature-integrate-google-drive-in-minutes


text:
Q: How to crop a region selected with mouse click, using Python? I'm working with python using Matplotlib and PIL and a need to look into a image select and cut the area that i have to work with, leaving only the image of the selected area.I alredy know how to cut imagens with pil(using im.crop) but how can i select the coordinates to croped the image with mouse clicks?
To better explain, i crop the image like this:
import Pil
import Image
im = Image.open("test.jpg")

crop_rectangle = (50, 50, 200, 200)
cropped_im = im.crop(crop_rectangle)

cropped_im.show()

I need to give the coordinates "crop_rectangle" with the mouse click in a rectangle that i wanna work with, how can i do it?
Thank you

A: You could use matplotlib.widgets.RectangleSelector (thanks to Joe Kington for this suggestion) to handle button press events:
import numpy as np
import matplotlib.pyplot as plt
import Image
import matplotlib.widgets as widgets

def onselect(eclick, erelease):
    if eclick.ydata>erelease.ydata:
        eclick.ydata,erelease.ydata=erelease.ydata,eclick.ydata
    if eclick.xdata>erelease.xdata:
        eclick.xdata,erelease.xdata=erelease.xdata,eclick.xdata
    ax.set_ylim(erelease.ydata,eclick.ydata)
    ax.set_xlim(eclick.xdata,erelease.xdata)
    fig.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)
filename="test.png"
im = Image.open(filename)
arr = np.asarray(im)
plt_image=plt.imshow(arr)
rs=widgets.RectangleSelector(
    ax, onselect, drawtype='box',
    rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=True))
plt.show()

A: are you using tk?  it will depend on what window management you are using.  High level though, you'll want something like:
def onMouseDown():
    // get and save your coordinates

def onMouseUp():
    // save these coordinates as well

    // now compare your coordinates to fingure out which corners
    // are being used and define your rectangle

The callbacks themselves will differ from window tool to window tool, but the concept will be the same:  capture the click down event and release event and compare the points where the events were triggered to create your rectangle.  The trick is to remember to figure out which corner they are starting at (the second point is always opposite that corner) and creating your rectangle to be cropped, relative to the original image itself.
Again, depending on the tool, you will probably need to put your click events in your image's coordinate space.


text:
Q: AWS Wrangler Athena and S3 read_csv UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position I am trying to use awswrangler's s3.read_csv function to read an Athena SQL query output. The output path is wr.athena.get_query_execution(query_execution_id). I can confirm that the output path exists. I then load the output using awswrangler's wr.s3.read_csv(outputpath) function. However, I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position.
df = wr.s3.read_csv(<s3path.csv>)

--snipped--
  File "pandas/_libs/parsers.pyx", line 711, in pandas._libs.parsers.TextReader._get_header
  File "pandas/_libs/parsers.pyx", line 905, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas/_libs/parsers.pyx", line 2034, in pandas._libs.parsers.raise_parser_error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 75: invalid start byte

Side note, I am trying to avoid wr.athena.read_sql_query(sql) because I am implementing a asynchronous function.
I tried to download the s3 object using boto3.s3_client, read the file and loaded it via pandas.read_csv() directly and works perfectly. So, I don't think it's a permission issue nor a corrupt file issue. Any idea what I am doing wrong with wr.s3.read_csv() call?

A: I had same issue, probably you're reading metadata file. If you're tring to read the output of Athena query, you should consider Athena creates metadata file. So maybe you have something like this:
s3://BUCKET/prefix/4a21ada3-d1d0-467e-907d-9abf5f0bb69c.csv.metadata
s3://BUCKET/prefix/4a21ada3-d1d0-467e-907d-9abf5f0bb69c.csv

If you're using with this code:
path = s3://BUCKET/prefix/4a21ada3-d1d0-467e-907d-9abf5f0bb69c.csv

wr.s3.read_csv(path)

you'll read two files, also metadata file, because metadata file has the same name until .metadata.
So the solution to this problem is use path_suffix argument.
wr.s3.read_csv(path, path_suffix='csv')


text:
Q: Field expression not allowed for generic SObject I am writing my trigger in an apex class, while doing this i am facing the error:

'Field expression not allowed for generic SObject at line 15 column
  94'.

Here is my apex class:
public class updateCaseHandler
{

public static void updatecaseclosed(list<Case> newlist)
{
         Map<Id, Task> taskMap = new Map<Id, Task>();

    for(Task t : [SELECT Id, WhatId FROM Task WHERE IsClosed=false AND WhatId IN :trigger.newMap.keySet()])
    {
        taskMap.put(t.WhatId, t);
    }

    for(Case c : Trigger.new)
    {

        if(taskMap.containsKey(c.Id) && c.IsClosed && c.IsClosed != Trigger.oldMap.get(c.Id).IsClosed)
            c.addError('Case Cannot be closed with open tasks');
    }
    }
}

Any idea? how can i avoid this error.
Thanks!

A: You may need to typecast the variables:
    public class updateCaseHandler  {

        public static void updatecaseclosed(list<Case> newlist) {
                 Map<Id, Task> taskMap = new Map<Id, Task>();

            for(Task t : [SELECT Id, WhatId FROM Task WHERE IsClosed=false AND WhatId IN :trigger.newMap.keySet()]) {
                taskMap.put(t.WhatId, t);
            }

            List<Case> lstNewCases = Trigger.new;

            for(Case c : lstNewCases) {

                Case objOldCase = (Case) Trigger.oldMap.get(c.Id);

                if(taskMap.containsKey(c.Id) &&
                    c.IsClosed &&
                    c.IsClosed != objOldCase.IsClosed) {

                    c.addError('Case Cannot be closed with open tasks');
                }
            }
        }
    }

A: I am assuming the Trigger is on Cases? Try casting Trigger.oldMap.get(c.Id).IsClosed to Case:
((Case)Trigger.oldMap.get(c.Id)).IsClosed

A: Try with this, i changed Trigger.new by newlist!
public class updateCaseHandler
{
    public static void updatecaseclosed(list<Case> newlist)
    {
        Map<Id, Task> taskMap = new Map<Id, Task>();

    for(Task t : [SELECT Id, WhatId FROM Task WHERE IsClosed=false AND WhatId IN :trigger.newMap.keySet()])
    {
        taskMap.put(t.WhatId, t);
    }

    for(Case c : newlist)
    {

        if(taskMap.containsKey(c.Id) && c.IsClosed && c.IsClosed != Trigger.oldMap.get(c.Id).IsClosed)
            c.addError('Case Cannot be closed with open tasks');
    }
    }
}


text:
Q: Книги и учебные ресурсы по С В этом вопросе собирается литература по языку C
Формат:

Имя Фамилия — «Название книги целиком и полностью», ГГГГ г..

Формат для переведенной литературы:

Имя Фамилия (Name Surname) — «Название книги целиком и полностью», ГГГГ перевода ("Full name of the book", YYYY )

A: *

*«Язык программирования Си» (англ. The C Programming Language, также известная как K&R) — книга Брайана Кернигана и Денниса Ритчи
Русские издания:
Брайан Керниган, Деннис Ритчи. Язык программирования Си. — Москва: Финансы и статистика, 1992. — 272 с. — ISBN 5-279-00473-1.
Брайан Керниган, Деннис Ритчи. Язык программирования Си. — Санкт-Петербург: Невский диалект, 2000. — 352 с. — (Библиотека программиста). — ISBN 5-7940-0045-7.
Брайан Керниган, Деннис Ритчи. Язык программирования C. — Москва: Вильямс, 2015. — 304 с. — ISBN 978-5-8459-1975-5.
(в сети также легко ищутся и pdf версии)

*Бен Клеменс   Язык C в XXI веке ДМК Пресс 2018 (есть издание 2015 г.)
(Ben Klemens 21st Century C O'REILLY 2015)

*Керниган Б.У., Пайк Р., Практика программирования,  2004.
Это не учебник по языку, а скорее хорошая книжка о том, как стоит писать программы, используя Си.


text:
Q: Error 1000 Fetching image failed. I can't upload a binary photo using the google business API [API google GMB] Can not upload a photo using the media.upload API for Upload from bytes.
Hi I am trying to upload a photo from bytes using the google my business API following the steps describe in the next guide: guide upload from bytes.
For test I am using curl requests.
the step are:

*

*Get the MediaItemDataRef  (This step work without problem):
curl -X POST  -v -H "Authorization: Bearer <access_token>"
"https://mybusiness.googleapis.com/v4/accounts//locations//media:startUpload"
I receive a "resourceName" variable.

*Use the resourceName returned by the call made in the
previous step to upload the bytes:
   curl -X POST -T ~/<patch_to_the_file.png> -v -H "Authorization:
   Bearer <access_token>"
   "https://mybusiness.googleapis.com/upload/v1/media/<resourceName>?uploadType=media"

*Call Media.Create using the resourceName returned in Step 1:

    curl -X POST
    --data '{"mediaFormat":"PHOTO","locationAssociation"{"category":"FOOD_AND_DRINK"},"dataRef":
    {"resourceName":"<resourceName>"}}'
    -H "Authorization: Bearer <access_token>
    -H "Content-Type: application/json"
    "https://mybusiness.googleapis.com/v4/accounts/<id_account>/locations/<id_
    locations>/media"

In the 3 step I receive the following error in the answers:
 {
    "error": {
       "code": 400,
       "message": "Request contains an invalid argument.",
       "status": "INVALID_ARGUMENT",
       "details": [
         {
           "@type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
           "errorDetails": [
             {
               "code": 1000,
               "message": "Fetching image failed."
             }
           ]
         }
       ]
     }
  }

I had to try the same steps in Python and I have the same error, so I want to know what my error is in the request.
Thank you.

A: I had a similar phenomenon.
And I was able to solve the problem.
In my case, the posting cycle for the same store was about 18 seconds, but when I corrected it to a 60-second cycle, it was resolved.


text:
Q: How to perform Zoom and onClick Action on Image View Using Android I have a image view which is zoomed and when we zoom and click on image i want to get color of image how is it possible

A: @Talha_Sheikh918 please check it,
Use this library this will help you to fulfill your requirements
https://github.com/chrisbanes/PhotoView
use like this way
your_activity.xml
<com.github.chrisbanes.photoview.PhotoView
    android:id="@+id/photo_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

YourActivity.java
PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
photoView.setImageResource(R.drawable.image);

Features

*

*Out of the box zooming, using multi-touch and double-tap.

*Scrolling, with smooth scrolling fling.

*Works perfectly when used in a scrolling parent (such as ViewPager).

*Allows the application to be notified when the displayed Matrix has changed.

*Useful for when you need to update your UI based on the current zoom/scroll position.

*Allows the application to be notified when the user taps on the Photo.

Edit
If you want to get color of pointed pixel.
PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);

Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();

imageView.setOnTouchListener(new OnTouchListener(){
        @Override
        public boolean onTouch(View v, MotionEvent event){
        int x = (int)event.getX();
        int y = (int)event.getY();
        int pixel = bitmap.getPixel(x,y);

        //the pixel data
        int redValue = Color.red(pixel);
        int blueValue = Color.blue(pixel);
        int greenValue = Color.green(pixel);

        return false;
        }
   });


text:
Q: How does Typed Racket's type inference work? What kind of type inference does Typed Racket do? I found the following snippet on the Racket mailing list:

The Typed Racket type system contains a number of features that go
  beyond what's supported in Hindley/Milner style type systems, and so
  we can't use that inference system.  Currently, Typed Racket uses
  local type inference to infer many of the types in your program, but
  we'd like to infer more of them -- this is an ongoing area of
  research.

The blurb above uses the term "local type inference", and I've also heard "occurrence typing" used a lot, but I'm not exactly sure what these terms mean.
It seems to me that the type inference system that Typed Racket currently uses is unnecessarily weak. Here's an example of what I mean. The following does not type check:
(struct: pt ([x : Real] [y : Real]))

(define (midpoint p1 p2)
  (pt (/ (+ (pt-x p1) (pt-x p2)) 2)
      (/ (+ (pt-y p1) (pt-y p2)) 2)))

You have to explicitly annotate midpoint with (: midpoint (pt pt -> pt)), otherwise you get the error: Type Checker: Expected pt, but got Any in: p1. Why can't the type checker just conclude from this that the types of p1 and p2 must be pt? Is this a fundamental limitation of the way that Racket implements types (i.e. is this line of reasoning actually wrong sometimes, because of some of Racket's more advanced type features), or is this something that could possibly be implemented in the future?

A: By default, unannotated top-level functions are assumed to have input and output types of Any. I offer this vague explanation: since Racket's type system is so flexible, it can sometimes infer types that you wouldn't expect, and allow some programs to typecheck when you might prefer them to emit a type error.
Tangent: you can also use the define: form if that is what suits you.
(define: (midpoint [p1 : pt] [p2 : pt]) : pt
  ...)


text:
Q: Reverse foreign key relation in Django ORM How to return all objects  instances of a particular model  that are being addresed as Foreign key by ANY object instance of a different model ?  Lets say there is a model Item  and a model ItemRequested that has foreign key relation to Item. How to print all Items that are being mentioned as foreign key in the ItemRequested table/model ? basically this is the SQL query that i want to execute in Django:
select * from backend_item where id in (select id from backend_itemrequested);

Obviously i want to avoid executing raw SQL commands from inside Django ORM

A: I'm not sure exactly what you're asking here. But perhaps this is what you want:
Item.objects.exclude(itemrequested=None)


text:
Q: Only pass function parameters if they exist I have python3 class function defined like below:
class class1:
    def funcOne(self, reqvar1, reqVar2, optVar1=default1, optVar2=default2, optVar3="server.domain", optVar4="defaultUser", optVar5="<default_Flags>"):

It gets called (I want to call it like this rather) in the main program like:
argsIn=argparser.parse_args()

classInst=class1()
classInst.funcOne(5, 12, argsIn.inVal1, argsIn.inVal2, argsIn.inVal3, argsIn.inVal4, argsIn.inVal5)

args.inVal[1-5] are optional on the command line when running. If they don't get supplied I want the class function to use the defaults, if they do get supplied then they would use the supplied values.
Currently if they are not supplied on the command line, inVal[1-5] are passed as 'None' which overwrite the actual default values.
The class function is maintained separately and they manage the defaults. Putting them into my script (for example in the argparser options) is not appropriate.
Is there a way to easily work with this situation that doesn't resort to:
if args.inVal1 and not args.inVal2...
if not args.inVal1 and args.inVal2 and not args.inVal3...

as the number of combinations gets large.
It seems like it should be simple, but I am not connecting something here.
Thank you for the help.

A: If you create a dictionary that contains the optional variable names, you can pass that dictionary to the function call. I only commented out the argparser for testing.
class class1:
    def funcOne(self, reqvar1, reqVar2, optVar1='default1', optVar2='default2', optVar3="server.domain", optVar4="defaultUser", optVar5="<default_Flags>"):
        print(optVar1)
        print(optVar2)
        print(optVar3)
        print(optVar4)
        print(optVar5)

#argsIn=argparser.parse_args()

optionalArgs = {'optVar1': 'TestingVar1',   #args.inVal1,
                'optVar2': None,            #args.inVal2,
                'optVar3': 'TestingVar3',   #args.inVal3,
                'optVar4': None,            #args.inVal4,
                'optVar5': None}            #args.inVal5}
optionalArgsClean = {k:v for k, v in optionalArgs.items() if v is not None}

classInst=class1()
classInst.funcOne(5, 12, **optionalArgsClean)

Running the above code produces:
TestingVar1
default2
TestingVar3
defaultUser
<default_Flags>


text:
Q: Refactor conditional SQL inner join from C# to Stored Procedure I have a repository class which uses a query that is constructed in C# by concatenating strings based on certain conditions.
I want to move this query from C# code to stored procedures. Now a piece of code does an inner join with a huge user table ( I am talking about millions of records) based on a condition.
Here is the snippet.
    StringBuilder sb = new StringBuilder();
    sb.AppendLine("  SELECT");
    sb.AppendLine("  I.[Code] AS ItemCode, IP.[PlatformCode]");
    sb.AppendLine("  FROM [product].[ProductPlatform] PP");
    sb.AppendLine("  JOIN [product].[Product] P ON PP.[ProductId] = P.[Id]");
    if (condition)
    {
        sb.AppendLine("    JOIN [user].[UserItem] UI ON I.[ItemCode] = UI.[ItemCode] AND IP.[PlatformCode] = UI.[PlatformCode] AND UI.[UserId] = @UserId");
    }
    if (condition2)
    {
        sb.AppendLine("    JOIN [user].[UserProductItem] UPI ON I.[Code] = UPI.[ProductItemCode] AND UPI.[UserId] = @UserId");
    }
    ...

There are other joins but they are not important. Now the two join strings will be totally ignored if the two conditions are false.
Now I want to move the entire SQL code into Stored Proc without compromising performance. I don't want the two joins be executed if the conditions are false, because those two tables are huge.
I created the following stored procedure where I pass the two C# condition variables as parameters to my stored proc, but I think a) it is not the same logic as if the condition is not met the query returns nothing, I guess I need a left join and b) performance is not preserved as before.
    JOIN [user].[UserItem] UI ON a.[ItemCode] = UI.[ItemCode] AND PP.[PlatformCode] = UI.[PlatformCode] AND UI.[UserId] = @UserId AND (@onlyConditionMet = 1)

    JOIN [user].[UserProduct] UP ON P.[Code] = UP.[ProductCode] AND UP.[UserId] = @UserId AND (@onlyCondition2Met = 1)

Now the question is how can I best move my code to stored proc by preserving performance and not changing the query too much.
UPDATE: Based on the solutions suggested by the folks here I ended up using IF blocks. My code is now verbose, but I have preserved performance which is paramount for my query. Now my code looks like this:
    IF ( condition1 = true AND condition2 = true AND condition3 = true)
        BEGIN
            SELECT * FROM someTable
            LEFT JOIN someOtherTable on someCondition
        END
    ELSE IF ( condition1 = true AND condition2 = true AND condition3 = false)
        BEGIN
            SELECT * FROM someTable
            LEFT JOIN someOtherThanTheOtherTable on someOtherCondition
        END
    ...
    ELSE IF ( condition1 = false AND condition2 = false AND condition3 = false)
        BEGIN
            -- Do something else
        END

A: Just make :
IF @condition = 1
[...  First SELECT WITH first JOIN ... ]
ELSE
[...  Second SELECT WITH second JOIN ... ]

Moreover, in terms of performance, using "dynamic queries" with Ado makes SQL Server recompiles the query and process a new execution plan each time. Using a stored procedure or a function will be faster than a dynamic query in Ado, since the query is compiled just once when you add it to your Database.
Moreover bis : If there is only some SELECT statements in your procedure, and each time the same returned values, why not make a Table Function ?
PS : From a performance point of view, it's not sure that a boolean inside the JOIN clause is less efficient that such a IF/THEN case. You should look at the execution plans and make some tests. SQL Server is really smart sometimes.

A: There's always sq_executesql, but you may want to write this as a high-level IF block:
If condition And NOT condition2
Begin

 -- Do query with UserItem join

end
if (NOT condition) And condition2
Begin

 -- Do query with UserProduct join

end
if condition And condition2

 -- Do query with both joins

end

Finally, depending on your conditions, you may be able to write them into the JOIN clause by using an OUTER JOIN type:
LEFT JOIN [user].[UserItem] UI ON condition AND I.[ItemCode] = UI.[ItemCode] AND IP.[PlatformCode] = UI.[PlatformCode] AND UI.[UserId] = @UserId

You mentioned performance as a concern, so I'll add that this last option can still perform quite well if the columns referenced for your condition are constant or match up well with the table indexes.


text:
Q: 1 Button 3 Command onclick android How to include 3 Commands into one button?
I want insert open another activity, when button click.
This my code:
btnUpload = (Button) findViewById(R.id.btn_submit);
btnUpload.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i(TAG, "submit clicked");
    if (!Ultils.isConnectingToInternet(SubmitPropertiesActivity.this)) {
       showMsg(getResources().getString(R.string.open_network));
    } else {
       doUpload();
    }
}
});

A: Just add line in onClick method
startActivity(new Intent(getApplicationContext(),anotherActivity.class));
like
btnUpload.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Log.i(TAG, "submit clicked");
        //other command
        startActivity(new Intent(getApplicationContext(),anotherActivity.class));
    }
});

A: Add start activity code in runOnUiThread after dismiss dialog and clear all data then add your start activity code.
 runOnUiThread(new Runnable() {
                            public void run() {
                                try {
                                    prgDialog.dismiss();
                                    title.setText("");
                                    price.setText("");
                                    content.setText("");
                                    address.setText("");
                                    area.setText("");
                                    lantai.setText("");
                                    luasbangunan.setText("");
                                    bathroom.setText("");
                                    bedroom.setText("");
                                    selected_amenities_list.clear();
                                    marker_selected = 0;

                                  //Here You add your start new activity code.

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });

A: Something like this could help you;
Write 3 Methods
1) Network check method
2) Upload image method
3) Start an Activity method
When the button is click;
Call Method (1)
if Network connection is there - then
Call Method (2) from Method (1)
Check if uploading method finishs, if it does -
Call Method (3) from there
This is a simple procedure, just giving you the idea I would use If I'm in the situation.


text:
Q: Reload stream without undeploying I have a stream with a custom sink module. When the stream is deployed the module connects and reads properties from database. I want to refresh the module properties without undeploying the stream, i.e., if a change is made in the database I should be able to refresh the properties without undeploying the stream.
Any thoughts or suggestions?
Thanks in advance.

A: You would have to use some kind of out-of-band technique to trigger the module to refresh its properties.
Possibilities include a JMX MBean, some other inbound-channel-adapter wired to a control-bus, ...


text:
Q: CF Location queries looping issue I am trying to figure out how to run queries through a MS sql database using ColdFusion in order to make a table that keeps track of Location, Percent of Total Checklists, and Location Total.
I am having trouble looping to show my locations only once and to run the totals for each location. I am not sure why my table is adding all of these lines like the picture below, any help with this would be greatly appreciated!
<cfset result = {} />
<cftry>
    <cfquery datasource="#application.dsn#" name="GetLocationInfo">
        SELECT *
        FROM cl_checklists
    </cfquery>

    <cfcatch type="any">
        <cfset result.error = CFCATCH.message >
        <cfset result.detail = CFCATCH.detail >
    </cfcatch>
</cftry>

        Location
        Percent of Total Checklists
        Location Total

    <cfquery name="allLocCode" dbtype="query">
        SELECT DISTINCT trans_location, COUNT(*) AS locCntr FROM GetLocationInfo GROUP BY trans_location ORDER BY trans_location
    </cfquery>
      <cfloop query="allLocCode">
      <cfset thisLocationName = trim(allLocCode.trans_location) />
      <cfoutput query="allLocCode">

              #thisLocationName#

          <cfset thisLocationName = "" />
      </cfoutput>
      </cfloop>

      Total

A: You only need to loop through the query once. Remove the additional cfoutput
<cfoutput query="allLocCode">
  <cfset thisLocationName = trim(allLocCode.trans_location) />

    #thisLocationName#

 </cfoutput>

A: Your code creates a nested loop.
  <cfloop query="allLocCode"> // loop over all items in the query
  <cfset thisLocationName = trim(allLocCode.trans_location) />
  <cfoutput query="allLocCode"> // loop again over all items in the query

          #thisLocationName#	 // print the string

      <cfset thisLocationName = "" /> // empties the string, hence next rows will be empty
  </cfoutput>
  </cfloop>

Change the line <cfoutput query="allLocCode"> to <cfoutput>.


text:
Q: How to change one column or another depending on value? I am working on a Tinder clone for school using node.js and mysql and have a system that involves liking and disliking people. I unfortunately based a lot of my database on a user's chosen username and am now coming up against the problem of when a user wants to change their username I need to change all instances of it in my database. (I know I should've used user ID's instead but at this point it's too late to change as the project is almost finished and it's only for learning purposes for school.) I'm having a problem changing the data in one column or another based on where the username exists. Example of my database table called likes:
Liker    | Liked
-------------------
jennifer | matt
jennifer | colin
jennifer | justin
joe1     | sarah
joe1     | tammy
joe1     | lindsay
celine6  | joe1
celine6  | curtis

So for example if joe1 has decided he now wants to go under the username buffdude27 I tried to use the following query in node using the mysql middleware to change all instances of his name in the table:
var change = ['buffdude27', 'buffdude27', 'joe1', 'joe1'];
connection.query('UPDATE likes SET liker = ? OR liked = ? WHERE liker = ? OR liked = ?', change, function(err, results){

...the actions I take after the query happens...
    });

The problem I'm having is that it will find all instances of joe1 and replace his username with a 0. What am I doing wrong and what is the proper way to do this? Thank you in advance for your help!

A: Either run two simple queries:
UPDATE likes SET liker = 'buffdude27' WHERE linker = 'joe1';
UPDATE likes SET liked = 'buffdude27' WHERE linked = 'joe1';

Or a more comlex one:
UPDATE likes
SET liker = CASE WHEN linker = 'joe1' THEN 'buffdude27' ELSE linker END,
    liked = CASE WHEN linked = 'joe1' THEN 'buffdude27' ELSE linked END
WHERE 'joe1' IN (liker, liked)

An even better way would be to have a users table with columns user_id and name. And store references (foreign keys) in the likes table (liker_user_id, liked_user_id).
If a user decides to change his name, you only need to update the name column in the users table. All other tables referencing the user_id don't need to be changed.


text:
Q: How to check progress of image upload to Firebase storage When the user registers for my app they choose a profile picture, input a name, email, and password. I use firebase to authenticate them using email and password. I am using FIRAuth.auth()?.addAuthStateDidChangeListener  to detect the change in a user's authentication status. If the user has been authenticated the code inside executes (this code sends the user to the next viewController). The problem is that the code inside fires off before my data can be added to the realtime database and FirebaseStorage. Is there a way to monitor when both tasks have succeeded so then I can trigger the change of view controllers? Thank you.

A: Firebase has a tutorial on how to track the progress of file uploaded to their servers:
let storageRef = FIRStorage.reference().child("folderName/file.jpg");
let localFile: NSURL = // get a file;

// Upload the file to the path "folderName/file.jpg"
let uploadTask = storageRef.putFile(localFile, metadata: nil)

let observer = uploadTask.observeStatus(.Progress) { snapshot in
  print(snapshot.progress) // NSProgress object
}

This snapshot gives you useful information, such as the total size of
  the file in bytes and how many bytes have been uploaded so far. Using
  this information, you can calculate the percentage uploaded and use it
  to update any UI control in your app.


text:
Q: AWS Mobile hub with Cocoa pods Apple Mach-O Linker error I generated a AWS Mobile hub iOS Swift application and tried to add Google Maps SDK using Cocoapods but after doing that It generates this Error
Error Screenshot
After searching several times I deleted the -ObjC linker flag and just added -force_load then it started giving Missing File or Directory error. How can I fix this.
I'm running on XCode 8.2, AWS Mobile hub project is Swift 2.3
PS: I tried adding use_frameworks! in Podfile.

A: Instead of using the -ObjC flag, you need to use the -force_load flag specifically for the Google Maps SDK. if you use the -ObjC flag, it will require all libraries to be force loaded even if they are not used in your app.
Thanks,
Rohan


text:
Q: Is it a good idea to use "is" to check which function is contained in a variable? I have a variable that contains a function.
def foo(x):
    return x + 42

def bar(x):
    return x - 42

my_var = foo

I want to check if that function is a certain function. Should I use is or ==?
my_var == foo
my_var == bar

and
my_var is foo
my_var is bar

both return what I expect.

A: They are the same thing for a function object. The == operator calls the __eq__ function to perform the comparison. The function object does not define an __eq__ method:
>>> def foo():
...   pass
...
>>> foo.__eq__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__eq__'

Therefore the interpreter uses the default implementation in PyObject:
res = (v == w) ? Py_True : Py_False;

which is basically a pointer comparison, essentially the same as is.

A: No, you should use ==.
A good rule of thumb is only use is when doing is None or is not None and nowhere else. In this case, comparing functions with is works, but if you try to compare a method of an instance of a class with itself you'll get False (even on the same instance), whereas comparing with == returns what you expect:
>>> class A:
...     def my_method(self):
...         pass
...
>>> a = A()
>>> a.my_method is a.my_method
False
>>> a.my_method == a.my_method
True

Better to avoid having to remember this and always compare functions with ==.
See this question: Why don't methods have reference equality?

A: Is checks for the identity of an object.  If you assign foo to myvar, then an alias is created and they both have the same id (in the case of functions at least).
Checking 2 functions for equivalence from a mathematical standpoint entails checking the equivalence of the domains and codomains of both functions.
So is is better.


text:
Q: Terminate running application in android I am using following code to terminate background app(calculator). for that I have created a service When I am running app. It is not killing background process(calculator)
Whats wrong with the code Ihave also given permission. "android.permission.KILL_BACKGROUND_PROCESSES"
  ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Activity.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> packageName = am.getRunningTasks(10);
                    // String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
                    for (RunningTaskInfo appinfo : packageName)
                    {
                        if((appinfo.topActivity.getPackageName().toString()).indexOf("calculator2")!= -1)
                        {
                        Log.i(Tag,""+ appinfo.topActivity.getPackageName());
                        Toast.makeText(MyService.this, ""+appinfo.topActivity.getPackageName(), Toast.LENGTH_SHORT).show();
                        am.killBackgroundProcesses(appinfo.topActivity.getPackageName());
                        }
                    }

A: refer to this answer
When we use this we do not need the "android.permission.KILL_BACKGROUND_PROCESSES" permission as well


text:
Q: Spark-sql error by defining UDAF Spark version 1.6.0 on AWS EMR with Zeppelin Notebook
I defined a UDAF with following codes:
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row;
import org.apache.spark.sql.expressions.MutableAggregationBuffer
import org.apache.spark.sql.expressions.UserDefinedAggregateFunction

import java.text.SimpleDateFormat
import java.util.Date

class AggregateTS extends UserDefinedAggregateFunction{
    def inputSchema: StructType = StructType(StructField("input", StringType) :: Nil)

    def bufferSchema: StructType = StructType(StructField("intermediate", StringType)::Nil)

    def dataType: DataType = StringType

    def deterministic: Boolean = true

    def initialize(buffer: MutableAggregationBuffer): Unit = {
        buffer(0) = "Init"
    }

    def update(buffer: MutableAggregationBuffer, input: Row): Unit = {
        if (buffer.getAs[String](0) == "Init"){
            buffer(0) = input.getAs[String](0)
        }
        else{
            // add two string
            buffer(0) = average_ts(input.getAs[String](0), buffer.getAs[String](0))
        }
    }

    def merge(buffer1: MutableAggregationBuffer, buffer2:Row):Unit = {
        buffer1(0) = average_ts(buffer1.getAs[String](0), buffer2.getAs[String](0))
    }

    def evaluate(buffer: Row): Any = {
        buffer.getAs[String](0)
    }
}

from which I got a compile error:
error: not found: type DataType
       def dataType: DataType = StringType

What does it mean ?

A: solved by myself. It seems to be some import collision error. I change the import sentence to explicit
import org.apache.spark.sql.types.{DataType}

it works then