text:
Q: Jaudio tagger library returns the track length as worng I use JAudiotagger library to get the track length of an audio file f.getAudioHeader().getTrackLength() I use this it returns 3.34 as length but the actual length is 5.34.
Am I wrong anywhere?

A: Its looks at the Xing/VRBI frame header rather than each audio frame itself whihc would be much slower to calculate


text:
Q: Error: An expression of non-boolean type specified in a context where a condition is expected, near ')' SQL Server Question built from this question (Still return records if unsatisfied cross join condition).
The database for this question is extended and provided below.
My desired output is to show the first four things bought in a month, and if bought on the same day, output the one with a larger amount.
I have added d_thing_id to see which thing, bought on the same day, has a larger amount.
However, I keep getting an error

An expression of non-boolean type specified in a context where a condition is expected, near ')'

Data:
create table Sales
(
    Date datetime,
    C_Name char(1),
    Thing varchar(100),
    Amount int
)

insert into Sales (Date, C_Name, Thing, Amount)
values   ('2021-02-21','A','Fruit', 20)
        ,('2021-02-22','A','Bottle', 15)
        ,('2021-02-22','A','Straw', 7)
        ,('2021-02-26','A','Doll' , 31)
        ,('2021-02-27','A','Drink', 29)
        ,('2021-02-27','A','Bread', 30)
        ,('2021-02-28','B','Book' , 67)
        ,('2021-06-03','B','Fruit' , 100)
        ,('2021-06-13','B','Shoes' , 10)
        ,('2021-06-10','C','Shoes', 90)
        ,('2021-07-07','A','Tablet', 4)
        ,('2021-07-11','A','Chair' , 77)
        ,('2021-07-11','A','Cushion', 43)
        ,('2021-07-20','A','Sofa' , 37)
        ,('2021-07-21','A','Coat' , 66)

Code
with d1(Date, C_Name, Thing, Amount, Month) as
(
    select *, month(Date) as Month
    from Sales
),
d2 (thing_id, Month, C_Name, Thing) as
(
    select
        'Thing' + cast(row_number() over (partition by C_Name, Month
                                          order by Date) as varchar(10)) as thing_id
           ,Month
           ,C_Name
           ,Thing
    from d1
    where
        (select row_number() over (partition by C_Name, Month, Date
                                   order by Date, Amount desc) as d_thing_id
         from d1
         where d_thing_id = 1)
)
select *
from d2
pivot
    (min(Thing)
         for thing_id in ([Thing1], [Thing2], [Thing3])
    ) as p;

EDIT
My expected output
month C_Name Thing1 Thing2 Thing3 Thing4
2       A    Fruit  Bottle  Doll  Bread
2       B    Fruit
6       B    Fruit  Shoes
6       C    Shoes
7       A    Tablet Chair  Sofa  Coat

A: this where clause has no operator
  where   (select row_number() over
                  (
                      partition by C_Name, Month, Date
                      order by Date, Amount DESC
                  ) as d_thing_id
             from d1
             where d_thing_id = 1
            )

It should be more like this for example
  where   (select row_number() over
                  (
                      partition by C_Name, Month, Date
                      order by Date, Amount DESC
                  ) as d_thing_id
             from d1
             where d_thing_id = 1
            ) = something

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF service binding content type mismatch - text/xml and application/soap+xml I have been at this for a few days trying to figure out why I am getting a content type mismatch error in my binding.  There are countless other people that seem to be having this issue but all the resolutions don't apply or haven't worked.
I have looked everywhere trying to figure out why I am getting the following error:
Server Error in '/' Application.
The content type application/soap+xml; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 823 bytes of the response were:
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><GetQuoteResponse xmlns="http://soap.service.GMO.com"><Quote_Response><errorMessage></errorMessage><return_List><item><errorMessage></errorMessage><monthlyPremiumAmount>6.0</monthlyPremiumAmount><webID>7P3W4Txst</webID><basePer1>1000.0</basePer1><basePer2>0.0</basePer2><baseRate1>0.05</baseRate1><baseRate2>0.0</baseRate2><benefitID>5365</benefitID><coverageAmount>100000</coverageAmount><grossPer1>1000.0</grossPer1><grossPer2>0.0</grossPer2><grossRate1>0.06</grossRate1><grossRate2>0.0</grossRate2></item></return_List></Quote_Response></GetQuoteResponse></soapenv:Body></soapenv:Envelope>.
The web service I am consuming is not hosted in IIS.  The web service itself seems to be working properly because we use SoapUI and get all the proper results returned to us.  As you can also see from the above error message, values are being returned from the web service.
I have also been using Fiddler and am able to confirm that the request header content type is text/xml and the response header content type is application/soap+xml.
We have a datalayer where the service reference resides.  The app.config looks like this:
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="IMSQuoteServiceBinding" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <security mode="None">
                    <transport clientCredentialType="None" proxyCredentialType="None"
                        realm="" />
                    <message clientCredentialType="UserName" algorithmSuite="Default"  />
                </security>

            </binding>

        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="http://hostingServerName:81/cgi-bin/jsmdirect?IMSQuote"
            binding="basicHttpBinding" bindingConfiguration="IMSQuoteServiceBinding"
            contract="Quote.IMSQuoteServicePortType" name="IMSQuoteServicePort" />
    </client>
</system.serviceModel>

The web site web.config looks like this:
<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="IMSQuoteServiceBinding" closeTimeout="00:01:00"
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
        allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
            realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>

    </binding>
  </basicHttpBinding>

</bindings>
<client>
  <endpoint address="http://hostingServerName:81/cgi-bin/jsmdirect?IMSQuote"
      binding="basicHttpBinding" bindingConfiguration="IMSQuoteServiceBinding"
      contract="Quote.IMSQuoteServicePortType" name="IMSQuoteServicePort" />
</client>

Any help would be very much appreciated.  I am somewhat new to WCF and am open to any and all ideas.
Thank you all in advance for your help.  If you need me to provide any more information, please let me know.

A: Just as an update.
I changed the service binding from basicHttpBinding to wsHttpBinding.  Changing the binding to wsHttpBinding changed the SOAP service to send as a SOAP 1.2 call rather than a SOAP 1.1 call.  Once I did this, the content types matched on the send and receive calls which resolved the binding mismatch error.


text:
Q: Zagier's "From 3-manifold invariants to number theory"? Zagier lectures on "From 3-manifold invariants to number theory" - do you know about texts of that or on the discussed web of ideas? ([https://www.mpim-bonn.mpg.de/de/node/10791])

A: In the following page there is some information on the lecture series. In particular, it is said that some student(?) has been taking notes which were initially private, but he decided to distribute it with kindness. You can find that through a link in that page.
https://www.math.sissa.it/course/phd-course/3-manifold-invariants-number-theory


text:
Q: CAS 6.6 How to authenticate user/password with Azure I have been unsuccessful in getting my CAS to use username/password of my Azure AD
Here is a snippet from cas.properties
cas.authn.attribute-repository.azure-active-directory[0].client-id= <id of the app>
cas.authn.attribute-repository.azure-active-directory[0].client-secret=<secret key>
cas.authn.attribute-repository.azure-active-directory[0].tenant= <id>
cas.authn.attribute-repository.azure-active-directory[0].domain=<domaine name>

whenever i try to enter username and password (azure) in cas login i get the message
[Invalid credentials: clientId is null or empty]
Am I missing another setting that's needed in my cas.properties?


text:
Q: Killing Fragment in Navigation Components without going previous fragment I have two fragments (like following code). After I switched from 1st Fragment to 2nd fragment when I clicked back button it's going back to 1st fragment and I don't want to be.
Here my code
nav_graph
<navigation>
  <fragmentone>
    <action
      destination= fragmenttwo/>
  </fragmentone>
  <fragmenttwo>
  </fragmenttwo>
</navigation>

How can navigate 2nd fragment like we used to change Activity with
finish();

A: In design tab you will see a pop behavior section

in pop upto, select fragment 1
in pop up to inclusive, select true

A: Exiting an app or (Finishing the navigation components activity) doesn't differ much from the traditional way, but what you need to catch is the back press button event on that fragment that you want to finish the activity on.
As per documentation, the current valid way to catch the back pressed button is to use OnBackPressedDispatcher, here is a demo:
On the 2nd fragment, register OnBackPressedDispatcher and handle finishing the activity on the handleOnBackPressed() callback:
requireActivity().onBackPressedDispatcher.addCallback(
    viewLifecycleOwner,
    object : OnBackPressedCallback(true) {
        override
        fun handleOnBackPressed() {

            // findNavController().popBackStack() // Popup to the first destination fragment
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                requireActivity().finishAndRemoveTask()
            } else {
                requireActivity().finish()
            }
        }
    })

Note: You can use findNavController().popBackStack() before finishing the activity, if you want to popup the back stack to the first destination fragment before finishing the activity, but this will show up the first fragment before the app exit which could be a behavior that not appeals to you.


text:
Q: Handshake errors with Ubuntu 14.0.4 OpenSSL 1.0.1f and TLSv1_2016 Please bear with me.  I'm no SSL encrpytion expert.  I just want to make connections to a server, using their API.  I am unable to.  When I use this api as indicated in the documentation, the following error occurs:
[Errno 1] _ssl.c:510: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

This API seems to be hosted on an AWS server somewhere, and the support person for it has referred me to this AWS document with the added information that their server uses  TLSv1_2016.  I'm not sure that that's correct, but that's what I was told.
This version of TLS is not supported by the OpenSSL that ships with Ubuntu 14.0.4 (openssl v1.0.1f). Version 1.2 IS supported.  I upgrade my system on a regular basis, and it doesn't seem that there is any approved Ubuntu release that supports this protocol.  I've been advised to upgrade, but it's not clear to what.
This is all Greek to me.  Can someone tell me what upgrade I might be able to do my system to solve this?
UPDATE problem persists after installing Ubuntu-18.04, which comes with openssl 1.1.0g.

A: Answer mostly from comments.
The problem is apparently that the server, like many SSL/TLS servers today especially those handling multiple domains like Cloudfront, requires the SNI (Server Name Indication) extension in SSL/TLS. This was (and easily is) checked with openssl s_client which (unlike most programs) has an option that controls whether to send SNI.
You didn't previously say that this code is Python. It is Python that links to and invokes OpenSSL. (The OS is not involved in SSL/TLS, only in the lower-level TCP/IP protocols.) According to http://docs.python-requests.org/en/master/community/faq/ (at the bottom)

Python3 and Python 2.7.9+ include native support for SNI in their SSL modules. For information on using SNI with Requests on Python < 2.7.9 refer to this Stack Overflow answer.

linking to using requests with TLS doesn't give SNI support which has several answers that appear to consist mostly of updating various things (and I am not in a position to test even if you gave details of your Python and Requests which you didn't).


text:
Q: Get Rectangle Coordinates drawn in Pane How do I get the coordinates of a drawn rectangle in a pane?
This is how I draw the rectangle:
Rectangle r = new Rectangle();
r.setX(50);
r.setY(50);
r.setWidth(200);
r.setHeight(100);
r.setStroke(Color.BLUE);
r.setStrokeWidth(1);
r.setFill(Color.TRANSPARENT);
DragResizeMod.makeResizable(r);
pane.getChildren().add(r);

this is the link of the class im using to resize the rectangle
https://github.com/varren/JavaFX-Resizable-Draggable-Node/blob/master/src/sample/DragResizeMod.java
So how do I get the coordinates of a drawn rectangle? Without passing the coordinates to a list before drawing it.
Thank you

A: There are several possible solutions, but an easy one could be to add a handler to the xProperty xProperty @ Rectangle JavaDoc and analogous yProperty like this:
rectangle.xProperty().addListener((Observable, oldValue, newValue) -> {
    System.out.println("X position changed from <" + oldValue + "> to <" + newValue + ">");
});

For completeness you should also add a handler to the widthProperty (and analogous the heightProperty), too. As the JavaDoc cites for the xProperty:

Defines the X coordinate of the upper-left corner of the rectangle.

Meaning that if you e.g. change the size but the upper left corner is still in the same position, you won't get notified for the xProperty!

A: If you just need the coordinates after resizing: use the boundsInParent property. Unless you apply transforms with a shear/rotate component, this will give you the bounds of the Rectangle. If you use a Parent that adjusts the position of it's children, the position may not be correct, but Pane is not one of them (but many of it's subclasses are):
Rectangle r = ...
...
// resize

Bounds boundsAfterResize = r.getBoundsInParent();


text:
Q: Create views from tables with different number of columns mysql I'm new to views in MySQL server.
I'm trying to create two VIEWS with "invoice_head" and "invoice_body", but in order to do that i need to get different keys from different tables (this tables have diferent number of columns).
This is the code that i'm trying to use:
CREATE VIEW invoice_head AS
SELECT
    date_order AS 'DATE OF ISSUE'
    FROM orders
UNION ALL
SELECT
    customer_name AS 'Client Name',
    customer_address AS 'Street adress',
    customer_district AS 'District',
    customer_country AS 'Portugal',
    customer_zipcode AS 'ZIP Code'
    FROM customer;

but this code is giving me the error: The used SELECT statements have different number of columns.
And the tables i'm using are something like this (for example)
Customer Table (8 columns)

customer_id
customer_name
customer_address
customer_district
(...)

1
maria xxx
street xxx
lisbon
(...)

Orders Table (9 columns)

order_id
customer_id
product_id
date_order
(...)

10
1
20
2020-12-15
(...)

The invoice_head is supposed to have information about the customer, the invoice_id, and the date of the order (invoice_date aka date_order).
Can someone tell me in what way is this possible to be made?
Is it impossible to do or I need to do something I'm not seeing?

A: Someone in the comments helped me. I just needed to use the "Join" instead of "Select":
DROP VIEW IF EXISTS `invoice_head`;
CREATE VIEW `invoice_head` AS
SELECT  date_order as `Date of issue`,
        customer_name AS `Client Name`,
        customer_address AS `Street adress`,
        customer_district AS `District`,
        customer_country AS `Country`,
        customer_zipcode AS `ZIP Code`
FROM orders
join customer
    on orders.customer_id = customer.customer_id;


text:
Q: If EM waves of radio range can pass through large obstacles, why antennas do receive them? For example a tiny antenna in the phone, why em wave do not pass through it, but pass through concrete walls?

A: For an antenna to pick up a sufficient signal, it does not need to stop the wave - it just needs to slightly attenuate it, which it does.
In general, when radio waves pass through obstacles, they get attenuated and, given the same level of conductivity, larger obstacles will cause greater attenuation, but even a small fraction of the absorbed energy could be sufficient for an adequate reception.
I would add that an antenna of a phone is tuned to a particular frequency range and, because of that, everything else the same, it will absorb more energy in that frequency range than a randomly shaped conductor of a similar size.

A: Simply put, cell phone antennas are made of metal, and are designed to absorb radio waves at cell phone frequencies. Concrete does not interact with radio waves as strongly as metal does and although concrete buildings may have some big pieces of metal in them, at cell phone wavelengths that metal tends to reflect and sometimes bend the radio waves instead of absorbing them.


text:
Q: How to pass context other than SecurityContext to swagger-codegen application using jaxrs-jersey The jaxrs-jersey code generator creates stubs along these lines:
@Path("/pet")

@io.swagger.annotations.Api(description = "the pet API")

public class PetApi  {
   private final PetApiService delegate;

   public PetApi(@Context ServletConfig servletContext) {
      PetApiService delegate = null;

      if (servletContext != null) {
         String implClass = servletContext.getInitParameter("PetApi.implementation");
         if (implClass != null && !"".equals(implClass.trim())) {
            try {
               delegate = (PetApiService) Class.forName(implClass).newInstance();
            } catch (Exception e) {
               throw new RuntimeException(e);
            }
         }
      }

      if (delegate == null) {
         delegate = PetApiServiceFactory.getPetApi();
      }

      this.delegate = delegate;
   }

    @POST

    @Consumes({ "application/json", "application/xml" })
    @Produces({ "application/xml", "application/json" })
    @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
            @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
            @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
        })
    }, tags={ "pet", })
    @io.swagger.annotations.ApiResponses(value = {
        @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) })
    public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body
,@Context SecurityContext securityContext)

...where only SecurityContext is injected.
Is there a way to influence code generation to inject other context state, or a way to pass an instance instead of class with blank instantiation?
Example source


text:
Q: How to resize shapes drawn on map based on zoom value with react-native-maps I am using react-native-maps to integrate maps in my application. I want to show some sort of radar heading the direction the user is heading, i want to area covered of different distances like 1 km, 5 km, and 10 km. resulting in something like the image below.

My initial solution was to draw shapes using View with position absolute,
i got something like this with the approach.

The problem with above approach is View height is static, and it doesn't respond to zoom value of the map, also the calculation of View height with respect to distance is non trivial.
My second solution was to draw circles around user marker of certain radius, rather then a full circle, i can create semi circles or semi-semi circles achieve the desire result. But i cannot find any way to draw semi circle with the library react-native-maps.
Any suggestion how can i achieve the desire result?

A: Your first solution seems good enough to me, maybe a little modifications should get you the result you are looking for, follow along:

*

*First lets associate all the relevant <View /> styling props to state values

// ... all your imports and other code

state ={
    viewHeight: 0, // or any default value you want
    viewWidth: 0, // or any default value you want

    // ... other view parameters used and other state values
}

// ... functions and other code

render() {
    return (
        // ... other rendered components etc

        <View
            style={{
                width: this.state.viewWidth,
                height: this.state.viewHeight
            }} />
    )
}

*

*Next we will get the map zoom level every time it changes and preform some sort of conditions

<MapView
    ref='map'                                       // <==== add the ref map so we can access the zoom level from our _onMapChange function later
    style={{ flex: 1 }}
    provider={PROVIDER_GOOGLE}                      // <==== this approach will not work on apple maps as the camera will not give us the zoom parameter so use google maps
    onRegionChange={() => this._onMapChange()} />   // <==== this will tell the map to fire the _onMapChange() function everytime there is a change to the map region

*The _onMapChange() function:

_onMapChange = async () => {
    const {
        zoom,
        pitch,
        center,
        heading
    } = await this.refs.map.getCamera();

    // Now set the conditions for the view style based on the zoom level, maybe something like this:

    if (zoom <= 5) {
        this.setState({
            viewWidth: 50,  // what ever width you want to set
            viewHeight: 50  // what ever height you want to set
            // ... other view parameters
        })
    } else if (zoom <= 10) {
        this.setState({
            viewWidth: 100,  // what ever width you want to set
            viewHeight: 100  // what ever height you want to set
            // ... other view parameters
        })
    }
}

Heads-Up: I am using my editor that's all so there might be some syntax errors
Hope this Helps!

A: You can use Overlay (circle, polygon) or can make your custom overlay to cover certain areas on the map.
Like this,

Link for overlay docs: react-native-community/react-native-maps
To make it dynamic, precisely calculate longitudeDelta and LatitudeDelta.


text:
Q: How do I extract values from Python groupby for data analysis? New to python and I am using Spotify's spotipy package in Python to try and create a "music taste diversity score" for my top spotify artists. I have clustered all the artists songs based on 7 of spotify's built in features and displayed the number of songs in each cluster as well as the distribution of artists in each cluster. I am struggling with getting these values into workable numpy arrays or df's to move onto generating my "diversity score" as this is my first full project dealing with python.
# display distribution of clusters

df2 = df.groupby(['cluster group'])['artist'].size()
df2

output:
cluster distribution
# display distribution of artists in cluster groups

df2 = df.groupby(['cluster group', 'artist']).size()
df2

output:
artist distribution in clusters
I have tried iterating for artist in cluster and other similar methods, but it seems the only iterable
in df2 is the count for each cluster's artists.
Can someone point me towards a way to extract the values for each cluster group to work with?

A:
I have tried iterating for artist in cluster and other similar
methods, but it seems the only iterable in df2 is the count for each
cluster's artists.

The reason is that df2 is, in fact, a pandas Series in both your examples.
Therefore df2 just contains the sequence of integer values indexed by cluster group in the first example and (cluster group, artist) in the second example.
The exact dataFrame that you work with is not specified, but based on what you wrote it seems that you want perform different aggregation for differernt columns. Is that correct?. Let's say, if there is column songs then the following should give you a single dataframe combining some information from your two df2s, namely, number of different artists and songs in each cluster.
 df.groupby(['cluster group']).agg({'artist': 'nunique', 'songs': 'nunique'})

As for the first example, applying the aggregate function size() only to artists column rather than all the remaining columns, does not make any difference, since only the number of rows is counted and therefore  df.groupby(['cluster group']).size() gives the same result.


text:
Q: Как изменить редактор коммитов на стандартный? Необходимо зменить редактор коммитов на стандартный.
Вот что получается при коммите:

svaitoslav@svaitoslav-R510-P510:/media/svaitoslav/0E05B44D60917463/Work/test$ git commit
  error: cannot run sublime_text: No such file or directory
  error: unable to start editor 'sublime_text'
  Please supply the message using either -m or -F option

Каким образом можно изменить редактор для коммитов на дефолтний по системе ubuntu? git config --global core.editor - не помогло.

A: проблема решилась переустановкой редактора vim


text:
Q: Get AdSense Ads to Reload on Route Change in Next JS We've implemented Google AdSense on our Next.JS website, but we'd like to have ads reload whenever the route changes.
Here is what I tried:
const AdBlock = props => {
  const { userLoaded, currentUserIsSilverPlus } = useAuth()

  useEffect(() => {
    window.adsbygoogle = window.adsbygoogle || []
    window.adsbygoogle.push({})
  }, [])

  const reloadAds = () => {
    const { googletag } = window
    if (googletag) {
      googletag.cmd.push(function () {
        googletag.pubads().refresh()
      })
    }
  }

  Router.events.on("routeChangeStart", reloadAds)

  if (userLoaded && !currentUserIsSilverPlus) {
    return (

    )
  }
  return ""
}

export default AdBlock

The ads load, however, they never appear to refresh. What am I missing?

A: My solution was to observe router event changes, when routeChangeStart ads had to be unmounted, when routeChangeComplete they had to be mounted remounted.
// components/Adsense.tsx

function Ads() {
  const adsRef = useRef<HTMLModElement | null>(null);

  useEffect(() => {
    const executeWindowAds = () => {
      try {
        // @ts-ignore
        (adsbygoogle = window.adsbygoogle || []).push({});
      } catch (error: any) {
        console.error('error ads======>', error.message);
      }
    };

    const insHasChildren = adsRef.current?.childNodes.length;
    if (!insHasChildren) {
      executeWindowAds();
    }
  }, []);

  return (

  );
}

export default function Adsense() {
  const router = useRouter();
  const [shouldMount, setShouldMount] = useState(true);

  useEffect(() => {
    const onRouteChangeStart = () => setShouldMount(false);
    const onRouteChangeComplete = () => setShouldMount(true);

    router.events.on('routeChangeStart', onRouteChangeStart);
    router.events.on('routeChangeComplete', onRouteChangeComplete);

    return () => {
      router.events.off('routeChangeStart', onRouteChangeStart);
      router.events.off('routeChangeComplete', onRouteChangeComplete);
    };
  }, [router.events]);

  return shouldMount ? <Ads /> : null;
}

On your layout page, for example a sidebar where each page has the same sidebar:
// components/LayoutBlogPost.tsx

import dynamic from 'next/dynamic';
const Adsense = dynamic(() => import('./Adsense'), { ssr: false });

export default function LayoutBlogPost({children}: {children: any}) {
  return (

      {children}
      <Adsense />

  );
}

A: try useRouter hook and handling router events inside useEffect:

import { useRouter } from 'next/router'

export default function Page() {
const router = useRouter();
useEffect(() => {
router.events.on('routeChangeError', handleChange)
  }, [])
  return (
    <>
    </>
  )
}


text:
Q: How to run parallel fork as single thread in perl? I was trying to check response messages written in perl which takes requests through Amazon API and returns responses..How to run parallel fork as single thread in perl?. I'm using LWP::UserAgent module and I want to debug HTTP requests.

A: As a word of warning - threads and forks are different things in perl. Very different.
However the long and short of it is - you can't, at least not trivially - a fork is a separate process. It actually happens when you run -any- external command in perl, it's just by default perl sits and waits for that command to finish and return output.
However if you've got access to the code, you can amend it to run single threaded - sometimes that's as simple as reducing the paralleism with a config parameter. (In fact quite often - debugging parallel code is a much more complicated task than sequential, so getting it working before running parallel is really important).
You might be able to embed a waitpid into your primary code so you've only got one thing running at once. Without a code example though, it's impossible to say for sure.


text:
Q: JQuery rule not validating input file I´m trying to validate a field in the form with the id #frmArchivos, but when I submit the form that field doesn't  respect the rules. My form is structured as this:
      <form id="frmArchivos" method="post" enctype="multipart/form-data" >
                    <input id="idHerramientas" value="" hidden="" readonly="" name="idHerramientas" />

                                    Archivo:
                                    <input type="file" id="inpfile" class="form-control" name="inpfile" />

       </form>

And my script is this:
$.validate({
            form: '#frmArchivos',
            rules: {
                inpfile: {
                    required: true,
                    extension: "docx|rtf|doc|pdf"
                }
            },
            messages: {
                inpfile: {
                    required: "input type is required",
                    extension: "select valid input file format"
                }
            }
        });

What could be the problem? I tried with different tags like $('#frmArchivos').validate() but the console throws me an error of nodeType undefined.
I also tried to validate trough html but it doesn´t validate the file extension when post the form.
If you need more information please tell me, and thank you very much.

A: Try with the next code

(function () {

    var validator = null;
    var frmArchivos = $("#frmArchivos");
    var inpfile = $("#inpfile");

    function initializeValidation() {
      validator = frmArchivos.validate({
      rules: {
          inpfile: {
            required: true,
            extension: "docx|rtf|doc|pdf"
          }
        },
      messages: {
          inpfile: {
            required: "input type is required",
            extension: "select valid input file format"
            }
          }
        });
    }

    $(document).ready(function () {

       initializeValidation();
       inpfile.change(function(){

       //Validate field
       inpfile.valid();

      });

    });

})();

<form id="frmArchivos" name="frmArchivos">
  <input id="idHerramientas" value="" hidden="" readonly="" name="idHerramientas" />

          Archivo:
          <input type="file" id="inpfile" class="form-control" name="inpfile" />

</form>

Used libraries:
JQuery
JQueryValidate


text:
Q: Libgdx - Actor's position is incorrect I'm pulling my hair out. I've spent a few hours now on this. Here is what I am doing. I have an image that is an actor. I can move this image to wherever I want. That works fine. I added a Slider so I can also resize this image. This is where the problem sets in. Once I resize it, I can still move it, but it is no longer where my finger is. It is, if it shrunk in size, to the NE. If it increased, it is to the SE. (of my finger). Anyways, I have no idea what is causing this. I spent an hour just writing different equations for adjusting per size, but nothing is working. Also, the world bounds become incorrect too. I shouldn't be allowed to move the actor/image outside of the screen. I do a simple check. (actor.getX() <= 0). I feel like I should note that before resizing, everything works fine. Anyways, the bounds check was simple, right? Well, if I make my image smaller, it gets stopped before it reaches the edge. If I make it larger, it can enter the edge a bit. The same for the opposite side, except that this time if its larger, it gets stopped before it reaches, and if its smaller, it can go in a bit. Here, let me show you some code...
My Table for the Slider:
private Table buildSlidersLayer() {
        Table layer = new Table();
        layer.right().top();
        Label label = new Label("A Button Size", skinLibgdx);
        layer.add(label);
        layer.row();
        sldSize = new Slider(0.0f, 1.0f, 0.01f, false, skinLibgdx);
        layer.add(sldSize);
        sldSize.addListener(new ChangeListener() {

            @Override
            public void changed(ChangeEvent event, Actor actor) {
                sldSizeVal = sldSize.getValue();
                divFacAButton = ((((1.0f - sldSizeVal) - 0.01f) * (2.0f - 0.7f)) / (0.99f - 0.01f)) + 0.7f;
                aButton.setSize(120 / divFacAButton, 120 / divFacAButton);
            }

        });
        // sldSize.setPosition(60, 60);
        return layer;
    }

My divFacAButton is between a range of 0.7 and 2.0(aprrox.). I divide 120 by these to get the size.
Now, this is how I move my image:
aButton = new Image(skinCydeonWorld, "a-button");
        layer.addActor(aButton);
        aButton.setSize(aButton.getWidth() / 1.5f,
                aButton.getHeight() / 1.5f);
        aButton.setOrigin(aButton.getWidth() / 2, aButton.getHeight() / 2);
        aButton.setPosition(GamePreferences.instance.aButtonX,
                GamePreferences.instance.aButtonY);
        aButton.setRotation(180f);

        aButton.addListener(new DragListener() {

            @Override
            public void touchDragged(InputEvent event, float x, float y,
                    int pointer) {
                float xAspect = stage.getWidth() / Gdx.graphics.getWidth();
                float yAspect = stage.getHeight() / Gdx.graphics.getHeight();
                aButton.setPosition(
                        (Gdx.input.getX() - aButton.getHeight() / 2f) * xAspect,
                        ((Gdx.graphics.getHeight() - Gdx.input.getY()) - aButton
                                .getHeight() / 2f) * yAspect);
                checkAndAdjustPos(aButton);
                super.touchDragged(event, x, y, pointer);
            }

        });

Here I move the image. I set the image position to wherever I clicked, minus half the width on the x, and half the height on the y.
Here's an illustration on how the positioning is off, as well as it being stopped too early from the wall:

And so that's basically it. After resizing, the bounds and positions seem to get out-of-whack. I'm totally lost and have a major headache. If anybody has any idea why this is happening, what I'm doing wrong, or how I can fix this, I would be eternally(ok, maybe not) grateful. :)

I found a solution with the help of BrainfoG313!
Here's my new code:
aButton.addListener(new DragListener() {

            @Override
            public void touchDragged(InputEvent event, float x, float y,
                    int pointer) {
                xAspect = Constants.VIEWPORT_GUI_WIDTH / Gdx.graphics.getWidth();
    yAspect = Constants.VIEWPORT_GUI_HEIGHT/ Gdx.graphics.getHeight();
                aButton.setPosition(
                        (Gdx.input.getX() - (aButton.getWidth() * divFacAButton / 2f))
                                * xAspect,
                        ((Gdx.graphics.getHeight() - Gdx.input.getY()) - (aButton
                                .getHeight() * (divFacAButton < 1.3f ? 0f : divFacAButton) / 2f))
                                * yAspect);
                checkAndAdjustPos(aButton);
                super.touchDragged(event, x, y, pointer);
            }

        });

Checking if the actor leaves the screen:
{
        if (actor.getX() - (aButton.getWidth() / 2 / divFacAButton) + 80f / 2f < 0)
            actor.setPosition(
                    (aButton.getWidth() / 2 / divFacAButton) - 80f / 2f,
                    actor.getY());
        if (actor.getX() + actor.getWidth()
                / (minSize + maxSize - divFacAButton) > stage.getWidth() * xAspect)
            actor.setPosition(stage.getWidth() * xAspect - actor.getWidth()
                    / (maxSize + minSize - divFacAButton), actor.getY());
        if (actor.getY() - (aButton.getHeight() / 2 / divFacAButton) + 80f / 2f < 0)
            actor.setPosition(actor.getX(),
                    (aButton.getWidth() / 2 / divFacAButton) - 80f / 2f);
        if (actor.getY() + actor.getHeight()
                / (minSize + maxSize - divFacAButton)/* / divFactor */> maxHeight * yAspect)
            actor.setPosition(actor.getX(), maxHeight * yAspect - actor.getHeight()
                    / (minSize + maxSize - divFacAButton));
    }

For checking if it left outside of the screen, I used two different formulas/equations:
For the x-axis:

xPosition - (1/2currentWidth / divFacAButton) + 1/2defaultWidth = leftEdge

For the y-axis:

yPosition - (1/2currentHeight / divFacAButton) + 1/2defaultHeight = bottomEdge

And my second formula/equation:
For the x-axis

xPosition + currentWidth / (minSize + maxSize - divFacAButton) = rightEdge

For the y-axis

yPosition + currentHeight / (minSize + maxSize - divFacAButton) = topEdge

It's not perfect, but it's pretty close and works fine! :D

A: Just breezin' through your code, it looks like the resizing slider is adjusting the image size and not the container. I ran into a similar situation when I was working with Circles and drawing images over them; the hitbox and image wouldn't align. Horrible picture, incoming!

float xAspect = stage.getWidth() / Gdx.graphics.getWidth();
float yAspect = stage.getHeight() / Gdx.graphics.getHeight();
This is the point in your code that makes me wonder.


text:
Q: Certificate chaining error : PKIX path validation failed I am frequently getting below exceptions. Please advise what to do..
javax.mail.MessagingException: Can't send command to SMTP host;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.j: PKIX path validation failed: java.security.cert.CertPathValidatorException: Fail to verify issuer; internal cause is:
    java.security.cert.CertPathValidatorException: Certificate chaining error
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1564)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1551)
    at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:935)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:426)
    at javax.mail.Service.connect(Service.java:288)
    at javax.mail.Service.connect(Service.java:169)

A: Very generic error, Possibly some certificates are missing(java.security.cert.CertPathValidatorException: Certificate chaining error) in the trust store.
Please include more info about what you are doing.

A: Probably your smtp server is using chained certificates and you imported only last one in chain. You will have to add as signers to the trust store all certificates in the path. Check this post Certificate chaining error in Websphere, it provides some additional info how to add certs to truststore.


text:
Q: Paypal Rest API : Getting Fraud Protection Does the Paypal REST API have any sort of Fraud Protection? I've run trial transactions in Production mode all day trying to get the REST API calls to detect and refuse a charge when the Security Code is wrong, Address mismatched -- but it charges them all regardless of my fraud filter settings. This is really risky behavior for a production environment.

A: The primary benefit to using the rest api is to take advantage of its vault. Prior to storing a card, you could authorize it, get the fraud filters, and cancel the auth. Yes, this is another scenario with a redundant paypal api call but having fraud detection is critical and i can't imagine charging cards without it.


text:
Q: Cache POST response from a System.Web.Http.ApiController I have a System.Web.Http.ApiController that performs 'calculations' and it knows how to do its own server side caching.  I would like to enable caching so that the browser returns 302 and the response is returned from the browser cache.
Unfortunately, I have to perform a POST, mostly because the size of the payload is to big to reasonably fit as a query string parameter (it could exceed the max length - very unlikely, but possible).
The logic of when the cache refreshes is more than just the 'input' coming into the request.  Part of the logic to clear the cache is dependent on whether or not the currently logged in user's data has changed...and this might occur on a different page.  Therefore, implementing a purely client side 'sessionStorage' type cache would be tricky.  I have some ideas, but in addition to cache busting logic, I'm (maybe naively) worried about the amount of data that could be stored in the sessionStorage and getting a bulletproof mechanism on clearing the storage when needed, etc.
Therefore, I'm hoping to just leverage browser caching and a status code of 302.  However, right now, I'm simply using $ajax and method: "POST" in the configuration.
I think if I am performing a GET, I could do something like:
$.ajax({
    url: "/url?withQueryString=true",
    cache: true,
    headers: { 'Cache-Control': 'max-age=0' }
}) ... ;

And on the server,
// Psuedo code, but more or less correct...
var requestIfModified = context.Request.Headers.Get( "If-Modified-Since" );
var lastModifiedDate = DateTime.Today; // This would be my 'date' representing when cache was valid

if ( requestIfModified >= lastModifiedDate.AddMilliseconds( -lastModifiedDate.Millisecond ) )
{
    // Set status = NotModified;
    // return;
}

// else, no cache hit...

// Set response cache last modified = lastModifiedDate
// Set response cache max age = new TimeSpan( 0, 0, 0 )
// Set response cache expires = 'now'

// return 'new' calculation result

However, as you might have guessed, in the client side code $.ajax(requestConfig).then( (response, status, jqXHR) => ... ), status = 'notmodified' but both the response and jqXHR.responseJSON are undefined.
I'm hoping there is a way around this problem?  I'm fearing that it is because $.ajax is ignoring my headers because of POST?  Can I submit POST another way?


text:
Q: Connect Polygon dApp to Wallect Connect using Alchemy RPC Provider We are currently using the "ethers" library to connect our dApp to Metamask and to send transactions on the Polygon blockchain.
We would like to allow users to connect to the dApp via Wallet Connect as well.
So far we tried this :
import WalletConnectProvider from "@walletconnect/web3-provider";

const provider = await new WalletConnectProvider({
  rpc: {
    137: 'https://polygon-mainnet.g.alchemy.com/v2/<OUR_ALCHEMY_RPC_PRIVATE_KEY>'
  },
  chainId: 137
});

await provider.enable();
const eProvider = await new ethers.providers.Web3Provider(provider)

... but provider.enable() never resolves without any error after scanning the QR Code and the connection never gets established...
We also tried the Polygon dedicated library for WallectConnect but still were not able to make it work :
const WalletConnectProviderPolygon = require('@maticnetwork/walletconnect-provider')

const wcProvider = new WalletConnectProviderPolygon({
  host: 'https://polygon-mainnet.g.alchemy.com/v2/<OUR_ALCHEMY_RPC_PRIVATE_KEY>',
  callbacks: {
    onConnect: (res: any) => {
      console.log('onConnect', res)
    },
    onDisconnect: (res: any) => {
      console.log('onDisconnect', res)
    }
  }
})
// await alchemyProvider.createWebconnector()
const eProvider = new ethers.providers.Web3Provider(wcProvider, 137)

... but not connection modal is displayed. If we uncomment await alchemyProvider.createWebconnector() an ugly distorted modal appears, without desktop options, and again it never resolves after scanning the QR Code...
Any idea how to make Wallect Connect work with our Alchemy provider ?
Thank you

A: I use an alchemy rpc and others rpc but, with web3 instead ethers.
    const providerOptions = {
        walletconnect: {
          package: WalletConnectProvider,
          options: {
            rpc: {
              137: "https://polygon-rpc.com"
            }
          }
        },
      };

      web3Modal = new Web3Modal({
        cacheProvider: false,
        providerOptions,
      });

Here the example:
codepen Web3modal
I'll try use ethers in a new example.


text:
Q: iptables - Redirect web traffic to LAN Server I have a webserver which is running on ip address 192.168.11.100
How can i use iptables to redirect all web traffic (http and https) to my webserver on LAN?
After that i want to add except list mac address to this rule. How can i do that?
I tried this command but nothing happened with LAN IP.
iptables -t nat -I PREROUTING -p tcp --dport 80  -j DNAT --to-destination 192.168.11.100
Update: with command above it seems like get affect. But i don't know why the result is: the webpage is not available.
But when i access 192.168.11.100 the server return me a index page. So how should i do?
Thank you!

A: You can try:
 iptables -t nat -A PREROUTING -p tcp -m multiport --dport 80,443 -i eth0 -d 192.168.11.100  -j DNAT --to-destination 192.168.11.100

You have to change interface eth0

A: Okay! My problem has been solve.
I used this command (like i posted above)
iptables -t nat -I PREROUTING -p tcp --dport 80  -j DNAT --to-destination 192.168.11.100
I don't know that is working because i tested on computer has ip address 192.168.11.100.
When i use mobile to connect to my network, it works!
So thank you guys so much for helping me!


text:
Q: Prove that any dihedral group can be generated by symmetry and reflections. One definition of a dihedral group $D_n$ is
$$\langle s,r : s^2=r^2=(sr)^n=1 \rangle.$$
where $s$ is a symmetry along an axis and $r$ is a rotation of $2\pi/n$. I was just thinking this is how dihedral groups are defined but is it possible to show that the dihedral groups can be generated by two generators of order 2?

A: Rotation by 2*pi/n generates all rotations, so it is left to prove that we can obtain also all symmetries.
Check what is $rsr^{-1},r^{2}sr^{-2},r^{3}sr^{-3}$,... up to $r^{n-1}sr^{-(n-1)}$


text:
Q: Sqlalchemy : InvalidRequestError: Object '' is already attached to session '2' (this is '3')
I'm working to modify a cookiecutter Flask app.  I'm trying to follow https://realpython.com/blog/python/handling-email-confirmation-in-flask/ to add email authorization.
My user model is in the screenshot and is also:
class User(UserMixin, SurrogatePK, Model):

    __tablename__ = 'users'
    username = Column(db.String(80), nullable=True)
    email = Column(db.String(80), nullable=False)
    #: The hashed password
    password = Column(db.String(128), nullable=True)
    created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
    first_name = Column(db.String(30), nullable=True)
    last_name = Column(db.String(30), nullable=True)
    active = Column(db.Boolean(), default=False)
    admin = Column(db.Boolean(), default=False)
    confirmed = db.Column(db.Boolean, default=False)
    confirmed_on = db.Column(db.DateTime, nullable=True)

    def __init__(self, username=username, email=email, password=None, **kwargs):
        db.Model.__init__(self, username=username, email=email, **kwargs)
        if password:
            self.set_password(password)
        else:
            self.password = None

    def set_password(self, password):
        self.password = bcrypt.generate_password_hash(password)

As part of the signup process I receive an email from a form and process it creating a token from it and creating a User , followed by sending a confirmation email to the email using:
@blueprint.route("/get_email/", methods=['GET', 'POST'])
def get_email():
    form = EmailForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        new_user = User.create(username=None,email=form.email.data)
        token = generate_confirmation_token(form.email.data)
        confirm_url = url_for('user.confirm_email', token=token, _external=True)
        html = render_template('users/activate.html', confirm_url=confirm_url)
        subject = "Please confirm your email"
        send_email(form.email.data, subject, html)
        return redirect(url_for("main.home"))

In this case I sent an email to:
cluemarine5@mailinator.com

The email contains a confirmation link that looks like:
http://127.0.0.1:5000/users/confirm/ImNsdWVtYXJpbmU1QG1haWxpbmF0b3IuY29tIg.CZ-urA.n5IErF0CPPG6EnIwJeSP6mPmDb4

which contains the embedded email 'cluemarine5@mailinator.com' In the token.
To confirm you click on that link which activates the following route:
@blueprint.route('/confirm/<token>')
def confirm_email(token):
    try:
        email = confirm_token(token)
    except:
        flash('The confirmation link is invalid or has expired.', 'danger')
    user = User.query.filter_by(email=email).first_or_404()
    if user.confirmed:
        flash('Account already confirmed. Please login.', 'success')
    else:
        user.confirmed = True
        user.confirmed_on = datetime.datetime.now()
        db.session.add(user)
        db.session.commit()
        flash('You have confirmed your account. Thanks!', 'success')
    return redirect(url_for('main.home'))

on debugging the code works fine down until
db.session.commit()

Then I get the error above. What am I doing wrong?

A: I finally realized that this cookiecutter is using a class called a 'CRUDMixin' for db operations, which is in database.py:
class CRUDMixin(object):
    """Mixin that adds convenience methods for CRUD (create, read, update, delete)
    operations.
    """

    @classmethod
    def create(cls, **kwargs):
        """Create a new record and save it the database."""
        instance = cls(**kwargs)
        return instance.save()

    def update(self, commit=True, **kwargs):
        """Update specific fields of a record."""
        for attr, value in kwargs.iteritems():
            setattr(self, attr, value)
        return commit and self.save() or self

    def save(self, commit=True):
        """Save the record."""
        db.session.add(self)
        if commit:
            db.session.commit()
        return self

    def delete(self, commit=True):
        """Remove the record from the database."""
        db.session.delete(self)
        return commit and db.session.commit()

class Model(CRUDMixin, db.Model):
    """Base model class that includes CRUD convenience methods."""
    __abstract__ = True

I then changed:
db.session.add(user)
db.session.commit()

To:
use.save()

and it started working


text:
Q: PHP Notice: Undefined offset: 0 I have error on Wordpress. Help please )
PHP Notice:  Undefined offset: 0 in /home/userpro/public_html/wp-content/themes/hoon/inc/tweaks.php on line 602

A: /**
 * Display Future Posts
 *
 * Display future post in the events category to all users.
 */
function hoon_show_all_future_posts( $posts ) {
global $wp_query, $wpdb;

if ( is_single() && $wp_query->post_count == 0 ) {
    $events_cat = hoon_option( 'events_category' );
    $request = $wpdb->get_results( $wp_query->request );
        // below line 602 //
    if ( post_is_in_descendant_category( $events_cat, $request[0]->ID )  || in_category( $events_cat, $request[0]->ID ) ) {
        $posts = $request;
    }
}

return $posts;

}
add_filter( 'the_posts', 'hoon_show_all_future_posts' );


text:
Q: Attempting to use an enum in template class, so that its values may be manipulated as a linked list I am attempting to create a queue or linked list that will allow me to manipulate enum values, in this case 10 vegetables, through the list.  At first I followed an example that allowed to manipulate ints and doubles, however now I am very confused. I don't know how replicate this behavior with an enum. Any insight is appreciated.
HEADER FILE
#ifndef LISTND_H
#define LISTND_H

template< class NODETYPE > class List; // forward declaration

enum vegetables_t
{
    potato = 1, carrot, broccoli, tomato, onion, celery,
    radish, kale, beet, eggplant
};

template< class NODETYPE >
class ListNode { ... }

Main function...
void testList( List < class T > &, const char* );

int main()
{

    /*List < enum value > vegList*/
    List < vegetables_t > vegList;
    testList ( vegList, "vegetable" ); // test integerList

    return 0;
}

Attempting to use enum values in testList


text:
Q: How to set the unique integer id in java for each request in the clustered environment? I want to set the unique integer id in each request, that we will send to other system. This id should start from 1 and should increament until 2147483647. Once it reached 2147483647, it should again start from 1.
We have a clustered environment and request could come from any servers. So from whichever server the request may come from, the unique id should always get the latest value set and should increament it by 1 and need to set the new value in the request.
How can I acheive this ?

A: Instead of keeping a uniqueID in the request and increasing the complexity. I would rather suggest of handling creation of uniqueId logic in your Controller endpoint. In that way your request need not worry about the uniqueID and can function independently as all request are supposed to be.


text:
Q: Excel 2010: Best use of CASE or IF to define SAVEAS location (VBA) Program:  Excel 2010
Experience:  Basic
Question
I am wanting to save my workbook sheet (and generated .pdf) in locations dependent on a cell value, rather than writing 5 Subs, I want to write one using either IF or CASE.  I do have a static save location (dropbox), however I also need to save duplicates in the respective Cell locations.
I can't get the syntax correct to get either working.
Sub saveManID()
    Dim sDB As String
    Dim sMDocs As String
    Dim sMBus As String
    Dim sName As String
    Dim sSel As String
    Dim sMan As String

    'define file name
    sName = Sheets("Statement").Range("B52").Text

    'define location name
    sDB = "E:\location dropbox\"
    sMDocs = "D:\My Documents\"
    sMBus = "D:\location alt\"

    '---- Either IF or CASE to define the SAVEAS location ----'
    If Sheets("Statement").Range("J2").Text = "3" Then
        sMan = "G:\location\folder3\"

    If Sheets("Statement").Range("J2").Text = "4" Then
        sMan = "G:\location\folder4\"

    '---- end ----'

    ActiveWorkbook.SaveAs Filename:=sMan & sName & Format(Date, "YYYYMMDD") & ".xls",_
     FileFormat:=52, ReadOnlyRecommended:=False, CreateBackup:=False

    Sheets("Statement").Range("A1:G49").ExportAsFixedFormat Type:=xlTypePDF, Filename:=sMan & sName & ".pdf", _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

        End if
    End if
End Sub

I need to get the Range("J2") to define location from the cell value & I need to create the name based on another cell value.
The Sub runs fine if I exclude the IF, but it means I have to have the code duplicated and a button assigned for each value.
To clarify - the Cell Value Range("J2") will determine where the file saves to, in the example above it is in the IF statement, which does not work.

A: To fix what you have written try moving your End If before your common code like this:
If Sheets("Statement").Range("J2").Text = "3" Then
    sMan = "G:\location\folder3\"
End If

If Sheets("Statement").Range("J2").Text = "4" Then
    sMan = "G:\location\folder4\"
End if

ActiveWorkbook.SaveAs Filename:=sMan & sName & Format(Date, "YYYYMMDD") & ".xls",_
 FileFormat:=52, ReadOnlyRecommended:=False, CreateBackup:=False

Sheets("Statement").Range("A1:G49").ExportAsFixedFormat Type:=xlTypePDF, Filename:=sMan & sName & ".pdf", _
    Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

Or like this:
If Sheets("Statement").Range("J2").Text = "3" Then
    sMan = "G:\location\folder3\"
ElseIf Sheets("Statement").Range("J2").Text = "4" Then
    sMan = "G:\location\folder4\"
End if

Or like this:
myVal = Sheets("Statement").Range("J2").Text
If myVal = "3" Then
    sMan = "G:\location\folder3\"
ElseIf myVal = "4" Then
    sMan = "G:\location\folder4\"
End if

To use a Select Case re-write it like this:
Select Case Sheets("Statement").Range("J2").Text
      Case "3"
           sMan = "G:\location\folder3\"

      Case "4"
           sMan = "G:\location\folder4\"

      Case Else
           'set sMan to your default dropbox location here
End Select


text:
Q: Can not edit the object after is fetched from json Project. When you type in the input field and the text on the shirt . Then press the button "see back" there is a downside.
Then click on the button "see front" and enter text in the input. Old text is saved , and the new is superimposed on top of it .
Question:
How to realize that the text would not overlap, and edited one that was introduced earlier?
   var canvas;
    var a;
    var b;
    var line1;
    var line2;
    var line3;
    var line4;

    $(document).ready(function() {
        canvas = new fabric.Canvas('FrontCanvas');

    $('#your-name').on('click', function() {
        clearCanvas();
        initTextString();
        $('#text-string').val('Your name')
    });

    var textSample;
    /*#text-string*/
    $('#text-string').on('keyup', function() {
        var text = $('#text-string').val();
        var activeText = canvas.getActiveObject();

        textSample = new fabric.Text(text, {
            originX: 'left',
            originY: 'top',
            fontSize: 32,
            fontFamily: 'MotorCyr',
            angle: 0,
            fontWeight: '',
            hasControls: false,
            hasBorders: true,
            top: 50
        });

        canvas.setActiveObject(textSample);
        canvas.remove(activeText);
        canvas.renderAll();
        canvas.add(textSample);
        canvas.centerObjectH(textSample);
        $('#position').show();
        $("#removePrint").show();
        if(document.getElementById('text-string').value.replace(/\s+/g, '').length < 1) {
            $('#position').hide();
            $("#removePrint").hide();
        }
    });
    /*#text-string*/

    function initTextString() {
        var text = $('#text-string').val();

        textSample = new fabric.Text(text, {
            originX: 'left',
            originY: 'top',
            fontSize: 32,
            fontFamily: 'MotorCyr',
            angle: 0,
            fontWeight: '',
            hasControls: false,
            hasBorders: true,
            top: 50
        });
        canvas.setActiveObject(textSample);
        canvas.renderAll();
        canvas.add(textSample);
        canvas.centerObjectH(textSample);
        $('#position').show();
        $("#removePrint").show();

        if(document.getElementById('text-string').value.replace(/\s+/g, '').length < 1) {
            $('#position').hide();
            $("#removePrint").hide();
        }
    }

    document.getElementById("text-string").addEventListener("focusout", deactivateAll);
    document.getElementById("text-string").addEventListener("focus", focusText);

    function deactivateAll() {
        canvas.deactivateAllWithDispatch();
    }
    function focusText() {
        if(textSample != undefined) {
            canvas.setActiveObject(textSample)
        }
    }

    $('#removePrint').on({
        click: function() {
            clearCanvas();
            $("#text-string").val("");
            $("#number-string").val("");
            $('#removePrint').hide();
            $('#position').hide();
        }
    });

    $(".printArea").hover(
        function() {
            canvas.add(line1);
            canvas.add(line2);
            canvas.add(line3);
            canvas.add(line4);
            canvas.renderAll();
        },
        function() {
            canvas.remove(line1);
            canvas.remove(line2);
            canvas.remove(line3);
            canvas.remove(line4);
            canvas.renderAll();
        }
        );

    $('#flip').click(function() {

        if ($(this).attr("data-title") == "Показать вид сзади") {

            var backSRC = $('#mainCanvas img').attr('data-back');
            console.log(backSRC);
            $(this).attr('data-title', 'Показать вид спереди');
            $(this).text('See front');
            $("#mainCanvas img").attr("src",backSRC);
            a = JSON.stringify(canvas);
            canvas.clear();
            try
            {
                var json = JSON.parse(b);

                canvas.loadFromJSON(b);
                canvas.loadFromJSON(b, function() {
                    canvas.renderAll();
                    console.log(canvas.item(0).name);
                });
            }
            catch(e)
            {
                console.log( e.name );
                console.log( e.message );
            }

        } else {
            var frontSRC = $('#mainCanvas img').attr('data-front');
            console.log(frontSRC);
            $(this).attr('data-title', 'Показать вид сзади');
            $(this).text('See back');
            $("#mainCanvas img").attr("src",frontSRC);

            b = JSON.stringify(canvas);
            canvas.clear();
            try
            {
                var json = JSON.parse(a);
                canvas.loadFromJSON(a, function() {
                    canvas.renderAll();
                    console.log(canvas.item(0).name);
                });
            }
            catch(e)
            {
                console.log( e.name );
                console.log( e.message);
            }
        }
    canvas.renderAll();
    setTimeout(function() {
        canvas.calcOffset();
    },200);
});

line1 = new fabric.Line([0,0,200,0], {"stroke":"#000000", "strokeWidth":1,hasBorders:false,hasControls:false,hasRotatingPoint:false,selectable:false});
line2 = new fabric.Line([199,0,200,399], {"stroke":"#000000", "strokeWidth":1,hasBorders:false,hasControls:false,hasRotatingPoint:false,selectable:false});
line3 = new fabric.Line([0,0,0,400], {"stroke":"#000000", "strokeWidth":1,hasBorders:false,hasControls:false,hasRotatingPoint:false,selectable:false});
line4 = new fabric.Line([0,400,200,399], {"stroke":"#000000", "strokeWidth":1,hasBorders:false,hasControls:false,hasRotatingPoint:false,selectable:false});

});//doc ready

function clearCanvas() {
    canvas.clear().renderAll();
}

A: When you call loadFromJson a new fabric text is created, you should attach the input #text-string with this new text when you call loadFromJSON and unlink #text-string from the old text object when you stringify canvas
canvas.loadFromJSON(a, function() {
  canvas.getObjects() //get the new text here and attach to input text
});

BTW, fabricjs has an itext object where you can type directly in the object


text:
Q: conditional xpath statement This is a piece of HTML from which I'd like to extract information from:

Provenance

Galerie Max Hetzler, Berlin
Acquired from the above by the present owner

I'd like to have an xpath expression which extracts the content of the 2nd
 ...
 depending if there's a sibling before with
 ... Provenance ...

This is to where I got so far:
if "Provenance" in response.xpath('//strong[@class="more-details-section-header"]/text()').extract():
            print("provenance = yes")

But how do I get to Galerie Max Hetzler, Berlin
Acquired from the above by the present owner ?
I tried
if "Provenance" in response.xpath('//strong[@class="more-details-section-header"]/text()').extract():
            print("provenance = yes ", response.xpath('//strong[@class="more-details-section-header"]/following-sibling::p').extract())

But am getting []

A: You should use
//p[preceding-sibling::p[1]/strong='Provenance']/text()


text:
Q: Office.context.document.settings.set Not working on Excel Mac I am working on a excel add-in, to save some settings in to Excel.
But its not working on Excel on Mac.   Is there any other way to save settings in Excel ?
Office.context.document.settings.set('keyToken', values.apiKey);
        Office.context.document.settings.saveAsync(function(asyncResult) {
            if (asyncResult.status == Office.AsyncResultStatus.Failed) {
               console.log("save token failed");
            } else {
                 ReactDOM.render(
                     <Home />,
                        document.getElementById("container")
                 );
           }
});

Excel version.

A: Just verified on my Mac which is exactly the same version 16.45. I did some modifications to your code, it works on my side. I guess there are some other errors that may not related to settings. please try on the following code.
async function save1(){
  await Excel.run(async (context) => {

  Office.context.document.settings.set('keyToken', 'myvalue');
  Office.context.document.settings.saveAsync(function (asyncResult) {
    if (asyncResult.status == Office.AsyncResultStatus.Failed) {
      console.log("save token failed");
    } else {
      console.log("save token success");
    }
  });
  });
}

async function read() {
  await Excel.run(async (context) => {
    Office.context.document.settings.refreshAsync((result: Office.AsyncResult<Office.Settings>) => {
      const value1 = result.value.get("keyToken");
      console.log("current value: " + value1);
    });
  });
}

My Mac version:


text:
Q: What is mean name after variable name in t-sql I have the next query:
DECLARE @startdate DATETIME
SET @startdate = ''1/1/1990''
;WITH cte
AS (
    SELECT @startdate DateVal
    UNION ALL
    SELECT DateVal + 1
    FROM cte
    WHERE DateVal + 1 <= @enddate
    )

Сan you please explain what it means instruction:
@startdate DateVal

Is a variable called startdate assigned a different name? But why?

A: First, I would write this as:
@startdate as DateVal

The two are equivalent, but this is clearer in intent (and less likely to cause problems).
In any case, @startdate is not a valid column name in a table -- or CTE.  So, you want to give it a valid name.  That is what this is doing.
If you don't give it a name, you will get an error, as illustrated here.
You should also use standard date formats, so I would suggest:
SET @startdate = '1990-01-01';  -- ISO standard format but could be affected by internationalization formats

or:
SET @startdate = '19900101';    -- SQL Server standard format.  Unambiguous.


text:
Q: How to vertically align column members How to make this all members of the last column get aligned vertically to top please?
\documentclass[french]{beamer}
\usepackage{babel}
\usepackage{amssymb}
\usepackage{array}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\begin{document}
\begin{frame}
\centering
\begin{table}
\centering
\caption{Comparatif entre Two Track Unified Process et Rational Unified Process}
\vspace{0.2cm}
\begin{tabular}{|C{0.07\textwidth}*{4}{|C{\dimexpr0.22\textwidth-2\tabcolsep\relax}}|}
\hline
& {\fontsize{9}{9}\selectfont Axé développement} & {\fontsize{9}{9}\selectfont Architecture logicielle} & {\fontsize{9}{9}\selectfont Technologies} & {\fontsize{9}{9}\selectfont Projets cibles} \\
\hline
RUP & \includegraphics[height=1.8ex]{images/danger} & \includegraphics[height=1.8ex]{images/danger} & \includegraphics[height=1.8ex]{images/danger} & \[\geqslant 10p\] \\
\hline
2TUP & \includegraphics[height=1.8ex]{images/func_ok} & \includegraphics[height=1.8ex]{images/func_ok} & \includegraphics[height=1.8ex]{images/func_ok} &  \[*\]  \\
\hline
\end{tabular}
\end{table}
\end{frame}
\end{document}

Thanks a lot!

A: Use the inline equation form \(...\) in the last column, instead of \[...\].
\documentclass[french, demo]{beamer}
\usepackage{babel}
\usepackage{amssymb}
\usepackage{array}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\begin{document}
\begin{frame}
\centering
\begin{table}
\centering
\caption{Comparatif entre Two Track Unified Process et Rational Unified Process}
\vspace{0.2cm}
\begin{tabular}{|C{0.07\textwidth}*{4}{|C{\dimexpr0.22\textwidth-2\tabcolsep\relax}}|}
\hline
& {\fontsize{9}{9}\selectfont Axé développement} & {\fontsize{9}{9}\selectfont Architecture logicielle} & {\fontsize{9}{9}\selectfont Technologies} & {\fontsize{9}{9}\selectfont Projets cibles} \\
\hline
RUP & \includegraphics[width=4ex,height=1.8ex]{images/danger} & \includegraphics[width=4ex,height=1.8ex]{images/danger} & \includegraphics[width=4ex,height=1.8ex]{images/danger} & \(\geqslant 10p\) \\
\hline
2TUP & \includegraphics[width=4ex,height=1.8ex]{images/func_ok} & \includegraphics[width=4ex,height=1.8ex]{images/func_ok} & \includegraphics[width=4ex,height=1.8ex]{images/func_ok} &  \(*\)  \\
\hline
\end{tabular}
\end{table}
\end{frame}
\end{document}


text:
Q: Pairing in Core Bluetooth Peripheral application iOS I have created an application in IPhone that can act as a BLE Peripheral.I want to initiate a pairing mechanism when a central send a request to connect. I have searched on net and came to know that individual characteristic can be encrypted and initiate pairing when read by central. I have read the
 Bluetooth 4.0 and 4.1 security document  which is saying there are various pairing mechanism are available.But i don't know how to use it in my application. Can anyone help?
Code i am using for creating the characteristic
var characteristic = CBMutableCharacteristic(type: charId, properties: charProperties, value: nil, permissions:CBAttributePermissions.ReadEncryptionRequired|CBAttributePermissions.WriteEncryptionRequired)


text:
Q: Invariant Violation: Invariant Violation: Text strings must be rendered within a  component creating an application in react-native running into this problem. basically I should create a page that prints the data of the user currently logged in to the database (firebase). I managed to create a sort of leaderboard that prints all users with data, on another page, but I can not figure out where I was wrong. can someone help me?
https://snack.expo.io/@khal_d/proj-p-3
import React, { Component } from 'react';
import { View, TouchableOpacity, StyleSheet, Button, Text, ScrollView, ListItem } from 'react-native';
import { Input, Card} from 'react-native-elements';

import * as firebase from 'firebase';

export default class User extends Component {
   static navigationOptions = {
    title: 'UserInfo',
  };

  state = {
    data: [],
  };

  // Controllare qui
  componentDidMount(){
    //leggere array dal db
    const currentUID = firebase.auth().currentUser.uid;
    const path ="/users/" + currentUID;
    const users = firebase.database().ref(path);
    users.on("value", snap => {
      console.log("log di snap" + snap);
      //ciclo
      var elenco = [];
      snap.forEach(child => {
        elenco.push({
          name: child.val().name,
          surname: child.val().surname,
          email: child.val().email,
          image: child.val().image,
        })
      });

      console.log("altro log finale" + elenco);
      this.setState({data:elenco})
    });

  }

// controllare fino a qua

  render() {

    return (
      <ScrollView>
      <View>
        <Card> //fix evertything all'interno di card
          {
    this.state.data.map((l, i) => (
      <ListItem
        key={i}
        leftAvatar={{ source: { uri: l.image } }}
        title={l.name}
        subtitle={l.surname}

      />
    ))
  }
        </Card>
      </View>
      </ScrollView>
    );
  }
}

A: Just delete the comments and extra { }from your code in render() or use them as below. In JSX you cannot have // in render():
 render() {

    return (
      <ScrollView>
      <View>
        <Card>

    { this.state.data &&
    this.state.data.map((l, i) => (
      <ListItem
        key={i}
        leftAvatar={{ source: { uri: l.image } }}
        title={l.name}
        subtitle={l.surname}

      />
    ))
    }

      </Card>
      </View>
      </ScrollView>
    );
  }
}

iOS has no problem with extra syntaxes in render(), but in android it will show that error.
Also because of asynchronous problem of setState, you will have and error of undefined is not an object. So it is better to have  {this.state.data &&  condition on your ListItem.  I hope I could help :)

A: I think the issue is because of the comment. In JSX, comment with  // doesn't work. It will be treated as a text.
You have to change your comments like below which will fix your issue
    {/* fix evertything all'interno di card */}

A: ListItem should be imported from react-native-elements and not from react-native.


text:
Q: Tails persistence Is there any way to find the last time a Tails persistent volume was accessed? I've reviewed the Tails website and searched extensively but can't find any discussion of this.

A: Persistence is specifically not recommended by tails.
In the event that you choose to do so anyway, the suggested persistence mount is

/dev/mapper/TailsData_unlocked on /home/amnesia type ext4
(rw,noatime,data=ordered)

noatime specifically says not to record access time.
If you ommitted noatime, then normal file access times should be available.


text:
Q: UITabbarController deallocating my viewcontrollers I having some problem: Im using UITabBarController and 3 tabs, witch one is camera. When i open camera, sometimes give Received Memory warning. And when it happens, all my views are deallocated except the camera. Is it normal? is there some way to control to not happen it? Gratz.
EDIT: im testing with a 3gs model

A: I presume you mean your view controllers' views are deallocated, rather than the view controllers themselves.
This is normal behavior.  UIViewController is built on the assumption that under low-memory conditions, the view can be thrown away if the view controller's view is not on-screen.  You can save your state in -viewWillUnload so that you can rebuild it when the view controller's view comes back on screen and is recreated.
This automatic-unloading behavior is removed in iOS 6.


text:
Q: Compares two column based on the value of a third column's value What I want to do is create a macro to look at a column (AF) and based on that value, compare column (BI), (BJ), and/or (BK) together and if its false, highlight the compared cells in yellow. I know that's a little hard to follow but this example should help clarify:
My Sheet has the following columns:
Column AF    Column BI    Column BJ    Column BK
PRODUCT      Height       Length       Width

I need a macro to look at the product type and compare the dimensions for that product as follows:
  - If product = A, then Length = Width, if not then highlight Length and Width Cells
  - If product = B then Length > Width, if not then highlight Length and Width Cells
  - If product = C then Width > Height < Length, if not highlight Length, Width, and Height cells
  - If product - D then Width = Length < Height, if not highlight Width, Length, and/or Height

My Data starts on row 3 and ends at row 5002.
I have tried researching this and was only able to find solutions that compare two cells then write a third column. I could combine an IF formula and conditional formatting to achieve this but I don't want to have this run all the time as the sheet will be sorted and color coded. I plan to place this macro into a command button.

A: Suggest to combine Statements such as Select Case, If...Then...Else, together with Operators And, Or. See the following pages:
https://msdn.microsoft.com/en-us/library/office/gg251599.aspx
https://msdn.microsoft.com/en-us/library/office/gg278665.aspx
https://msdn.microsoft.com/EN-US/library/office/gg251356.aspx
After which you should be able to write something that resembles this:
(Code below is just a sample, it will not work)
Select Case Product
Case A
    If Length <> Width Then
        Rem Highlight Length And Width  Cells
    End If
Case B
    If Length <= Width Then
        Rem Insert here the code to highlight Length And Width Cells
    End If
Case C
    If Width <= Height And Height >= Length Then
        Rem Insert here the code to highlight Length, Width, and Height cells
    End If
Case D
    If Width <> Length And Length >= Height Then
        Rem Insert here the code to highlight Width, Length, and/or Height
    End If
End Sub

In case you don't know to highlight the Width, Length and Height Cells; I suggest to do it manually while recording a macro, this shall give a good starting point.

A: I suggest to work with objects, defining variables for the Data range, each row being validated, the position of the fields to validate, etc. see below code with comments
Sub Highlight_Cells_based_Comparison()
Dim rData As Range
Dim rRow As Range
Dim rCllsUnion As Range
Rem Set variables to hold Fields position within the DATA range
Dim bPosProd As Byte, bPosHght As Byte, bPosLeng As Byte, bPosWdth As Byte
Rem Set variables to hold Fields values
Rem (data type Variant as don't know type of values these fields are holding, change as appropriated)
Rem see https://msdn.microsoft.com/en-us/library/office/gg251528.aspx)
Dim sProd As String, vHght As Variant, vLeng As Variant, vWdth As Variant
Dim lRow As Long

    Rem Set Range (assuming it goes from column C to BK - change as needed)
    Rem Not starting from column A on porpuse
    Set rData = ActiveSheet.Range("C3:BK5002")

    Rem Get Fields position from Header row
    Rem Suggest to use this method instead of hard coding columns
    On Error Resume Next
    With rData
        bPosProd = WorksheetFunction.Match("PRODUCT", .Rows(1), 0)
        bPosHght = WorksheetFunction.Match("Height", .Rows(1), 0)
        bPosLeng = WorksheetFunction.Match("Length", .Rows(1), 0)
        bPosWdth = WorksheetFunction.Match("Width", .Rows(1), 0)
    End With
    If Err.Number <> 0 Then Exit Sub
    On Error GoTo 0

    Rem Loop thru each row excluding header
    For lRow = 2 To rData.Rows.Count
            Set rRow = rData.Rows(lRow)
            With rRow
                Rem Get Row Field values
                sProd = .Cells(bPosProd).Value2
                vHght = .Cells(bPosHght).Value2
                vLeng = .Cells(bPosLeng).Value2
                vWdth = .Cells(bPosWdth).Value2

            Select Case sProd
            Case A 'Change value of A as required
            Rem If product = A, then Length = Width, if not then highlight Length and Width Cells
            Rem If Length <> Width Then Highlight Length And Width  'Cells
                If vLeng <> vWdth Then
                    Set rCllsUnion = Union(.Cells(bPosLeng), .Cells(bPosWdth))
                    Rem Suggest to use a subroutine for this piece as it's a repetitive task
                    Rem see https://msdn.microsoft.com/en-us/library/office/gg251648.aspx
                    GoSub CllsUnion_Highlight
                End If

            Case B
                Rem repeat as in Case A with required changes
            Case C
                '...
            Case D
                '...
    End Select: End With: Next

Exit Sub
Rem Subroutine to highlight cells
CllsUnion_Highlight:
    With rCllsUnion.Interior
        .Color = 65535
        .TintAndShade = 0
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .PatternTintAndShade = 0
    End With
    Return

End Sub


text:
Q: Question about using string arrays as function parameters I am a novice, I encountered a little problem today, I hope to get someone's answer, thank you very much.
Code show as below。
#include<iostream>
using namespace std;
void sub(char b[]){
    b[] = "world";    //I alse try b*/b,but it is not ok
}
int main(void){
    char a[10] = "hello";
    sub(a);
    cout<<a<<endl;

    system("pause");
    return 0;
}

error: expected primary-expression before ']' token
b[] = "world";
^
The error
I want the final output will be "world".  The function sub() can run correctly.  What should I do?

A: strcpy(b, "world"); // need <string.h>

But I would use std::string (instead of c-string) directly.
#include<iostream>
#include<string>
using std::cout;
using std::string;

void sub(string &b){
    b = "world";
}

int main(){
    string a = "hello";
    sub(a);
    cout << a << endl; // output

    system("pause");
    return 0;
}

A: as other people told you it's not c++ style but c style, I will try to explain why it does not compile.
when you write b[i] you tell the compiler: "please go to memory location b + sizeof(b type) * i", so when you write b[], the compiler can't understand what you want.


text:
Q: Make an Independent Popup in Qt Quick I have an app which is small in terms of width and height, I want a popup to show when a button is clicked. Problem is the popup is larger than the app window and when i open it, it scales down and looks weird
APP

APP WITH POPUP

POPUP CONTENT IN DESIGNER

How can i make the popup independent from the app window, like this:

Or is there a better approach rather than using popup, it would be nice if i were able to move the popup/window around. It still needs to be somehow connected to the main app because it get's data from there

A: A Popup in QML appears as a layer on top of the parent window, so it cannot be bigger than the parent window. If you want a separate, top level window, you should use a Window or a Dialog instead.

A: I've gotten it sorted out. I encapsulated the component i wanted to show inside a window and created it using Qt.createComponent()
var playListComponent = Qt.createComponent("CustomPlaylist.qml")
var window = playListComponent.createObject(rootWindow)
window.show()

The root element of CustomPlaylist.qml is a Window


text:
Q: Variable is undefined after assignment on JavaScript This is getting frustrating, variable is always undefined after assignment. Please explain what I am doing wrong here.
$(document).ready(function() {
    $("#submitButton").click(function() {
        var startDate = $('#startDate').val();
        var endDate = $('#endDate').val();

        if (!isDate(startDate) && !isDate(endDate))
        {
            alert ('Start Date and End Date is invalid');
            return false;
        }
        ... other condition removed for clarity
    });
});

function isDate(dateText)
{
    var comp = [];
    var comp2 = '';
    var y_length = 0;

    comp = dateText.split('/');
    comp2 = comp[2];
    y_length = comp2.length;

    //invalid if year length is less than or greater than 4
    if (y_length < 4 || y_length > 4) {
        return false;
    }

    var m = parseInt(comp[0], 10);
    var d = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);

    var date = new Date(y, m - 1, d);

    if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
        return true;
    } else {
        return false;
    }
}

I amg getting 'Cannot read property length of undefined' on line y_length assignment, this line:
//comp2 here is undefined
y_length = comp2.length;

Additionally, do you have any suggestion on date validation using JavaScript. Thank you.

A: If dateText doesn't have at least 2 instances of / in it you are going to end up with less than 3 elements after the split so
comp2 = comp[2];

sets comp2 to undefined and
y_length = comp2.length;

will error out. If you are entering a dateText which has 2 (or more instances) of / in it you shouldn't be getting this error. If you are, you will want to check the value of dateText (with an alert or console.log)
You might want to do something like
if (comp.length > 2) {
    comp2 = comp[2];
    ...
else {
    // error handling
    ...


text:
Q: ng-if -> multiple 'OR' condition is not working ng-if="self_employment.business_type != 'Trust' || self_employment.business_type !== 'Partnership'"

A: Use != instead of !==  :
ng-if="self_employment.business_type != 'Trust' || self_employment.business_type != 'Partnership'"

A: When You face this kind of problems, First check the object is defined or not. print the {{self_employment.business_type}} in the Html/console. If it is coming "trust/partnership" then it is in lowercase. if it is lowercase it may cause to fail the condition.
"trust" === "Trust" // false
"trust" == "Trust"  // false
"trust" == "trust"  // true


text:
Q: Portable way in C++ to get desktop resolution I'm making a C++ game, and I want it to automatically get the user's desktop resolution.
I've found windows-only solutions so far - is there a way/library to find the resolution on Windows/Mac/Linux?

A: There are several libraries helping you at getting the low-level stuff to work out. You'll probably need more stuff on those platforms anyways, so I'll list some:

*

*SFML is a C++ library abstracting much of the I/O stuff, including display management. Also supports several platforms.

*The classic SDL, although being a C library is widely used in platform independent game development and supports several platforms. Like SFML, it does more than just display management.

*GLFW, see wardds answer, also a C library and also poses an abstraction layer, but more focused on display and keyboard/mouse I/O instead of broader I/O (audio etc.)

A: GLFW provides a crossplatform (for Windows, Mac, and Linux) way to get the desktop video mode. It is a C api, but it will work in C++. The relevant function (and documentation) is here:
void glfwGetDesktopMode( GLFWvidmode *mode )
Parameters
mode
Pointer to a GLFWvidmode structure, which will be filled out by the function.
Return values
The GLFWvidmode structure pointed to by mode is filled out with the desktop video mode.
Description
This function returns the desktop video mode in a GLFWvidmode structure. See glfwGetVideoModes
for a definition of the GLFWvidmode structure.
Notes
The color depth of the desktop display is always reported as the number of bits for each individual color
component (red, green and blue), even if the desktop is not using an RGB or RGBA color format. For
instance, an indexed 256 color display may report RedBits = 3, GreenBits = 3 and BlueBits = 2, which
adds up to 8 bits in total.
The desktop video mode is the video mode used by the desktop at the time the GLFW window was
opened, not the current video mode (which may differ from the desktop video mode if the GLFW
window is a fullscreen window).
typedef struct {
  int Width, Height; // Video resolution
  int RedBits; // Number of red bits
  int GreenBits; // Number of green bits
  int BlueBits; // Number of blue bits
} GLFWvidmode;

See Jonas Wielicki's answer for alternatives.

A: I did a cross-platform c++ function:
#if WIN32
  #include <windows.h>
#else
  #include <X11/Xlib.h>
#endif

//...

void getScreenResolution(int &width, int &height) {
#if WIN32
    width  = (int) GetSystemMetrics(SM_CXSCREEN);
    height = (int) GetSystemMetrics(SM_CYSCREEN);
#else
    Display* disp = XOpenDisplay(NULL);
    Screen*  scrn = DefaultScreenOfDisplay(disp);
    width  = scrn->width;
    height = scrn->height;
#endif
}

int main() {
    int width, height;
    getScreenResolution(width, height);
    printf("Screen resolution: %dx%d\n", width, height);
}


text:
Q: Cumulative translation on Matrix3x2F I am working on a WinRT app that uses D2D to display a bitmap.  I am looking to incorporate multitouch to be able to pan and zoom in the bitmap.
I am using the OnManipulatedUpdated event to update a cumulative transform.  I have found a way to find a cumulative scale factor, but can't seem to find a cumulative translation factor (I don't want the user to pan outside of the size of the scaled image.
Is there a way to find out what the cumulative translation is?
Here is my code:
D2D1::Matrix3x2F m_mxTransform;

property float CurrentScaleFactor
    {
        float get() { return sqrt(fabs(m_mxTransform.Determinant())); }
    }

void OnManipulationUpdated(
_In_ Windows::UI::Input::GestureRecognizer^ recognizer,
_In_ Windows::UI::Input::ManipulationUpdatedEventArgs^ args)
{
Point position = args->Position;
Point positionDelta = args->Delta.Translation;

float currentScale = CurrentScaleFactor;
float preAdjustedScale = args->Delta.Scale;
ManipulationDelta adjustedDelta = LimitManipulationScale(args->Delta, currentScale);
float newScale = currentScale * adjustedDelta.Scale;

//Update the transformation to
D2D1::Matrix3x2F transformDelta;
if (preAdjustedScale == adjustedDelta.Scale)
{
    transformDelta =
        D2D1::Matrix3x2F::Scale(adjustedDelta.Scale, adjustedDelta.Scale, D2D1::Point2F(args->Position.X, args->Position.Y)) *
        D2D1::Matrix3x2F::Translation(args->Delta.Translation.X, args->Delta.Translation.Y);
}
else  // don't translate
{
    transformDelta =
        D2D1::Matrix3x2F::Scale(adjustedDelta.Scale, adjustedDelta.Scale, D2D1::Point2F(args->Position.X, args->Position.Y));
}
m_mxTransform = m_mxTransform * transformDelta;

....
m_d2dContext->SetTransform(m_mxTransform);
}

A: I think i found it...
    /* x-coordinate that we are currently translated by */
    property float CurrentTranslationX
    {
        float get() { return m_mxTransform._31; }
    }

    /* y-coordinate that we are currently translated by */
    property float CurrentTranslationY
    {
        float get() { return m_mxTransform._32; }
    }


text:
Q: special paging requirement in symfony Im triing to create this logic, but i can't reach any goal.
i habe a list of Feeds.It is sometimes veri large almost 2000 entries.
now i want to create a Read function which gives me the first 40 entries and when i have read them or i have scrolled fully to the buttom the next 40 entries should be append at the buttom of the list.
My current staff:
i created a Paging with page and pagesize but the Problem is the following:
let say we have total 20 entries and a begin to request the entries:
page 1 5 items items 0 - 5 of the list (if the ar read they aren't in the list anymore!)
not i load page 2 => items 5-0 aso.. at a point it crosses itself and no items will be retrned!
has anyone an Idea how i can fix this ??
thanks

A: You must use Paginator class. There is a working example on one of my repositories class:
<?php

namespace Fluency\Bundle\GeneralBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository,
    Doctrine\ORM\Tools\Pagination\Paginator;
use Fluency\Bundle\GeneralBundle\Entity\Country;

/**
 * CountryRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CountryRepository extends EntityRepository
{
    /**
     * @param array $criteria
     * @param null $limit
     * @param null $start
     * @return array with this format (0 => $result, 1 => $counter)
     */
    public function findAllByCriteria($criteria = array(), $limit = null, $start = null)
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('c')
            ->from($this->getEntityName(), 'c')
            ->orderBy('c.name', 'ASC');

        if(null !== $limit)
        {
            $query->setMaxResults($limit);
        }

        if(null !== $start)
        {
            $query->setFirstResult($start);
        }

        if(!empty($criteria))
        {
            if($criteria['active'])
            {
                $query->andWhere($query->expr()->eq('c.active', $criteria['active']));
            }
        }

        $paginator = new Paginator($query);

        return array($query->getQuery()->getArrayResult(), $paginator->count());
    }
    .................
}


text:
Q: Unit testing Bottle app with WebTest I've been attempting to familiarize myself with unit testing but have been having a lot of trouble with it. I have a bottle app that I tried using Unittest, which didn't seem appropriate, so now I'm trying WebTest.
The trouble is that I can't get it to even remotely work, even following along with the most basic/superficial example on the site.
Here's the example:
from webtest import TestApp
import mywebapp

def test_functional_login_logout():
    app = TestApp(mywebapp.app)

    app.post('/login', {'user': 'foo', 'pass': 'bar'}) # log in and get a cookie

    assert app.get('/admin').status == '200 OK'        # fetch a page successfully

    app.get('/logout')                                 # log out
    app.reset()                                        # drop the cookie

    # fetch the same page, unsuccessfully
    assert app.get('/admin').status == '401 Unauthorized'

my code:
@get('/')
def page():
    letters = scorer.get_letter_set()
    c = db_connect()
    c.execute('SELECT player_name,score FROM Scores order by score DESC limit 5')
    data = c.fetchall()
    c.close()

    return template('board', letters=letters, scores=data, letterset=json.dumps(letters))

Then, in the console (one problem is that I can't seem to get any testing code to work from a file. If I run any file in my project directory, bottle runs the development server instead. Any attempt to run test files results in import errors.)
>>> from webtest import TestApp
>>> import board
>>> app = TestApp(board.page)
>>> res = app.get('/')

I get this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/webtest/app.py", line 322, in get
    expect_errors=expect_errors)
  File "/usr/local/lib/python2.7/dist-packages/webtest/app.py", line 605, in do_request
    res = req.get_response(app, catch_exc_info=True)
  File "/usr/local/lib/python2.7/dist-packages/webob/request.py", line 1313, in send
    application, catch_exc_info=True)
  File "/usr/local/lib/python2.7/dist-packages/webob/request.py", line 1281, in call_application
    app_iter = application(self.environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/webtest/lint.py", line 198, in lint_app
    iterator = application(environ, start_response_wrapper)
TypeError: page() takes no arguments (2 given)

A: As @ron.rothman mentions, the problem is that you are trying to wrap a method inside TestApp instead of the application.
And from your code-
@get('/')
def page():
    letters = scorer.get_letter_set()
...

its evident that you are using the default application instead of creating an instance of the Bottle yourself.
Fix-
Make the following changes-

*

*Add these first two lines before you page() method-
app = Bottle()
@app.get('/')
def page():
    letters = scorer.get_letter_set()
...

*Make sure you save the file containing your above code as mywebapp.py

*In your unit test code, write the wrapper line like this-
def test_functional_login_logout():
    app = TestApp(mywebapp.app)
...

A: The problem is here:
app = TestApp(board.page)

Instead, you need to wrap TestApp around your Bottle app, which I'm presuming (since you didn't show it) lives in board.py.
So, something like this should fix it up:
app = TestApp(board.app)


text:
Q: How do I install Google Chrome on Raspberry Pi 4 running Ubuntu 19.10? How do I install Google Chrome on a Raspberry Pi 4 running Ubuntu 19.10?

A: Raspberry Pi4 uses 64-bit quad-core ARM Cortex-A72 processor, thus, all the applications running on it must be for ARM64. But on the other hand Google Chrome is only available for AMD64 CPU architecture. So, it's impossible to get Google Chrome on Raspberry Pi.
Alternatively you can use Firefox or Chromium browser.
Note: Chromium Browser on 19.10 is available only as a snap package.

Futher Reading:
What is the difference between ARM64 and AMD64? And which one is faster? - Quora