text:
Q: Hide buttons in an activity after a while in android studio I am working on a map application, using android studio.
I have a map activity and I need some buttons on my map, for example zoom in,zoom out,search,...
I want to hide these buttons after a while and show them again onClick.
but I don't know how to do that.
here is my code
MapActivity.java
package com.example.tourismproject;

import android.location.Location;

import android.content.IntentSender;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    public static final String TAG = MapsActivity.class.getSimpleName();

    /*
     * Define a request code to send to Google Play services
     * This code is returned in Activity.onActivityResult
     */
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private float zoomLevel = 15; //street view

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1000); // 1 second, in milliseconds

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("I am here!");
        mMap.addMarker(options);

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        } else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            /*
             * Thrown if Google Play services canceled the original
             * PendingIntent
             */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }
}

and my XML file is :
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tourismproject.MapsActivity" />

A: Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
 public void run() {
    //hide buttons after 1 sec
    yourbutton.setVisibility(false);
 }
}, 1000);

A: You can use
      @Override
        public void onClick(View v) {
            button.setVisibility(false);
        }

you can use
      Thread.sleep(3000);//for three seconds
      button.setVisibility(false);

to make it invisible after a while //in this case after three seconds
i hope this is helpful

A:  someView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               if(button.getVisibility()==View.VISIBLE){
                   button.setVisibility(View.GONE);
               } else {
                   button.setVisibility(View.VISIBLE);
               }
            }
        });

Also for better usability you can add some fading animation with something like this:
 ObjectAnimator alpha = ObjectAnimator.ofFloat(button, "alpha", 1, 0);
 //alpha.setDelay(500);
 //alpha.setDuration(1000);
 alpha.start();


text:
Q: How to import long decimals as numeric in R I have a CSV that contains integers and long decimal percentages, such as:
71,4,0.056338028169014086,0.028169014084507043

When I import the CSV in R using
df <- as.data.frame(read.csv('/file/location.csv', header = TRUE, stringsAsFactors=FALSE))

all of the integers import as integers, but the long decimal columns import as character. How can I get them to import as numeric?

A: Currently, too long real numbers are imported as factor. A workaround is
db <- read.csv('/file/location.csv', header = TRUE,
               colClasses=c("integer","integer","numeric","numeric"))

A: I would need to take a closer look at your data to be sure but I think the reason why your decimals are imported as characters is that in Excel, they are written with a "," instead of a ".".
In R, "," is a character, hence the character type. I can't tell whether this is your problem without seeing your data (are your example copied from your csv file or did you write them manually ?) but I had the same few months ago for this reason.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show woocommerce errors I have a woocommerce store and want to show wocommerce error messages in specific place of my theme, for example under submit button.
I know wocommerce error messages come from here:

<?php foreach ( $messages as $message ) : ?>

<?php echo wp_kses_post( $message ); ?>

<?php endforeach; ?>

But, when i put this code in my page (for example edit-my-address.php page), its giving error!
What is working or simple code for showing messages in woocommerce?
Thanks in advance.

A: you can use both methods here..
woocommerce_show_messages();
wc_print_notices();

You can also show woocommerce custom notices according to your condition like...
wc_add_notice( 'This is a Success notice', 'success' );
wc_add_notice( 'This is a Error notice', 'error' );
wc_add_notice( 'This is a \'Notice\' notice\'', 'notice' );

A: You can add this piece of code to functions.php of your child theme
add_shortcode('woocommerce_notices', function($attrs) {
    if (wc_notice_count() > 0) {
    ?>

    <?php wc_print_notices(); ?>

    <?php
    }
});

And then use it as a shortcode [woocommerce_notices] in any desired post or page, or use <?php echo do_shortcode('[name_of_shortcode]'); ?> in a desired PHP template.
Tested and works. Good luck.

A: A bit late to the party but here is a solution.
Try to use the following piece of code (taken from the original file here: wp-content/plugins/woocommerce/templates/single-product.php)
<?php
  /**
   * woocommerce_before_main_content hook.
   *
   * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
   * @hooked woocommerce_breadcrumb - 20
   */
  do_action( 'woocommerce_before_main_content' );
?>

Hope it helps

A: you missed to add this line of code:
<?php wc_print_notices(); ?>

A: Add this to your functions.php file inside your child theme (or main theme if there is no child).
add_shortcode('woocommerce_notices', function($attrs) {
    if (function_exists('wc_notice_count') && wc_notice_count() > 0) {
        ?>

            <?php wc_print_notices(); ?>

        <?php
        // You can execute some php here
        wc_clear_notices();
    }
});

Then add a shortcode to your page as:
[woocommerce_notices]

The notices and the code will get executed wherever you paste the shortcode.


text:
Q: Convert a List of Object arrays to a List of model Beans grouped by id I have a model bean like this:
@Getter
@ToString
@Builder(toBuilder = true)
public class MyBean {
    private Integer id;
    private String name;
    private Map<String, Object> customAttributes;

    // equals and hashCode are implemented based on the id
}

From a method call I'm getting a List of Object arrays like shown below:
// pseudo code
List<Object[]> arr = query.getResultList();

arr[0] = 1, arr[1] = "name 1", arr[2] = "custom_attr_1", arr[3] = "custom_attr_1_val_1"
arr[0] = 1, arr[1] = "name 1", arr[2] = "custom_attr_2", arr[3] = "custom_attr_2_val_1"
arr[0] = 1, arr[1] = "name 1", arr[2] = "custom_attr_3", arr[3] = "custom_attr_3_val_1"

arr[0] = 2, arr[1] = "name 2", arr[2] = "custom_attr_1", arr[3] = "custom_attr_1_val_2"
arr[0] = 2, arr[1] = "name 2", arr[2] = "custom_attr_2", arr[3] = "custom_attr_2_val_2"
arr[0] = 2, arr[1] = "name 2", arr[2] = "custom_attr_3", arr[3] = "custom_attr_3_val_2"

arr[0] = 3, arr[1] = "name 3", arr[2] = "custom_attr_1", arr[3] = "custom_attr_1_val_3"
arr[0] = 3, arr[1] = "name 3", arr[2] = "custom_attr_2", arr[3] = "custom_attr_2_val_3"
arr[0] = 3, arr[1] = "name 3", arr[2] = "custom_attr_3", arr[3] = "custom_attr_3_val_3"

I want this List<Object[]> to be transformed into List<MyBean> such that:
// pseudo code
List<MyBean> beans = helpNeededToConvert(List<Object[]>);

// 0th location in the list:
id = 1, name = "name 1", customAttributes = ("custom_attr_1", "custom_attr_1_val_1"), ("custom_attr_2", "custom_attr_2_val_1"), ("custom_attr_3", "custom_attr_3_val_1")

// 1st location in the list:
id = 2, name = "name 2", customAttributes = ("custom_attr_1", "custom_attr_1_val_2"), ("custom_attr_2", "custom_attr_2_val_2"), ("custom_attr_3", "custom_attr_3_val_2")

// 2nd location in the list:
id = 3, name = "name 3", customAttributes = ("custom_attr_1", "custom_attr_1_val_3"), ("custom_attr_2", "custom_attr_2_val_3"), ("custom_attr_3", "custom_attr_3_val_3")

That is, merge the items in List<Object[]> to a List<MyBean> grouped by the id.
I can achieve this with the for loop and some logic. But just want some help to achieve this with streams and related methods. Populating the Map<String, Object> customAttributes is something I am not sure how to achieve.
The ordering of the items in the resulting list is immaterial.
If someone wants to try this, then the below program can be used that populates the List<Object[]>:
public class TestClass {
    public static void main(String[] args) {
        TestClass test = new TestClass();
        List<Object[]> resultList = test.buildResultList();

        // convert to List<MyBean>
    }

    private List<Object[]> buildResultList() {
        List<Object[]> resultList = new ArrayList<>();

        Object[] arr1 = new Object[4];
        arr1[0] = 1; arr1[1] = "name 1"; arr1[2] = "custom_attr_1"; arr1[3] = "custom_attr_1_val_1";
        resultList.add(arr1);

        Object[] arr2 = new Object[4];
        arr2[0] = 1; arr2[1] = "name 1"; arr2[2] = "custom_attr_2"; arr2[3] = "custom_attr_2_val_1";
        resultList.add(arr2);

        Object[] arr3 = new Object[4];
        arr3[0] = 1; arr3[1] = "name 1"; arr3[2] = "custom_attr_3"; arr3[3] = "custom_attr_3_val_1";
        resultList.add(arr3);

        Object[] arr4 = new Object[4];
        arr4[0] = 2; arr4[1] = "name 2"; arr4[2] = "custom_attr_1"; arr4[3] = "custom_attr_1_val_2";
        resultList.add(arr4);

        Object[] arr5 = new Object[4];
        arr5[0] = 2; arr5[1] = "name 2"; arr5[2] = "custom_attr_2"; arr5[3] = "custom_attr_2_val_2";
        resultList.add(arr5);

        Object[] arr6 = new Object[4];
        arr6[0] = 2; arr6[1] = "name 2"; arr6[2] = "custom_attr_3"; arr6[3] = "custom_attr_3_val_2";
        resultList.add(arr6);

        Object[] arr7 = new Object[4];
        arr7[0] = 3; arr7[1] = "name 3"; arr7[2] = "custom_attr_1"; arr7[3] = "custom_attr_1_val_3";
        resultList.add(arr7);

        Object[] arr8 = new Object[4];
        arr8[0] = 3; arr8[1] = "name 3"; arr8[2] = "custom_attr_2"; arr8[3] = "custom_attr_2_val_3";
        resultList.add(arr8);

        Object[] arr9 = new Object[4];
        arr9[0] = 3; arr9[1] = "name 3"; arr9[2] = "custom_attr_3"; arr9[3] = "custom_attr_3_val_3";
        resultList.add(arr9);

        return resultList;
    }
}

@Getter @ToString @Builder(toBuilder = true)
class MyBean {
    private Integer id;
    private String name;
    private Map<String, Object> customAttributes;
}

That's how I approached this problem. Looking for better ways to achieve this behavior.
public class TestClass {
    public static void main(String[] args) {
        TestClass test = new TestClass();
        List<Object[]> resultList = test.buildResultList();

        Map<Integer, List<Object[]>> idObjectsLookup = resultList.stream()
                .collect(Collectors.groupingBy(o -> (Integer)o[0]));

        List<MyBean> beans = new ArrayList<>();

        idObjectsLookup.forEach((k, v) -> {
            MyBean mb = new MyBean();
            mb.setId(k);
            Map<String, Object> customAttributes = new HashMap<>();
            for (Object[] arr : v) {
                mb.setName((String)arr[1]);
                customAttributes.put((String)arr[2], arr[3]);
                mb.setCustomAttributes(customAttributes);
            }
            beans.add(mb);
        });

        System.out.println(beans);
    }

    private List<Object[]> buildResultList() {
        List<Object[]> resultList = new ArrayList<>();

        Object[] arr1 = new Object[4];
        arr1[0] = 1; arr1[1] = "name 1"; arr1[2] = "custom_attr_1"; arr1[3] = "custom_attr_1_val_1";
        resultList.add(arr1);

        Object[] arr2 = new Object[4];
        arr2[0] = 1; arr2[1] = "name 1"; arr2[2] = "custom_attr_2"; arr2[3] = "custom_attr_2_val_1";
        resultList.add(arr2);

        Object[] arr3 = new Object[4];
        arr3[0] = 1; arr3[1] = "name 1"; arr3[2] = "custom_attr_3"; arr3[3] = "custom_attr_3_val_1";
        resultList.add(arr3);

        Object[] arr4 = new Object[4];
        arr4[0] = 2; arr4[1] = "name 2"; arr4[2] = "custom_attr_1"; arr4[3] = "custom_attr_1_val_2";
        resultList.add(arr4);

        Object[] arr5 = new Object[4];
        arr5[0] = 2; arr5[1] = "name 2"; arr5[2] = "custom_attr_2"; arr5[3] = "custom_attr_2_val_2";
        resultList.add(arr5);

        Object[] arr6 = new Object[4];
        arr6[0] = 2; arr6[1] = "name 2"; arr6[2] = "custom_attr_3"; arr6[3] = "custom_attr_3_val_2";
        resultList.add(arr6);

        Object[] arr7 = new Object[4];
        arr7[0] = 3; arr7[1] = "name 3"; arr7[2] = "custom_attr_1"; arr7[3] = "custom_attr_1_val_3";
        resultList.add(arr7);

        Object[] arr8 = new Object[4];
        arr8[0] = 3; arr8[1] = "name 3"; arr8[2] = "custom_attr_2"; arr8[3] = "custom_attr_2_val_3";
        resultList.add(arr8);

        Object[] arr9 = new Object[4];
        arr9[0] = 3; arr9[1] = "name 3"; arr9[2] = "custom_attr_3"; arr9[3] = "custom_attr_3_val_3";
        resultList.add(arr9);

        return resultList;
    }
}

@Getter @ToString @Setter @NoArgsConstructor
class MyBean {
    private Integer id;
    private String name;
    private Map<String, Object> customAttributes;
}

A: To achieve that, we need to group the data by id and name.
For that, we can create an intermediate map. The key of this map should contain two peaces of information id and name. A quick and dirty way is to concatenate these properties as a string, or wrap them with a list or array of Object type, which even is a more nasty workaround.
The proper way of doing this with Java 8 would to define a separate class as data carrier for the keys and with Java 16 onwards, we can define it as a record. But since you've said that MyBean implements equals/hashCode contract based on the id property, we can use it as key in the intermediate map.
For convenience, I've added one method parse() to the MyBean class (if this change is undesirable, you can extract it away from the class and place this logic into the collector).
public class MyBean {
    private Integer id;
    private String name;
    private Map<String, Object> customAttributes;

    public MyBean(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public static MyBean parse(Object[] args) {
        return new MyBean((Integer) args[0], (String) args[1]);
    }

    // getters, setters, equals/hashCode, toString
}

To generate a map using Stream API we can make use of the collector groupingBy(). As a classifier we need to provide function that creates a key - MyBean based on array Object[]. And a downstream collector we can use a collector that combines all "custom attributes" mapped to the same key into a map.
Then we can create a stream over the entries of the intermediate map and parse each entry into MyBean. And finally collect the beans into a list.
That's how it might look like:
public static void main(String[] args) {
    List<Object[]> arrays = buildResultList();

    List<MyBean> beans = arrays.stream()
        .collect(Collectors.groupingBy(
            MyBean::parse,
            Collector.of(
                HashMap::new,
                (Map<String, Object> map, Object[] arr) -> map.put((String) arr[2], arr[3]),
                (left, right) -> { left.putAll(right); return left; })
        ))
        .entrySet().stream()
        .map(entry -> new MyBean(entry.getKey().getId(),
            entry.getKey().getName(),
            entry.getValue()))
        .collect(Collectors.toList());

    beans.forEach(System.out::println);
}

And since MyBean is mutable, take advantage of this by reusing the keys. Note that it's not considered to be a good practice to change the state of the attributes of the lambda expression, for that reason to mutate the key of the map a plain I'm using an enhanced for loop.
public static void main(String[] args) {
    List<Object[]> arrays = buildResultList();

    Map<MyBean, Map<String, Object>> attributesByBean = arrays.stream()
        .collect(Collectors.groupingBy(
            MyBean::parse,
            Collector.of(
                HashMap::new,
                (Map<String, Object> map, Object[] arr) -> map.put((String) arr[2], arr[3]),
                (left, right) -> { left.putAll(right); return left; })
        ));

    List<MyBean> beans = new ArrayList<>();

    for (Map.Entry<MyBean, Map<String, Object>> entry : attributesByBean.entrySet()) {
        MyBean k = entry.getKey();
        k.setCustomAttributes(entry.getValue());
        beans.add(k);
    }

    beans.forEach(System.out::println);
}

Output:
MyBean{id=3, name='name 3', customAttributes={custom_attr_2=custom_attr_2_val_3}}
MyBean{id=1, name='name 1', customAttributes={custom_attr_2=custom_attr_2_val_1}}
MyBean{id=3, name='name 3', customAttributes={custom_attr_3=custom_attr_3_val_3}}
MyBean{id=3, name='name 3', customAttributes={custom_attr_1=custom_attr_1_val_3}}
MyBean{id=2, name='name 2', customAttributes={custom_attr_3=custom_attr_3_val_2}}
MyBean{id=1, name='name 1', customAttributes={custom_attr_3=custom_attr_3_val_1}}
MyBean{id=2, name='name 2', customAttributes={custom_attr_1=custom_attr_1_val_2}}
MyBean{id=1, name='name 1', customAttributes={custom_attr_1=custom_attr_1_val_1}}
MyBean{id=2, name='name 2', customAttributes={custom_attr_2=custom_attr_2_val_2}}


text:
Q: Как в модели SQLALchemy создать свойство класса, а не экземпляра? У меня есть таблица Source которая связывается с моделью Task через таблицу sources_tasks по "методу" Many-To-Many. Также в этой модели определил 2 свойства, которые возвращают динамическое значение, где из БД возвращается всего 2 записи (как мне и нужно):
sources_tasks = db.Table('sources_tasks',
    db.Column('source_id', db.Integer, db.ForeignKey('sources.id', ondelete='CASCADE'), nullable=False),
    db.Column('task_id', db.Integer, db.ForeignKey('tasks.id', ondelete='CASCADE'), nullable=False)
)

class Source(db.Model):

    __tablename__ = 'sources'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    dt_from = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, index=True)
    dt_to = db.Column(db.DateTime, nullable=True)
    url = db.Column(db.String(2048), nullable=False)
    name = db.Column(db.String(60), nullable=True)
    update_period = db.Column(db.Integer, nullable=False, default=1440)
    is_enabled = db.Column(db.Boolean(), nullable=False, default=True)

    user = db.relationship(User, backref=db.backref('sources', lazy='dynamic'), lazy='select') # One-To-One

    # В relationship левая сторона это Source, а правая сторона это таблица Task, т.е. Source связывается с Task:
    tasks = db.relationship('Task',
                            secondary=sources_tasks, # Промежуточная таблица
                            primaryjoin=(sources_tasks.c.source_id == id),
                            secondaryjoin=(sources_tasks.c.task_id == Task.id),
                            backref=db.backref('sources', lazy='dynamic'),
                            # order_by=db.desc(Task.id),
                            lazy='dynamic') # Many-To-Many

    @property
    def last_tasks(self):
        if not hasattr(self, '_last_tasks'):
            self._last_tasks = self.tasks.filter( ((Task.start_dt != None) & (Task.finish_dt != None)) | (Task.finish_dt == None) ) \
                                        .order_by(db.desc(Task.id)).limit(2).all()
        return self._last_tasks

    @property
    def current_task(self):
        if len(self.last_tasks) > 0 and self.last_tasks[0].finish_dt is None:
            return self.last_tasks[0]
        return None

Но проблема заключается в том, что, если у меня несколько Sources в БД, то для каждой записи в БД которая отражается в модели будет вызваться отдельный SQL запрос:
SELECT *
FROM tasks, sources_tasks
WHERE sources_tasks.source_id = ?
  AND sources_tasks.task_id = tasks.id
  AND (tasks.start_dt IS NOT NULL AND tasks.finish_dt IS NOT NULL OR tasks.finish_dt IS NULL)
ORDER BY tasks.id DESC

Если записей 50, то будет 50 SQL запросов. Это плохо. В идеале, я бы хотел получить 2 записи на каждый экземпляр Source, но при этом был бы всего 1 SQL запрос, как например это делает relationship в SQLAlchemy. Например, вот эта связь c lazy='subquery' генерирует один SQL запрос для всех моих Sources:
last_tasks = db.relationship('Task',
                            secondary=sources_tasks, # Промежуточная таблица
                            primaryjoin=(sources_tasks.c.source_id == id),
                            secondaryjoin=((sources_tasks.c.task_id == Task.id) & (Task.start_dt != None) & (Task.finish_dt != None)),
                            order_by=db.desc(Task.id), # Get last task
                            uselist=True, viewonly=True, lazy='subquery') # One-To-One

Получается следующий SQL запрос:
SELECT *
  FROM (SELECT sources.id AS sources_id
          FROM sources
         WHERE ? = sources.user_id
           AND sources.dt_to IS NULL) AS anon_1
  JOIN sources_tasks AS sources_tasks_1
    ON sources_tasks_1.source_id = anon_1.sources_id
  JOIN tasks
    ON sources_tasks_1.task_id = tasks.id
   AND tasks.start_dt IS NOT NULL
   AND tasks.finish_dt IS NOT NULL

ORDER BY anon_1.sources_id, tasks.id DESC

Всё бы хорошо, но возвращает relationship избыточное количество записей, которых может быть 500 или более, а мне нужны только 2 первые записи из этого relationship. Если бы в relationship был бы параметр что-то типа limit=2, которая ограничивала бы выборку из БД, то моя проблема была бы решена.
Как сделать так, чтобы небыло запросов к БД для каждого из экземпляров?

A: Спасибо всем, кто хоть сколько потратил время на мой вопрос, но ответ уже нашёл. Не вдаваясь в подробности, ответ - использовать column-property
В моём случае проблема решается так:
sources_tasks = db.Table('sources_tasks',
    db.Column('source_id', db.Integer, db.ForeignKey('sources.id', ondelete='CASCADE'), nullable=False),
    db.Column('task_id', db.Integer, db.ForeignKey('tasks.id', ondelete='CASCADE'), nullable=False)
)

class Source(db.Model):

    __tablename__ = 'sources'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    dt_from = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, index=True)
    dt_to = db.Column(db.DateTime, nullable=True)
    url = db.Column(db.String(2048), nullable=False)
    name = db.Column(db.String(60), nullable=True)
    update_period = db.Column(db.Integer, nullable=False, default=1440)
    is_enabled = db.Column(db.Boolean(), nullable=False, default=True)

    # Загружается как колонка-подзапрос в родительском SELECT
    next_update_dt = db.column_property(
        db.select(columns=[db.func.coalesce(Task.deferred_dt, datetime.utcnow())])
        .where((sources_tasks.c.source_id == id) & (sources_tasks.c.task_id == Task.id) & (Task.finish_dt == None))
    )

    # Загружается как колонка-подзапрос в родительском SELECT
    last_update_dt = db.column_property(
        db.select(columns=[Task.finish_dt])
        .where((sources_tasks.c.source_id == id) & (sources_tasks.c.task_id == Task.id) & (Task.finish_dt != None))
        .order_by(Task.finish_dt.desc())
        .limit(1)
    )


text:
Q: Generate natural language based on similar phrases I am working on a project and was hoping the community could share some thoughts on how best to approach it.
Situation:

*

*In a current business process, people are manually producing similar but slightly distinct descriptions (distinct in terms of syntax, grammar)

*These descriptions are derived from a set of structured data points. More of such data points are being generated continuously

*The objective is to automatically produce descriptions from these data points

The data points are organised as a dictionary in Python, for example:
thisdict = { "company": "Amazon", "team": "Global Procurement", "employees": 15.0, "contractors": 2.0 }
Below three examples of typical descriptions that are derived from this dictionary:

*

*Amazon Global Procurement is supported by 15.0 employees and a team of 2.0 contractors.

*15 employees are dedicated to Amazon Global Procurement with 2.0 contractors supporting.

*Amazon Global Procurement is supported by 15 heads and an additional 2.0 contractors.

I have a rich data set of these descriptions and the accompanying dictionary with which I hope to train a model that produces descriptions based on new additions to the dictionary.
I thought that the sentence generation task could be approached via Markov Chains. However, I need to preserve the associations in the dictionary (i.e. the number 15.0 needs to be linked to the term 'employees' or related synonyms) and I am not sure how to incorporate these dictionary pairs into the model.
Any suggestions would be appreciated.
Thanks

A: If I understood correctly, you are trying to generate text/sentences given structured data i.e. entities for this particular case. This project does the same. You can try out this project.


text:
Q: ui:param not working when f:metaData is present I'm using JSF 2.1 and I want to pass a parameter to a custom tag that records the url and the page title using ui:param to the tag. This works fine, but if there is a f:metadata section no data is passed, i.d. the dynamicBreadCrumb.addItem() from the template is not called during the preRenderView.
This is the page using a template

<ui:param name="tilte" value="#{msg['PAGE_HEADER.ORDER']}"/>

<f:metadata>
    <f:viewParam name="orderNumber"
                 value="#{editOrder.model.orderNumber}"/>
</f:metadata>

... and so on

This is the custom tag
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
            xmlns:h="http://java.sun.com/jsf/html"
            xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:param name="page" value="#{page}"/>
<ui:param name="param" value="#{paramValues}"/>
<h:form id="history" >
    <h:outputText value="#{msg['COMMON.HISTORY_BAR']}" />

        <ui:repeat value="#{dynamicHistoryBean.items}" var="item">

#{item.title}

        </ui:repeat>

</h:form>

This is the template
<ui:param name="title" value="#{title}"/>
<ui:param name="param" value="#{paramValues}"/>

<f:metadata>
    <f:event type="preRenderView" listener="#{dynamicHistoryBean.addHistoryItem(title,param)}"/>
</f:metadata>


text:
Q: JAVA: No way to get destination address of a received datagram packet? Searched a lot in the web, but seemed there is no way to let me know the destination address of a received datagram packet in Java.
My Java UDP server is running on a multiple interfaces host (most of them are virtual interfaces), so when the server received a packet, I need to get the packet's destination address, with which I would be able to create a socket that bind to this specific receiving address then use it to send the response.
socket = new DatagramSocket(12345);
socket.receve(packet);
/* here I need to bind the socket to the same address as that in
 * the destination part of the received packet.
 * But I found I can't ...
 */
socket.send(new DatagramPacket('data', len, packet.getSocketAddress());

I just cannot believe such a simple thing (in C) cannot be accomplished in Java. Could someone give me hint?  Thanks in advance!


text:
Q: Python try except finally invalid syntax error So I was trying to use this exception handling in python. I'm using python2.7 and flask for this. Also I am new to both python and flask so I must be doing something wrong here.
if test:
    cursor = conn.cursor()
    try:
        print cursor.execute("INSERT INTO Users (email, password, firstname, lastname, home, gender, dob, bio, profile_Image) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}')".format(email, password, firstname, lastname, home, gender, dob, bio, photo_data))
        conn.commit()
        #log user in
        user = User()
        user.id = email
        flask_login.login_user(user)
        uid = getUserIdFromEmail(flask_login.current_user.id)
        today = str(date.today())
        print today
    except Exception as e:
        print e
        print "Something Went wrong"
        return flask.redirect(flask.url_for('register'))
    print cursor.execute("INSERT INTO Album (uid, aname, adate, cover) VALUES ('{0}', 'default', '{1}', '{2}')".format(uid, today, photo_data))
    aid = getAIDfromAname('default', uid)
    cursor.execute("INSERT INTO Photo (uid, aid, data, caption) VALUES ('{0}', '{1}', '{2}', 'profile')".format(uid,aid,photo_data))
    cursor.execute("INSERT INTO Scoreboard (uid) VALUES ('{0}')".format(uid))
    conn.commit()
    finally:
        cursor.close()
    return render_template('profile.html', firstname=firstname, message='Account Created!')

else:
    print "couldn't find all tokens"
    return render_template('register.html', message='Email Already Exists')

and then It gives me this error if I run the app
  File "app.py", line 540
finally:
      ^SyntaxError: invalid syntax

I am wondering why it's giving me the error :/

A: if test:
    cursor = conn.cursor()
    try:
        print cursor.execute("INSERT INTO Users (email, password, firstname,
lastname, home, gender, dob, bio, profile_Image) VALUES ('{0}', '{1}', '{2}',
'{3}', '{4}', '{5}', '{6}', '{7}', '{8}')".format(email, password, firstname,
lastname, home, gender, dob, bio, photo_data))
        conn.commit()
        #log user in
        user = User()
        user.id = email
        flask_login.login_user(user)
        uid = getUserIdFromEmail(flask_login.current_user.id)
        today = str(date.today())
        print today
    except Exception as e:
        print e
        print "Something Went wrong"
        print cursor.execute("INSERT INTO Album (uid, aname, adate, cover) VALUES ('{0}', 'default', '{1}', '{2}')".format(uid, today, photo_data))
        aid = getAIDfromAname('default', uid)
        cursor.execute("INSERT INTO Photo (uid, aid, data, caption) VALUES ('{0}', '{1}', '{2}', 'profile')".format(uid,aid,photo_data))
        cursor.execute("INSERT INTO Scoreboard (uid) VALUES ('{0}')".format(uid))
        conn.commit()
        return flask.redirect(flask.url_for('register'))
    finally:
        cursor.close()
    return render_template('profile.html', firstname=firstname, message='Account
Created!'))

else:
    print "couldn't find all tokens"
    return render_template('register.html', message='Email Already Exists'

This would work. The indentation on the line "print cursor.execute" inside except block was incorrect.


text:
Q: Operator does not exist: jsonb = integer I am getting the following postgres error:
"operator does not exist: jsonb = integer"

I have my application hosted on Heroku and am using a Postgres 9.4 DB. Below is what my accounts controller looks like with the ahoy_matey analytics gem.
Accounts Controller
class AccountsController < ApplicationController
  before_filter :authenticate_user!

  def index
    if current_user.business_id
      @business = Business.find(current_user.business_id)
      # analytics
      @monthly_business_views = ahoy_event_sum("Page Viewed", @business.id)
      @monthly_get_websites = ahoy_event_sum("Visited Website", @business.id)
      @monthly_get_directions = ahoy_event_sum("Directions Viewed", @business.id)
      @monthly_get_fb_shares = ahoy_event_sum("Shared via Facebook", @business.id)
      @monthly_get_tweets = ahoy_event_sum("Tweeted via Twitter", @business.id)
      @reviews = Review.where(:business_id => @business).all
    end
  end

  ...

  def ahoy_event_sum(event, business_id)
    Ahoy::Event.where(name:event, properties: business_id).count
  end

end

Ahoy Events Model
module Ahoy
  class Event < ActiveRecord::Base
    self.table_name = "ahoy_events"

    belongs_to :visit
    belongs_to :user

    serialize :properties, JSON
  end
end

I have intermediate skills and apologize if this question has a simple fix, please provide any details on how I would solve this issue. Thanks!


text:
Q: Not able to solve KlockWork Buffer Overflow error I am not able to figure out the solution for this KlockWork issue.
KlockWork is showing ABV.GENERAL (1:P1) Defer for the following code
void fun1(uint32_t size)
{
  if(size > 256)
  {
    return;
  }
  uint32_t *arr = (uint32_t *)malloc(size * sizeof(uint32_t));
  if(arr == NULL)
  {
    return;
  }
  memset(arr, 0, size * sizeof(uint32_t));
  fun2(arr, size);
  free(arr);
}

void fun2(uint32_t *arr, uint32_t size)
{
  uint32_t i = 0;
  if(size > 256)
  {
    return;
  }
  while( i < size )
  {
    arr[i] = i;
    printf("%d", arr[i]);
    i++;
  }
}

Error: Array 'arr' of size 'size*4' may use index values(s) min(size+(-1), 255)..min(size+(-1), 255)

Please suggest some ways to avoid this error.
Thanks

A: In my opinion, you lack one of these header files, or the forward function prototype for the fun2 function:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>

void fun2(uint32_t*arr, uint32_t size);

I have compiled your code prepending all this stuff, and no warnings or errors got.  Plus what I have told you in the comments to your question.


text:
Q: Google Analytics find total session duration of all users I'm digging through my Google Analytics menu and I can't seem to find a report that displays the total session duration of all users in a time period. Is this possible?

A: You are looking for Average Session Duration, yes?
Average Session Duration is shown as a sparkline widget in Audience - Overview. You might need to scroll your browser page down to see it.
Avg Session duration is also a column in the Home screen.
If you want Total Session Duration, just multiply total visits by Avg Session Duration.  I don't know why you'd want that though - it sounds like a useless statistic.


text:
Q: Windows file content not updated in Explorer/Powershell On a Windows Server a logging tool writes .log files to disk continuesly and rotates log files daily at midnight. Every day the new log file gets created, but almost every day its content / meta data does not get updated afterwards in Windows Explorer and Powershell.
Example: A file was created on May 17th, 2022 at 0:00. It has a size of roughly 24KB in Windows Explorer and has a last write time at about midnight (I didn't check the exact time to the second). If I use Powershell
(Get-Item).Length

I get a size of 24401.
Now when I right click the same file the Windows Explorer and inspect its properties it updates the size to 4,593KB and last write time to May 17th, 2022 09:34. The exact time and size does not really matter, but the problem is this: Why is the Windows Explorer and Windows Powershell completeley out of sync with the underlying filesystem like that? What can even cause a discrepancy like this?
Another time I used this to test if the file gets copied out of sync or with the correct content:
Copy-Item ".. source file .." -Destination ".. somewhere .."

the attributes of the original file get updated so I can use that as a really bad workaround to always have the latest version of the file actually available in Powershell as I'm analysing the file with a Powershell script and really need all of its content and not only the content the file had when it was created 9h earlier.
Did anyone ever witness this kind of behaviour in Windows?

*

*Filesystem: NTFS

*OS: Windows Server 2019 Version 1809 Build
17763.2803

*"Hardware": virtual Server on VMware ESXi Server

A: Yes this is because the process is still writing to the file and the buffers are not flushed.
Typically, when you want to write to a file you can (roughly) do something like that:
1. Create/Open a file and retrieve a "channel" (a handle) towards the file
2. Write something
3. Flush the buffer/Close the file "channel" (handle) (=commit to disk)
(then, repeat 1, 2 and 3 when you want to write something again)

However doing something like that is okay if you want to write something once in a while, because "Opening the handle to the file" and "Flushing the buffers" is not "free" when it comes to performance.
This means that if you plan to frequently write to a file, it's better to just Create/Open a file, then Write multiple times, as needed, and when you're done Flush or Close the handle (in my example above this means 1, 2 [repeat step 2 as needed], then, later, 3)
And while the data are not Flushed to disk / committed: you can't rely on them!
Microsoft provides more details about that:
Flushing System-Buffered I/O Data to Disk

[...]Windows stores the data in file read and write operations in system-maintained data buffers to optimize disk performance. When an application writes to a file, the system usually buffers the data and writes the data to the disk on a regular basis[...]

The FlushFileBuffers Windows API doc says:

[...]Typically the WriteFile and WriteFileEx functions write data to an internal buffer that the operating system writes to a disk or communication pipe on a regular basis. The FlushFileBuffers function writes all the buffered information for a specified file to the device or pipe.
Due to disk caching interactions within the system, the FlushFileBuffers function can be inefficient when used after every write to a disk drive device when many writes are being performed separately.[...]

CreateFile documentation:

[...]When an application is finished using the object handle returned by CreateFile, use the CloseHandle function to close the handle. This not only frees up system resources, but can have wider influence on things like sharing the file or device and committing data to disk. Specifics are noted within this topic as appropriate.[...]

More information about File Caching available here, note that:

File system metadata is always cached. Therefore, to store any metadata changes to disk, the file must either be flushed or be opened with FILE_FLAG_WRITE_THROUGH.

So, as you can see, the behavior depends on the design of the application, it's not uncommon to see that log files are only flushed to disk only once in a while for performance reasons and you can't rely on metadata such as date/time, file size, or even file content while the application is still writing to the file.


text:
Q: How can I read windows product licence key from UEFI in Linux? There are some machines with windows 10 preinstalled where the product key is stored in the UEFI. How can I retrieve this key?

A: The key is stored in an ACPI table named MSDM which can be retrieved via
~# xxd /sys/firmware/acpi/tables/MSDM
00000000: 4d53 444d 5500 0000 0364 4d45 4449 4f4e  MSDMU....dMEDION
00000010: 4d45 4449 4f4e 4147 0000 0000 5445 5354  MEDIONAG....TEST
00000020: 0000 0000 0100 0000 0000 0000 0100 0000  ................
00000030: 0000 0000 1d00 0000 1234 1234 1234 1234  ........HERE-THE
00000040: 1234 1234 1234 1234 1234 1234 1234 1234  WINDOWS-PRODUCT-
00000050: 1234 1234 12                             KEY

Or, even simpler
~# strings /sys/firmware/acpi/tables/MSDM
MSDMU
dMEDIONMEDIONAG
TEST
YOUR-WINDOWS-LICENCE

Source


text:
Q: difference between 'first grader' and 'first year student' I'm sorry I don't have any context. But I'm just wondering if there's a difference between 'first grader' and 'first year student'.

A: If you don't have any context, I'm afraid, these are not the same phrases.
Because, first grader means (US) a child in the first grade but when you say 'First year student' it could be the first year of a professional degree as well. Say -- A first year student of arts/science/commerce whatever...

A: First grade is the first class in elementary school. Children in these classes are usually between 6 and 7 years old.
The term 'first year student' can be used for all people who are in first class (primary, secondary school, etc.).
Conclusion: Without any context, there is a difference.


text:
Q: Почему выдаёт ошибку при попытки скачивания библиотеки pyAudio? (venv) david@MacBook-Air-David Apex % pip install pyaudio
Collecting pyaudio
  Using cached PyAudio-0.2.12.tar.gz (42 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: pyaudio
  Building wheel for pyaudio (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for pyaudio (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [16 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.macosx-10.9-universal2-cpython-311
      copying src/pyaudio.py -> build/lib.macosx-10.9-universal2-cpython-311
      running build_ext
      building '_portaudio' extension
      creating build/temp.macosx-10.9-universal2-cpython-311
      creating build/temp.macosx-10.9-universal2-cpython-311/src
      clang -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -DMACOSX=1 -I/usr/local/include -I/usr/include -I/Users/david/Documents/Apex/venv/include -I/Library/Frameworks/Python.framework/Versions/3.11/include/python3.11 -c src/_portaudiomodule.c -o build/temp.macosx-10.9-universal2-cpython-311/src/_portaudiomodule.o
      src/_portaudiomodule.c:31:10: fatal error: 'portaudio.h' file not found
      #include "portaudio.h"
               ^~~~~~~~~~~~~
      1 error generated.
      error: command '/usr/bin/clang' failed with exit code 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pyaudio
Failed to build pyaudio
ERROR: Could not build wheels for pyaudio, which is required to install pyproject.toml-based projects


text:
Q: Angular2 ngFor: What am I doing wrong? I'm having difficulty overcoming the "Cannot find a differ supporting object '[object Object]' of type 'object'" error that seems to be really common with Angular2, and I'm hoping someone has encountered something similar.
Here's the (anonymized) JSON coming from my service, which is really simple:
[
    {
        "item_id": 1,
        "item_type": 2,
        "item_name": "Item 1",
        "item_description": "First item"
    },
    {
        "item_id": 2,
        "item_type": 4,
        "item_name": "Item 2",
        "item_description": "Second item"
    }
]

And here's the contents of my class, service, and component that describes these objects:
// item.ts
export class Item {
    item_id: number;
    item_type: number;
    item_name: string;
    item_description: string;
}

//item.service.ts snippet
getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then((response) => {
        let body = response.json();
        return body as Item[];
    })
    .catch(this.handleError);
}

//item.component.ts snippet
items: Item[];

getItems(): void { // Function that calls the item service
    this.itemService
    .getItems()
    .then((items) => {
        console.log(items); // I use this to verify that I'm getting an array.
        this.items = items;
    });
}

And finally, the ngFor component:

         {{item.item_name}}

I'm not seeing anything wrong with any part of this. The retrieved data definitely does reach the item component, which means my imports are correct, and what shows up in my console.log is definitely an array, with the __proto__:Array[0] property and everything. It even looks identical to what gets output if I console log the Angular tutorial Heroes app. Yet it simply will not iterate over the array, insisting that it's an object.
What am I doing wrong? Is ngFor just broken?
Edit
Here is the complete (anonymized) class, with unrelated bits removed:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Headers, Response, Http, RequestOptions } from '@angular/http';
import { Item } from '../../classes/item/item';
import { ItemService } from '../../services/item/item.service';

@Component({
    moduleId: module.id,
    selector: 'my-items',
    templateUrl: 'items.component.html'
})
export class ItemComponent implements OnInit {
    items: Item[] = [];

    constructor(
    private router: Router,
    private itemService: ItemService
    ) { }

    getItems(): void {
        console.log(this.items);
        this.itemService
        .getItems()
        .then((items) => {
            console.log(items);
            this.items = Array.from(items);
        });
    }

    ngOnInit() {
        this.getItems();
    }
}

Edit 2:
I got it! And I think it might be a bug in Angular2. Above, I sanitized my code by using a generic variable name called "items." But in the real, production code, the variable is called "entities." And for the whole time, I've had it named like that. On a whim, I changed the name of the variable to "testentities," and it worked!
So just to make sure, I tested with multiple variations, and it worked every time. Then I changed it back to "entities," and the error reappeared. It seems to be a reserved variable of some kind.
I'll rigorously test this out, and if it is consistently reproducible, I'll report it on the bug tracker.

A: Give this a try
item.service.ts snippet
getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then((response) => {
        let body = response.json();
        return body;
    })
    .catch(this.handleError);
}

item.component.ts snippet
items: Item[] = []; // For whatever reason it thinks this is an Object

getItems(): void { // Function that calls the item service
    //this.items = Array.from(this.items);
    this.itemService.getItems().then(items => this.items = items);
}

[UPDATE]
Alight, you have exhausted my debugging resources, so I will take it to the basics,
Angular 2 HTTP Client is where they show you how to make a GET request. Then HERE is the Promise based setup.
So going off of that this is what yours should look like.
item.service.ts snippet
getItems(): Promise<Item[]> {
    return this.http.get('http://apiurl', { withCredentials: true })
    .toPromise()
    .then(this.extractData)
    .catch(this.handleError);
}
private extractData(res: Response) {
  let body = res.json();
  return body || { };
}
private handleError (error: any) {
  // In a real world app, we might use a remote logging infrastructure
  // We'd also dig deeper into the error to get a better message
  let errMsg = (error.message) ? error.message :
    error.status ? `${error.status} - ${error.statusText}` : 'Server error';
  console.error(errMsg); // log to console instead
  return Promise.reject(errMsg);
}

item.component.ts
items: Item[] = [];

getItems(): void {
  this.itemService.getItems().then(items => this.items = items);
}

UPDATE #2
It sounds like the OP figured out his problem and it had to do with the name of one of the variables, it would appear that a variable named entites could cause Angular 2 to break.

"But in the real, production code, the variable is called "entities." And for the whole time, I've had it named like that. On a whim, I changed the name of the variable to "testentities," and it worked!
So just to make sure, I tested with multiple variations, and it worked every time. Then I changed it back to "entities," and the error reappeared."

entities: any{};


text:
Q: Python | librosa: how to stretch signal in time by adding more points I need help figuring out how to stretch a sample of, say, from 0.25 to 1 second using librosa package. I suppose librosa.effects.time_stretch is a function to do so, but instead of stretching a signal, it does something else. What is the correct way of applying it or some other librosa or numpy function (or pydub)?
Here is my attempt using 16 KHz sampling rate, i.e. 4K samples is given over 0.25 second time period. As the output, I need 16K samples for the full 1 second duration, keeping the sampling rate constant.
import numpy as np, librosa
x = np.sin(np.linspace(-np.pi, np.pi, 4000))  # wav sample
y = librosa.effects.time_stretch(x, rate=4000/16000)
plt.plot(x)  # plotted in blue
plt.plot(y)  # plotted in orange

that yields the following plot:

Notably, the sine signal was not stretched. I'm using sin() as an example. The intent is to stretch voice audio wav files, where the analytical function is unknown.

A: I think that time_stretch applies some processing to try to preserve the pitch of the audio. What you want is probably
y = librosa.core.resample(x, 4000, 16000)

which gives this plot:


text:
Q: Why ssh fingerprint now is given in base64 format instead of hex? I see an old question showing that when ssh connecting to a server, a hex fingerprint is displayed.
Why now is given in base64 format? What's the benefit?
I know MD5 is broken and now the default is sha256, but as for the fingerprint format, however, base64 encode and hex strings, are/indicates the same thing. What's the benefit on changing the format then?

A: It's not just the output format that has changed, but the algorithm used to generate the fingerprint. It used to be MD5, and now it is SHA256. MD5 is broken in many respects, and the general recommendation is to use SHA256 or the like. A change like that was long in coming.
From the release notes:

*

*Add FingerprintHash option to ssh(1) and sshd(8), and equivalent
  command-line flags to the other tools to control algorithm used    for
  key fingerprints. The default changes from MD5 to SHA256 and    format
  from hex to base64.
Fingerprints now have the hash algorithm prepended. An example of
  the new format: SHA256:mVPwvezndPv/ARoIadVY98vAC0g+P/5633yTC4d/wXE
  Please note that visual host keys will also be different.

You can still get the old output:
ssh -o FingerprintHash=md5 ...

SHA256 hashes have 256 bits of output, which translates to 64 characters in hex. That's double the length of the 32-character MD5 hash in hex. Base64 encoded SHA256 characters are only 44 bytes in length (and the last = for padding is omitted anyway).


text:
Q: Can you split a file using ffmpeg directly from a db? I am splitting a file using ffmpeg and python. I am able split a file if I input a file path, but if I send in the file itself from my mongodb, it errors out. Is there a way to get ffmpeg to run using the file instead of the path to the file?
python code:
args = [ffmpeg_binary,
                         "-v", "quiet",
                         "-y", "-i", video_file, "-vcodec", "copy", "-acodec", "copy",
                 "-ss", "00:00:00", "-t", "00:00:10", "-sn",
                 output_file_name ]

pipe = sp.Popen(args)

if video_file is a gridfs.grid_file.GridOut object or a (gridfs.grid_file.GridOut object).read(), I get:
Traceback (most recent call last):
  File "C:/dev/youniversity/test.py", line 21, in <module>
    split_vid_from_file(vid_file)
  File "C:\dev\youniversity\src\lib\ffmpeg_lib.py", line 107, in split_vid_from_file
    pipe = sp.Popen(args)
  File "C:\Python27\lib\subprocess.py", line 709, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 957, in _execute_child
    startupinfo)
TypeError: must be string without null bytes or None, not str

How do I split the video directly from the DB?
EDIT: I found that you can do this:
... "-y", "-", ...

pipe = sp.Popen(args, stdin=sp.PIPE)

but I don't want the user to type input, I want to pipe in the variable.

A: I suggest to you use django-multimedia in order to split videos.
https://github.com/jbittel/django-multimedia


text:
Q: Adding filters to dynamic search engine php i'm working on adding filters to my database but i have no knowledge and google didnt really help so i appreciate all the advice =)
I would like to add filters like name and price and arrange by asc and desc order.
my db has 4 columns, id(int15) , brand/model(varchar50), picture(longblob), price (varchar50).
Any advice on how to approach this(best if have some examples as i'm a beginner)?
Currently below i created the form asc and desc below but i have no idea on how to integrating to my php code. I've set the form name as "results"
What i currently have is
index.php
<form action="search.php" type="text"  method="POST">
Name: <input type ="text" name="search_name" size='30' />
<input type="submit" value="Search">

Arrange Price by :

<select name="results">
<option value="">Select...</option>
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>

<?php

if (isset($_POST['search_name'])) {
        $search_name = $_POST['search_name'];

        if (!empty($search_name)){

            if (strlen($search_name)>=3) {

            $query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY `price` ASC";
            $query_run = mysql_query($query);
            $query_num_rows = mysql_num_rows($query_run);

            if ($query_num_rows>=1) {
                echo $query_num_rows.' Results found:
';

                while ($query_row = mysql_fetch_array($query_run)) {

                        $picture = $query_row['picture'];
                        echo "
";
                        echo $query_row ['brand/model'];
                        echo str_repeat(' ', 15); // adds 5 spaces
                        echo $query_row ['price'];
                        echo "
";
                        echo "
";
                        //header("content-type: image/jpeg");
                        echo "";
                        echo "
";

                }
            } else {
                echo 'No Results Found.';
            }
        } else {
            echo 'Text field must be more than 3 characters.';
        }

    } else {
        echo 'Text Field Cannot be Empty!';
    }
}

?>

A: Use of POST is fine, so long as you are sanitizing your input to prevent against SQL injections.  To further protect yourself, you can use prepared statements.  Also, I see you are using the mysql_* API.  I highly recommend you switch to MySQLi or PDO instead.  I'll place emphasis on MySQLi in this case since it looks as if you are using MySQL (although PDO will work for MySQL as well).
For the searching component:
Fields are best searched if they have been indexed.  The database will use this behind the scenes to get at your data quicker.  However, using the LIKE % <your search string> % with the wildcards (%) like you are will negate any index you have placed on a column.  This is because using a wildcard on the left hand side of a search doesn't allow the MySQL to make use of the index. (Long story short, it simply can't figure out if text matches unless it scans the entire table.) What it sounds like you need is a FULLTEXT index which you can run queries using the MATCH...AGAINST syntax.  You can use LIKE on an indexed column if you want, but drop the left hand wildcard, e.g.: SELECT * FROM ...... LIKE 'your search value'% .....
So from here I would suggest you look into the following concepts/topics:

*Prepared statements in PHP using MySQLi (or PDO)

*Column indexes (specifically FULLTEXT indexes for searching purposes)

*Fulltext searching for MyISAM tables (MySQL < 5.6) or Fulltext searching for InnoDB (MySQL 5.6+)

*Internal "scoring" for FULLTEXT and how to use it

*Boolean and natural language searching.
Adding a search filter like you want is a nice feature, but it takes a little more than what you are trying to do.  (And trust me, Google will provide you plenty of information and these subjects.  It is a matter of practicing and getting use to using the newer features of MySQL.)

A: • Use PDO or Mysqli prepared statement .
• I'll use regex to filter the inputs (remove all non-words,numbers and some chars) .
example: $string = preg_replace('~[^\w\s-_\.,]~','',$string);

• I'll use full text search .

A: Try using this code,

*

*Changes what I have done are, created anchor's of your field name as table header

*by default the headers are in ASC order, if we click it, it changes to DESC order

*the sql query then uses the field name in GET to order the records

*the search term is also then saved in the GET request so that we can persist it ahead

*as search term is sometimes received in GET and sometimes in POST, have used REQUEST here, to get data

    if (!empty($search_name)){

        if (strlen($search_name)>=3) {

            if(empty($_REQUEST['searchTrm']))
                $_REQUEST['searchTrm'] = 'price';

            if(empty($_REQUEST['order']))
                $_REQUEST['order'] = 'ASC';

            $query = "SELECT * FROM `shoes` WHERE `brand/model` LIKE '".mysql_real_escape_string($search_name)."%' ORDER BY ".$_REQUEST['searchTrm']." ".$_REQUEST['order'];

            $query_run = mysql_query($query);
            $query_num_rows = mysql_num_rows($query_run);

        if ($query_num_rows>=1) {
            echo $query_num_rows.' Results found:
';
?>

                    <?php
//use your sql field name as searchTrm value
if($_REQUEST['searchTrm'] == 'brand/model' && $_REQUEST['order'] == 'DESC') { ?>
                        <a href='?searchTrm=brand/model&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Brand Name
                    <?php } else { ?>
                        <a href='?searchTrm=brand/model&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Brand Name
                    <?php } ?>

                    <?php if($_REQUEST['searchTrm'] == 'price' && $_REQUEST['order'] == 'DESC') { ?>
                        <a href='?searchTrm=price&order=ASC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'ASC'>Price
                    <?php } else { ?>
                        <a href='?searchTrm=price&order=DESC&search_name=<?php echo $_REQUEST['search_name']?>' title = 'DESC'>Price
                    <?php } ?>

                Image

            <?php
            while ($query_row = mysql_fetch_array($query_run)) {
                 $picture = $query_row['picture'];
                ?>

                    <?php echo $query_row['brand/model'];?>
                    <?php echo $query_row['price'];?>
                    <img src='image.php?id=<?php echo $query_row['id'];?>' width='300' height='200' />

                <?php
            }
        ?>
 <?php
        } else {
            echo 'No Results Found.';
        }
    } else {
        echo 'Text field must be more than 3 characters.';
    }

} else {
    echo 'Text Field Cannot be Empty!';
}
}


text:
Q: Change values inside array based on logic - Python I have an array (called 'img') that I want to modify.
img
array([[[244, 244, 244],
    [248, 248, 248],
    [249, 249, 249],

I want to change the values in the array to 0 if they are below 200 and convert to 255 if they are above or equal to 200:
for value in img:
    if value < 200:
         value = 0
    else:
         value = 255

However, I am getting this error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How can I get this code to work?

A: You can use a boolean array in np.where:
np.where(img<200, 0, 255)

For the example you provided all values are above 200 so it will return 255 all the time but for 245:
np.where(img<245, 0, 255)
Out[4]:
array([[[  0,   0,   0],
        [255, 255, 255],
        [255, 255, 255]]])

A: Simple solution using Numpy where method. Pass Logic as first argument, if True (second argument), if False (third argument).
img = np.where(img<200.0, 0.0, 255.0)


text:
Q: DataGrid export to excel I have a DataGrid control that fills with a data set.
I don't show all fields of data set in DataGrid control.
I want to create an excel file from my DataGrid.
How to get solution?
(windows form , vb net 1.1)

A: Try this
Link
OR
Try This
Imports Excel = Microsoft.Office.Interop.Excel

Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

 wBook = excel.Workbooks.Add(System.Reflection.Missing.Value)
wSheet = wBook.Sheets("sheet1")

  With wBook
.Sheets("Sheet1").Select()
.Sheets(1).Name = "NameYourSheet"
End With

For i = 0 To DataGrid1.RowCount - 1
For j = 0 To DataGrid1.ColumnCount - 1
wSheet.Cells(i + 1, j + 1).value = DataGrid1.Rows(i).Cells(j).Value.tosring
Next j
Next i

wSheet.Columns.AutoFit()

A: Private Sub btnExportToExcel_Click(sender As Object, e As EventArgs) Handles btnExportToExcel.Click

        Dim xlApp As Excel.Application = New Excel.Application

        xlApp.SheetsInNewWorkbook = 1

        Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Add
        Dim xlWorkSheet As Excel.Worksheet = xlWorkBook.Worksheets.Item(1)

        xlWorkSheet.Name = "Example_Export"

        For nRow = 0 To dgvDataToExport.Rows.Count - 1

            For nCol = 0 To dgvDataToExport.Columns.Count - 1
                xlWorkSheet.Cells(nRow + 1, nCol + 1) = dgvDataToExport.Rows(nRow).Cells(nCol).Value
            Next nCol

        Next nRow

        xlApp.DisplayAlerts = False

        xlWorkBook.SaveAs("C:\Example.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
                           Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges)

        xlWorkBook.Close()
        xlApp.Quit()

    End Sub

A: Try with this one:
Sub create_excel(sender As Object, e As EventArgs)
    Dim strFileName As string
    Dim tw As New StringWriter()
    Dim hw As New HtmlTextWriter(tw)

    strFileName = "some_excel_from_datagrid.xls"
    Response.ContentType = "application/vnd.msexcel"
    Response.AddHeader("Content-Disposition", "attachment; filename=" & strFileName)
    Response.Charset = "UTF-8"
    Response.ContentEncoding = Encoding.Default

    DataGridID.RenderControl(hw)

    Response.Write(tw.ToString())
    Response.End()
End Sub

A: Maybe in this princip work.
  String path = @"D:\users\....";
    //your path

String connStr = "Provider=//your provider;Data Source=" + path + ";Extended Properties=Excel 12.0;";

            //The connection to that file

            OleDbConnection conn = new OleDbConnection(connStr);

            //The query

            string strSQL = "SELECT * FROM [?]";

            //The command

            OleDbCommand cmd = new OleDbCommand(/*The query*/strSQL, /*The connection*/conn);

            DataTable dT = new DataTable();

            conn.Open();

            try

            {

                OleDbDataReader dR = cmd.ExecuteReader();

                dT.Load(dR);

                bS.DataSource = dT;

                dGV.DataSource = bS;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            finally

            {

                conn.Close();

            }

A: Try
        If Not dgv.RowCount = 0 Then
            Dim folderBrowser As New FolderBrowserDialog
            folderBrowser.Description = "Select location to save the report"
            Dim filepath1 As String = ""
            If (folderBrowser.ShowDialog() = DialogResult.OK) Then
                filepath1 = folderBrowser.SelectedPath
            Else
                Exit Sub
            End If

            Dim xlApp As Microsoft.Office.Interop.Excel.Application
            Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
            Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
            Try

                Dim misValue As Object = System.Reflection.Missing.Value
                Dim i As Integer
                Dim j As Integer
                xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
                xlWorkBook = xlApp.Workbooks.Add(misValue)
                xlWorkSheet = xlWorkBook.Sheets("sheet1")
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                Dim titleStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle1")
                titleStyle.Font.Bold = True
                titleStyle.Font.Size = "18"
                titleStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)

                xlWorkSheet.Cells(2, 2) = "Employee Payment Report"
                xlWorkSheet.Cells(2, 4) = DateAndTime.Now.ToString("dd/MM/yyyy")
                xlWorkSheet.Cells(2, 2).Style = "NewStyle1"
                xlWorkSheet.Cells(2, 4).Style = "NewStyle1"
                ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

                '======================================================================================================
                Dim headerStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle")
                headerStyle.Font.Bold = True
                headerStyle.Font.Size = "12"
                headerStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Brown)

                For k = 1 To dgv.Columns.Count
                    xlWorkSheet.Cells(4, k) = dgv.Columns(k - 1).HeaderText
                    xlWorkSheet.Cells(4, k).Style = "NewStyle"

                Next
                '=======================================================================================================
                Dim str As String = ""
                Dim l As Integer = 1
                j = 6
                Dim amt As Double = 0.0
                For i = 0 To dgv.RowCount - 1
                    amt = amt + dgv.Rows(i).Cells(4).Value
                    For m = 0 To dgv.ColumnCount - 1
                        xlWorkSheet.Cells(j, l) = dgv(m, i).Value.ToString()
                        str = dgv(m, i).Value.ToString()
                        l = l + 1
                    Next
                    j = j + 1
                    l = 1
                Next
                '======================================================================================================
                Dim lastStyle As Excel.Style = xlWorkSheet.Application.ActiveWorkbook.Styles.Add("NewStyle2")
                lastStyle.Font.Bold = True
                lastStyle.Font.Size = "12"
                lastStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)
                Dim c As Integer = dgv.ColumnCount
                xlWorkSheet.Cells(j + 2, c - 1) = "Total Amount"
                xlWorkSheet.Cells(j + 2, c) = amt.ToString
                xlWorkSheet.Cells(j + 2, c - 1).Style = "NewStyle2"
                xlWorkSheet.Cells(j + 2, c).Style = "NewStyle2"
                '=======================================================================================================
                xlWorkSheet.SaveAs(filepath1 + "\EmployeePaymentReport.xlsx")
                xlWorkBook.Close()
                xlApp.Quit()

                cls.releaseObject(xlApp)
                cls.releaseObject(xlWorkBook)
                cls.releaseObject(xlWorkSheet)

                MsgBox("You can find the file at " + filepath1 + "\EmployeePaymentReport.xlsx")
            Catch ex As Exception
                MsgBox(ex.Message)
                For Each Process In System.Diagnostics.Process.GetProcessesByName("EXCEL")
                    If Process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE") Then
                        Process.Kill()
                    End If
                Next
            End Try
        Else
            Exit Sub
        End If
    Catch ex As Exception

    End Try
End Sub


text:
Q: How to make the code compile and preserve functionality? i am new into java.. How do i fix this, so it will compile and preserve the functionality without changing dingo method. So this code should check if Pingo is a valid class.
class Pingo<T> {
    public void dingo(T t ) {
        System.out.println(t.bingoString( )) ;
    }
}

A: The T is a generic type. In your case it's the Object class which doesn't have a method called bingoString. You need to create a class which has this method for the template. E.g.:
// still your class
class Pingo<T extends Blub> {
    public void dingo(T t) {
        System.out.println(t.bingoString());
    }
}
// a class which provides the signature
class Blub {
    public String bingoString() {
        return "test";
    }
}


text:
Q: Creating a Pause in Swift I'm trying to make a very simple app in Xcode, basically each day that a user is using the app, a new message will appear in the center.  The trouble is, I'm using an index to attempt to make a simple counter.  However when it first starts, the app doesn't load until it reaches the final quote.  When I attempt to create a function where it pauses for a certain amount of time, the app waits until that time has fully passed for each individual index so that when it loads it still only shows the last quote.
If anyone has any suggestions on how to create a pause that won't freeze the app, or for a better method for doing this, it would be greatly appreciated.
This is all that I pretty much have for the coding right now:
@IBOutlet var quoteLabel: UILabel!
var quotearray = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]

override func viewDidLoad() {

for index in 0...9 {
quoteLabel.text = (quotearray[index])
    }

A: Declare:
   func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }

Use this function for pause as:
delay(3.0) {
 // your code here
}

Store the index in UserDefaults and increment everytime you show your quote.


text:
Q: Firebase Auth and Caledar API I am trying to log in a user and create an event in their calendar.
I am using Firebase Auth and Google Calendar API. I am not sure how I can use Firebase Access Token to create event for the user.

 <script type="text/javascript">
      initApp = function() {
        firebase.auth().onAuthStateChanged(function(user) {
          if (user) {
            user.getIdToken().then(function(accessToken) {
            //how can I use this accessToken to create event in the calendar?
            });
          } else {}
        }, function(error) {});
      };

      window.addEventListener('load', function() {
        initApp();
      });
    </script>

I have a script that can log in a user and I have a script that can create an event (code not posted because the code is very similar to the attached links). How can I combine these two tasks?
From reading the documentation, I know that I have to add Calendar scopes and discovery documents to the auth script. However, I am struggling with the next steps.
Thanks for the help!

A: You can't use the Firebase ID token to call Google Calendar APIs.
You need to use the Google JS library to sign in to Google and to call calendar APIs. You can then get the Google ID token token to sign in with Firebase.
// Build Firebase credential with the Google ID token.
const credential = firebase.auth.GoogleAuthProvider.credential(
    googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential)
  .then((authResult) => {
    // User signed in with Firebase.
  })
  .catch((error) => {
    // Error while signing in.
  });


text:
Q: Ruby: Discarding Variables from Multiple Assignment from Array For the given variable assignment from array:
a,b,c,d,e = [ "foo","bar","discard","discard","blah" ]

Is there a way to only have a, b, and e assigned and discard c and d? Is there an undef like in perl (Perl assignment with a dummy placeholder).

A: Yes.
a,b,_,_,e = [ "foo","bar","discard","discard","blah" ]

A: You can use the splat operator.
 a,b,*,e = ["foo","bar",nil,nil,"blah"]

A: If the array is longish, this is an alternative:
a,b,e = [ "foo","bar","discard","discard","blah" ].values_at(0,1,4)


text:
Q: Artifactory not generating InRelease file for Debian repositories Artifactory Cloud is not generating Inrelease file or Release.gpg file for Debian repositories. Thus not allowing repository metadata signing.
I have uploaded a private/public gpg file to Artifactory settings, yet no signing is taking place in the repos.

A: TL;DR: Try using gpg --full-generate-key and manually specify a 2048-bit key.
I had this same issue, and just worked through it with jfrog support. I was creating key pairs using gpg, which defaults to 3072-bit keys. It appears that at least some versions of artifactory will silently fail to handle these keys. Once I used gpg --full-generate-key and manually specified a 2048-bit key, my key was recognized, and the InRelease and Release.gpg files were created (after recalculating the index).
If you go to Application | Artifactory | Artifacts and click on the top level folder, you should see an information panel like this:

When I was using 3072-bit keys, the final line "Signing Key" did not appear. This is despite the "Verification" process in the admin panel claiming that the key and passphrase were successfully verified.

A: What worked for me was to define a passphrase when defining gpg keys.
You can add a passphrase when you are uploading keys through UI:

or, as in my case, with help of Terraform JFrog provider:
resource "artifactory_keypair" "some-keypair6543461672124900137" {
  pair_name   = "some-keypair6543461672124900137"
  pair_type   = "RSA"
  alias       = "foo-alias6543461672124900137"
  private_key = file("samples/rsa.priv")
  public_key  = file("samples/rsa.pub")
  passphrase  = "your-super-secret-passphrase"

  lifecycle {
    ignore_changes = [
      private_key,
      passphrase,
    ]
  }
}

The gpg key was genereted with gpg --gen-key command.
After uploading the key with a passhrase and hitting Recalculate Index the InRelease and Release.gpg were created by Artifactory.


text:
Q: Similar proposals to the Muggle Protection Act? In the book Chamber of Secrets there are references to the Muggle Protection Act proposed by Arthur Weasley, aimed to protect the non-magic population against harmful or cursed artifacts made or possessed by wizards who wish to do them harm.
Were in the other books any reference to similar official proposals aiming to improve the circumstances of the 'weaker' minorities in the wizarding world (for example werewolves, centaurs or goblins) or any effort to try to cancel the discriminating legislation against them by those members of the Order of Phoenix who were Ministry of Magic employees or by Dumbledore, as the member of`the Wizenmagot? Or was there at least any public statement,  quoted in the wizarding newspapers/radio of any Order member on the subject?

A: Yes. In the third issue of the real life Daily Prophet, they mention the Bill of Goblin Rights. And in the second issue, there's the Troll rights movement.
(source: HP Lexicon)

A: Over the years, there have been several proposals for minorities in the Wizarding world, (namely Ghosts, Squibs, Muggles, House-elves, Trolls, and Goblins), but none seem to have been very successful.

*

*Protest Floats - c.1815

Question 6 out of 15
  Match the Minister for Magic with the major upheaval of his/her term in office, dates of which are marked.
  Part 2 out of 6
  Grogan Stump (1811 - 1819)
  ☐ Attempted assassination by centaur
  ☐ Pureblood riots during Squib Rights marches
  ☐ Several of the oldest Wizengamot wizards walk out in protest at Minister's appointment
  ☐ Persistent denial of notorious Dark wizard's existence forces Minister's resignation after notorious Dark wizard appears at the Ministry of Magic
☐ Ghost demonstrations at the Ministry of Magic ("protest floats")
  ☐ A night of large-scale breaches of the International Wizarding Statute of Secrecy
W.O.M.B.A.T. - Grade Three - Question 6

*Squib Rights marches - c.1968

Question 6 out of 15
  Match the Minister for Magic with the major upheaval of his/her term in office, dates of which are marked.
  Part 4 out of 6
  Nobby Leach (1962 - 1968)
  ☐ Attempted assassination by centaur
☐ Pureblood riots during Squib Rights marches
  ☐ Several of the oldest Wizengamot wizards walk out in protest at Minister's appointment
  ☐ Persistent denial of notorious Dark wizard's existence forces Minister's resignation after notorious Dark wizard appears at the Ministry of Magic
  ☐ Ghost demonstrations at the Ministry of Magic ("protest floats")
  ☐ A night of large-scale breaches of the International Wizarding Statute of Secrecy
W.O.M.B.A.T. - Grade Three - Question 6
Eugenia Jenkins
  1968 - 1975
  Jenkins dealt competently with pure-blood riots during Squib Rights marches in the late sixties, but was soon confronted with the first rise of Lord Voldemort. Jenkins was soon ousted from office as inadequate to the challenge.
Pottermore - Ministers for Magic

*Appeal Against House-Elf Slavery - c.1973

Question 3 out of 15
  Choose the Ministry of Magic decision that, in your estimation, had the MOST DAMAGING effect on present day wizarding life.
  ☐ The creation of the International Statute of Wizarding Secrecy in 1692.
  ☐ The defeat of the Appeal Against House-Elf Slavery in 1973.
  ☐ The drive into hiding of the surviving giants in the early 1980s.
  ☐ The 1865 decision to leave full control of Gringotts in goblin hands.
  ☐ The Wand Ban of 1631, which forbade Non-Human Magical Beings to carry wands.
W.O.M.B.A.T. - Grade Three - Question 3

*Muggle Protection Act - c.1992

"I have not been visited yet. The name Malfoy still commands a certain respect, yet the Ministry grows ever more meddlesome. There are rumors about a new Muggle Protection Act — no doubt that flea-bitten, Muggle-loving fool Arthur Weasley is behind it and as you see, certain of these poisons might make it appear —"
*Harry Potter and the Chamber of Secrets - Chapter Four
"Weasley has brought the Ministry into disrepute," Mr. Malfoy told our reporter. "He is clearly unfit to draw up our laws and his ridiculous Muggle Protection Act should be scrapped immediately."
*Harry Potter and the Chamber of Secrets - Chapter Twelve
"And imagine," Dumbledore went on, "what might have happened then. . . . The Weasleys are one of our most prominent pure-blood families. Imagine the effect on Arthur Weasley and his Muggle Protection Act, if his own daughter was discovered attacking and killing Muggle-borns. . . . Very fortunate the diary was discovered, and Riddle's memories wiped from it. Who knows what the consequences might have been otherwise. . . ."
*Harry Potter and the Chamber of Secrets - Chapter Eighteen

*Troll Rights Movement - c.1993

Miss Heliotrope Willis, leader of the Troll Rights Movement, spoke defiantly through Lawlson's abandoned megaphone of the trolls' essentially peace-loving nature."
The Daily Prophet #2 - Troll Rights Movement Out of Control

*Bill of Goblin Rights - c.1993

[paraphrased] Ministry of Magic representatives were meeting a delegation from the goblin pressure group B.O.G. (Brotherhood of Goblins) in Chipping Clodbury, in an effort to reach agreement on a new Bill of Goblin Rights.
The Daily Prophet #3 - Goblin Riots Erupt in Chipping Clodbury

Additionally, while there is no indication of any official statements/movements, the following two WOMBAT questions indicate that there was some public support for minority rights.

Question 5 out of 17
  Which of the following wizarding laws, in your view, stands in most urgent need of change?
  ☐ The detection of underage magic in all-magic households (currently impossible)
  ☐ The ban of goblin possession of wands (ought to be lifted)
  ☐ The re-classification of centaurs and merpeople (ought to take their views into account)
  ☐ The guidelines on house-elf welfare (need to be enforced)
  ☐ Definitions of 'Muggle-baiting' (need to be made less stringent)
W.O.M.B.A.T. - Grade One - Question 5
Question 12 out of 18
  What change would 18% of wizards like to see to the requirements for membership of the Wizengamot? (source: Ministry of Magic poll)
  ☐ Average age lowered from 87
  ☐ Proof of pure-blood status
  ☐ Maximum of three years in post
  ☐ Goblin representation
W.O.M.B.A.T. - Grade Two - Question 12


text:
Q: How to stop devise users from deleting other users posts? I have a devise user ( that I call a Provider in my app) and I am trying to write a custom authentication method to prevent the Providers from deleting each other's posts (called Procedures in my app).  Right now I have the correct_user method in my procedures controller.
def correct_user
  @provider = @procedure.provider.find(params[:id])
  redirect_to(provider_path(current_provider)) unless current_provider?(@provider)

end
I call it with the following before filter, also in my procedures controller:
before_filter :correct_user, :except => [:index, :show]

And I get the following error when trying to edit a procedure, even the provider's own procedure:
NoMethodError (undefined method `provider' for nil:NilClass)
app/controllers/procedures_controller.rb:8:in `correct_user'
Parameters: {"id"=>"523"}

From the looks of this error, the correct_user method is finding the procedure id instead of the provider id.  How can I fix this? Thanks

A: The error message tell you this:
Your variable @procedure is nil at the time that the method correct_user is called.

A: Authentication is about making sure that the user is who he says is. Devise is an authorization library. The only access control it provides is that you can make actions off limits for unknown users.
Authorization is making rules about who gets to do what. Popular libraries include Pundit & CanCanCan.
Even without a lib you could write a simple authorization rule like this:
class Provider < ActiveRecord::Base
  class NotAuthorized < StandardError; end
end

class ApplicationController < ActionController::Base

  rescue_from Provider::NotAuthorized, with: :deny_access

  private

    def deny_access
      render 'some_view', status: 403
    end
end

class ProceduresController < ApplicationController

  before_action :find_procedure, only: [:show, :edit, :update, :destroy]
  before_action :authorize_resource!, except: [:new, :index, :show]

  # DELETE /procedures/:id
  def destroy
    # This line never gets run if the user is not authorized.
    @procedure.destroy
  end

  private

   def find_procedure
     @procedure = Procedure.find(params[:id])
   end

   def authorize_resource!
     unless current_provider == @procedure.provider
       raise Provider::NotAuthorized and return false
     end
   end
end

Notice that in the authorize_resource! method you compare the user id of the record that you are authorizing against the user id from the session.
If you used the id from the params you're leaving yourself wide open to a spoofing attack where a user pretends to be someone else by passing another user's id in the params.
However, I would not recommend that you write an authorization solution from scratch unless you really know what you are doing.


text:
Q: Getting AttributeError: 'NoneType' object has no attribute 'get' using Pytest When I try to run my automation python script for a different browsers through the terminal window by using the command:
pytest -s -v testcase/test_login --browser Chrome

where test_login the python main file getting the Attribute error.
The below code is for test_login:
from self import self
from pageObjects.LoginPage import LoginPage
from utilities.readProperties import ReadConfig
from utilities.customLogger import LogGen

class Test_001_Login:
    baseURL = ReadConfig.getApplicationURL()
    username = ReadConfig.getUseremail()
    password = ReadConfig.getPassword()
    logger = LogGen.loggen()

def test_login(self, setup):
    self.driver = setup
    self.driver.get(self.baseURL)
    self.logger.info("URL iS loaded successfully")
    self.driver.maximize_window()

    self.lp = LoginPage(self.driver)

    self.lp.setUserName(self.username)
    self.logger.info("username   entered successfully")
    self.lp.setPassword(self.password)
    self.logger.info("password   entered successfully")
    self.lp.clickLogin()
    self.logger.info("clicked on login button")
    self.driver.close()

Below code is conftest.py:

@pytest.fixture()
def setup(browser):

if browser == 'Chrome':
    driver = webdriver.Chrome(executable_path="C:\Chromedriver1\chromedriver.exe")

elif browser == 'firfox':
    driver = webdriver.Chrome(executable_path="C:\Chromedriver1\chromedriver.exe")

elif browser == 'edge':
    driver = webdriver.Chrome(executable_path="C:\Chromedriver1\chromedriver.exe")

    return driver

def pytest_addoption(parser):
    parser.addoption("--browser")

@pytest.fixture()
def browser(request):
    return request.config.getoption("--browser")

A: The CLI argument is errorprone. You need to replace test_logn with the eact name of the test class i.e. test_login, effectively:
pytest -s -v testcase/test_login --browser Chrome

Furhter, setup() is a function, not an object. Update def test_login() as follows:
def test_login(self, browser):
    setup(browser)
    self.driver.get(self.baseURL)


text:
Q: Acomodar icono en un extremo Como ven en la siguiente imagen, tengo un ítem "computadora" y ese "+"; necesito que este lo más pegado a  la derecha posible; esto es un fragmento de un sidebar y necesito que todos los "+" queden iguales.

A continuación les pongo el código de este fragmento:

                <button class="btn text-left" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
                    Computadoras
                </button>

Notebook

PC's Armadas

Si para las recomendaciones es necesarios sacar los &nbsp ; entonces no hay problema. Pero necesito moverlos.

la imagen verde es un ejemplo de lo que necesito hacer!

A: Ya que estás con bootstrap te doy una solución con este framework

                <button class="btn d-flex justify-content-between w-25" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"  >
                Computadoras

                </button>

Notebook

PC's Armadas

He puesto el botón en display flex. El título del botón lo he colocado en un span, ahora el d-flex junto a justify-content-between mantiene cada parte en un extremo.
He quitdo el text-align.
Para que ves que funciona le dado un ancho al botón con la clase w-25.
En general las alineaciones se solventan bastante bien con el modelo flex-box.

A: 1 creamos una estructura de iconos para eso, creamos una clase "icon" y le  asignamos el pseudoelemento ::after (después) y usamos la propiedad font-family para indicar el tipo de fuente, en tu caso FontAwesome, como valor colocas 'Font Awesome 5 Free'.
.icon::after {
font-family: 'Font Awesome 5 Free';
font-weight: 900;}

2 creamos los iconos de la siguiente forma "nombredeicon::after" y asignamos la propiedad content y como valor colocamos el identificador del icono.
.icon-plus::after {
content: "\f067";}

3 modificamos la clase btn de Bootstrap agregando la propiedad "position" y le asignamos el valor "relative". Por que ? por que de esta forma evitamos que el icono se salga del contenedor (btn).
.btn {position: relative;}

4 tenemos que hacer que el icono se posicione lo mas a la derecha posible, eso lo logramos con "padding-left", "margin-left" o con "position: absolute" junto con "right: 0", de la siguiente forma
#headingTwo .icon-plus::after {
padding-left: 15px;}

o
#headingTwo .icon-plus::after {
margin-left: 15px;}

Nota: si optas por la opción de padding o margin no es necesario que modifiques la clase .btn de Bootstrap.
#headingTwo .icon-plus::after {
position: absolute;
right: 0;}

y por ultimo indicamos el ancho de la siguiente forma
#headingTwo .btn {
min-width: 180px;}

Nota: para que el icono no este tan pegado al borde modifica el valor de right de 0 a 15px por ejemplo. Si quieres hacerlo como lo muestra la imagen esta debería ser la forma.

A: Te recomiendo usar un span para eso.
Para que el span dé a la derecha, usaremos CSS:
button {
    position: relative;
}

button span {
    position: absolute;
    right: 0;
}

Teniendo en cuenta que button es un contenedor, estamos en la libertad de usar position: relative.
Puedes hacerle algunas modificaciones si lo necesitas.

A: Por favor intenta este código:

                Computadoras<button style="float: right" class="btn text-left" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">

                </button>

Notebook

PC's Armadas

Explicación ☕:
Modifiqué el elemento button para que flotara hacia la derecha utilizando el atributo style="" en el elemento.


text:
Q: Deny access of files via browser I am creating files with PHP:
 $handle = fopen('backup/db-'.date("ymdhis").'.sql.gz','w+');
 fwrite($handle, $gzdata);
 fclose($handle);
 chmod('backup/db-'.date("ymdhis").'.sql.gz', 0700);

but the created file is accessible via web browser. Is here some way to not allow that?

A: Add your .htaccess file
 <FilesMatch "\.(inc)$">
    Order deny,allow
    Deny from all
</FilesMatch>

Also good advice: put your includes in a directory and deny access to that directory in your .htaccess file.

A: there are two ways:
if you must use public space address, protect it writing also an apropiate "deny" on .htaccess
on the other hand, put it on a private space