text:
Q: View a list of all schema in a PostgreSQL database in r? I'm connecting and querying a PostgreSQL database through the dplyr package in R. I know I can list all the tables in the database using dbListTables(con).
But, my tables are organized into different schema. What is the easiest way I can view all of the schema that are present in my database using R?

A: dbGetQuery(con, "SELECT nspname FROM pg_catalog.pg_namespace")


text:
Q: Pinch zooming with ScrollView: Updating its scrolling behaivor when child size changes I have a custom class which I extended from the ScrollView. What I want to do is to implement pinch zooming with this class, with which I want to zoom to the ScrollView's child and scroll the zoomed content as needed. Basically, I want the same behavior which the UIScrollView class of iOS has (it is a SHAME that Android does not provide any built-in zooming feature like iOS and we have to write everything from scratch). I have a ScaleGestureListener inside of my class and I update the layout dimension of the child view inside of the ScrollView, when I receive onScale events: I multiply the layout width and height with the scale factor I receive from ScaleGestureListener. What bothers me is that the ScrollView does not update its scrollbars according to its child's new dimensions. For example, if the width of the child becomes larger than the ScrollView's, it won't show a horizontal scrollbar. I call invalidate and requestLayout both on the scroll view and its child, but they failed.
In the following I give my code:
public class PinchZoomScrollView extends ScrollView{

private ScaleGestureDetector mScaleDetector;// = new ScaleGestureDetector(context, new ScaleListener());
private float mScaleFactor = 1.0f;
private float referenceTextSize;
private static final float MIN_ZOOM_AMOUNT = 1.0f;
private static final float MAX_ZOOM_AMOUNT = 2.0f;

private float refChildWidth;
private float refChildHeight;

private boolean shownForTheFirstTime = true;
//private View content;

private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    private WeakReference<PinchZoomScrollView> containerRef;

    public ScaleListener(PinchZoomScrollView container)
    {
        super();

        containerRef = new WeakReference<PinchZoomScrollView>(container);
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        mScaleFactor *= detector.getScaleFactor();

        // Don't let the object get too small or too large.
        mScaleFactor = Math.max(MIN_ZOOM_AMOUNT, Math.min(mScaleFactor, MAX_ZOOM_AMOUNT));

        //Get Child object
        View content = containerRef.get().getChildAt(0);

        if(shownForTheFirstTime)
        {
            shownForTheFirstTime = false;

            refChildWidth  = content.getWidth();
            refChildHeight = content.getHeight();
        }

        LayoutParams params = new LayoutParams(Math.round(mScaleFactor*refChildWidth), Math.round(mScaleFactor*refChildHeight));
        content.setLayoutParams(params);

        System.out.println("this.width="+containerRef.get().getWidth());
        System.out.println("content.width="+Math.round(mScaleFactor*refChildWidth));

        content.invalidate();
        content.requestLayout();

        containerRef.get().updateViewLayout(content, params);

        containerRef.get().invalidate();
        containerRef.get().requestLayout();

        return true;
    }
}

public PinchZoomScrollView(Context context)
{
    super(context);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}

public PinchZoomScrollView(Context context, AttributeSet attrs)
{
    super(context,attrs);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}

public PinchZoomScrollView(Context context, AttributeSet attrs, int defStyle)
{
    super(context,attrs,defStyle);
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener(this));
}

@Override
public boolean onTouchEvent(MotionEvent ev) {

    super.onTouchEvent(ev);

    mScaleDetector.onTouchEvent(ev);

    return true;
}

}

To take long story short, I need the ScrollView to update its scrollbars according to its child's updated size, everytime the user makes a pinching zoom in and out.
Thanks in advance

A: Here is a solution:

*

*Rather than extending ScrollView, I wrote a TwoDimensionScrollView extending FrameLayout which is a combination of ScrollView and HorizontalScrollView so that it can show both horizontal/vertical scrollbars, even if the child is scaled. Also I did not use gesture detector. Instead, I implement my own pinch-to-zoom.

*To update scroll bars, rewrite the functions below:
@Override
protected int computeVerticalScrollRange() {
    final int count = getChildCount();
    final int contentHeight = getHeight() - getPaddingBottom()
        - getPaddingTop();
    if (count == 0) {
        return contentHeight;
    }

@Override
protected int computeVerticalScrollOffset() {
    int result = Math.max(0, super.computeVerticalScrollOffset());
    return result - getScrollVerticalMin();
}
@Override
protected int computeHorizontalScrollRange() {
    final int count = getChildCount();
    final int contentWidth = getWidth() - getPaddingLeft()
        - getPaddingRight();
    if (count == 0) {
        return contentWidth;
    }

    int scrollRange = getChildAt(0).getRight();
    final int scrollX = getScrollX();
    final int overscrollRight = Math.max(0, scrollRange - contentWidth);
    if (scrollX < 0) {
        scrollRange -= scrollX;
    } else if (scrollX > overscrollRight) {
        scrollRange += scrollX - overscrollRight;
    }
    return (int) (scrollRange * mScaleFactor + getScrollHorizontalMin());
}

@Override
protected int computeHorizontalScrollOffset() {
    int result = Math.max(0, super.computeHorizontalScrollOffset());
    return result - getScrollHorizontalMin();
}
@Override
protected int computeVerticalScrollExtent() {
    return getHeight() + getScrollVerticalMin();
}

@Override
protected int computeHorizontalScrollExtent() {
    return getWidth() + getScrollHorizontalMin();
}
private int getScrollHorizontalMin() {
    if (this.getChildCount() < 1)
        return 0;
    View child = this.getChildAt(0);
    return (int) ((1 - mScaleFactor) * child.getPivotX());
}

private int getScrollVerticalMin() {
    if (this.getChildCount() < 1)
        return 0;
    View child = this.getChildAt(0);
    return (int) ((1 - mScaleFactor) * child.getPivotY());
}
private int getScrollVerticalRange() {
    int scrollRange = 0;
    if (getChildCount() > 0) {
        View child = getChildAt(0);
        scrollRange = (int) Math.max(0, child.getHeight() * mScaleFactor
                - (getHeight() - getPaddingBottom() - getPaddingTop())
                + getScrollVerticalMin());
    }
return scrollRange;
}

private int getScrollHorizontalRange() {
    int scrollRange = 0;
    if (getChildCount() > 0) {
        View child = getChildAt(0);
        scrollRange = (int) Math.max(0, child.getWidth() * mScaleFactor
                - (getWidth() - getPaddingRight() - getPaddingLeft())
                + getScrollHorizontalMin());
    }
    return scrollRange;
}

*You also need to find all code calling SpringBack() and fling(), and then set the min value for x and y using the above functions getScrollHorizontalMin() and getScrollVerticalMin() instead of 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot fetch data from Smart Bluetooth LE Device Android I am using a bluetooth LE device to connect with android app and i am able to make connection.
But after making the connection i am not able to get the callback for the updates from device.
I am not sure what i am doing wrong , so following is a part of the documentation from the manufacturer which i could not understand :-
"The oximeter supports a Display Sync command in its control point. The Display Sync command is a 2 octet message that is written to the control point. This feature can be used to synchronize the display of the oximeter with the display of the host device, which helps the operator confirm the pulse oximeter reading was received correctly."
where the 1st octet will have the value 0x61 and second octet should have a value between
5 and 25 seconds
In order to get this i did the following :-

*

*In LeScanCallback i connect the BluetoothDevice to BluetoothGattCallback

*In onServicesDiscovered i write the following line of code which i highly doubt is the
correct way of achieving it and may be that is the reason i am not getting the data from
Bluetooth Device :-
BluetoothGattCharacteristic oximeterCharacteristic =
noninService.getCharacteristic(UUID.fromString(Oximeter_characteristic_uuid));
    BluetoothGattCharacteristic noninControlPointCharacteristic =

   noninService.getCharacteristic(UUID.fromString(Nonin_control_point_characteristic_uuid));

   oximeterCharacteristic.setValue(0x61, oximeterCharacteristic.FORMAT_SINT16, 1);
    oximeterCharacteristic.setValue(15, oximeterCharacteristic.FORMAT_SINT16, 2);
    noninControlPointCharacteristic.setValue(0x61, noninControlPointCharacteristic.FORMAT_SINT16, 1);
    noninControlPointCharacteristic.setValue(15, noninControlPointCharacteristic.FORMAT_SINT16, 2);

gatt.writeCharacteristic(noninControlPointCharacteristic);
    gatt.writeCharacteristic(oximeterCharacteristic);
    gatt.setCharacteristicNotification(oximeterCharacteristic, true);
    gatt.setCharacteristicNotification(noninControlPointCharacteristic, true);

A: I am not sure how the multiple set values are going to work, but there are a couple of other things that I can point out you need to change.
You want to set your Notification alerts before you do the write. Its also not enough to just call setCharacteristicNotification, you would also need to write down the notification descriptor (you can see an example of this in the Android bluetooth examples) and wait for the callback saying that the descriptor is written to the device. Once you get the call back saying the descriptor write is successful, you can do the writes.
Once you make these changes to the code, I would advise restarting both the device and the phone, because the Android bluetooth stack tends to get into an unstable mode that does not recover unless you restart the phone.


text:
Q: Not Able to connect to Oracle Autonomous Datawarehouse Cloud using any of the way I am trying to connect to the Oracle Autonoumous Datawarehouse using JDBC Thin connections and wallet using below ways:
1. SQLDeveloper
2. Sqlcl
I am following the steps mentioned in https://docs.oracle.com/en/cloud/paas/autonomous-data-warehouse-cloud/user/connect-jdbc-thin-wallet.html#GUID-5ED3C08C-1A84-4E5A-B07A-A5114951AA9E.
I have downloaded the wallet file and modified the sqlnet.ora file and set the directory pointing to the location of wallet file also TNS_NAME variable is also set and pointing to the right directory.
I am getting "Error Message = IO Error: An existing connection was forcibly closed by the remote host, Authentication lapse 0 ms." in both the ways, by sql developer and Sqlcl.
Also there is no proxy configured in the network. So proxy configurations are not added to the configuration file.

A: Use the special connection type we setup for you, Cloud PDB.

In SQLcl, simply run

set cloudconfig c:path/to/wallet.zip

Then

show tns

To get a list of the services you can connect to.
Docs for Connecting with SQL Developer
Docs for Connecting with SQLcl
As you can see in the screenshot, for version 18.3, the connection type has been renamed to 'Cloud Wallet' and we added support for defining a HTTP Proxy for connections.
This connection type is designed for both Autonomous Data Warehouse and Autonomous Transaction Processing Oracle Cloud Services (ATP and ADW).

A: Thank you for your reply.
I tried to connect through v18.3 and used the Cloud Wallet connection type but facing the same issue mentioned above. Below is the error message we are getting.
An existing connection was forcibly closed by the remote host, Authentication lapse 0 ms.
Is there any special configuration required in the client to connect to the Oracle cloud?
We are using the client provided VPN and there is no proxy being used in our VPN.
Please have a look at the screenshot attached for more details.


text:
Q: Rellenar Atributo mapeado si la condición de atributo boolean en Entidad Padre se cumple (Hibernate) Tengo tres entidades
@Entity
Class Padre{
    //Este id puede pertenecer a 2 Fuentes
    @Basic
    @Column(name="referencia_id")
    @getter @setter private Integer referenceId;
    //Esta variable controla de que fuente viene el Id
    @Basic
    @Column(name="referencia_a")
    @getter @setter private boolean referenciaA

    @ManyToOne
    //En caso que referenciaA == true, llenar esta variable
    @getter @setter private ReferenciaA fuenteA;

   @ManyToOne
   //En cas que referenciaA == false, llenar esta variable
   @getter @setter private ReferenciaB fuenteB;

}

@Entity
//Aqui no existe referenia al Padre, no la necesito
public class ReferenciaA{
   @getter @setter private Id;
}

@Entity
//Aqui tampoco existe referencia a la entidad Padre
public class ReferenciaB{
   @getter @setter private Id;
}

El caso es que necesito obtener el objeto ReferenciaA si en el padre el atributo referenciaA es true, si referenciaA es false entonces tengo que traer llena la referenciaB.
Las soluciones que he probado son @Where y el @Filter, estas tienen la particularidad que el @Where filtra del lado de ReferenciaA o ReferenciaB pero no del lado del Padre.

A: Encontré la solución.
Con la anotación @JoinFormula puedo pasarle un SQL que me haga el join y el filtro.
 @ManyToOne
 @JoinFormula(value = "(case when referencia_a= 'true' then (select
                       a.id from esquema.fuenta_a where a.id = fuente_a_id) end)"
        ,referencedColumnName = "id")
 @getter @setter private ReferenciaA fuenteA;

 @ManyToOne

 @JoinFormula(value = "(case when referencia_a= 'false' then (select
                       b.id from esquema.fuente_b b where b.id =
 fuente_b_id) end)" ,referencedColumnName = "id")
 @getter @setter private ReferenciaB fuenteB;

De esta manera condicionamos si traer la fuenteA o la fuenteB, hay que tomar en cuenta que referencia_aes un valor booleano, el valor debemos ponerlo entre comillas, de esta manera: referencia_a = 'true',de lo contrario genera error.


text:
Q: How to make the SIZE of a pdf field dynamic I am writing to a pdf from a java servlet, and I was wondering if the size of the pdf fields are able to be resized based on the information that is dynamically received.  Here is my pdf:
This is to verify that [first_middle_last_name] is entered into......

So when I originally made the pdf I surrounded that space with tons of spaces to be able to handle large names, but now when i get a small name it just looks bad.  So is there anyway to counter this?
This doesnt seem like a programming question, but the data is written from a java servlet, and I figured there might be a way to do this in the code.  Thanks in advance.


text:
Q: Selecting a Validation Framework - ASP.NET Which validation framework would you prefer for a webforms application. This would be for a rather large complex app. I would want to specify rulesets and business validation in a single place and integrate it both on the client and server side. I'd prefer jquery for client side.
Anyone has any suggestions?

A: You can look at .NET 3.5 DataAnnotations. because it integrates well with ASP.NET, but I don't believe it supports the concepts of rule sets. Another option is Enterprise Library Validation Application Block, which supports custom rule sets, however, it will take you slightly more time to integrate that with ASP.NET. However there is online material that should give you a kick start. Here an article (written by myself) about integrating VAB with O/RM tools and here is an interesting article about integrating VAB with ASP.NET.
Good luck.

A: For web forms or MVC?  Here are the options I've seen so far:

*

*JQuery validate plugin (client side only)

*XVal: xval.codeplex.com, has client and server side components, but I think it's MVC only.  Not sure.  I do believe this integrates with teh JQuery validate plugin.

*Enterprise library validation app block - server-side only last time I checked, but great way to supply your logic.  Can supply rules in config file, as attributes on your code, or alternative stores.  You could then use JQUery validate for the front-end.  Not a single solution for client/server.

*Standard ASP.NET validators, which does work client and server side.  Both ASP.NET and MVC have implementations as you probably now.

A: For WebForms, the standard validators provide a good base, if you use jQuery, you can replicate the asp.net validation checks quite easily and react accordingly, ie replace and provide better feedback to the user than the Validation Summary control.
for instance you can find the validation controls using jquery, validate and get the control-to-validate to target, this will help in getting error messages, change form field classes etc.


text: Q: Not save the user in the storage with react-native-google-signin Is it possible with this library to get only the id and not to save the user in the storage? I need only the google id of the user who logged in and then pass it to my back end.


text:
Q: How to update value in multiple documents searching by id's in PyMongo MongoDB I'm trying to update multiple documents searching by id's
I already tried like this:
users = await user_collection.update_many(
    {"_id": {"$in": users_id}}, {"$push": {
                    "assigned_buildings": building_id
                }}

MongoDB returns ok but none of documents are updated.
When I'm adding ObjectId:
users = await user_collection.update_many(
    {"_id": {"$in": ObjectId(users_id)}}, {"$push": {
                    "assigned_buildings": building_id
                }}
)

MongoDB returns id must be an instance of (bytes, str, ObjectId), not <class 'list'>

A: As a workaround I made it like this but I'm still looking for more sophisticated way:
updated_users_id = []
for user_id in users_id:
    updated_users_id.append(ObjectId(user_id))

users = await user_collection.update_many(
    {"_id": {"$in": updated_users_id}}, {"$push": {
                    "assigned_buildings": building_id
                }}
)


text:
Q: Magento 2: RuntimeException it is being used by another process When I do clear cache using command line & refresh page on Frontend 1st time it gives below exception.

1 exception(s): Exception #0 (RuntimeException): The path
  "D:/wamp/www/magento2/var/generation/Magento/Checkout/Model/Session/Interceptor.php.6260"
  cannot be renamed into
  "D:/wamp/www/magento2/var/generation/Magento/Checkout/Model/Session/Interceptor.php"
  Warning!rename(D:/wamp/www/magento2/var/generation/Magento/Checkout/Model/Session/Interceptor.php.6260,D:/wamp/www/magento2/var/generation/Magento/Checkout/Model/Session/Interceptor.php):
  The process cannot access the file because it is being used by another
  process. (code: 32)

When i refresh same page again/2nd time it loads page proper. What will be cause for above exception?

A: My best guess is that while the setup:di:compile compilation process is running and Magento is processing requests (e.g. tries to bootstrap), this exception might appear.
Suggestion:

*

*enable maintenance mode

*stop cron processing

*deploy your changes (run compilation, static content deploy, etc)

From my perspective this is not a bug, but imperfect deploy process.
I will try to update the answer if I found out any more details.

A: Improper deployment process leads to this kind of error, just remove all the files from var/generation folder and run a setup:upgrade command, this issue must be resolved after this.This works for me.

A: try to remove everything from var/generation folder, and execute that commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
if you still get the error please check var/exception.log for more informations


text:
Q: Pass arguments to callr::r() background process and access them within? R code can be run in a background process like so
callr::r(function(){ 2 * 2 })
# [1] 4

When I attempt this with args I can't figure out how to access them. I tried a few obvious things:
callr::r(function(){ 2 * 2 }, args = list(x=3))

callr::r(function(){ 2 * x }, args = list(x=3))

callr::r(function(){ 2 * args$x }, args = list(x=3))

callr::r(function(){
  args <- commandArgs()
  2 * args$x
  },
  args = list(x=3))

# Error: callr subprocess failed: unused argument (x = base::quote(3))
# Type .Last.error.trace to see where the error occurred

I also tried to debug using browser() but in this case it didn't work in the usual way.
Question
How can arguments be passed to a background process invoked with callr::r() and those arguments be accessed within the background process?

A: You have to move the argument inside both the list of args and inside function(), like so:
callr::r(function(x){ 2 * x }, args = list(x = 3))
# [1] 6

Or like this:
x <- 3
callr::r(function(x){ 2 * x }, args = list(x))
# [1] 6

Same idea for multiple arguments:
x <- 3
y <- 4
z <- 5

callr::r(function(x, y, z) { 2 * x * y * z }, args = list(x, y, z))
# [1] 120

Source: here


text:
Q: Install parent POM without building Child modules I have a parent POM in a Maven project, with this structure:
             parent
               |
        ---------------
        |             |
      child1       child2

I want to install the POM of the "parent" in the local REPO to allow child1 take some changes that I did in the dependencyManagement, but I cannot do a regular "clean install" because "child2" is broken and will not build.
Which is the proper way to do this with maven (other than going to the parent pom and commenting the "child2" module).

A: While Guillaume is indeed right and that is the correct option, I would personally recommend keeping your parent as a separate module.
I find the best approach for inheritance to be as follows:
aggregator
|- module1/ (extends parent)
| |- pom.xml
|- module2/ (extends parent)
| |- pom.xml
|- parent/
| |- pom.xml
|- pom.xml

This way you can always install the parent only, with mvn clean install without extra options.
You can also have the parent outside the aggregator so you can re-use it between more projects.
There are numerous benefits to keeping the parent and the aggregator as two separate things. But in the end, you choose what's best for your project/environment.

A: Use the '-N' option in the mvn command.
From mvn -h:

-N,--non-recursive                     Do not recurse into sub-projects


text:
Q: how to show comment in presto after creating a table? I created a table like below with some comment
CREATE TABLE some_catalog.some_schema.tmp (
  address VARCHAR COMMENT 'address',
  name VARCHAR COMMENT 'name'
)
COMMENT 'some comment'
;

How could users find the comment when they make a query, describe does NOT show it?
>describe somme_catalog.some_schema.tmp;
presto> describe somme_catalog.somme_schema.tmp;
 Column  |  Type   | Extra | Comment
---------+---------+-------+---------
 address | varchar |       | address
 name    | varchar |       | name
(2 rows)

Also, what is the Extra column for?
I'm using https://prestosql.io/

A: Just write: SHOW CREATE TABLE some_catalog.some_schema.tmp
This will show you pretty much the same command you wrote when creating the table, so you will be able to see the comment as well.


text:
Q: SwiftUI Tabview inside TabView and List items highlight behaviour strange? I am new in Swift, please help me a hand
The first question is Can use TabView inside a TabView?
If it can be, I got an issue related to List, items inside List is highlighted when I tap into another place
// This tab will have many pages and can swap left/right to change tabs
struct Tab1: View {
    var body: some View {
        TabView(selection: $otherSelected) {
            SubOfTab1()
                .tag("tag1")

            ... other tabs
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
}

// This tabview will display tab item as bottom
struct ContentView: View {
    var body: some View {
        TabView(selection: $selected) {
            var body: some View {
                Tab1()
                    .tag("tagParent1")

                ... other tabs
            }
        }
    }
}

struct SubOfTab1: View {
    VStack {
        Text("Try to tab this text")   ------> Try to tab this and all list items below is hightlighted??? why???
            .frame(height: 100)

        List() {
            Text("XX")
            Text("XX")
            Text("XX")
            Text("XX")
            ...
        }
    }
}

First run

Tapped to the text above, all items in List are highlighted??

A: I had similar issue with List of .plain style inside a TabView, tapping outside list resulted to selection all visible list items.
Setting .listRowBackground() of list cell fixed it.
In your case:
List() {
        Text("XX")
            .listRowBackground(Color.black)
        Text("XX")
            .listRowBackground(Color.black)
        Text("XX")
            .listRowBackground(Color.black)
        Text("XX")
            .listRowBackground(Color.black)
        ...
}


text:
Q: dynamically add top in css? Is there a way to dynamically add top in css/less? I have the following structure:
.a2a-desktop-right {
    right: 0px;

    .a2a_svg {
        position: absolute;
        right: 8px;
    }
}

.a2a_svg has some animation effects on hover and needs to be absolutely positioned, however there can be n-types of this element. Each one needs a top of 40px more than the previous. Any way to accomplish this without js?
EDIT
I can't define the style inline - it's a 3rd party script that generates these elements. That's also why javascript is out of the question - I won't know when the elements are rendered, and if I did it would still take time for the new styles to be applied.

A: I managed to find a way to do it with less after seeing the below by edwinnwebb.
/* Define two variables as the loop limits */
@from : 0;
@to : 10;

/* Create a Parametric mixin and add a guard operation */
.loop(@index) when(@index =< @to) {

/* As the mixin is called CSS is outputted */
div:nth-child(@{index}) {
    top: unit(@index * 100, px);
}

/* Interation call and operation */
.loop(@index + 1);
}

/* the mixin is called, css outputted and iterations called */
.loop(@from);

/*

## Output

div:nth-child(0) {
    top: 0px;
}
div:nth-child(1) {
    top: 100px;
}
div:nth-child(2) {
    top: 200px;
}
div:nth-child(3) {
    top: 300px;
}
div:nth-child(4) {
    top: 400px;
}
div:nth-child(5) {
    top: 500px;
}
div:nth-child(6) {
    top: 600px;
}
div:nth-child(7) {
    top: 700px;
}
div:nth-child(8) {
    top: 800px;
}
div:nth-child(9) {
    top: 900px;
}
div:nth-child(10) {
    top: 1000px;
}

*/

Applied to my problem becomes...
@iterations: 0;

.svg-loop (@iterations) when (@iterations =< 5) {
    .a2a-button.a2a-desktop-right:nth-of-type(@{iterations}) {
        .a2a_svg{
            top: unit((@iterations * 40) - 33, px);
        }
    }

    .svg-loop(@iterations + 1);
}


text:
Q: In python, for imports is there a simple way to use the more common pathing syntax provided by most OS tools, PYcharm, etc? Hi there I'm a former C# dev here switching over to python for a new project that we hope to incorporate machine learning into, thus python since tensorflow is the gold standard and it was first released in python.
I was just starting out writing my first few files and it's really interesting that the pathing for directories in python uses all dots. I'm not very used to that syntax and I was quite surprised python chose to change this from the more conventional slashes.
So for example in Python I find myself writing:
from package1.subpackage2.subpackage3.subpackage4.module5 import function6

and for every import I have to replicate that syntax?
It seems strange given the industry in general always uses slashes to denote paths. This winds up with dozens and dozens of tools not quite giving me something I can quickly iterate on. The OS in windows gives slashes, the OS in mac has multiple ways to copy path and they both also give slashes even though mac comes with python installed by default! Even when calling through file paths from a webserver or API you use slashes like so:
https://stackoverflow.com/questions/ask
or
F:\Google\Chrome\Application\38.0.2125.111\Locales
What is really crazy is, given this python specific IDE called PYCharm which I am just now learning, even it's paths when you select files and choose to copy paths comes to the clipboard using slashes! What gives?! Certainly the people building python specific IDEs would realize that syntax is not valid for imports and set it up so developers could use something that matches the way we have to write them.
So I've dug in and searched through stackoverflow and the broader web in general looking for a solution, but I don't see anything simple out there. Even the python docs don't mention a more appropriate approach! I'm hoping I am just missing something. Is there a tool that gives me the paths correctly for python?  Or were the python devs able to see this being an issue and maybe they set up an escape character I can use to easily format the slash paths that are common from all the other tools into my imports?

A: If you're using pycharm, then it's very easy to use tab-expansion to build your import paths, or pycharm's recommendation is to use the auto-import features. Those are the more appropriate approaches. Either of these should be a lot faster than copy-pasting a file path and then replacing slashes manually. And in fact you shouldn't be copy-pasting file paths and modifying them to become imports anyway.
More on pycharm's auto-imports:
https://www.jetbrains.com/help/pycharm/creating-and-optimizing-imports.html
The key here is that packages and directories are not always the same thing. For instance, using an __init__.py you can define additional variables at the package-level that do not exist anywhere else in the files/directories of your project, or you can move functions defined at the package level up to the module level via the same mechanism. And if you're using tensorflow in Python then there should be no need to convert from slashes to dots, as any example you'll find is going to use dots for its imports.
Remember, when you import, you are not truly dealing with paths. You are dealing with packages and modules that may resolve to a valid path, but may not. And since everything involving actual file paths uses slashes, of course copy-pasting a path isn't going to convert that path to dots.

A: Nope, anytime you need to use a simple path to a file through other directories you'll use the dots in python it's pretty tedious at first but you'll get used to it.


text:
Q: Setting onclick function to
* element I am trying to dynamically add onclick function to "li" tagged elements.
But the event does not fires.
Here is my code:
var arrSideNavButtons = [];
var sideNavLi = document.getElementsByClassName('side-nav')[0].getElementsByTagName('li');
var arrayOfSceneAudios = [scene1Audio, scene2Audio,...];

for (var i = 0; i < sideNavLi.length; i++) {
    sideNavLi[i].onclick = function() {
        arrayOfSceneAudios[i].play();
    }
    arrSideNavButtons.push(sideNavLi[i]);
}

Is it possible to code it this way?
If yes, what is my mistake?
Thanks a lot.

A: Wrap your onclick handler in a closure, else it only get assigned to the last elem in the loop:
for (var i = 0; i < sideNavLi.length; i++) {
    (function(i) {
        sideNavLi[i].onclick = function() {
            arrayOfSceneAudios[i].play();
        }
        arrSideNavButtons.push(sideNavLi[i]);
    })(i)
}

A: I think it's better to reuse one single function, instead of creating a new one at each iteration:
var arrSideNavButtons = [],
    sideNavLi = document.getElementsByClassName('side-nav')[0].getElementsByTagName('li'),
    arrayOfSceneAudios = [scene1Audio, scene2Audio,...],
    handler = function() {
        this.sceneAudio.play();
    };

for (var i = 0; i < sideNavLi.length; i++) {
    sideNavLi[i].sceneAudio = arrayOfSceneAudios[i];
    sideNavLi[i].onclick = handler;
    arrSideNavButtons.push(sideNavLi[i]);
}


text:
Q: RecentlyViewed not working for Account for portal user recentlviewed not working for Account for portal user
listRecent = [SELECT Id, Name,Type FROM RecentlyViewed WHERE type   IN('Contact','Account','Opportunity','Lead') and LastViewedDate !=null    ORDER BY LastViewedDate DESC  LIMIT 7 ];

query returns value for other object in portal but not for account


text:
Q: Firebase Firestore auth token infinite loop after signing in
*

*When the app is connected to Firestore and a user is signed in (in our app), an auth token infinite loop appears.

*Without Firestore connection, this effect doesn't occur.

*You can see the issue on the GIF file included herein as the link (see below).

*Interestingly, this problem is present only when the project runs on Linux Mint (19.1 Cinnamon) in contrast to Windows 10 or 8.1 (I didn't run it on Mac).

*The project was bootstrapped with Create React App.

Video-presentation of the issue
I integrated Firebase with ReactJS with this tutorial: https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial
and found very useful the class-based Firebase connection and HOC/Context API session handling presented therein. However, I have no idea how to fix this auth token infinite loop.
Below, there are files responsible for signing in/out and Firebase connection, as well as package.json:
index.js:
import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import * as serviceWorker from './serviceWorker';

import App from './App';
import Firebase, { FirebaseContext } from './components/Firebase';

ReactDOM.render(
  <FirebaseContext.Provider value={new Firebase()}>
    <App />
  </FirebaseContext.Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();

App.js:
import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom';

import Navigation from './components/Navigation';
import LandingPage from './components/LandingPage';
import SignInPage from './components/SignInPage';
import HomePage from './components/HomePage';
import HomePage2 from './components/HomePage2';

import { withAuthentication } from './components/Session';
import * as ROUTES from './components/constants/routes';

const App = () => (
  <Router>
    <Navigation />
    <hr />
    <Switch>
      <Route exact path={ROUTES.LANDING} component={LandingPage} />
      <Route path={ROUTES.SIGN_IN} component={SignInPage} />
      <Route path={ROUTES.HOME} component={HomePage} />
      <Route path={ROUTES.HOME2} component={HomePage2} />
    </Switch>
  </Router>
);

export default withAuthentication(App);

Firebase / context.js:
import React, { createContext } from 'react';

const FirebaseContext = createContext(null);

export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    {firebase => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);
export default FirebaseContext;

Firebase / firebase.js:
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

const config = {
  apiKey: process.env.REACT_APP_API_KEY,
  authDomain: process.env.REACT_APP_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_DATABASE_URL,
  projectId: process.env.REACT_APP_PROJECT_ID,
  storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_ID
};

class Firebase {
  constructor() {
    app.initializeApp(config);
    this.auth = app.auth();
    this.db = app.firestore();
  }
  // Auth API
  doSignInWithEmailAndPassword = (email, password) => this.auth.signInWithEmailAndPassword(email, password);
  doSignOut = () => this.auth.signOut();
}

export default Firebase;

Firebase / index.js:
import FirebaseContext, { withFirebase } from './context';
import Firebase from './firebase';

export default Firebase;
export { FirebaseContext, withFirebase };

Session / context.js:
import { createContext } from 'react';

const AuthUserContext = createContext(null);

export default AuthUserContext;

Session / index.js:
import AuthUserContext from './context';
import withAuthentication from './withAuthentication';
import withAuthorization from './withAuthorization';

export { AuthUserContext, withAuthentication, withAuthorization };

Session / withAuthentication.js:
import React, { useState, useEffect } from 'react';

import AuthUserContext from './context';
import { withFirebase } from '../Firebase';

const withAuthentication = Component => {
  const WithAuthentication = (props) => {
    const [authUser, setAuthUser] = useState(null);
    useEffect(() => {
      const listener = props.firebase.auth.onAuthStateChanged(authUser => {
        authUser
          ? setAuthUser(authUser)
          : setAuthUser(null);
      });
      return () => listener();
    }, []);
    return (
      <AuthUserContext.Provider value={authUser}>
        <Component {...props} />
      </AuthUserContext.Provider>
    );
  };

  return withFirebase(WithAuthentication);
};

export default withAuthentication;

Session / withAuthorization.js:
import React, { useEffect } from 'react';

import AuthUserContext from './context';
import { withFirebase } from '../Firebase';
import * as ROUTES from '../constants/routes';

const withAuthorization = (Component) => {
  const WithAuthorization = (props) => {
    useEffect(() => {
      const listener = props.firebase.auth.onAuthStateChanged(
        authUser => {
          if (!authUser) {
            props.history.push(ROUTES.SIGN_IN);
          }
        }
      );
      return () => listener();
    }, []);
    return (
      <AuthUserContext.Consumer>
        {authUser => !!authUser && <Component {...props} />}
      </AuthUserContext.Consumer>
    );
  };

  return withFirebase(WithAuthorization);
};

export default withAuthorization;

package.json:
{
  "name": "react-firebase-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "firebase": "^7.14.5",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1",
    "recompose": "^0.30.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "dotenv": "^8.2.0"
  }
}


text:
Q: How do I read configuration data (DB credentials) in a PHP web role in azure? I want that PHP/Drupal reads configuration settings which are stored in my CSCFG file and in my cloud service instance respectively.
How do I read configuration data (DB credentials) in a PHP web role in azure? I need them to access my database.
I have my DB credentials in two places

*

*my azure account

*(possibly) in my cscfg file

In my PHP script I want to get this data, so that my CSPKG files don't need to contain credentials. Example:
$db_host = azure_getconfig("DbHost");
$db_user = azure_getconfig("DbUser");
$db_password = azure_getconfig("DbPassword");

Is there a standard way how to do this?
About php_azure.dll: The approach that is usually described did not work for me. The suggested php extension php_azure.dll seems to be abandonded as it is marked as obsolete. I tried to load the extensions in all it's flavors but didn't succeed ("Unable to load dynamic library 'D:\Program Files (x86)\PHP\v5.3\ext\php_azure.dll' - The specified module could not be found.", even though the file exists for sure at the right path.).
So I assume, I shouldn't use php_azure.dll anyway.
There is a similar but unanswered question here:
How can I access ConfigurationSettings using a PHP Cloud Service on Windows Azure?


text:
Q: How to convert a date of any language to a specific language How to convert a date of any language(Arabic) to a specific language(English).
While changing the region format to arabic, the dates are getting changed. When I am picking the date value from some controls(UIButtons or UILabels) for saving in database, its picking the date in arabic language and saving in the same format. Here I want to convert the date from arabic to english before saving it in database.
I tried this but its returning nil
NSDate *currentDate = //My date coming like  "٢٠١٤-٠٥-١٥ ١٢:١٠:٢٣ "
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale: usLocale];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:s a"];
NSString *formattedDate = [formatter stringFromDate: currentDate];

Can anyone please help me ?

A: You shouldn't store dates in any language. You should store NSDate, which has no language or locale or time zone, and display it as appropriate. If your database cannot store NSDate, you can store [myDate timeIntervalSince1970] and convert it to an NSDate using the class method dateWithTimeIntervalSince1970:

A: I solved in this way
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:s"];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:usLocale];
    NSString *dateString = [dateFormatter stringFromDate:myDate];

A: You should use UIDatePicker as the input instead of UIButtons or UILabels. Save the timeIntervalSince1970 into your database, so that it can be presented by any language.
NSDate *currentDate = //My date coming like  "٢٠١٤-٠٥-١٥ ١٢:١٠:٢٣ "
NSTimeInterval timeToBeSavedInDatabase = [currentDate timeIntervalSince1970];
//in the future, you can show this date in any language
NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970]];

A: You may use this to get the date with preferred local
 NSDate * dateNow = [NSDate new];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

[dateFormat setLocale: usLocale];

[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSString *   dateString = [dateFormat stringFromDate:dateNow];


text:
Q: Difference between 5.5.43-enterprise-commercial-advanced-log and 5.5.43-log version of mysql? Is there any difference in below two version of mysql if yes then what are the differences? any reference would be helpful.
As both version is same but the licence type is different -
5.5.43-enterprise-commercial-advanced-log
MySQL Enterprise Server - Advanced Edition (Commercial)
5.5.43-log
MySQL Community Server (GPL)

A: Well, you could have simply checked out mysql's website on the different products. To see the difference between community edition and any commercial editions, see items marked with 1 in the feature list.

A: Both are different version as first one is Enterprise version whereas second one commercial version.
Reason for showing -log at the end is showing because any one of the below logs were enabled by default, which caused the "-log" available while fetching the version information using below query.
Binary log
Slow log
General query log
if -log is not showing then enable any one log from the above and restart the database will fix the issue.
SHOW VARIABLES LIKE "%version%";
Cheers,
Suraj


text:
Q: How can I pass structs from an Actix middleware to the handler? I'm trying to write an authentication middleware for my Actix application. When validating the request in the middleware, I make a call to a database to retrieve the necessary user data to validate the incoming request. Once the request has been authorised, I want to be able to pass this user data to the handler as this will allow me to avoid having the query for the same data twice.
I can't find a solution for this. The best suggestion I could find so far was to "set a request extension". There doesn't seem to be any examples for this and there is also too little documentation around this to work out what to do here.

A: You can pass data from middleware (service) to handler via extensions. First of all you have to insert extension (in service).
For ServiceRequest struct is implemented HttpMessage witch hase extensions_mut() function. It must be mutable becouse you will be inserting new extension.  It might look something like this:
req.extensions_mut().insert(user);

Then you have to implement FromRequest trait for your data structure.
impl FromRequest for User {
    type Error = actix_web::Error;
    type Future = futures::future::Ready<Result<Self, Self::Error>>;
    type Config = ();

    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
        match req.extensions().get::<User>() {
            Some(user) => return ok(user.clone()),
            None => return err(actix_web::error::ErrorBadRequest("ups..."))
        };
    }

}

Then you're ready to use it in handler.
pub async fn get_user_handler(user: User) {}


text:
Q: rename files matching specific mtime value within directory I use simple set of shell commands to in order to create mysqldumps daily. The script is called by cron daemon. It looks like:
presentdate="`date +%d-%m-%Y_%H:%M.%S`"
basedir="/var/db_my_backup"
mysqldump -u username -ppassword --all-databases |
  gzip -9 -c > $basedir/mysqlbackup.$presentdate.sql.gz |
  find -L $basedir/'*' -type f -mtime +7 exec rm -f {} \; |
  chown -R user:group $basedir | (
    cat <<EOF
Copy of MySQL successfully placed in $basedir directory as file named mysqlbackup.$presentdate.sql.gz.
Now it is ready to be moved to QNAP backup device as scheduled.
EOF
    cat
  ) | /bin/mail -s "Report from scheduled job for mysqldumps" root

My concern is: how can I possibly make it more elegant? Would it be possible to build a function for selecting and renaming files that are older than 7 days? I don't like using find as it produces strange warnings like for example:
find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression]

that are hard to deal with (at least for me) in such a script.

A: Your method of deleting old backups is fine, and in my opinion better than renaming files. The ugliest thing about it is the long chain of pipes, which serve little purpose in your example but make the line too long. I would write it using a block of { ... } like this:
presentdate="`date +%d-%m-%Y_%H:%M.%S`"
basedir="/var/db_my_backup"
{
mysqldump -u username -ppassword --all-databases | gzip -9 -c > $basedir/mysqlbackup.$presentdate.sql.gz
find -L $basedir/'*' -type f -mtime +7 -exec rm -v {} \;
chown -vR user:group $basedir
cat <<EOF
Copy of MySQL successfully placed in $basedir directory as file named mysqlbackup.$presentdate.sql.gz.
Now it is ready to be moved to QNAP backup device as scheduled.
EOF
} 2>&1 | /bin/mail -s "Report from scheduled job for mysqldumps" root

The 2>&1 near the end is to include error output in the email, you can remove it if you don't want that. I also added some -v flags for more verbosity.
As a commentor put it, find does not give strange errors if you use it correctly. There was a mistake in your parameters to find, using exec instead of -exec. To get the parameters right play with it for a bit, while reading up on man find.


text:
Q: Move snap's multi-GB subdir "/var/lib/snapd/snaps" to different partition, then symlink to it? I have "only" a 64 Gigabyte root partition, /, hence implicitly the /var dir is on this partition, and so is  snap's multi-GB subdir /var/lib/snapd/snaps . Snap stores the snap images in this directory. This takes quite some disk space.
I have freshly installed these snaps: boxy-svg, core, core18, core20, core22, eclipse, fx, gnome-3-34-1804, gnome-3-38-2004, go, gtk-common-themes, inkscape, minizinc, postman, powershell, rustup, slack, snapd, tidy, youtube-dl, zoom-client, and they already need 2,7G for a single-instance install. For backups this will increase to 10 GB quickly, because snap stores images of the 2 previous images too, in the long run.
I want to move these 10 GB on /var/lib/snapd/snaps to a different partition, on a different SSD. How can I do that properly?
I've tried by

*

*just by stopping snapd with sysctl,

*move /var/lib/snapd/snaps
to a different partition

*symlinking to that partition ln -s  /mnt/big-disk/snaps /var/lib/snapd/snaps
1, restart snapd

However, this construct does not "survive" reboots (snaps cannot be mounted during startup), and also the snaps cannot be updated easily. As a workaround I've tried scripting commands such as
mount /var/lib/snapd/snaps/inkscape_10426.snap           /snap/inkscape/10426
(with /var/lib/snapd/snaps/ being a symlink),
but these are a nightmare to maintain, because the release ids such as 10426 always change.


text:
Q: how to write a t-sql master procedure to catch sub procedures raised error I am new to T-SQL programming. I need to write a main procedures with 5 different sub procedures in it. How could i structure the program so that subprograms will not abort.  Instead, they will capture errors and report them back to the main program in the output parameters. Please provide me with pseudo code if you can. Thanks.

A: something like that BEGIN TRANSACTION represents a point at which the data referenced by a connection is logically and physically consistent.
COMMIT TRANSACTION makes all data modifications performed since the start of the transaction a permanent part of the database, frees the resources held by the transaction, and decrements @@TRANCOUNT to 0. If @@TRANCOUNT is greater than 1, COMMIT TRANSACTION decrements @@TRANCOUNT only by 1 and the transaction stays active.
ROLLBACK TRANSACTION to erase all data modifications made from the start of the transaction or to a savepoint. It also frees resources held by the transaction.
ERROR_NUMBER() returns the number of the error.
ERROR_SEVERITY() returns the severity.
ERROR_STATE() returns the error state number.
ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
ERROR_LINE() returns the line number inside the routine that caused the error.
ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
-- try block will start
        BEGIN TRY

          BEGIN TRANSACTION TranName
            EXECUTE usp_First;
        -- if sub procedure have some parameter then we can pass
            EXECUTE usp_Second param1, param2;
            .
            .
            EXECUTE usp_Fifth;
         COMMIT TRANSACTION TranName

        END TRY
        -- if soemthing goes wrong then catch
        BEGIN CATCH
          IF (@@TRANCOUNT > 0)
           BEGIN
              ROLLBACK TRANSACTION TranName
           END
           -- get error detail
            SELECT
                ERROR_NUMBER() AS ErrorNumber,
                ERROR_SEVERITY() AS ErrorSeverity,
                ERROR_STATE() AS ErrorState,
                ERROR_PROCEDURE() AS ErrorProcedure,
                ERROR_LINE() AS ErrorLine,
                ERROR_MESSAGE() AS ErrorMessage
        END CATCH

for more information https://msdn.microsoft.com/en-IN/library/ms175976.aspx


text:
Q: How to completely black out background on Android dialog? I am showing an Activity with dialog theme (android:theme="@android:style/Theme.Dialog")
When I pop up this activity, I want to completely blacken out the background activity. Currently, the activity underneath has too much clutter, and even though it is blurred, it is still too visible.
Thanks.

A: Try this:
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.dimAmount=1.0f;
dialog.getWindow().setAttributes(lp);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

A: make a file style.xml and put this xml code
<style name="blackDialog" parent="android:style/Theme.Dialog" >
        <item name="android:background">@null</item>
</style>

In your manifest file add android:theme="@style/AppTheme" attribute in your activity
<activity android:theme="@style/blackDialog"
      android:name=".Activity2"
      android:label="@string/title" />


text:
Q: TypeAdapter in Hive Flutter How to register multiple TypeAdapter in Flutter Hive?
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();

  if (!Hive.isAdapterRegistered(ModelOneAdapter().typeId)) {
    Hive.registerAdapter(ModelOneAdapter());
  }

  if (!Hive.isAdapterRegistered(ModelTwoAdapter().typeId)) {
    Hive.registerAdapter(ModelTwoAdapter());
  }

  runApp(const MyApp());
}

This is my code and I can't register the second one.
ModelTwoAdapter()


text:
Q: Find mean of a column for every 1000000 count in R I have a dataframe which has the following structure with two columns data1 and data2. Below is the sample data:
data1       data2
800000    1
800030    0.956521739130435
1000000   0.480916030534351
1686626   0.496
1687492   0.174757281553398
2148463   0.0344827586206897
2850823   0.05
2959087   0.0416666666666667

I would like to calculate the mean of second row i.e. data2 for every 1000000 count in data1.
which means it should give the mean for first 2 rows then for next 3 rows and then for the next 3 rows and so on...
The output should be a dataframe with last value within the interval 1000000 and the mean value of data2 in that interval: Sample output is shown below:
 800030  0.97826087
 1687492 0.38389110
 2959087 0.04204981

Could some help to do this in R?

A: Assuming your data is in data.frame DF , you can use aggregate function to do this
> with(DF, aggregate(data2, by=list((data1+0.01)%/%1000000), mean ))
  Group.1          x
1       0 0.97826087
2       1 0.38389110
3       2 0.04204981

To get the values in column over which mean was calculated, you will have to use aggregate again - this time on data1 column itself. After that you can merge two resultant dataframes.
res <- with(DF, merge(aggregate(data1, by = list((data1 + 0.01)%/%1e+06), paste), aggregate(data2, by = list((data1 + 0.01)%/%1e+06), mean), by = "Group.1"))
names(res) <- c("Group", "Values", "Mean")
res
##   Group                    Values       Mean
## 1     0            800000, 800030 0.97826087
## 2     1 1000000, 1686626, 1687492 0.38389110
## 3     2 2148463, 2850823, 2959087 0.04204981

A: You can do something like this :
group <- cut(df$data1, c(0,1000000,2000000,3000000))
tapply(df$data2, group, mean)
# (0,1e+06] (1e+06,2e+06] (2e+06,3e+06]
# 0.81247926    0.33537864    0.04204981

EDIT : To automatically compute the breaks in seq, you can replace c(0,1000000,2000000,3000000) with something like :
c(seq(0, max(df$data1), by=1000000),max(df$data1))

EDIT 2 : The following, using ddplyfrom plyr, will return both mean and max in a data frame :
group <- cut(df$data1, c(seq(0, max(df$data1), by=1000000),max(df$data1)))
ddply(df, .(group), summarize, mean=mean(data2), max=max(data2))
#              group       mean   max
# 1        (0,1e+06] 0.81247926 1.000
# 2    (1e+06,2e+06] 0.33537864 0.496
# 3 (2e+06,2.96e+06] 0.04204981 0.050

A: For the sake of diversity, here's another solution using split:
sapply(split(df,df$data1%/%1e6), function(x)mean(x$data2))
         0          1          2
0.97826087 0.38389110 0.04204981

Edit: or even simpler:
sapply(split(df$data2,df$data1%/%1e6), mean)

A: For the sake of completeness, I would like to propose a solution in the
tidyverse universe
library(tidyverse)

df <- tribble(
~data1,   ~data2,
800000,    1,
800030,    0.956521739130435,
1000000,   0.480916030534351,
1686626,   0.496,
1687492,   0.174757281553398,
2148463,   0.0344827586206897,
2850823,   0.05,
2959087,   0.0416666666666667)

df |>
  mutate(group= data1 %/% 1000000) |>
  group_by(group) |>
  summarize(max_in_group = max(data1), mean_data2 = mean(data2), n_in_group = n())
#> # A tibble: 3 x 4
#>   group max_in_group mean_data2 n_in_group
#>   <dbl>        <dbl>      <dbl>      <int>
#> 1     0       800030     0.978           2
#> 2     1      1687492     0.384           3
#> 3     2      2959087     0.0420          3

Although it seems not all decimals are printed, it is only an output format
of dplyr. All decimals are computed as shown below
df |>
  mutate(group= data1 %/% 1000000) |>
  group_by(group) |>
  summarize(max_in_group = max(data1), mean_data2 = mean(data2), n_in_group = n()) |>
  pull(mean_data2)
#> [1] 0.97826087 0.38389110 0.04204981

Created on 2022-03-05 by the reprex package (v2.0.1)


text:
Q: Force image size on WP custom field I want to force the images smaller to the width="128px" height="78px". They are being pulled in with Wordpress custom field.
HTML
     <?php $description = get_post_meta($post->ID, "project-thumb", $single = true);
if($description !== '') { echo $description; } ?>

For working example:
Rollover to the right of the screen, (need JS enabled)and notice the oversized image
http://www.warface.co.uk/clients/warface.co.uk/the-london-police

A: Have you tried calling the image by its URL and running it through the free timthumb script?
Tutorial: http://c.hadcoleman.com/2008/06/adding-timthumb-to-your-wordpress-theme/


text:
Q: How to force tesseract to read left to right, Python I have a barchart which I would like to extract the data points from.

However, when tesseract reads the image, it is reading left to right AND top to bottom. From my output, you can see that bars with the same height are read in the left to right order:
60.8
58.8 58.8
58.1
56.9 56.8
54.6 547
51.8 52.2
51:3
48.7

Jul 2019 Oct 2019 Jan 2020 Apr 2020

I do not want bars of the same height to be read at the same time. instead, I want tesseract to read only left to right (instead of the additional top to bottom it seems to be doing).
I read in another post that the image should be transposed to achieve this, but if I do that, tesseract seems to have trouble reading the transposed image.
Any insight you have would be helpful. Thanks
from PIL import Image, ImageEnhance, ImageFilter
#from pytesseract import image_to_string
import pytesseract
import cv2

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
from pytesseract import image_to_string
im = Image.open(r'C:\Users\Root\im.png')
print(im)

#Resizing and Transposing
new_size = tuple(6*y for y in im.size)
im = im.resize(new_size, Image.ANTIALIAS)
im  = im.transpose(Image.ROTATE_90)
im.save(r'C:\Users\Root\test.png', 'PNG')

#Grayscale for enhanced reading quality
im = cv2.imread(r'C:\Users\Root\test.png')
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print(image_to_string(gray, lang='eng'))

A: This is unfortunately not the most portable solution, but if you are going to have a lot of bar graphs that look like this, you can slice the image into pieces for each bar, left to right, and run the OCR on each slice separately:
width, height = im.size
numBars = 12
bottomLabelHeight = 100
leftOffset = 10
rightOffset = 20
barWidth = (width - leftOffset - rightOffset) // numBars
for i in range(leftOffset + barWidth, width - rightOffset, barWidth):
    left = i - barWidth
    right = i
    top = 0
    bottom = height - bottomLabelHeight
    bar = im.crop((left, top, right, bottom)).convert('L') # Convert to grayscale
    # bar.show() # uncomment to show bar for testing

    # Need digits whitelist for OCR to work properly
    value = image_to_string(bar, lang='eng',
        config='--psm 10 --oem 3 -c tessedit_char_whitelist=.0123456789')
    print(value)

    # Read label for bar
    top = height - bottomLabelHeight
    bottom = height
    label = im.crop((left, top, right, bottom)).convert('L')
    print(image_to_string(label, lang='eng'))

Output:
60.8

58.1
Jul 2019
58.8

56.9

51.8
Oct 2019
54.6

56.8

58.8
Jan 2020
54.2

51.3

52.2
Apr 2020
48.7


text:
Q: Remove "[ ]" from a column in a pyspark dataframe I need to remove the brackes '[', ']' from a column in a pyspark data frame and keep the data inside it.
The data frame looks like this -
+--------+---------------+-------+------------+
|  app_Id|         doc_id|doc_typ|        date|
+--------+---------------+-------+------------+
|12000015|FASWI4EVPPOPPYS|   SPEC|[2007-12-06]|
|12000022|FA33AVYGPPOPPYS|   ABST|[2007-12-07]|
|12000038|FA3WODYZPPOPPYS|   SPEC|[2007-12-07]|
|12000038|FA3WODZLPPOPPYS|    CLM|[2007-12-07]|
|12000054|GQNPYCKXPPOPPYS|    CLM|[2011-07-25]|
+--------+---------------+-------+------------+

But I need the brackets removed from the date field leaving only the date.  This is shown in the example below.
+--------+---------------+-------+----------+
|  app_Id|         doc_id|doc_typ|      date|
+--------+---------------+-------+----------+
|12000015|FASWI4EVPPOPPYS|   SPEC|2007-12-06|
|12000022|FA33AVYGPPOPPYS|   ABST|2007-12-07|
|12000038|FA3WODYZPPOPPYS|   SPEC|2007-12-07|
|12000038|FA3WODZLPPOPPYS|    CLM|2007-12-07|
|12000054|GQNPYCKXPPOPPYS|    CLM|2011-07-25|
+--------+---------------+-------+----------+

A: from pyspark.sql.functions import *

df  = spark.createDataFrame(
  [
  ('12000015','FASWI4EVPPOPPYS','SPEC','[2007-12-06]')
,('12000022','FA33AVYGPPOPPYS','ABST','[2007-12-07]')
,('12000038','FA3WODYZPPOPPYS','SPEC','[2007-12-07]')
,('12000038','FA3WODZLPPOPPYS','CLM','[2007-12-07]')
,('12000054','GQNPYCKXPPOPPYS','CLM','[2011-07-25]')
  ], ['app_Id','doc_id', 'doc_typ', 'date']
)

df.withColumn('date', regexp_replace(regexp_replace('date', '\\[', ''),'\\]', '')).show()

+--------+---------------+-------+----------+
|  app_Id|         doc_id|doc_typ|      date|
+--------+---------------+-------+----------+
|12000015|FASWI4EVPPOPPYS|   SPEC|2007-12-06|
|12000022|FA33AVYGPPOPPYS|   ABST|2007-12-07|
|12000038|FA3WODYZPPOPPYS|   SPEC|2007-12-07|
|12000038|FA3WODZLPPOPPYS|    CLM|2007-12-07|
|12000054|GQNPYCKXPPOPPYS|    CLM|2011-07-25|
+--------+---------------+-------+----------+

A: from pyspark.sql import DataFrame
from pyspark.sql.types import *
import pyspark.sql.functions as F
df  = spark.createDataFrame(
  [
  ('12000015','FASWI4EVPPOPPYS','SPEC','[2007-12-06]')
,('12000022','FA33AVYGPPOPPYS','ABST','[2007-12-07]')
,('12000038','FA3WODYZPPOPPYS','SPEC','[2007-12-07]')
,('12000038','FA3WODZLPPOPPYS','CLM','[2007-12-07]')
,('12000054','GQNPYCKXPPOPPYS','CLM','[2011-07-25]')
  ], ['app_Id','doc_id', 'doc_typ', 'date']
)

df = df.withColumn("date",(F.regexp_replace("date","[\[\]]", "")))
df.show()
+--------+---------------+-------+----------+
|  app_Id|         doc_id|doc_typ|      date|
+--------+---------------+-------+----------+
|12000015|FASWI4EVPPOPPYS|   SPEC|2007-12-06|
|12000022|FA33AVYGPPOPPYS|   ABST|2007-12-07|
|12000038|FA3WODYZPPOPPYS|   SPEC|2007-12-07|
|12000038|FA3WODZLPPOPPYS|    CLM|2007-12-07|
|12000054|GQNPYCKXPPOPPYS|    CLM|2011-07-25|
+--------+---------------+-------+----------+


text:
Q: GoogleMaps basic iOS demo app crash - unrecognized selector sent to instance Im trying to run the basic iOS demo SDK code. I have created the API keyand it loads ok.
Although i've transfered the code from viewDidLoad to loadView the effect remains. See the following code
-(void)loadView{
    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                        longitude:151.20
                                                             zoom:6];
    _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

    _mapView.myLocationEnabled = YES;
    self.view = _mapView;

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
    marker.title = @"Sydney";
    marker.snippet = @"Australia";
    marker.map = _mapView;
}

The camera is created but when this line is executed
_mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

an NSException is thrown with the description -> -[GMSMapView animateToCameraPosition:]: unrecognized selector sent to instance.

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GMSMapView
  animateToCameraPosition:]: unrecognized selector sent to instance
  0x14dbb870'
  * First throw call stack: (0x2f462f4b 0x39cd96af 0x2f4668e7 0x2f4651cb 0x2f3b44d8 0x4cebe9 0x4cd78f 0x4ccc41 0x4ccb3d 0x21ced5
  0x31bda1bd 0x31bda139 0x1d4b27 0x1d4a83 0x1d51cd 0x31bda37b 0x31c850f1
  0x31c85007 0x31c845e3 0x31c8430d 0x31c8407d 0x31c84015 0x31bd5da3
  0x3185cc6b 0x3185847b 0x3185830d 0x31857d1f 0x31857b2f 0x31bce0c3
  0x2f42e1cd 0x2f42bb71 0x2f42beb3 0x2f396c27 0x2f396a0b 0x34097283
  0x31c3a049 0xf58b1 0x3a1e1ab7) libc++abi.dylib: terminating with
  uncaught exception of type NSException

A:
I think you may have forgotten to make the class a GMSMapView delegate. The GMSMapViewDelegate bit after the () needs to be between <>

I don't assign that delegate as well as Googles Base Code does not assign it.
I have fortunetly managed to get it working. The google documentation on Google Maps states what follows:

Choose your project, rather than a specific target, and open the Build Settings tab.
  In the Other Linker Flags section, add -ObjC. If these settings are not visible, change the filter in the Build Settings bar from Basic to All.

But their example project, after my examination, has the flag set on target. Setting it on the build target within my project in my case helped and my posted code works fine.

A: I had the same error because I've mistakenly written -objC instead of -ObjC (with capital O)
if it helps someone

A: It's important to note that you should be adding the -ObjC to the Other Linker Flags section in your project.... NOT in your specific target.

A: Other people have mentioned the following section from Google's Documentation

Choose your project, rather than a specific target, and open the Build Settings tab. In the Other Linker Flags section, add -ObjC. If these settings are not visible, change the filter in the Build Settings bar from Basic to All.

However, it wasn't until I added the -ObjC flag into my projects 'Other Linker Flags' section, and NOT the targets 'Other Linker Flags' section, was I able to resolve the unrecognized selector error.

A: Add -ObjC in your project's
GoTo:
Click on your Project->Targets->Build Setting->search(Other Linker Flags)
->Set (-ObjC)
Refer the Screenshot:

A: You most probably have forgotten to do this: (as stated in the google docs)
Choose your project, rather than a specific target, and open the Build Settings tab.
    In the Other Linker Flags section, add -ObjC. If these settings are not visible, change the filter in the Build Settings bar from Basic to All.

A: I think you may have forgotten to make the class a GMSMapView delegate. The GMSMapViewDelegate bit after the () needs to be between <>
@interface StructuredGeocoderViewController () GMSMapViewDelegate

@end

@implementation StructuredGeocoderViewController {
  GMSMapView *_mapView;
  GMSGeocoder *_geocoder;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868
                                                          longitude:151.2086
                                                               zoom:12];

  _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
  _mapView.delegate = self;

  _geocoder = [[GMSGeocoder alloc] init];

  self.view = _mapView;
}

A: When you want to submit it to the store or test flight puts the flag -ObjC in the release too

A: There is only few modification you have to do.

*

*Give the class name of the Custom UIView as "GMSMapView".

*Then make a outlet to your class.
@IBOutlet var locationMapView: GMSMapView!

*In ViewDidLoad() add the following code.
let camera = GMSCameraPosition.camera(withLatitude: 10.1518, longitude: 76.3930, zoom: 6.0)
self.locationMapView.camera = camera

let initialLocation = CLLocationCoordinate2DMake(10.1518, 76.3930)
 let marker = GMSMarker(position: initialLocation)
 marker.title = "Kochi"
 marker.snippet = "Kerala"
 marker.map = locationMapView
 marker.snippet = "Kerala"


text:
Q: Easy way to inject js in tinymce iframe? I was wondering if there is any direct hook to inject some javascript into tinymce iframe?

A: WordPress injects its own external script files in the TinyMCE editor iframe, see for example the wp-includes/js/tinymce/plugins/wpembed/plugin.js file:
(function ( tinymce ) {
    'use strict';

    tinymce.PluginManager.add( 'wpembed', function ( editor, url ) {
        editor.on( 'init', function () {
            var scriptId = editor.dom.uniqueId();

            var scriptElm = editor.dom.create( 'script', {
                id: scriptId,
                type: 'text/javascript',
                src: url + '/../../../wp-embed.js'
            } );

            editor.getDoc().getElementsByTagName( 'head' )[ 0 ].appendChild( scriptElm );
        } );
    } );
})( window.tinymce );

The plugin.js file is loaded in TinyMCE using the tiny_mce_plugins filter.

A: Not possible, Tinymce uses this javascript to create iframe, so you've to edit the javascript to load additional javascript file into iframe.
Thats why there will not be any hook to inject javascript into iframe.


text:
Q: Como acessar o valor de um array através da chave? Tenho o seguinte array:
var arr = [
  {'David': '1'},
  {'Camilla': '2'},
  {'Sadat': '3'},
  {'Vanuza': '4'},
  {'Diego': '5'}
];

Queria acessar o valor "Camilla" do array que criei.
Ps: quero acessar o valor da chave e não o índice.

A: Você pode iterar sobre as chaves de um objeto usando o for..in:

var arr = [
  {'David': '1'},
  {'Camilla': '2'},
  {'Sadat': '3'},
  {'Vanuza': '4'},
  {'Diego': '5'}
];

arr.forEach(function(objeto) {
  for ( var chave in objeto )
      document.body.innerHTML += "Chave: " + chave + "; Valor: " + objeto[chave] + "<br>";
});

Se seu objeto só tem uma chave, esse loop só executará uma vez, então o valor que você quer estará na variável chave.
No entanto, eu não recomendaria representar os dados desse jeito, a menos que você tenha um motivo muito bom para tal, pois além da forma de acessar ser inconveniente ainda torna mais difícil estender os objetos no futuro (vai que você precisa colocar mais propriedades). Porque não usar algo mais estruturado?
var arr = [
  {nome:'David', valor: '1'},
  {nome:'Camilla', valor: '2'},
  {nome:'Sadat', valor: '3'},
  {nome:'Vanuza', valor: '4'},
  {nome:'Diego', valor: '5'}
];

A: Se os objetos estão dentro de um array var ArrayValues = [ { objeto }, { } objeto , ...] ; O seguinte assessores da matriz regular funcionará:

var ValorDavid = arr[0].David.toString();
var ValorCamilla = arr[1].Camilla.toString();

<!DOCTYPE html>
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <title></title>
      <meta charset="utf-8" />
      <script>
        function clica() {
          var arr = [
          { 'David': '1' },
          { 'Camilla': '2' },
          { 'Sadat': '3' },
          { 'Vanuza': '4' },
          { 'Diego': '5' }
          ];

          var ValorDavid = arr[0].David.toString();
          var ValorCamilla = arr[1].Camilla.toString();
        }
      </script>

    </head>
    <body>

      <input type=button onClick="clica();" value="Testa">
    </body>
    </html>

A: Seguindo a idéia do @Gabriel Katamura, temos como criar esta função:
function getArrValue(arr, m) {
  var filteredArr = arr.find(function(v){ return (m in v); });
  return (!!filteredArr) ? filteredArr[m] : null;
}

Depois usar assim getArrValue(arr, 'Camilla') ;)

A: arr.find(function(element) {
  return element.hasOwnProperty('Camilla')
})['Camilla'];

A: Qual o contexto em que está utilizando esse array?
Talvez o problema não esteja em como recuperar os valores, mas sim na estrutura de dados que está construindo.
A sua estrutura de dados precisa ser planejada para evitar futuros problemas.
Recomendo utilizar uma estrutura mais genérica, exemplo:
var arr = [
 { name: 'David', id: '1'},
 { name: 'Camilla', id: '2'},
 { name: 'Sadat', id: '3'},
 { name: 'Vanuza', id: '4'},
 { name: 'Diego', id: '5'}
];

Dessa forma conseguirá iterar melhor com sua matriz de dados quando necessitar. Nesse caso por exemplo poderia utilizar uma biblioteca de utilitários como o lodash (método _.find) que possui vários métodos que te ajuda a manipular dados.

EDITADO:
Se ainda preferir deixar a estrutura de dados da forma que está ou não puder muda-la, é possível criar uma função para acessar o valor:
function getValueByKey (collection, key) {
  var value;

  collection.map(function (item) {
    if (key in item) value = item[key];
  })

  return value;
}

https://jsfiddle.net/t0kt8vkn/


text:
Q: Needed help?? installing Tensorflow-GPU for Win 10 Pro 9-2-18 1.Create a new environment through conda create --name tftest. (You can replace tftest with e.g. the name of your current project.)
2.Activate that new environment through activate tftest.
3.Install TF into this environment through conda install tensorflow.
4.Ensure that you're in the right environment through where python (which should produce a path containing "tftest").
5.Run Python through python.
6.import tensorflow as tf in a shell in that environment.
Thanks to great community as I found this thanks to another post!!!

A: Starting with version 1.6.0, prebuild binaries need AVX instructions.
There are some bug reports by people who tried to use the precompiled binaries but whose doesn't support AVX instructions and got the same error as you posted here:
https://github.com/tensorflow/tensorflow/issues/17761
https://github.com/tensorflow/tensorflow/issues/17386
Maybe you have this problem? If yes, you may have to build tensorflow from sources or downgrade to tensorflow 1.5.1.


text:
Q: Hey folks, I'm new in sqlite and I got stuck on a training question The database is as follows:

The output I want to get is:

My sql query is like this and the output I get is this.
SELECT score as "0-25" , COUNT(*) FROM Gamer WHERE (score > 0 and score<25)
UNION
SELECT score as "26-50", COUNT(*) FROM Gamer WHERE (score > 26 and score<50)
UNION
SELECT score as "51-75", COUNT(*) FROM Gamer WHERE (score > 51 and score<75)
UNION
SELECT score as "76-100", COUNT(*) FROM Gamer WHERE (score > 76 and score<=100)

A: You an use conditional aggrgation. In SQLite:
select
    sum(score between  0 and  25) as s_00_25,
    sum(score between 26 and  50) as s_26_50,
    sum(score between 51 and  75) as s_51_75,
    sum(score between 76 and 100) as s_76_100
from gamer


text:
Q: MVC - where to implement form validation (server-side)? In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?

A: From Wikipedia:

Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.

Thus, model - it holds the application and the business rules.

A: I completely agree with Josh. However you may create a kind of validation layer between Controller and Model so that most of syntactical validations can be carried out on data before it reaches to model.
For example,
The validation layer would validate the date format, amount format, mandatory fields, etc...
So that model would purely concentrate on business validations like x amount should be greater than y amount.

A: My experience with MVC thus far consists of entirely rails.
Rails does it's validation 100% in the Model.
For the most part this works very well. I'd say 9 out of 10 times it's all you need.
There are some areas however where what you're submitting from a form doesn't match up with your model properly. There may be some additional filtering/rearranging or so on.
The best way to solve these situations I've found is to create faux-model objects, which basically act like Model objects but map 1-to-1 with the form data. These faux-model objects don't actually save anything, they're just a bucket for the data with validations attached.
An example of such a thing (in rails) is ActiveForm
Once the data gets into those (and is valid) it's usually a pretty simple step to transfer it directly across to your actual models.

A: The basic syntax check should be in the control as it translates the user input for the model. The model needs to do the real data validation.


text:
Q: Виджет "Популярные записи" (по просмотрам) для блога WP Подскажите статью или готовое решение самописного виджета для WordPress, чтобы популярные записи выводил, в зависимости от просмотров, например.
Готовые решения (плагины) слишком громоздкие и не дают возможности тонкой настройки.

A: Простой пример реализации популярных постов без использования плагина.
1) вставить код в файл functions.php вашей темы:
function setPostViews($postID) {
  $count_key = 'post_views_count';
  $count = get_post_meta($postID, $count_key, true);
  if($count==»){
  $count = 0;
  delete_post_meta($postID, $count_key);
  add_post_meta($postID, $count_key, '0');
  }else{
  $count++;
  update_post_meta($postID, $count_key, $count); } }

function getPostViews($postID){
  $count_key = 'post_views_count';
  $count = get_post_meta($postID, $count_key, true);
  if($count==»){
  delete_post_meta($postID, $count_key);
  add_post_meta($postID, $count_key, '0');
  return "0"; }
  return $count;}

2) Далее код счетчика нужно вставить в файл single.php внутрь цикла loop:
<?php setPostViews(get_the_ID()); ?>

3) И выводим список популярных статей путем вставки последнего кода в нужное место вашей темы, допустим в сайтбар:

Популярные статьи

   <?php
   $args = array( 'posts_per_page' => 5, 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); query_posts($args);
   while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

   <?php endwhile; wp_reset_query(); ?>


text:
Q: Python xml elementree how to check if element if present and process code? <rules>
    <entry name="rule name 1">
      <to>
        <member>untrust</member>
      </to>
      <from>
        <member>trust</member>
      </from>
      <source>
        <member>object1</member>
      </source>
      <destination>
        <member>any</member>
      </destination>
      <service>any</service>
      <description>'NAT Rule 1'</description>
      <nat-type>ipv4</nat-type>
      <source-translation>
        <static-ip>
          <bi-directional>yes</bi-directional>
          <translated-address>object1-pub</translated-address>
        </static-ip>
      </source-translation>
    </entry>
    <entry name="rule name 2">
      <to>
        <member>untrust</member>
      </to>
      <from>
        <member>trust</member>
      </from>
      <source>
        <member>any</member>
      </source>
      <destination>
        <member>object2-pub</member>
      </destination>
      <destination-translation>
        <translated-address>object2</translated-address>
      </destination-translation>
      <service>any</service>
      <description>'NAT Rule 2'</description>
      <tag>
        <member>DST NAT</member>
      </tag>
    </entry>
</rules>

Hi,
I am trying to process above xml using xml elementree in python. I am looking for a way to check if the <'source-traslation'> or <'destination-translation'> is present. In short, if it if source-translation then set nat-type varialble to source nat and proceed further to get  and <'translated-address'> values. If <'destination-address'> is present then process logic to get values for . I am putting all this data in a dict with a format like this...
rules{
        rule_name: <name>
        options:{
                src_zone:<from>
                source:<source>
                dst_zone:<to>
                destination:<destination>
                nat-type:<appliaction>
                service:<service>
                traslated-address:<translated-address>
                destination-address:<destination-address>
        }
}

I have tried various combinations however it is not working for me.

A: To check if your element exists you can have an if statement like this:
import xml.etree.ElementTree as ET
root = ET.parse('PATH_TO_YOUR_FILE').getroot()
if len(root.findall('source-translation')) > 0:
    PUT YOUR CODE HERE


text:
Q: PowerShell - "RETURN" in function returns values two times INSTEAD of just one I was assuming that "return" in PowerShell function will return the value and exit the function, but instead of that I am getting the values for two times!!!!???
Please assist me.
I have a default value, I have logic for retreiving the real value (if exists) but instead I am getting two fules as output - but I do not want that! I need just one value.
Thank you in advance!!!
function GetTenantTagValue($TAG_SET_NAME) {
    Write-Host("Tag Set Name:"+$TAG_SET_NAME)
    $TAG_SET_VALUE = "N/A"
    $TENANT_TAGS = "Customer Code/HEDGE"

    $TENANT_TAGS | ForEach-Object {
        $TAG_NAME = $_.split("/")[0]
        $TAG_VALUE = $_.split("/")[1]

        if ($TAG_NAME -eq $TAG_SET_NAME) {
            # $TAG_SET_VALUE = $TAG_VALUE
            Write-Host("Tag Value:"+$TAG_VALUE)
            Write-Host("#########################")
            return $TAG_VALUE
        }
    }
    Write-Host("Tag Set Value:"+$TAG_SET_VALUE)
    return $TAG_SET_VALUE
}

I invoke the function with:
GetTenantTagValue "Customer Code"


text:
Q: How to keep basic formatting when store html to database? I have a asp.net textbox multiline. I would like to store basic text formatting like next line brake.
example:
lorem ipsum
lorem ipsum
lorem ipsum

so when I output to literal control it shows the same way
here is my code
when store
private string KeepBasicFormating(string text)
        {
            var temp = text;
            temp = Server.HtmlEncode(temp);
            temp = temp.Replace(" ", " ");
            temp = temp.Replace("\r\n", "
");
            return temp;
        }

when outout
<asp:Literal ID="LcNotes" Mode="Transform" runat="server"></asp:Literal>
LcNotes.Text = storedText;

but it shows as one line text without any formatting
lorem ipsum lorem ipsum lorem ipsum

A: Use DIV instead:

    div.InnerHtml = storedText;

A: Try
... Mode="PassThrough" ...


text:
Q: How to print an array /object in magento On Magento I have tried
   Mage::log ($order);

I suppose to get the array printed on my
   var/log/system.log

But instead the website does not load again, after few min it comes as timed out.

A: try this
Mage::log($order->toArray());

A: Try that: Zend_Debug::dump($your_variable);
And this is one of the best posts about that in my opinion: MAGENTO DEBUGGING HINTS

A: Following print the entire array in to MyArray.log
   Mage::log("Query product: ".print_r($order->debug(), true),null,'MyArray.log');

MyArray.log can be found in
   var/log/MyArray.log

The following Prints the array Keys
   Mage::log(array_keys($order->getData()));


text:
Q: Trouble installing tp link tl-wn821N V5 on 16.04 I am trying to install the USB wifi adapter: tp-link TL-WN821N V5.
I found a driver for the V5 version but it won't compile. In the manual of the Linux driver it is said that the driver is for: 14.04.01 with GCC v4.8.2.
My Linux edition is Ubuntu 16.04 with GCC v5.3.1.
I've run lsusb but my USB adapter wasn't listed:
Bus 001 Device 004: ID 2357:0107
Bus 001 Device 003: ID 0781:5406 SanDisk Corp. Cruzer Micro U3
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 046d:c52e Logitech, Inc. MK260 Wireless Combo Receiver
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

I've run lsusb with and without the adapter plugged and without the adapter the line
The adapter works on Win 7 after installing the appropriate driver.
Bus 001 Device 004: ID 2357:0107

was missing.

A: You are in luck as I made a commit on github that enables that device.  We will use Mange's github as he included the commit and has dkms support so the driver will automatically get rebuilt for a kernel update.
You will need to have Secure Boot disabled if your computer is equipped with that feature
sudo apt-get install build-essential linux-headers-generic dkms git
git clone https://github.com/Mange/rtl8192eu-linux-driver.git
sudo dkms add ./rtl8192eu-linux-driver
sudo dkms install rtl8192eu/1.0
Reboot
If you do not have an active internet connection download https://github.com/Mange/rtl8192eu-linux-driver/archive/master.zip
Transfer the file to the Ubuntu install, then extract it to the desktop.  Then in terminal
cd Desktop
sudo dkms add ./rtl8192eu-linux-driver
sudo dkms install rtl8192eu/1.0
Reboot
EDIT to add:
Now that you have installed it using make, I would suggest
cd Desktop/rtl8192eu-linux-driver
make clean
Before you install dkms with sudo apt-get install dkms and install the driver using the dkms commands


text:
Q: Apply Green's theorem for $\iint_D (x+2y)dxdy$ on region bounded with $x = t- \sin (t), y = 1 - \cos (t)$. Basically, I am stuck with his exercise. It asks to compute the integral:

$$\int_C P\,dx + Q\,dy =  \iint_D \left(\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y}\right)dxdy = \iint_D (x+2y)dxdy $$
  where D is the region bounded by the x axis and the arc of $$ x = t- \sin (t),\;\;\; y = 1 - \cos (t),\;\; 0 \leq t \leq 2\pi $$

I have tried calculating F by knowing its 2D curl, but I never get the right solution: $$ -2\pi(3\pi+2) $$
Can you please tell me how to solve this problem?

A: The idea behind Green's Theorem is that the curl of a vector field is a measure of the infinitisimal circulation ("swirl") caused by the vector field at a point. So Green's theorem states that, if we want the circulation along a closed path, we can take the area integral of all the "swirl" inside the curve, which all in a sense cancels out, leaving only the circulation on the boundary.

The curl for a vector field $\vec{F} = \langle F_x, F_y, F_Z \rangle$ is defined as:
$$ \nabla \times \vec{F} = \begin{vmatrix} \vec{i} & \vec{j} & \vec{k} \\ \frac{\partial}{\partial x} & \frac{\partial}{\partial y} & \frac{\partial}{\partial z} \\ F_x & F_y & F_z \end{vmatrix} $$
its direction gives the axis of rotation of the infinitisimal circulation (oriented by the right-hard rule), and its magnitude is the infinitisimal circulation.
Green's Theorem is the application of this to a 2D case where we take $F_z = 0$, working with a vector field in the $x$-$y$ plane. In this case, the curl points in the $\vec{k}$ direction and we simply use the scalar curl, the magnitude of the curl:
$$ \nabla \times \vec{F} = \frac{\partial F_y}{\partial x} - \frac{\partial F_x}{\partial y} $$
In this problem, you have the area integral
$$ \iint_{D} (x + 2y)\, dA $$
where $D$ is the region enclosed by the plane curve mentioned and the x-axis.
In order to use Green's theorem, we need a vector field whose curl is $x + 2y$.
One such vector field is
$$ \vec{F}(x,y) = \left\langle -y^2 ,\frac{x^2}{2} \right\rangle $$
and so take the the line integral:
$$ \int_{\partial D} \vec{F}(\vec{x}) \cdot d\vec{s}$$
where $\partial D$ is the oriented boundary of the region $D$. It is important to note that it is oriented:

we must traverse the boundary in a counterclockwise direction, and the parametrization given is (1) only the arc, not the flat line, and (2) clockwise starting from the origin to the right. So we parametrize the lower line as:
$$ \vec{x}_1(t) = \langle t,0 \rangle \qquad t \text{ from } 0 \text{ to } 2\pi $$
and the curve as
$$ \vec{x}_2(t) = \langle t-\sin t,1 - \cos t \rangle \qquad t \text{ from } 2\pi \text{ to } 0 $$
so we have:
\begin{align*}
\iint_{D} (x + 2y)\, dA &= \int_{\partial D} \vec{F}(\vec{x}) \cdot d\vec{s} \\
&= \int_0^{2\pi} \vec{F}(\vec{x}_1(t)) \cdot \vec{x}_1'(t) dt + \int_{2\pi}^0 \vec{F}(\vec{x}_2(t)) \cdot \vec{x}_2'(t) dt \\
&= \int_0^{2\pi} \langle 0, t^2/2 \rangle \cdot \langle 1,0 \rangle \, dt - \int_0^{2\pi} \langle -(1-\cos t)^2, (t-\sin t)^2/2 \rangle \cdot \langle 1 - \cos t, \sin t \rangle \, dt \\
&= \int_0^{2\pi} 0 \, dt - \int_0^{2\pi} \left[\sin t (t- \sin t)^2/2 -(1-\cos t)^3 \right] dt \\
&= \int_0^{2\pi} \left[(1-\cos t)^3 - \sin t (t- \sin t)^2/2 \right] dt \\
&= \pi(3\pi + 5) \\
\end{align*}

A: It's a bit tedious, but not too hard, to compute the double integral directly, but if you're interested in recovering $F$, you can use a technique for finding antiderivatives of differential forms that are defined in star-shaped regions relative to the origin.
The integrand is equivalent to the 2-form $x+2y\,dx\wedge dy$. To find an antiderivative:

*

*Make the substitutions $x\to tx$, $dx\to(x\,dt+t\,dx)$ and similarly for $y$: $$(tx+2ty)\,(x\,dt+t\,dx)\wedge(y\,dt+t\,dy)$$

*Expand, moving $dt$ to the left and discarding any terms that don't involve it: $$(tx+2ty)(tx\,dt\wedge dy-ty\,dt\wedge dx)$$

*Integrate over $t$ from $0$ to $1$, treating the integrand as an ordinary function of $t$: $$\int_0^1(tx+2ty)(tx\,dy-ty\,dx)\,dt=-{xy+2y^2\over3}dx+{x^2+2xy\over3}dy$$

In short, integrate $\left(-f(tx,ty)ty,f(tx,ty)tx\right)$, where $f(x,y)$ is the integrand in the double integral.
So, one possible vector field that has the given curl is $$F(x,y)=\left(\frac13(xy+2y^2),\frac13(x^2+2xy)\right).$$
As with integration of single-variable functions, you can add a "constant" of integration, which here is any vector field with vanishing curl. For example, adding $\left(\frac13(xy-y^2),\frac16(x^2-4xy)\right)$ to this gives the vector field in Manuel Guillen's answer.


text:
Q: Multiple textboxes input and multiple textboxes output via array For an assignment I have to programm a form which compaires the avarage temperature with the given temperature (in which the user can fill in). The input is in 7 different textboxes, and the output has to be in 7 different textboxes as well. I got the input of the different textboxes into an array.
However, I have trouble in calculation the differences between temperatures. Also I have trouble with the output textboxes, I can not get a loop to work for placing the values into the 7 different output textboxes. I have to do the calculation via an array..
Maybe someone can see where I went wrong?
private void btnCalculate_Click(object sender, EventArgs e)
{
    string temperature = Convert.ToDouble(txtZo.Text + txtMa.Text + txtDi.Text +
                    txtWo.Text + txtDo.Text + txtVr.Text + txtZa.Text).ToString("0.00");
    double average =  10,2 ;
    double resultaatZo = 1;   // I think there could be a loop for this right?
    double resultaatMa = 1;
    double resultaatDi = 1;
    double resultaatWo = 1;
    double resultaatDo = 1;
    double resultaatVr = 1;
    double resultaatZa = 1;
    int regelnummer = 1;
for (int i = 1; i < temperature.Length; i++)
{
    resultaatZo = average - temperature[0];
    txtAfwZo.Text = txtAfwZo.Text + resultaatZo.ToString();

    resultaatMa = average - temperature[1];
    txtAfwMa.Text = txtAfwMa.Text + resultaatMa.ToString();

    resultaatDi = average - temperature[2];
    txtAfwDi.Text = txtAfwDi.Text + resultaatDi.ToString();

    resultaatWo = average - temperature[3];
    txtAfwWo.Text = txtAfwWo.Text + resultaatWo.ToString();

    resultaatDo = average - temperature[4];
    txtAfwDo.Text = txtAfwDo.Text + resultaatDo.ToString();

    resultaatVr = average - temperature[5];
    txtAfwVr.Text = txtAfwVr.Text + resultaatVr.ToString();

    resultaatZa = average - temperature[6];
    txtAfwZa.Text = txtAfwZa.Text + resultaatZa.ToString();
}

Design of my programm.

I already spent hours and hours on this and I am really lost.
Thank you!

A: Maybe try this way:
Private fields in Form class ....
    private Label[] _answers = new Label[NUMBER_OF_VERIABLES];

    private TextBox[] _textBoxes = new TextBox[NUMBER_OF_VERIABLES];

    private double[] _results = new double[NUMBER_OF_VERIABLES];

In click button event handler:
 void ButtonClick(object sender, EventArgs e)
{
    for (int i = 0; i < NUMBER_OF_VERIABLES; i++)
    {
        this._answers[i].Text =  double.TryParse(this._textBoxes[i].Text, out this._results[i]) ? $"{averageTemp + this._results[i]}" : INFORMATION_EMPTY_VALUE;
    }
}


text:
Q: Is there an alternative to "let!" to support function chaining? Is there an alternative to "let!" to support function chaining?
I currently have this:
async {

    let! result = token |> queryDay
    result |> toTransactions
}

However, I would like to consolidate the above code into something like this:
async {

    // NOTE: Async.Await isn't a thing
    let result = token |> queryDay |> Async.Await |> toTransactions
}

Is there a way to achieve this?

A: From your examples I'm assuming that:
queryDay : 'a -> Async<'b>
toTransactions : 'b -> Async<'c>

Chaining monadic functions like that is called "bind". This is the core operation of a monad, the very essense of it. In fact the let! construct gets desugared into a call to async.Bind, and so does do!.
Unfortunately, the F# standard library doesn't offer a built-in standalone implementation of bind for Async. But there is one in FSharpx that you can use:
open FSharpx.Control

async {
   let! result = token |> queryDay |> Async.bind toTransactions
}

Or if you don't want to use FSharpx, you can easily make one yourself by delegating to the computation builder:
module Async =
    let bind f a = async.Bind(a, f)


text:
Q: How to get autocomplete / hinting for cypress.json inside WebStorm Cypress is very popular e2e testing framework but apparently WebStorm does not give any hinting/suggestions when editing its configuration file (cypress.json).
Question is how to get hinting for cypress.json in WebStorm?
P.S. I know you can add a custom JSON schema in WebStorm and if such exists for cypress.json I could add it and get maybe the hinting. But I could not find such schema for cypress.json.

A: The cypress.json schema is available at Schemastore - see https://raw.githubusercontent.com/cypress-io/cypress/develop/cli/schema/cypress.schema.json
You can download it and set up schema mappings in Settings | Languages & Frameworks | Schemas and DTDs | JSON Schema Mappings

A: The Cypress docs have an own section dedicated to setting up Intelligent Code Completion in your IDE (this includes full code completion for the whole API and even for your custom commands).
Regarding your question, it advises to use https://on.cypress.io/cypress.schema.json in order to enable full hinting for cypress.json, as this seems to always point to the latest schema.

A: Three is a paid plugin (I'm the author) for IntelliJ platform (IDEA, WebStorm etc.)
It provides out of the box the following features for the Cypress configuration file: autocomplete, hinting, validation (including validation by JSON schema) and others.
See this overview for details: https://youtu.be/Laj4zzN74Jk


text:
Q: A sequence that converges weakly but not in the Cesàro sense Let $H$ be a Hilbert space over $\mathbb{C}$ with inner product $\langle\cdot,\cdot\rangle$, and let $\{x_n\}_{n=1}^\infty\subseteq H$, $x\in H$. I'm using the following definitions:

*

*$\{x_n\}_{n=1}^\infty$ norm converges to $x$ $\Longleftrightarrow$ $x_n\rightarrow x$ $\Longleftrightarrow$ $\lim_{n\rightarrow\infty}\|x_n-x\|=0$.

*$\{x_n\}_{n=1}^\infty$ converges weakly to $x$ $\Longleftrightarrow$ $x_n\rightharpoonup x$ $\Longleftrightarrow$ $\lim_{n\rightarrow\infty}\langle y,x_n\rangle=\langle y,x\rangle$ for all $y\in H$.

*$\{x_n\}_{n=1}^\infty$ converges in the Cesàro sense to $x$ $\Longleftrightarrow$ $x_n\xrightarrow{Ces} x$ $\Longleftrightarrow$ $\lim_{N\rightarrow\infty}\|\frac{1}{N}\sum_{n=1}^Nx_n-x\|=0$.

If $x_n\rightarrow x$, then $x_n\rightharpoonup x$ and $x_n\xrightarrow{Ces}x$. On the other hand, if $H=\mathbb{C}$ with the standard inner product, then $(-1)^n\xrightarrow{Ces}0$ but $(-1)^n\not\rightharpoonup 0$. I'm having some difficulty, however, finding a sequence that converges weakly but not in the Cesàro sense. Since weak and strong convergence are equivalent in a finite-dimensional space, such a sequence can only exist if $H$ is infinite-dimensional. I'm therefore trying to find an example in the space $\ell^2(\mathbb{N})$ of sequences $\alpha=(\alpha_1,\alpha_2,\ldots)$ such that $\sum_{n=1}^\infty|\alpha_n|^2<\infty$ with the usual inner product $\langle\alpha,\beta\rangle=\sum_{n=1}^\infty\bar{\alpha}_n\beta_n$.
The sequence I'm considering is
$$x_1=\left(1,\frac{1}{2},\frac{1}{3},\ldots\right),$$
$$x_2=\left(0,1,\frac{1}{2},\ldots\right),$$
$$x_3=\left(0,0,1,\ldots\right),$$
$$\vdots$$
i.e, the sequence consisting of repeatedly shifting the harmonic sequence to the right. I've managed to show that $x_n\rightharpoonup 0$, but I haven't been able to show that $\{x_n\}_{n=1}^\infty$ doesn't converge in the Cesàro sense. Am I on the right track? If so, how do I show that Cesàro convergence fails? If not, what would be a sequence that actually works?

A: I am currently not sure about your sequence, but I will edit the answer if I see something.
Meanwhile, the following example works: Define
$$
x_n := e_k \text{ for } 2^k \leq n < 2^{k+1},
$$
where $e_k$ is the $k$th member of the standard basis of $\ell^2$.
Then we have $x_n \rightharpoonup 0$, but
$$
\bigg(\frac{1}{2^{k+1} - 1} \sum_{\ell = 1}^{2^{k+1} - 1} x_\ell \bigg)_{k} = \frac{(2^{k+1} - 1) - 2^k + 1}{2^{k+1}-1} = \frac{2^{k}}{2^{k+1} - 1} \rightarrow \frac{1}{2}.
$$
In particular, this shows
$$
\limsup_k \bigg \Vert \frac{1}{2^{k+1} - 1} \sum_{\ell = 1}^{2^{k+1} - 1} x_\ell \bigg\Vert \geq \limsup_k \bigg| \bigg(\frac{1}{2^{k+1} - 1} \sum_{\ell = 1}^{2^{k+1} - 1} x_\ell \bigg)_{k} \bigg|  \geq 1/2
$$
and thus $(x_n)_n$ does not converge Cesaro to $0$.
The intuition here is that if we are at $2^{k+1}$, then still about half of all the sequence members we will have seen are equal to $e_k$.
Note though, that even though Cesaro convergence does not hold in general, Mazur's lemma (https://en.wikipedia.org/wiki/Mazur%27s_lemma) shows that we can always find some convex combination which converges strongly.