text:
Q: How to use multiple models in one ListView Class on Django I want to create pege which previews auhors profile and posts with Django.
I created UserPostListView Class, then I want to search on Profile model by author's name and get profile.
How can I do this?
All code here
models.py
class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg',upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        output_size = (300,300)
        img.thumbnail(output_size)
        img.save(self.image.path)

views.py(UserPostListView Class)
class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

    def get_context_data(self, **kwargs):
        context = super(UserPostListView, self).get_context_data(**kwargs)
        context['profiles'] = Profile.objects.all()
        return context

A: If I understand, you want the author profile of the posts which are in your post queryset that is a single user, so in your get_context_data you can get author for each post.
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["profile"] = Profile.objects.filter(user__username=self.kwargs.get("username"))
        return context


text:
Q: Making sense of generic Java method header I was reading up on generics in Java here and here, and while I understand the point of having them, I'm having a little trouble understanding the header of a generic Java method. I'm used to:
public returnType methodName(parameters){body}

What keeps confusing me is the specification of a generic method declaration:
public *genericType* returnType methodName(parameters){body}

or
public static <T> void fromArrayToCollection(Collection<T> c) {}

What is this type declaration (<T> between static and void) affecting? Is it just outlining the type that the method parameters can be?

A: The <T> between static and void in this case means "There is a generic type parameter being referred to as T in this method."
Compare case 1:
class Foo<T> {
     public void doFoo(Collection<T> items) ...
}

with case 2:
class Foo {
    public <T> void doFoo(Collection<T> items) ...
}

and case 3:
class Foo {
    public void doFoo(Collection<T> items) ...
}

In the first case, T is a generic type for the whole class, so if you call doFoo, the <T> in the collection you pass in needs to be the same T as the generic type of the instance of Foo<T>.
In the second case, T is a generic type existing only in the method doFoo.
In case 3, T must be an actual type, because there is no declaration that it is a generic type parameter.

A: The <T> declared as return type references the <T> declared in the parameter. That way you know that if you feed your method a collection of Strings, you'll get a String as a result.
So in conclusion, a generic type give you the ability to reference in your code a type without having to specify it yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity framework core generic query I have a external DLL with my classes and I would like to make the query depending on the type. I explain better.
I get the type with the function GetType:
Type targetType = Type.GetType("...");
If there is any way to make a select like this:
_context.Set<targetType>().ToList()

Assuming that _context is my DBContext.
Thanks

A: Indeed there is:
var method = typeof(DbContext).GetMethod("Set").MakeGenericMethod(targetType);
var query = method.Invoke(ctx, null) as IQueryable;
var list = query.OfType<object>().ToList();

A: Well i did something like that.
Here is an example
Public class repository: dbcontext
{
 public IDbset<car> Cras {get;  set;}

Public IQueryable<T> Get<T>()
{
return this.gettype().getproberties().find(x=>.  x.propertytype== typeof(T)). Getvalue(this)  as IQueryable<T>;
}
}

Hop this get you started.
Writen from moble :)


text:
Q: Time series data visualization issue I have a time series data like below where the data consists of year and week. So, the data is from 2014 1st week to 2015 52 weeks.

Now, below is the line plot of the above mentioned data

As you can see the x axis labelling is not quite what I was trying to achieve since the point after 201453 should be 201501 and there should not be any straight line and it should not be up to 201499. How can I rescale the xaxis exactly according to Due_date column? Below is the code
rand_products = np.random.choice(Op_2['Sp_number'].unique(), 3)
selected_products = Op_2[Op_2['Sp_number'].isin(rand_products)][['Due_date', 'Sp_number', 'Billing']]

plt.figure(figsize=(20,10))
plt.grid(True)

g = sns.lineplot(data=selected_products, x='Due_date', y='Billing', hue='Sp_number', ci=False, legend='full', palette='Set1');

A: the issue is because 201401... etc. are read as numbers and that is the reason the line chart has that gap. To fix it, you will need to change the numbers to date format and plot it.
As the full data is not available, below is the two column dataframe which has the Due_date in the form of integer YYYYWW. Billing column is a bunch of random numbers. Use the method here to convert the integers to dateformat and plot. The gap will be removed....
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns

Due_date = list(np.arange(201401,201454)) #Year 2014
Due_date.extend(np.arange(201501,201553)) #Year 2915
Billing = random.sample(range(500, 1000), 105) #billing numbers
df = pd.DataFrame({'Due_date': Due_date, 'Billing': Billing})
df.Due_date = df.Due_date.astype(str)
df.Due_date = pd.to_datetime(df['Due_date']+ '-1',format="%Y%W-%w") #Convert to date

plt.figure(figsize=(20,10))
plt.grid(True)

ax = sns.lineplot(data=df, x='Due_date', y='Billing', ci=False, legend='full', palette='Set1')

Output graph


text:
Q: AndroidX: can't resolve method findViewById (toolbar) I imported AndroidX libraries and Toolbar findViewById method doesnt work anymore.
BaseAppCompatActivity.java:
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.navigation.NavigationView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;

FrameLayout lytContent;
    //protected FrameLayout leftDrawer;
    NavigationView leftDrawer;
    //  protected FrameLayout rightDrawer;
    DrawerLayout drawerLayout;
    ActionBarDrawerToggle mDrawerToggle;
    //protected  RelativeLayout lytContents;

final Handler mHandler = new Handler();

protected SwipeRefreshLayout swipeView;
protected CoordinatorLayout coordinatorLayout;
protected Toolbar toolbar;

private MenuItem menuProgress;
private View lytDrawer;
private View lytDrawerHeader;
private View lytProgress;
private ProgressBar progressBase;
private View lytMessage;
private CustomTextView txtMessage;
private ImageView ivMessage;

private ImageView ivUserDP;
private ProfileBean profileBean;
private CustomTextView txtName;
private CustomTextView txtPhone;
private CustomTextView txtEmail;

private boolean isDriverLocationUpdated;
toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //leftDrawer = (FrameLayout) findViewById(R.id.leftDrawer);
        leftDrawer = (NavigationView) findViewById(R.id.navigation_view_base_appcompat);
        //  rightDrawer = (FrameLayout)findViewById(R.id.rightDrawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_appcompat);
        lytContent = (FrameLayout) findViewById(R.id.lyt_contents_appcompat);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorlayout_base_appcompat);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            toolbar.setPadding(0, App.getStatusBarHeight(getApplicationContext()), 0, 0);
            leftDrawer.setPadding(0, 0, 0, 0);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }

Also getWindow method doesn't work. Im using sdkVersion 28.

implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'

A: can you try import this androidx.appcompat.app.AppCompatActivity?
for bind view you must bind in onCreate method or you can use butterKnife lib.
I usually create method bindView() and put this on method onCreate().


text:
Q: IntelliJ TypeScript import of Angular marked with squiggle I'm using IntelliJ IDEA 2017.2.4 to develop Angular (4 not js) app. Everything works and running fine but IntelliJ marks all @angular imports in TypeScript files with a red squiggle.
The error message is TS2307: Cannot find module '@nagular/abc'
There is also issue open in Jetbrain's support Typescript does not resolve modules through tsconfig.json's baseUrl

This is my tsconfig.json file.
Please note that tsconfig.json file is stored not in the root of the project but in ./app/ui directory - if that matters.
{
  "compilerOptions": {
   "alwaysStrict": true,
   "noImplicitReturns": true,
   "emitDecoratorMetadata": true,
   "experimentalDecorators": true,
   "module": "system",
   "target": "es5",
   "removeComments": true,
   "suppressImplicitAnyIndexErrors": true,
   "outDir": "generated",
   "inlineSourceMap": true,
   "importHelpers": true,
   "baseUrl": ".",
   "paths": {
     "tslib": [
      "../../node_modules/tslib/tslib.d.ts"
     ]
   },
   "skipLibCheck": true,
   "downlevelIteration": true
  },
  "exclude": [
   "lib"
  ]
}

A: All of your angular related package should be in.
for e.g:
node_modules/@angular/common/index.d.ts
node_modules/@angular/compiler/index.d.ts
node_modules/@angular/core/index.d.ts
node_modules/@angular/http/index.d.ts
node_modules/@angular/platform-browser/index.d.ts
node_modules/@angular/platform-browser-dynamic/index.d.ts
node_modules/@angular/router/index.d.ts
node_modules/@angular/router-deprecated/index.d.ts

However, All of these should be there if you have used the package.json file from the standard quickstart https://angular.io/docs/ts/latest/quickstart.html and run npm install
Also check tsconfig.json settings of your IDE
File->settings->Languages & Frameworks -> TypeScript ->enable typescript compiler & Use tsconfig.json

A: When using "module": "system" TypeScript uses Classic module resolution, which does not resolve node modules, see details at https://www.typescriptlang.org/docs/handbook/module-resolution.html
To make it work, you need to switch to a different module system, like CommonJS, or there might be another configuration to explicitly include node_modules in resolution while using "module": "system".


text:
Q: How do you show a picture in python? I am wondering, is it possible to display images in python?

A: The easiest way is to  use PIL and the Image.show method. This brings up an external viewer program on the image.

A: Almost all GUI toolkits (wxWindows, pyQt, pyGTK, Tkinter) have Canvas or other-type widgets that allow you to draw an image.
The standard library way to draw an image is to use Tkinter's Canvas widget.

A: The question needs more clearing up.
Do you want to put the picture on a system display?
Or on a window in a desktop app?
Or render it to a http response?
Python can do all these things in different manners, but for people to explain it - you need to specify your question a bit more.

A: The various OpenCV bindings for Python also provide ways to display images (and videos). Might be a bit heavy if you just want to display an image.

A: The easiest way is to use a web server I reckon. You can script a nice, simple server with bottle and turn out a UI with images.
It depends what you want to do. Python can do it all, but needs something to work with. There's pygame and stuff like that if you're just starting out.

A: Using wx.Python here is an example. The picture printed is 'bitmaps/image.jpg'.
It prints on the panel using the wx.StaticBitmap() class.
        from Main import opj
    def showPic(frame, nb, log):
        jpg = wx.Image(opj('bitmaps/image.jpg'), wx.BITMAP_TYPE_JPEG).ConvertToBitmap()
        panel = wx.Panel(nb, -1)
        wx.StaticBitmap(panel, -1, jpg, (10, 10))
        return panel


text:
Q: HA Proxy URL Rewrite/Redirect I'm trying to rewrite a URL but so far not succeeded.
URL Access from outside - https://example.domain.com/health (Which gives 404)
Backend URL Need to redirect - http://example.domain.com/appname/health
I have multiple domains configured this HAproxy. such as example1, example2
Haproxy Ver is  1.4.22
I tried few workarounds reqrep(messed with regex I guess), redirect(can't match 404) non of them succeeded so far. Its great somebody can suggest me a workaround with regular expressions if applicable.

A: It would be easier if you provided your config, however, it seems all you want is redirect a specific URL to another URL.
You can achieve this with the "redirect" keyword.
There are multiple ways you could achieve what you want, using different "redirect" keyword combination, so here's one solution:
frontend http
   acl is_health url_reg ^/health

   redirect prefix http://www.example.com/appname code 301 if is_health

and here's another:
frontend http
   acl is_health url /health

   redirect location http://www.example.com/appname/health code 301 if is_health


text:
Q: How to use environment variable in js file with gulp I'm helping on the project consisting of html, css and js plugins all built with gulp. The project was bought as a template and customized by our marketing team (yep...) and I'm supposed to help with scripting.
Now there is a plugin which sends form data to server with $.ajax() call. Url param is set as a constant, like this:
$.ajax({
  url: 'exact-api-url',
  type: 'POST'
  ...
});

How can I replace it with env variable and where exactly should I store it? There are different URLs for prod and dev. I want it to look like this:
$.ajax({
  url: environment.API_URL,
  type: 'POST',
  ...
});

From solutions I found I got the feeling that they mostly deal with env variables within gulpfile.js itself not the js code in project. One workaround suggested using global js variables which I don't like. What's the proper way to do it?
I'm an an Angular/React guy, working mostly with webpack and I find gulp's lack of environment folder disturbing.

A: Below is one of solution.
You can generate a config file as config.js using template config.tmpl.js
module.exports = <%= url %>

Below are my gulp task to set the url for Dev & prod.
gulp.task('set-dev-node-env', function() {
    return process.env.url = 'exact-dev-url';
});

gulp.task('set-prod-node-env', function() {
    return process.env.url = 'exact-prod-url';
});

Task to generate the config file.
var gulp = require('gulp');
var template = require('gulp-template');
var rename = require('gulp-rename');

gulp.task('config', function() {
    return gulp.src('path/to/config.tmpl.js')
      .pipe(template({url: `${process.env.url}`}))
      .pipe(rename('config.js'))
      .pipe(gulp.dest('path/to/config.js'));
});

Below are task to build for dev and prod
gulp.task('build_for_prod', ['set-prod-node-env','config'], function() {
    runSequence(
        '...buildSteps'
    );
});

gulp.task('build_for_dev', ['set-dev-node-env','config'], function() {
    runSequence(
        '...buildSteps'
    );
});

and finally, in your JS file
var config = require('path/to/config.js');

$.ajax({
    url: config.url,
    type: 'POST',
    ...
});

Hope this helps :)


text:
Q: configuration the roots with angular 4 i used webStorm 2017.1.4 and i want to construct the front End of my application J2EE. I have 2 components about and contacts in the last component i want to add all the contacts in the DataBase My Sql but i have a problem ContactsComponent.ts when i want to add the type of the Http in the constructor is with bar in the Http but the import library is import { Http } from '@angular/http';
here the image

import { Component, OnInit } from '@angular/core';
   import { Http } from '@angular/http';
   import 'rxjs/add/operator/map';

   @Component({
   selector: 'app-contacts',
   templateUrl: './contacts.component.html',
   styleUrls: ['./contacts.component.css']
   })
   export class ContactsComponent implements OnInit {

   pageConstants: any;

   constructor(public http: Http ) {}

   ngOnInit() {
    this.http.get('http://localhost:8080/chercherContacts?mc=sa&page=2&size=6')
      .map( resp => resp.json())
      .subscribe( data => {
          this.pageConstants = data;
      }, err => {
        console.log('Erreur : ' + err);
      });
   }
  }

i think in this code is correctly but in the console of my google Chrome the erreur is
Failed to load http://localhost:8080/chercherContacts?mc=sa&page=2&size=6:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4225' is therefore not allowed access.

in red and the other mistake is
Erreur : Response with status: 0  for URL: null
contacts.component.ts:25
zone.js:2969 Cross-Origin Read Blocking (CORB) blocked cross-origin response
http://localhost:8080/chercherContacts?mc=sa&page=2&size=6 with MIME type
application/json. See https://www.chromestatus.com/feature/5629709824032768
for more details.

here the image of the mistakesin the google chrome

can you help me where is the problem in my project with angular 4?
And thinks of all

A: Http is deprecated in the newer version of angular. It is replaced by Httpclient.
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient){}

Rest you can read from here HttpClient

A: the big problem is of the notation in the servlet of the server in the J2EE. it is necessary to add the @CrossOrigin("*") this notation is necessary to security to the server external when it is resolve the issue
Already it is occasional to change ** HttpClientModule** of the appModule.ts of the library import { HttpClientModule} from '@angular/common/http';
And
import { HttpClient } from '@angular/http';
constructor(private http: HttpClient){}

and the problem is resolved
Thank you all my friend :)


text:
Q: Google Maps v3 - Overriding Default SmoothZoom Behavior Is there a way to prevent a Google Map from automatically doing the Smooth Zoom transition when zooming in or out? I would like it to just snap to the desired zoom level.
In the ModestMaps Library for Flash, for example, I can set zoomDuration to 0 to force all transitions to be instant rather than animated.

A: You can do this by calling setCenter
map.setCenter(latlng, zoomLevel);

Should work in Maps API V3.


text:
Q: How can I fix this error message in D365 (Quantity cannot be invoiced because inventory transactions with a status of Received are insufficient I'm trying to see how to fix this error in D365 when a Project Invoice proposal is trying to Post. There are no inventory for an item that this invoice is coming from. I checked the item model groups and tested different scenarios. A customer returned the items and now I'm trying to take them out of our transactions for the Sales Order from a project.
There is no packing slip or anything that ties to the return nor an RMA issued. Where am I not looking in D365 or have not clicked on to remove this error message from allowing the project invoice to post?


text:
Q: Does Spring Context have equivalent of Java CDI's @Inject @Any In Java CDI there is great functionality on gathering all managed beans, that share a supertype. Let's say I what to gather all managed instances of MyInterceptor, I just have to write:
@Inject
@Any
Instance<MyInterceptor> myInterceptors;

Similar functionality I was able to obtain when I was working on EJB, although solution there was way less pretty (I needed to call BeanManager).
Can similar functionality I can obtain working on @Component's managed by Spring context?
[Edit]
Why is not a duplicate of What is the Spring equivalent for CDI's Instance, or Guices Provider
From my understanding, in the above question, there is a hidden assumption, that I have both contexts: Spring and CDI, which may not be always the case (especially in Java SE applications). Furthermore, I have a bad experience in mixing contexts, they often claim that they are compatible, but it isn't always the case. You can get trapped in unexpected problems, like this: https://blog.akquinet.de/2017/01/04/dont-get-trapped-into-a-memory-leak-using-cdi-instance-injection/

A: If you specify the the field as a List with a generic type MyInterctptor you should be able to achieve what you are looking for. Ex:
@Autowired
List<MyInterceptor> interceptors;

More info can be found here: https://dzone.com/articles/load-all-implementors


text:
Q: Codeigniter: Prefix string in select to all columns specified I have the following select queries.
    $this->db->select("$order_table.user_id, $order_table.total_price,
                       $order_table.shipping, $order_table.tax,
                       $order_table.filled, $order_table.shipped,
                        $order_table.tracking");
    $this->db->select("$user_table.first_name as user_first_name,
                       $user_table.last_name as user_last_name,
                       $user_table.email as user_email");
    $this->db->select("$mailing_address_table.first_name as mailing_first_name,
                       $mailing_address_table.last_name as mailing_last_name,
                       $mailing_address_table.address as mailing_address,
                       $mailing_address_table.address_2 as mailing_address_2,
                       $mailing_address_table.city as mailing_city,
                       $mailing_address_table.state as mailing_state,
                       $mailing_address_table.zip_code as mailing_zip_code,
                       $mailing_address_table.country as mailing_country");

    $this->db->select("$billing_address_table.first_name as billing_first_name,
                       $billing_address_table.last_name as billing_last_name,
                       $billing_address_table.address as billing_address,
                       $billing_address_table.address_2 as billing_address_2,
                       $billing_address_table.city as billing_city,
                       $billing_address_table.state as billing_state,
                       $billing_address_table.zip_code as billing_zip_code,
                       $billing_address_table.country as billing_country");

    $this->db->join($user_table,
                   "$user_table.id = $order_table.user_id", "left");
    $this->db->join($mailing_address_table,
                   "$mailing_address_table.user_id = $user_table.id", "left");
    $this->db->join($billing_address_table,
                   "$billing_address_table.user_id = $user_table.id", "left");

Is there anyway, I imagine using CONCAT, that I can prefix "billing_" to each column that I'm selecting in billing. I can't seem to figure this out when I'm not selecting everything, but rather just specific columns.
Id like each column I select from $user_table to be prefix with "user_", $mailing_table "mailing_" and so on.
Note:
1) I am not selecting all the fields from each column in these select queries, so I can't do SELECT * FROM...
2) I don't want to UPDATE the column names in the database, just for this specific SELECT use.

A: Here you can create to field list:
SET @SCHEMA = 'toimport';

SET @PREFIX = 'billing_';
SET @POSTFIX = 'address';

SELECT GROUP_CONCAT(
 CONCAT(@SCHEMA,'.',@PREFIX,'.',@POSTFIX,'.',COLUMN_NAME,
 ' AS ',@PREFIX,COLUMN_NAME) SEPARATOR ',\n')
 FROM information_schema.COLUMNS
 WHERE TABLE_SCHEMA = @SCHEMA AND TABLE_NAME = CONCAT( @PREFIX,  @POSTFIX );

The Result look likes:
toimport.billing_.address.id AS billing_id,
toimport.billing_.address.name AS billing_name,
toimport.billing_.address.street AS billing_street,
toimport.billing_.address.a1 AS billing_a1,
toimport.billing_.address.a2 AS billing_a2

A: Here your Answer for more Tables:
The Query:
SET @SCHEMA = 'toimport';

SELECT
  GROUP_CONCAT(
    CONCAT(
      @SCHEMA,'.',
      SUBSTRING_INDEX(TABLE_NAME, '_', 1),'.',
      SUBSTRING_INDEX(TABLE_NAME, '_', -1),'.',
      COLUMN_NAME, ' AS ',
      SUBSTRING_INDEX(TABLE_NAME, '_', 1),'_',COLUMN_NAME
    ) SEPARATOR ',\n'
  )
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = @SCHEMA
  AND TABLE_NAME IN ('billing_address', 'email_post');

The Result is like:
toimport.billing.address.id AS billing_id,
toimport.billing.address.name AS billing_name,
toimport.billing.address.street AS billing_street,
toimport.billing.address.a1 AS billing_a1,
toimport.billing.address.a2 AS billing_a2,
toimport.email.post.id AS email_id,
toimport.email.post.name AS email_name,
toimport.email.post.street AS email_street,
toimport.email.post.a1 AS email_a1,
toimport.email.post.a2 AS email_a2


text:
Q: What do the horse's messages mean? I get a cryptic message every time I click on the horse. Example:

Other messages include

*

*Gazing into the horse's eyes, you feel on the verge of understanding
a deep mystery.

*You ponder the horse's speed, and are inspired to
quicken your own step.

*The horse's calm in the face of danger steels your will.

*The horse gazes upon you calmly, reminding you that patience is a virtue.

*Peering deep into the horse's eyes, you feel you are not yet ready for its wisdom.

*The horse fixes you with a withering gaze.

These sound a lot like the stat increase messages in ADOM, because they reference things like speed and willpower; however, my stats don't seem to be increasing on their own, and I get the feeling that the game might be just messing with me...

A: As far as I know, the Horse's only purpose is to hint at the "Secret Horse Level", much how Diablo had a cow that could be clicked (though the Secret Cow Level only existed in the sequel).
To clarify, the cows in Diablo also responded when clicked on:

*

*"Yup, that's a cow all right!"

*"I am not thirsty"

*"Hey! I am no milkmaid!"


text:
Q: laravel storage is not writing the right content into the file I have a server url of my sql dump file.
I am passing that into my code to download the server file into my local project directory. It is not saving the sql content into my file. It is saving file url as content.
$fullPath = 'http://www.server.com/api/sql/L2hvbWUvdmFncmFudC9jb2RlL2N5YmV4L2RhdGFiYXNlL2R1bXBzL2N5YmV4IG15c3FsIDIwMTgtMDctMjcgMDgtNDQtMjMgY2M0MjU5MGY4NzdhZjAzY2UxNjZkYWQwZGM1NzI1M2RmOWE5NTZjNy5zcWw=';

public function fileDownload($fullPath)
{
    $url     = $fullPath;
    $content = file_get_contents($url);

    Storage::disk('snapshots')->put('mysqldump.sql', $content);
}

How do I download the file itself and store in my snapshot directory?


text:
Q: Do functions clear dynamic memory upon exiting scope? In C++, how does a function treat memory that has been dynamically allocated upon exiting the scope of the function? Is this memory cleared, or can it be passed back into the main block?
In context: I have a function, and I pass it a pointer to double to serve as an array. I dynamically allocate this memory within the function, initialise the elements and the exit the function.
            void my_func(double* ptr){
            ptr = new double[2];
            ptr[0] = 15; ptr[1] = 10;
            }

In the main block, I then use the newly allocated array.
            int main(){
            double* ptr;
            my_func(ptr);
            cout << ptr[0] + ptr[1] << endl;
            delete[] ptr;
            return 0;

Will this work? Are there dangers/pitfalls associated with this approach?

A:
In C++, how does a function treat memory that has been dynamically allocated upon exiting the scope of the function? Is this memory cleared, or can it be passed back into the main block?

In C++, memory that has been manually (dynamically) allocated has to be manually deallocated.

In context: I have a function, and I pass it a pointer to double to serve as an array. I dynamically allocate this memory within the function, initialise the elements and the exit the function.

You are taking the pointer by value, so while you can change the contents of what the pointer points to you cannot change the pointer itself. Doing so changes only the local copy of the pointer. If you take the pointer by reference, then it would work:
void my_func(double*& ptr)
{
    ptr = new double[2];
    ptr[0] = 15; ptr[1] = 10;
}

Will this work? Are there dangers/pitfalls associated with this approach?

It will mostly work, but its not the way to go in C++ because of the associated pitfalls. Better go with a vector:
std::vector<int> my_func()
{
    std::vector<int> buffer;
    buffer.push_back(15);
    buffer.push_back(10);
    return buffer;
}

A:
Will this work? Are there dangers/pitfalls associated with this approach?

It may work as long as nothing goes wrong. If an exception gets thrown, it'll generally leak memory. To avoid that, you generally want to free the memory in the destructor of some class, then create an instance of that class with automatic storage duration. That means it'll be destroyed when it goes out of scope, and will (in turn) release the memory it's controlling.
The standard library already has a variety of containers to do that. What you have is closest to a std::vector, but there are also std::deque, std::list etc.


text:
Q: Cycle2: Center Carousel active slide below main slideshow I have a jCycle2 slideshow with pager carousel like this demo
I would like to have the active slide centered under the main carousel, but I have not found a valid solution. I have tried adding data-cycle-carousel-offset="40%" to the carousel, which works great, but then I can not access the final 3 slides of the carousel because of the offset. I have also tried a CSS solution with the same results.
Images attached of desired result.
Current:

Desired:

Thanks!


text:
Q: Mod Rewrite 500 Internal Server Error Problem I keep getting a 500 Internal Server Error when I try to change Example 1 to Example 2 using mod_rewrite. Can someone help me fix this problem?
Example 1
http://www.example.com/posts/1/abcd

Example 2
http://www.example.com/posts.php?aid=$1

Here is my mod rewrite.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/
RewriteRule ^index\.php$ http://www.example.com/ [R=301,L]
RewriteRule ^(-[1-9]+)? $ http://www.example.com/posts.php?aid=$1 [L]
</IfModule>

A: Try changing your last RewriteRule to something like this:
RewriteRule   ^([A-Za-z0-9-]+)/?$ http://www.example.com/posts.php?aid=$1 [L]


text:
Q: correctly sizing a D3 bar graph I am attempting to add labels/axis/titles/etc to a D3 bar graph. I can get something close to the right size, however I end up clipping off part of the last bar (so the last bar is skinnier than the others).
Here is the pertinent code:
var x = d3.scale.linear()
.domain([0, object.data.length])
.range([0, object.width]);
var y = d3.scale.linear()
.domain([object.min-(object.max-object.min)*.15, object.max (object.max-object.min)*.15])
.rangeRound([ object.height - 30, 0]);

var vis = d3.select(object.ele)
    .append("svg:svg")
    .attr("width", object.width)
    .attr("height", object.height)
    .append("svg:g");

vis.selectAll("g")
.data(object.data)
.enter().append("rect")
.attr("x", function(d, i) { return x(i); })
.attr("y", function(d) { return object.height - y(d.value); })
.attr("width", object.width/object.data.length - 1)
.attr("height",  function(d) { return y(d.value); })
.attr("transform", "translate(30,-30)");

At the moment everything (labels, axis, and so on) is 30px. How do I correctly alter the graph to make room for whatever else I need?

A: You are cutting off your last bar because you use translate the x coordinate but your the range of your x is only to the width without the extra 30 pixels.
Also it may be easier to simplify your y domain to use .domain([object.min, object.max]) then have the "y" and "height" functions reversed. This way you start the rect at the y(d.value) and make it's height object.height - y(d.value).
I would create three groups initially, one for your y axis, one for x axis, and then another for the bars. Draw your bars inside the last group and then translate the whole group itself instead of each individual bar. Increase the size of your object.width and object.height to match the total space you want.


text:
Q: How to handle oneSignal notification received I want to make notification count badge on toolbar icon. i use onesignal to get a real time notification. so everytime there is new notification, i will save the count to sharedPreference and show it to toolbar icon like picture below
how to achieve this ?
so the main problem here is how to handle notification received from one signal?
this is my notif count sharedpreference class
public class NotifCountSession {

// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
SharedPreferences.Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpreference file name
private static final String PREF_NAME = "notif";

// User name (make variable public to access from outside)
public static final String KEY_COUNT = "count";

// Constructor
public NotifCountSession(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void saveCount(int count){

    // Storing value in pref
    editor.putInt(KEY_COUNT, count);

    editor.commit();
}

public HashMap<String, Integer> getCount(){
    HashMap<String, Integer> notif = new HashMap<>();
    // user name
    notif.put(KEY_COUNT, pref.getInt(KEY_COUNT, 0));

    return notif;
}

public void resetCount(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();
}
}

A: Please try below solution :
Initialize one signal on your activity with context :
   OneSignal.startInit(this)
   .setNotificationReceivedHandler(new ExampleNotificationReceivedHandler(this))
   .init();

Now you can use context on your onesignal class :
 private Application application;

    public ExampleNotificationReceivedHandler(Application application) {
        this.application = application; //Done now you have a context

    }

A: According to OneSignal Documentation Implement OneSignal.NotificationReceivedHandler inside your Notification class
Then use setNotificationReceivedHandler(new NotifCountSession(this)) method where (usually Application class) you are initializing your OneSignal instance like below:
OneSignal.startInit(this)
   .setNotificationReceivedHandler(new NotifCountSession(this))
   .init();


text:
Q: OS X Safari HTML select visual artifact when zoomed in? First off, I know this is an extremely narrow edge case, but in the interest of due diligence with a client, I have to ask. Consider everyone's favorite no-frills HTML tutorial site, W3Schools.com, specifically their demo page on HTML select boxes: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_select2
Open that page up in Safari on OS X (may exist in Windows, but honestly, who uses Safari for Windows?) and zoom in four times. Open up the select box. See where the normal check mark has changed to two dots?

I'm perfectly content to call that a Safari bug and close it as cantfix. Googling "safari html select two dots" doesn't get me anywhere. Is this fixable?


text:
Q: How to aggregate iterators over errors when using filter_map with a fallible mapping function? Suppose I want to read all files in a directory. I might define a function like this:
use std::error::Error;
use std::fs;
use std::io;

type Result<T> = std::result::Result<T, Box<dyn Error>>;

fn read_entry(entry: io::Result<fs::DirEntry>) -> Result<Option<String>> {
    let entry = entry?;
    if entry.file_type()?.is_file() {
        Ok(Some(fs::read_to_string(entry.file_name())?))
    } else {
        Ok(None)
    }
}

And then try to use it...
use std::path::Path;

fn read_all(dir: &Path) -> Result<Vec<String>> {
    Ok(fs::read_dir(dir)?
        .filter_map(|entry| read_entry(entry).unwrap())
        .collect())
}

This compiles but it just unwrap()s errors. collect() normally can aggregate iterators over errors but I can't quite figure out how to do this with filter_map(). How can I fix this?
Playground

A: There's a nice implementation of FromIterator for Iter<Item = Result> (which is an underlying trait for Iterator::collect), so this works:
fn read_all(dir: &Path) -> Result<Vec<String>> {
    fs::read_dir(dir)?
        .filter_map(|entry| read_entry(entry).transpose())
        .collect()
}

A: Instead of returning Result<Option<T>> you need Option<Result<T>>, i.e. before:

*

*Ok(Some(T)): It was a file and we read it successfully

*Ok(None): It wasn't a file but we didn't have any errors finding that out.

*Err: There was an error.

After:

*

*Some(Ok(T)): It was a file and we read it successfully

*None: It wasn't a file but we didn't have any errors finding that out.

*Some(Err): There was an error.

You can change the original implementation but then it means that you can't use the ? operator, which sucks.
A better solution - as @Kitsu pointed out is to use the built in function transpose() which will convert a Result<Option<T>> into an Option<Result<T>>.

A: Just for completion, the reason the read_entry fails is because is using entry.file_name() instead of entry.path().
So this:
Ok(Some(fs::read_to_string(entry.file_name())?))

should be:
Ok(Some(fs::read_to_string(entry.path())?))


text:
Q: Named Pipe Server throws UnauthorizedAccessException when creating a second instance if PipeSecurity is set I am trying to write a (elevated privilege) service that will talk to a non privileged winforms application. I was able to have two console applications (one elevated one not) talk back and forth no problem but I am having a problem doing a service and a winforms app.
The first instance of the pipe works perfectly. However after my client connects and I try to create a new instance so it will be ready if a 2nd client connects, but the constructor for NamedPipeServerStream throws a exception
System.UnauthorizedAccessException was unhandled
  Message=Access to the path is denied.
  Source=System.Core
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.Pipes.NamedPipeServerStream.Create(String fullPipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize, PipeAccessRights rights, SECURITY_ATTRIBUTES secAttrs)
       at System.IO.Pipes.NamedPipeServerStream..ctor(String pipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
       at System.IO.Pipes.NamedPipeServerStream..ctor(String pipeName, PipeDirection direction, Int32 maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, Int32 inBufferSize, Int32 outBufferSize, PipeSecurity pipeSecurity)
       at PipeServer.Server.Client..ctor(String pipeName, List`1 container) in E:\Visual Studio 2010\Projects\Sandbox Service\PipeServer.cs:line 27
       at PipeServer.Server.ListenForClients() in E:\Visual Studio 2010\Projects\Sandbox Service\PipeServer.cs:line 148
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

 Example removed see example at the bottom for simpler test case
The first iteration works fine. it is when the client connects and client = new Client gets called a second time, which in turn calls Pipe = new NamedPipeServerStream and that will throw the exception.
Can anyone see what mistake I am making?

A little more information, Out of curiousity I went back to my console app. To test multiple instances I just ran the exe multiple times. When i put two new NamedPipeServerStream in the same executable I get the same error... So why is it ok if you have separate exe's acting as the server pointing to the same named pipe address but it is forbidden to do it inside the same exe?
static void Main()
{
    PipeAccessRule pr = new PipeAccessRule("Users", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
    PipeSecurity ps = new PipeSecurity();
    ps.AddAccessRule(pr);
    using (NamedPipeServerStream pipeServer =
        new NamedPipeServerStream("testpipe",PipeDirection.InOut,10,
                                    PipeTransmissionMode.Message,
                                    PipeOptions.WriteThrough,4028,4028,ps))
    using (NamedPipeServerStream pipeServer2 = //v-- Throws the execption, but if you comment this out and run the EXE twice it works fine. creating a new instance of ps and pr does not change anything.
        new NamedPipeServerStream("testpipe", PipeDirection.InOut, 10,
                                    PipeTransmissionMode.Message,
                                    PipeOptions.WriteThrough, 4028, 4028, ps))
    {

More Information:
If I don't set PipeSecurity it does not throw the exception, but when I set the security it will. It does not matter if i pass both instances the same PipeSecurity or two instances with the same settings it still throws the exception.

A: There are two things which can cause the instantiation of a second or subsequent
NamedPipeServerStream on the same pipe to fail:

*

*the maxNumberOfServerInstances ctor argument must have been set to more than 1 when the first instance of the pipe server was created. If not, the second call will fail unless the first instance has already been closed completely.

*the process calling the ctor must have the access right represented by PipeAccessRights.CreateNewInstance. This is a powerful right which the pipe server should guard jealously, as it allows its possessor the ability to act as a pipe server.

The service process should set the pipe security thus:
PipeSecurity ps = new PipeSecurity();
    ps.AddAccessRule(new PipeAccessRule(myPipeUsersGroup, PipeAccessRights.ReadWrite, AccessControlType.Allow));
    ps.AddAccessRule(new PipeAccessRule(myPipeServerIdentity, PipeAccessRights.FullControl, AccessControlType.Allow));

where:

*

*myPipeUsersGroup is a placeholder for  a group which contains all the prospective client identities which will connect to the pipe. Depending on your requirements/use case this might be a specific client identity, a custom group, or a built in group such as "Users" or "Administrators".

*myPipeServerIdentity is a placeholder for the service identity. This might be set, for example, to WindowsIdentity.GetCurrent().Owner. When the pipe server is hosted in a Windows service, then even better (but a good deal harder to implement) would be the Logon SID identity of the service process - this would ensure that only the specific service process could create instances of the pipe.

If you want to ensure that pipe access is restricted to just users logged on locally i.e. to prevent remote access across a network, you can also add a deny ACE for Network Users into the pipe security ACL.

A: The solution that works on localized versions of Windows:
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
  accessRights, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, null),
  PipeAccessRights.FullControl, AccessControlType.Allow));
pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
  PipeAccessRights.FullControl, AccessControlType.Allow));

A: I figured it out.
static void Main()
{
    PipeSecurity ps = new PipeSecurity();
    ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
    ps.AddAccessRule(new PipeAccessRule("CREATOR OWNER", PipeAccessRights.FullControl, AccessControlType.Allow));
    ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));
    ps.AddAccessRule(pa);
    using (NamedPipeServerStream pipeServer =
        new NamedPipeServerStream("testpipe",PipeDirection.InOut,10,
                                    PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024,1024,ps))
    using (NamedPipeServerStream pipeServer2 =
        new NamedPipeServerStream("testpipe", PipeDirection.InOut, 10,
                                    PipeTransmissionMode.Message, PipeOptions.WriteThrough,1024,1024,ps))
    {

By adding the rights PipeAccessRights.CreateNewInstance it now works fine.

I hit another snag but i solved it, but wanted to post it in case other people found this through Google. by providing your own Pipe security object it removes the default one, so if you need it you need to re-add the System group so it can talk to the pipe if you are writing a service. I updated my above code to what I used to get a elevated service and a non elevated winforms app to talk to each other (Creator owner is likely unnecessary)

A: "Creator Owner" can be replaced by System.Security.Principal.WindowsIdentity.GetCurrent().Name and delete PipeAccessRights.CreateNewInstance for any users.
static void Main()
{
    PipeSecurity ps = new PipeSecurity();
    ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite, AccessControlType.Allow));
    ps.AddAccessRule(new PipeAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, PipeAccessRights.FullControl, AccessControlType.Allow));
    ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));
    ps.AddAccessRule(pa);

A: I know there are many answers to this question, but i fixed a similar problem by setting the level of requestedExecutionLevel to requireAdministrator in the app.manifest file of the project where my namedpipe code resides.
And this fixed the UnauthorizedAccessException for me

A: This will make server to be accessible for everyone for read and write,
It will also work on the OS with all languages, as the username is not hard coded
public NamedPipeServerInstance(string pipeName, int maxNumberOfServerInstances)
{
    var ps = new PipeSecurity();
    var sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
    var everyone = sid.Translate(typeof(NTAccount));
    ps.SetAccessRule(new PipeAccessRule(everyone,
        PipeAccessRights.ReadWrite, AccessControlType.Allow));

    server = new NamedPipeServerStream(pipeName,
        PipeDirection.InOut,
        maxNumberOfServerInstances,
        PipeTransmissionMode.Message,
        PipeOptions.Asynchronous,
        4028, 4028, ps);

    var asyncResult = server.BeginWaitForConnection(OnConnected, null);
}

client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.Asynchronous);

A: For me, the server side is running as an Administrator user, and the client side is running as a normal user. So the solution is to simply reopen them using the same identity.


text:
Q: Overriding portal's styles with module's style - spaces between div tags I have some labels aligned horizontically with textboxes and dropdown lists. A gap appears between the dropdowns and the textboxes. If I inspect element it shows me the css file of the portal which does not include information of what is causing the gap/vertical space which I would like to reduce. What I want is to override those settings on the module level.
On the screenshot, I highlight the style with the 'web developer' tool on firefox. The gap between the dropdown list appears.

        <asp:Label ID="lblCategory" runat="server" Text="Category" CssClass="labelStyle" style="position: relative"></asp:Label>

        <asp:DropDownList ID="ddlCategory" runat="server"  DataSourceID="sqlCategories" DataTextField="Name" DataValueField="CategoryID" AutoPostBack="True"></asp:DropDownList>

        <asp:Label ID="lblSubCategory" runat="server" Text="Sub Category" CssClass="labelStyle"></asp:Label>

        <asp:DropDownList ID="ddlSubCategory" runat="server" DataSourceID="sqlSubCategory" DataTextField="Name" DataValueField="SubCategoryID"></asp:DropDownList>

My styles:
div.ColOne {
    width: 150px;
    float: left; /* to place the column next to the other*/
    padding-left: 0px;
    padding-top: 12px;
    clear: none;
}

div.ColEmpty {
    margin-top:0;
}

Clicking on the Display Style information I get the following:
/* Line 28 */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, caption, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video
{
  margin-top: 0px;
  margin-right: 0px;
  margin-bottom: 0px;
  margin-left: 0px;
  padding-top: 0px;
  padding-right: 0px;
  padding-bottom: 0px;
  padding-left: 0px;
  border-top-width: 0px;
  border-right-width-value: 0px;
  border-bottom-width: 0px;
  border-left-width-value: 0px;
  border-top-style: none;
  border-right-style-value: none;
  border-bottom-style: none;
  border-left-style-value: none;
  border-image-source: none;
  border-image-slice: 100% 100% 100% 100%;
  border-image-width: 1 1 1 1;
  border-image-outset: 0 0 0 0;
  border-image-repeat: stretch stretch;
  font-family: inherit;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-size: inherit;
  line-height: inherit;
  font-size-adjust: inherit;
  font-stretch: inherit;
}

A: I have fixed it by adding the following
div.ColEmpty input[type="text"], select, textarea {
    margin-top:0;
    position: relative;
  line-height:0px;
    top: 2px;
     margin-bottom: 0px;
}

        <asp:DropDownList ID="ddlSubCategory" runat="server" DataSourceID="sqlSubCategory" DataTextField="Name" DataValueField="SubCategoryID"></asp:DropDownList>


text:
Q: VBA Copying data from one table to another and rearranging columns I have 99 columns in one table called tbl_raw. I need to copy 96 of those columns into another table with the same exact header names, but they are rearranged in a different order. What is the most efficient way to do this?
The only way I knew was:
raw_data.Range("tbl_raw[EMPLOYEE]").Copy
processed_data.Range("tbl_processed[EMPLOYEE]").PasteSpecial
However, this would take a lot of code (96 * 2 = 192 lines) and I wasn't sure if there was a more efficient way to do it.
I tried to use https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables, but I couldn't figure out a way to do it with that information either.
Any guidance would be greatly appreciated.

A: Here's a basic example of copying over all but some columns from one table to another:
Dim tbl1 As ListObject, tbl2 As ListObject
Dim h As ListColumn

Set tbl1 = ActiveSheet.ListObjects("Table1")
Set tbl2 = ActiveSheet.ListObjects("Table2")

'loop over the headers from the source table
For Each h In tbl1.ListColumns
    'is the column name in the "excluded" list?
    If IsError(Application.Match(h.Name, Array("col10", "col11"), 0)) Then

        'ok to copy...
        h.DataBodyRange.Copy tbl2.ListColumns(h.Name).DataBodyRange(1)

    End If
Next h

A: Avoid dealing with copying ListObject columns and use a direct value transfer.
Option Explicit

Sub raw2processed()

    Dim lc As Long, mc As Variant, x As Variant
    Dim raw_data As Worksheet, processed_data As Worksheet
    Dim raw_tbl As ListObject, processed_tbl As ListObject

    Set raw_data = Worksheets("raw")
    Set processed_data = Worksheets("processed")
    Set raw_tbl = raw_data.ListObjects("tbl_raw")
    Set processed_tbl = processed_data.ListObjects("tbl_processed")

    With processed_tbl
        'clear target table
        On Error Resume Next
        .DataBodyRange.Clear
        .Resize .Range.Resize(raw_tbl.ListRows.Count + 1, .ListColumns.Count)
        On Error GoTo 0

        'loop through target header and collect columns from raw_tbl
        For lc = 1 To .ListColumns.Count
            Debug.Print .HeaderRowRange(lc)
            mc = Application.Match(.HeaderRowRange(lc), raw_tbl.HeaderRowRange, 0)
            If Not IsError(mc) Then
                x = raw_tbl.ListColumns(mc).DataBodyRange.Value
                .ListColumns(lc).DataBodyRange = x
            End If
        Next lc

    End With

End Sub

A: ForEach/For are the magic of working with arrays and collections.
There are ways to make the following code more efficient, but I think that may get in the way of understanding what is happening.
It has been about 6 months or so since I last worked with VBA, but I believe this should work. I suggest stepping through and watching your locals to see what is going on. If there are issues with variable assignments, there might need to be a 'Let' changed to a 'Set'.
Code follows:
'// PROBLEM:
'// Copy data from one list to a second list.
'// Both lists have the same column names and the same number of columns.
'// Copy data based on the column name.

'// Modify to return a custom source-destination association.
Private Function GetColumnTranslations(zLeftColumns As ListColumns, zRightColumns As ListColumns) As Variant
  Dim zReturn(,) As Variant
  ReDim zReturn(0 To zLeftColumns.Count As Long, 0 To 1 As Long)
  Dim zReturnOffset As Long '// Specifies what index we are working at during our ForEach interations.

  Dim zLeftVar As Variant
  Dim zRightVar As Variant

  ForEach zLeftVar in zLeftColumns
    '// Go through each 'left' column to Find the first 'right' column that matches the name of the 'left' column.
    '// Only the first 'right' column with a matching name will be used. Issue is solved with another ForEach, but beyond forum question's scope.
    ForEach zRightVar in zRightColumns

      If zLeftVar.Name = zRightVar.Name Then

        '// Store the association and exit the nested ForEach.
        Let zReturn(zReturnOffset, 0) = zLeftVar.Range.Column '// Source.
        Let zReturn(zReturnOffset, 1) = zRightVar.Range.Column '// Destination.
        Let zReturnOffset = zReturnOffset + 1

        Exit ForEach
      End If
    Next zRightVar
  Next zLeftVar

  '// Assign return value.
  Let GetColumnTranslations = zReturn
End Function

'// Take each source row and copy the value to a new destination row.
'// New rows are added to the end of the destination list.
Public Sub CopyList(zSourceList As ListObject, zDestinationList As ListObject)
  Dim zColumnTranslations As Variant '// Will be 2-dimensional array.
  Dim zTranslationVar As Variant '// Will be array of 2 elements.
  Let zColumnTranslations = GetColumnTranslations(zSourceList.Columns, zDestinationList.Columns)

  Dim zSourceRowVar As Variant '// Will translate to Range.
  Dim zDestinationRow As Range

  '// Every source row needs copied to a new row in destination.
  ForEach zSourceRowVar in zSourceList.Rows
    Set zDestinationRow = zDestinationList.Rows.Add.Range

    ForEach zTranslationVar in zColumnTranslations
      '// Value may copy formula.
      Let zDestinationRow(0,zTranslationVar(1)).Value = zSourceRowVar(0,zTranslationVar(0)).Value
    Next zTranslationVar
  Next zSourceRowVar
End Sub


text:
Q: Julia ArgumentError: Package RCall not found in current path: I just opened a new Jupyter notebook, and want to load some libraries.
using LinearAlgebra
using SparseArrays
using Statistics
using StatsBase
using RCall

Everytime I run the cell, I keep on getting the same error:
ArgumentError: Package StatsBase not found in current path:
- Run `import Pkg; Pkg.add("StatsBase")` to install the StatsBase package.

So I run the suggested commands:
import Pkg; Pkg.add("StatsBase")

I rerun the top cell, and I get a new error:
ArgumentError: Package RCall not found in current path:
- Run `import Pkg; Pkg.add("RCall")` to install the RCall package.

What I don't get is why I get these error messages, as have installed these packages previously. If I open one of my pre-existing Jupyter notebooks, whis in a different directory, this error does not occur.  However, if I run Julia in terminal I get the same error. Seemingly it is working in some directories, and not others.
What may be causing the problem?

A: Julia can have many virtual environments. The Julia virtual environment has its own package installation state, independent from the global environment.
Contrary to Python, each environment just keeps links to a package repository in local hard drive rather than contain full copies of each package.
The environment is defined in the Project.toml file.
Simply run Pkg.status() to check which environment you are working currently with (this time it shows my global environment):
julia> Pkg.status()
      Status `C:\JuliaPkg\Julia-1.6.1\environments\v1.6\Project.toml`
  [6e4b80f9] BenchmarkTools v1.1.0
  [1e616198] COSMO v0.8.1
  [336ed68f] CSV v0.8.5
  ...

For Jupyter notebooks those are defined in the Project.toml that is located at the same folder as your notebook. This is most likely the source of your problems and the reason why you observe "strange" package installation states.
The Procet.toml file is normally created when you activate a folder:
julia> using Pkg

julia> Pkg.activate(".")
  Activating new environment at `C:\SomeMyFolder\Project.toml`

However, when you run Jupyter (e.g. notebook(dir=".")) Pkg.activate(".") happens automatically where a Project.toml file is found in the current folder.


text:
Q: ajax and asp.net-mvc - should I use PartialView or Json? I have an asp.net-mvc site.  I have a page with a grid of data on it and when  I want to edit a row (by showing up a popup form).  I have 2 options:

*

*Preloading and hiding the form on initial page load in a hidden div and then returning json from the server, binding all of the fields and attributes on the client side and then showing it.

*Returning PartialView() from the server of a PartialView() in which case all the binding is on the server side
It seems that this is decision of convinience versus performance.
Option #2 is much easier because I can do all the binding (and any logic) in C# but it seems like #1 would be much faster because I am not sending over all of that HTML over the network (just the json data).  This assumes that the binding on the client side is going to be faster than the performance hit of the extra network hit.
Is there any other factors that I am missing in this decision to return json or a PartialView() when using asp.net-mvc to populate a form

A: I think it is not a question of JSon or Partial View. Rather this is a question of approach. I would rephrase this as "Should I load the data on page in hidden divs or Should I load the partial view when needed"?
I would prefer the partial view as it doesn't make the initial load bulky and also helps to maintain clear seperation of what is rendered when.

A: Another argument in favour of the json way is platform independence. If you do it the json way, it will be much easier later on to switch platforms, if needed. Partial views tie you tightly to the .NET platform. Json can be served from many different platform solutions, for example nodejs.

A: For your particular scenario, i would recommend the partial view method.
here is a great article that discusses options for modal dialogs in mvc. the jQuery-UI dialog is the clear winner and his example works perfect.
http://www.codeproject.com/KB/ajax/jQuery-Modal-Dialogs.aspx
I also like the idea of loading partial views because u can strongly type them, which is always a good idea.


text:
Q: Why doesn't the compiler automatically add or generate an include guard by default? I know C or C++ code usually needs to use include guards like this:
#ifndef __A__H__
#define __A__H__
class A{
};
#endif

and to speed up compile time, in other cpp (e.g.:B.cpp), it can change
#include "A.h"

to:
#ifndef __A__H__
#include "A.h"
#endif

but the question is why doesn't the compiler automatically add or generate the include guard, and therefore why does the programmer need to add it manually if an include guard is usually required?

A: There are times when it is absolutely incorrect to generate the header guard.  The standards contain an example: <assert.h> in C and <cassert> in C++.
The effect of reincluding those headers depends on the state of the NDEBUG macro when the header is (re)included.  It is legitimate to write:
#undef NDEBUG
#include <assert.h>
…code using assert…
#define NDEBUG 1
#include <assert.h>
…more code using assert…

If the compiler automatically generated a header guard, that would not work correctly.  Therefore, compilers do not generate header guards automatically.

Incidentally, user code should not use header guard macro names that start with double underscore, or underscore capital letter.  Such names are reserved for the implementation.  In C++, no user-defined name may legitimately contain a double underscore at all.  Use something more like:
#ifndef A_H_INCLUDED
#define A_H_INCLUDED
…body of header…
#endif

A: The compiler, or more strictly the pre-processor cannot determine the programmer's intent in using inclusion.  The compiler does not explicitly distinguish between .h files and .c or .cpp files; they differ only in the type of code one places in them.  In fact the compiler deals only in a single translation unit; it is the responsibility of the C preprocessor to concatenate all included files into a single file for compilation.  It would be incorrect for the pre-processor to omit an inclusion that it has previously included because it has no semantic knowledge of the code and may cause intended behaviour to change by second-guessing the developer.
In some circumstances, an IDE may add include guards for template code that it has generated.  For example Microsoft Visual Studio will add them for code that it generates via its project start-up wizards.  If it happens at all, it is properly the responsibility of the IDE rather than the compiler or pre-processor.


text:
Q: Waveshare e-ink display - content faded when boxes drawn below I'm using a Waveshare e-ink display (5x7) attached to a Pi Zero W via a HAT. I'm building the content from top to bottom.
As you can see from this photo (apologies for the reflection of the conservatory roof), all is fine up until this point :

However, if I then proceed to draw one or more boxes below the content, the weather icons fade out from right to left, like so :

The order in which I draw is irrelevant - it happens whether I draw the boxes then the weather data, or vice versa.
Relevant code is as follows :
    # Draw one rectangle for top data
    draw.rectangle([(0,0),(479,120)],outline = 0)
    # And another for the tasks
    draw.rectangle([(0,220),(239,700)],outline = 0)
    # And a third for something else
    draw.rectangle([(241,220),(479,700)],outline = 0)

    # Draw the forecast (on a loop)
    # If we have 400 pixels to play with, forecast covers next 5 hours, so 80 pixels per entry
    i = 0
    xoffset = 40
    yoffset = 130
    forecast = get_forecast()
    while i < 5:

        # Get the data
        icon = get_icon(forecast[i]['icon'])
        time = forecast[i]['time']
        temperature = str(forecast[i]['temperature']) + u'\N{DEGREE SIGN}' + "C"

        # Draw the forecast time
        timewidth = forecastfont.getsize(time)[0]
        textx = calculate_offset(xoffset, timewidth, xoffset)
        texty = yoffset
        draw.text((textx, texty), time, font = forecastfont, fill=0)

        # Draw the forecast icon
        iconwidth = weather24.getsize(icon)[0]
        iconx = calculate_offset(xoffset, iconwidth, xoffset)
        icony = yoffset + forecastfont.getsize(time)[1] + 5
        draw.text((iconx, icony), icon, font = weather24, fill = 0)

        # Draw the forecast temperature
        tempwidth = temperaturefont.getsize(temperature)[0]
        tempx = calculate_offset(xoffset, tempwidth, xoffset)
        tempy = yoffset + forecastfont.getsize(time)[1] + weather24.getsize(icon)[1] + 5
        draw.text((tempx, tempy), temperature, font = temperaturefont, fill=0)

        # Advance the loop and move the offset
        i += 1
        xoffset += 60

My research appears to suggest that sleeping the display after writing should help, but I'm already doing that :
    epd.display(epd.getbuffer(image))
    epd.sleep()

A: This seems to be caused by too much light when the screen does update. It happends  also once the screen is static but in reverse (screen darken with direct light).
It's a bit disapointing but you may want to move the screen in a darken place and especially avoid any direct lighting.
I noted this with a waveshare 7.5 v2 screen with esp32 drivers.


text:
Q: Redundant data in crystal reports I have two tables viz TblTransactions and TblAdjustments
I want to display all transaction in first (detail-a) and then all adjustments in second (Details B). Upon preview, it shows one transaction and all adjustments, then 2nd transaction and all adjustments, (thus seven transaction with five adjustments show 35 records). How can I overcome this problem.
Thanks in advance!

A: to my knowledge if there is no sub report then how you are getting detail 2 rows as on set after detail 1?
If you need to get all TblTransactions first and all TblAdjustments next then take 2 sub reports in 2 detail sections... one for transactions and one for adjustements


text:
Q: API Database Picker (Im trying my best to write everything right, but I normaly dont speak english)
So, I have a problem. I dont know how to do that things Below...
Topic: A player write his Player TAG (#XXXXXX) in my text box. After that he will recieve all the data from an external website/api (for example his LVL or XP)
(I put numbers on the picture i Linked so you can follow along (1.2.3 on the pictures))
Picture Description

*

*I have a Text input box (for a TAG "#XXXXXX") and a send button on my website. Thats all working.

*Now i want, that the "TAG" (Which someone wrote in this box) to apear in my php exactly at the end of a link which will result a link to the API with all his information (look picture two)

*This link will show all the information (Picture 3)

*Now I want for example that the name gets displayed in my html (where my TAG input field is)
Can someone please tell me how to do that and maybe provide me with some code. Maybe with code, where it reads out the information of picture 3
Thank you guys
(Btw the user shouldnt see picture nr3 that should load in the background)

A: I'm operating on the assumption, based on NR2, that you're using some sort of MVC with a router, as you're definitely not using query-string params. I'm also assuming that your API is fully capable of doing the lookup since you've no provided any context on what that is.
That said, you should be able to simply construct the url as a string and call it in js/jquery.
    var theId
    var urlString = "myurl.com/test/api/"+theId;
    $.ajax({
      url: urlString
    }).done(function(foo){
        console.log('bar',foo);
    });

The .done() function should be able to make any changes you need to do such as altering the .text() on the fields to reflect the data returned.
Some code from your actual project would be helpful, pictures can't be explored and there's no real context for what you're trying to bring about.


text:
Q: What does it mean to dualize a constraint in the context of Lagrangian relaxation? In the context of Lagrangian relaxation of discrete optimization problems, what does it mean to 'dualize a constraint'?

A: You have a function $f(\vec x)$ you wish to optimise, given some constraints $g_i(\vec x)=c_i$. Then you can write a Lagrangian $$L=f-\sum_i \lambda_i(g_i-c_i)$$Then to dualise this means to rewrite it as a problem where you optimise a function $F(\vec\lambda)=\sum_i\lambda_ic_i$, with respect to some constraints $G_i(\vec\lambda)=C_i$. When rewriting the problem like this, the components $x_i$ become the Lagrange multipliers for the Lagrangian for this dual problem.


text:
Q: Run KDE and Unity Is there a way to run Unity alongside KDE? I have installed Kubuntu/KDE and I am wondering if I can install Unity so I can switch back and forth between the two.

A: Yes you can use unity in Kubuntu.
sudo apt-get install ubuntu-desktop

Use this command to install unity. You can choose the unity or KDE environment in the login screen.


text:
Q: CSS - SearchBox overlapping divs' padding I had this problem quite a few times and never were able to solve it.
I basically just have a div with 20px padding and would like to fit the searchbox 100% relative to the divs' possible width (including the padding). But the searchbox keeps overlapping the padding from the div. Can anybody help me there?

        <form id='submit' action='' method=''>
            <input type='text' autofocus='on' placeholder='Search with DuckDuckGo' autocomplete='off' id='searchBox'>
        </form>

Lorem

Lorem

Lorem

.content { # This is the main div!
   background-color: rgba(240,240,240, 1);
   padding: 20px;
   display: inline-block;
   text-align: center;
   margin-top: 25%;
   width: 40%;
   box-shadow: 0px 0px 20px 3px #101010;
}

#searchBox { # This here is the search box that keeps overlapping the padding from the content div...
   width: 100%;
   height: 30px;
   padding: 10px;
   font-size: 20px;
   border: 1px rgba(10,10,10, 0.2) solid;
   #border: none;
   color: rgba(10,10,10, 0.5);
   font-family: 'Roboto', 'Tahoma', 'sans-serif';
}

Here is a JS fiddle example to visualize it a little bit better.

A: You can remove the padding property for #searchBox and explicitly set the padding-top and padding-bottom property to 10px (Which will remove left and right padding).
#searchBox {
    width: 100%;
    height: 30px;
    padding-top: 10px;
    padding-bottom: 10px;
    font-size: 20px;
    border: 1px rgba(10,10,10, 0.2) solid;
    color: rgba(10,10,10, 0.5);
    font-family: 'Roboto', 'Tahoma', 'sans-serif';
}

https://jsfiddle.net/0e2Ljgr8/1/
An alternative solution would be to reduce the width of #searchBox to 90% width, as shown in this JSFiddle:
https://jsfiddle.net/0e2Ljgr8/3/


text:
Q: Female cats taking over worlds and fighting humans This was a book series I read years ago.
It was about a female warrior cat species traveling through space and taking over worlds and humans trying to fight back. The males were a sub-species only used for mating once every couple of years and the females had to go back to their home planet to mate. Humans were considered property by the cats and had to wear collars. There was a prophecy concerning a cat and a male human, something about trading blood which was forbidden but would ensure the survival of the cat species.
I'm sure it was two series of books, the second set written after the first, but as a prequel.
It's not Warrior Cats.


text:
Q: Help with function limit I need to say whether the limit
$$\lim_{(x,y)\to(0,0)}f(x,y),$$
exists, where
$$f(x,y)=\frac{x^{2}y^{2}}{|x^{3}|+|y^{3}|}.$$
Can anyone give a hand?

A: I like to use polar coordinates for questions like this. Let $x=r\cos\theta$ and $y=r\sin\theta$
$$\frac{x^2y^2}{|x^3|+|y^3|} \equiv \frac{r^4\cos^2\theta\sin^2\theta}{|r^3\cos^3\theta|+|r^3\sin^3\theta|} \equiv r \left(\frac{\cos^2\theta\sin^2\theta}{|\cos^3\theta|+|\sin^3\theta|}\right)$$
As $r$ tends to zero, this limit tends towards zero, independently of the choice of $\theta$.
I've plotted an image of the function $z = x^2y^2/(|x^3|+|y^3|)$ for $x$ and $y$ within the circle, centre $(0,0)$ with radius $1/5$ and this seems to confirm a well-defined limit. The limit is $z=0$, but I haven't included axes.

A: In this case the function is not continuous at the point in question and so we can't just plug in the point.  So, since the function is not continuous at the point there is at least a chance that the limit doesn't exist.  If we could find two different paths to approach the point that gave different values for the limit then we would know that the limit didn't exist. Two of the more common paths to check are the x and y-axis so let's try those.
x-axis (y = 0)
$$\lim_{(x,y)\to(0,0)}\frac{x^{2}y^{2}}{|x^{3}|+|y^{3}|} =
\lim_{(x,0)\to(0,0)}\frac{x^{2}(0)^{2}}{|x^{3}|+|(0)^{3}|} = \lim_{(x,0)\to(0,0)}0 = 0$$
So along the x-axis the function will approach zero as we move in towards the origin.
y-axis (x = 0)
$$\lim_{(x,y)\to(0,0)}\frac{x^{2}y^{2}}{|x^{3}|+|y^{3}|} =
\lim_{(0,y)\to(0,0)}\frac{(0)^{2}y^{2}}{|(0)^{3}|+|y^{3}|} = \lim_{(0,y)\to(0,0)}0 = 0$$
Although both limits converge at 0 this does not mean that there exists a limit, this only means that the limits exists along two paths.
Let's take a look at the path y = x to confirm:
$$\lim_{(x,y)\to(0,0)}\frac{x^{2}y^{2}}{|x^{3}|+|y^{3}|} =
\lim_{(x,x)\to(0,0)}\frac{x^{2}x^{2}}{|x^{3}|+|x^{3}|} =
\lim_{(x,x)\to(0,0)}\frac{x^4}{2x^3} =
\lim_{(x,x)\to(0,0)}\frac{x}{2} = 0$$
This gives us the same value as the previous two paths, therefore it is safe to conclude that a limit of 0 exists.


text:
Q: How to create dependency property which get value from two other properties I'm making animation of moving window on desktop. I have found somewhere info that the best way for this is creating own property and animate it instead of Left and Top separately.
The problem is that this property is initialized with value (0, 0). I want my property to get value from Top and Left of my window, and set it.
My property:
public static readonly DependencyProperty PositionProperty = DependencyProperty.Register("Position", typeof(Point), typeof(MainCard),
        new PropertyMetadata(PositionPropertyChanged) );

private static void PositionPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs prop)
{
    MainCard mw = (MainCard)dependencyObject;
    Point value = (Point)prop.NewValue;

    mw.Top = value.Y;
    mw.Left = value.X;
}

public Point Position
{
    get
    {
        return (Point)GetValue(PositionProperty);
    }
    set
    {
        SetValue(PositionProperty, value);
    }
}

A: Check out MultiBinding and IMultiValueConverter.  This will let you bind to two source properties and convert them into a single value for your Position.

EDIT: It sounds like what you really want to do here is animate a Point rather than seperate Left and Top values, so this probably doesn't apply to your case.  The real problem here is that you have a two-way problem; this property represents the same information as Top and Left, so if you change it, then Top and Left should change.  Likewise, since Top and Left are mutable, if those change, you really want your property to reflect that.
One option is to register a property changed handler for LeftProperty and TopProperty.  Now, when those change, update your PositionProperty.  You have to be careful here not to trigger repeated updates (I change Left, which changes Position, which changes Left, which...)

A: I don't really understand what you're trying to achieve but... here's my take on your question :

*

*first, you can't put the "default" value for your property to the top/left values of your windows, since it is only know at runting, whereas the "default" value for the property must be provided at compilation time.

*so basically, what you have to to is to set the value of your property right when you have it (for instance in the "show()" method of your window) like this :
myMainCard.SetCurrentValue(MainCard.PositionProperty, new Point() { X = myWindow.Left, Y = myWindow.Top });


text:
Q: How to access spring ApplicationContext in junit @BeforeClass static method? I tried to get it by:
private static ApplicationContext applicationContext;
@Autowired
    public static void setApplicationContext(ApplicationContext applicationContext) {
        AuditorTest.applicationContext = applicationContext;
    }

But it doesn't work as all other attempts.
How to autowire static ApplicationContext?

A: You can't autowire spring beans on static methods. You've to make it an instance method instead, and let it assign the value to static variable (that will work fine):
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
    AuditorTest.applicationContext = applicationContext;
}

But I don't think this is what you want. I guess you should annotate the test class with SpringJUnitRunner, and @ContextConfiguration, and then you'll be able to autowire the ApplicationContext there:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)  // configuration location
public class TestClass {
    @Autowired
    private ApplicationContext context;
}

A: Probably you might have figured out a workaround by now.
May help someone else here.
I ran across the similar issue. Most of the spring framework options
provided does not allow static access of ApplicationContext.
The workaround is simple. Create your own ApplicationContext using
ClassPathXmlApplicationContext using the bean configuration but statically.
<code>
public class BaseTestCase {
    static {
        ApplicationContext context = new ClassPathXmlApplicationContext("test-config.xml");
             // Do what you want to do with the context
             // Probably store in static variable to access somewhere else
         }
    }
</code>


text:
Q: Allowing https for Elastic Beanstalk I'm about to lose my mind trying to set this up. I have lost the whole day and can't seem to get near what I want to do.
I have a node js rest api uploaded trough elastic beanstalk, and I'm trying to setup a webpage to present the api, but for the live example to work the api needs to be accessed trough https. I've read the instructions for setting up the https for elastic beanstalk (and like everything on the AWS documentation it is a ridiculous maze). It has sent me trough several different AWS services.
What I basically got from it so far is that I need to set up a Load Balancer that will receive the connection trough https and forward the user to my instance. But I can't get it to work. I have a domain from freenom: bibliaparahumanos.tk, it is setup with an A alias to my EC2 IP, and it works with http, but if I try to access it trough https, I get "connection refused". If I use my normal Elastic Beanstalk url (http://apibibliahumana-env.eba-3nbmrphf.us-east-2.elasticbeanstalk.com/) with https it works, but I get a warning that the connection is not secure due to the domain on the certificate being different from the domain I'm accessing (which I understand, since the domain in the certificate is for my freenom domain).
I have the Load Balancer Listener set up with:

*

*Protocol: https

*Port: 443

*Default action: forward to target group
(I have tried the target group with both http and https and the problem remains).
My certificate is from AWS Certificate Manager.
I have also seem this other tutorial but it confused me more. It adds some steps for configuring stuff on the app bundle, but I don't understand if it's required or an alternate way. I have tried setting that up, but it asks me to add the certificate's public key, which I can't figure out how to find.

A: I would suggest adding a CNAME record to your DNS towards apibibliahumana-env.eba-3nbmrphf.us-east-2.elasticbeanstalk.com.
A big advantage of using elastic beanstalk is that you can do blue/green deployments; as you will instead add the app URL to your DNS you can build an entire new environment in elastic beanstalk, test/wait until its stable and swap the app urls; which results in deployments without any downtime.
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.CNAMESwap.html


text:
Q: Android 8 Bug: Starting apk installation via adb doesn't work, needs permission REQUEST_INSTALL_PACKAGES I need to start the installation of an apk on an android 8 phone, but this should not be silent (adb install). The behavior should be as if the user has touched the apk file on the device.
Before android 8 it was possible to launch the installation of an apk by adb like this:
adb shell am start -d file:"///sdcard/foobar.apk" -p com.google.android.packageinstaller

This is not possible anymore on android 8. According to the log file the permission android.permission.REQUEST_INSTALL_PACKAGES is necessary.
09-25 16:39:55.691  6066  6066 E InstallStart: Requesting uid 2000 needs to declare permission android.permission.REQUEST_INSTALL_PACKAGES

I know that since android 8 apps that requests installing other apps needs this permission, but this shouldn't be the case by doing it via adb, right?
Is this a bug in android 8? Is it somehow possible to do it in an other way?

A: Try adding in Manifest
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>


text:
Q: Is there any way to inline a recursive function? This is a follow-up to my previous question on which I asked why stream fusion wasn't kicking in a certain program. Turns out the problem was that certain functions weren't inlined, and an INLINE flag improved the performance by about 17x (which showcases the importance of inlining!).
Now, notice that, on the original question, I hardcoded 64 calls of incAll at once. Now, suppose that, instead, I create an nTimes function, which calls a function repeatedly:
module Main where

import qualified Data.Vector.Unboxed as V

{-# INLINE incAll #-}
incAll :: V.Vector Int -> V.Vector Int
incAll = V.map (+ 1)

{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes 0 f x = x
nTimes n f x = f (nTimes (n-1) f x)

main :: IO ()
main = do
  let size = 100000000 :: Int
  let array = V.replicate size 0 :: V.Vector Int
  print $ V.sum (nTimes 64 incAll array)

In this case, just adding an INLINE pragma to nTimes won't help, because AFAIK GHC doesn't inline recursive functions. Is there any trick to force GHC to expand nTimes at compile time and, thus, recover expected performance?

A: No.
You could write
{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes n f x = go n
  where go 0 = x
        go n = f (go (n-1))

and GHC would inline nTimes, and likely specialize the recursive go to your particular arguments incAll and array, but it would not unroll the loop.

A: No, but you can use better functions. I'm not talking about V.map (+64), which would make things certainly a lot faster, but about nTimes. We have three candidates that already do what nTimes does:
{-# INLINE nTimesFoldr #-}
nTimesFoldr :: Int -> (a -> a) -> a -> a
nTimesFoldr n f x = foldr (.) id (replicate n f) $ x

{-# INLINE nTimesIterate #-}
nTimesIterate :: Int -> (a -> a) -> a -> a
nTimesIterate n f x = iterate f x !! n

{-# INLINE nTimesTail #-}
nTimesTail :: Int -> (a -> a) -> a -> a
nTimesTail n f = go n
  where
    {-# INLINE go #-}
    go n x | n <= 0 = x
    go n x          = go (n - 1) (f x)

All versions take around 8 seconds, compared to the 40 seconds your versions take. Joachim's version also takes 8 seconds, by the way. Note that the iterate version takes more memory on my system. While there is an unroll plugin for GHC, it hasn't been updated in the last five years (it uses custom ANNotations).
No unroll at all?
However, before we despair, how well does GHC actually try to inline everything? Let's use nTimesTail and nTimes 1:
module Main where
import qualified Data.Vector.Unboxed as V

{-# INLINE incAll #-}
incAll :: V.Vector Int -> V.Vector Int
incAll = V.map (+ 1)

{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes n f = go n
  where
    {-# INLINE go #-}
    go n x | n <= 0 = x
    go n x          = go (n - 1) (f x)

main :: IO ()
main = do
  let size = 100000000 :: Int
  let array = V.replicate size 0 :: V.Vector Int
  print $ V.sum (nTimes 1 incAll array)

$ stack ghc --package vector -- -O2 -ddump-simpl -dsuppress-all SO.hs

main2 =
  case (runSTRep main3) `cast` ...
  of _ { Vector ww1_s9vw ww2_s9vx ww3_s9vy ->
  case $wgo 1 ww1_s9vw ww2_s9vx ww3_s9vy
  of _ { (# ww5_s9w3, ww6_s9w4, ww7_s9w5 #) ->

We can stop right there. $wgo is the go defined above. Even with 1 GHC does not unroll the loop. It's disturbing since 1 is a constant.
Templates to the rescue
But alas, it's not all for naught. If C++ programmers are able to do the following for compile time constants, so should we, right?
template <int N>
struct Call{
    template <class F, class T>
    static T call(F f, T && t){
        return f(Call<N-1>::call(f,std::forward<T>(t)));
    }
};
template <>
struct Call<0>{
    template <class F, class T>
    static T call(F f, T && t){
        return t;
    }
};

And sure enough, we can, with TemplateHaskell*:
-- Times.sh
{-# LANGUAGE TemplateHaskell #-}
module Times where

import Control.Monad (when)
import Language.Haskell.TH

nTimesTH :: Int -> Q Exp
nTimesTH n = do
  f <- newName "f"
  x <- newName "x"

  when (n <= 0) (reportWarning "nTimesTH: argument non-positive")

  let go k | k <= 0 = VarE x
      go k          = AppE (VarE f) (go (k - 1))
  return $ LamE [VarP f,VarP x] (go n)

What does nTimesTH do? It creates a new function where the first name f is going to be applied to the second name x for a total of n times. n now needs to be a compile-time constant, which suits us, since loop-unrolling is only possible with compile-time constants:
$(nTimesTH 0) = \f x -> x
$(nTimesTH 1) = \f x -> f x
$(nTimesTH 2) = \f x -> f (f x)
$(nTimesTH 3) = \f x -> f (f (f x))
...

Does it work? And is it fast? How fast compared to nTimes? Let's try another main for that:
-- SO.hs
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Times
import qualified Data.Vector.Unboxed as V

{-# INLINE incAll #-}
incAll :: V.Vector Int -> V.Vector Int
incAll = V.map (+ 1)

{-# INLINE nTimes #-}
nTimes :: Int -> (a -> a) -> a -> a
nTimes n f = go n
  where
    {-# INLINE go #-}
    go n x | n <= 0 = x
    go n x          = go (n - 1) (f x)

main :: IO ()
main = do
  let size = 100000000 :: Int
  let array = V.replicate size 0 :: V.Vector Int
  let vTH   = V.sum ($(nTimesTH 64) incAll array)
  let vNorm = V.sum (nTimes 64 incAll array)
  print $ vTH == vNorm

stack ghc --package vector -- -O2 SO.hs && SO.exe +RTS -t

True
<<ghc: 52000056768 bytes, 66 GCs, 400034700/800026736 avg/max bytes residency (2 samples), 1527M in use, 0.000 INIT (0.000 elapsed), 8.875 MUT (9.119 elapsed), 0.000 GC (0.094 elapsed) :ghc>>

It yields the correct result. How fast is it? Let's use another main again:
main :: IO ()
main = do
  let size = 100000000 :: Int
  let array = V.replicate size 0 :: V.Vector Int
  print $ V.sum ($(nTimesTH 64) incAll array)

     800,048,112 bytes allocated in the heap
           4,352 bytes copied during GC
          42,664 bytes maximum residency (1 sample(s))
          18,776 bytes maximum slop
             764 MB total memory in use (0 MB lost due to fragmentation)

                                     Tot time (elapsed)  Avg pause  Max pause
  Gen  0         1 colls,     0 par    0.000s   0.000s     0.0000s    0.0000s
  Gen  1         1 colls,     0 par    0.000s   0.049s     0.0488s    0.0488s

  INIT    time    0.000s  (  0.000s elapsed)
  MUT     time    0.172s  (  0.221s elapsed)
  GC      time    0.000s  (  0.049s elapsed)
  EXIT    time    0.000s  (  0.049s elapsed)
  Total   time    0.188s  (  0.319s elapsed)

  %GC     time       0.0%  (15.3% elapsed)

  Alloc rate    4,654,825,378 bytes per MUT second

  Productivity 100.0% of total user, 58.7% of total elapsed

Well, compare that to the 8s. So for a TL;DR: if you have compile-time constants, and you want to create and/or modify your code based on that constants, consider Template Haskell.
* Please note that this is my first Template Haskell code I've ever written. Use with care. Don't use too large n, or you might end up with a messed up function.

A: There is a little known trick which Andres has told me before where you can actually get GHC to inline recursive functions by using type classes.
The idea is that instead of writing a function normally where you perform structural recursion on a value. You define your function using type classes and perform structural recursion on a type argument. In this example, type-level natural numbers.
GHC will happily inline each recursive call and produce efficient code as each recursive call is at a different type.
I didn't benchmark this or look at the core but it is noticeably faster.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where

import qualified Data.Vector.Unboxed as V

data Proxy a = Proxy

{-# INLINE incAll #-}
incAll :: V.Vector Int -> V.Vector Int
incAll = V.map (+ 1)

oldNTimes :: Int -> (a -> a) -> a -> a
oldNTimes 0 f x = x
oldNTimes n f x = f (oldNTimes (n-1) f x)

-- New definition

data N = Z | S N

class Unroll (n :: N) where
    nTimes :: Proxy n -> (a -> a) -> a -> a

instance Unroll Z where
    nTimes _ f x = x

instance Unroll n => Unroll (S n) where
    nTimes p f x =
        let Proxy :: Proxy (S n) = p
        in f (nTimes (Proxy :: Proxy n) f x)

main :: IO ()
main = do
  let size = 100000000 :: Int
  let array = V.replicate size 0 :: V.Vector Int
  print $ V.sum (nTimes (Proxy :: Proxy (S (S (S (S (S (S (S (S (S (S (S Z)))))))))))) incAll array)
  print $ V.sum (oldNTimes 11 incAll array)


text:
Q: Ranking by partition in visual foxpro I have the following table that looks like
+ --- + --- +
| AID | Tag |
+ --- + --- +
| 1   | 1   |
| 2   | 2   |
| 2   | 3   |
| 2   | 820 |
| 2   | 821 |
| 3   | 2   |
| 4   | 5   |
| 4   | 18  |
| 4   | 2744|
| 4   | 2745|
+ --- + --- +

When I write the following SQL Server 2008 code
select AID,
       Tag,
       RANK() over (partition by AID order by Tag asc) as rank
from My_Table

it produces the following results
+ --- + --- + ---- +
| AID | Tag | Rank |
+ --- + --- + ---- +
| 1   | 1   | 1    |
| 2   | 2   | 1    |
| 2   | 3   | 2    |
| 2   | 820 | 3    |
| 2   | 821 | 4    |
| 3   | 2   | 1    |
| 4   | 5   | 1    |
| 4   | 18  | 2    |
| 4   | 2744| 3    |
| 4   | 2745| 4    |
+ --- + --- + ---- +

which is exactly what I want.
Now, I want to write the same thing in Visual FoxPro 9 SQL. I tried it using recno() as demonstrated here; this numbers my records, but doesn't seem to support the ability to partition, and correlated subqueries don't seem to be supported in VFP 9 SQL. I know that I could do this with cursors and scans, but I don't want to do it that way. Any suggestions?

A: In VFP there is not a rank() function. However, you can achieve the same effect in a number of ways. One way is simple scan...endscan pass updating the ranking value as in the following example:
*** Sample Data
    Create Cursor mytable ( AID Int, Tag Int)
    Insert Into mytable Values (1,1   )
    Insert Into mytable Values (2,2   )
    Insert Into mytable Values (2,3   )
    Insert Into mytable Values (2,820 )
    Insert Into mytable Values (2,821 )
    Insert Into mytable Values (3,2   )
    Insert Into mytable Values (4,5   )
    Insert Into mytable Values (4,18  )
    Insert Into mytable Values (4,2744)
    Insert Into mytable Values (4,2745)
*** Sample Data

Select AID, Tag, Cast(0 As Int) As rank ;
    from mytable ;
    order By AID, Tag ;
    into Cursor crsRanked ;
    readwrite

Scan
    AID = AID
    rcno = Recno()
    Replace rank With Recno()-m.rcno+1 While AID = m.AID
    Skip -1
Endscan

Locate
Browse

EDIT: Yesterday I overlooked how MS SQL server's RANK() function work, sorry. Here is one that work like MS SQL Server's Rank(), Dense_Rank(), Row_number():
Create Cursor mytable ( AID Int, Tag Int)
Insert Into mytable Values (1,1   )
Insert Into mytable Values (2,2   )
Insert Into mytable Values (2,3   )
Insert Into mytable Values (2,820 )
Insert Into mytable Values (2,821 )
Insert Into mytable Values (3,2   )
Insert Into mytable Values (4,5   )
Insert Into mytable Values (4,18  )
Insert Into mytable Values (4,18  )
Insert Into mytable Values (4,18  )
Insert Into mytable Values (4,2744)
Insert Into mytable Values (4,2745)

Select AID, Tag, ;
    Cast(0 As Int) As rownum, ;
    Cast(0 As Int) As rank, ;
    Cast(0 As Int) As denserank ;
    from mytable ;
    order By AID, Tag ;
    into Cursor crsRanked ;
    readwrite

Local AID,rank,denserank,nextrank,rcno
Scan
    AID = AID
    rank = 0
    nextrank = 0
    denserank = 0
    rcno = Recno()
    Scan While m.AID = AID
        Tag = Tag
        rank = nextrank + 1
        denserank = m.denserank + 1
        Replace ;
            rank With m.rank, ;
            denserank With m.denserank, ;
            rownum With Recno()-m.rcno+1 ;
            While AID = m.AID And Tag = m.Tag
        nextrank = m.nextrank + _Tally
        Skip -1
    Endscan
    Skip -1
Endscan

Locate
Browse

A: I discovered the answer, for anyone who cares to know. The following SQL code is supported in Visual FoxPro 9.0 and will do what we want.
select  t1.aid, ;
        t1.tag, ;
        count(*) as rank ;
    from my_table t1 ;
    inner join my_table t2 ;
        on t2.aid = t1.aid ;
        and t2.tag <= t1.tag ;
    group by t1.aid, t1.tag

To see why, let's take a closer look at the inner join by leaving out the aggregate and including the tags from t2.
select  t1.aid, ;
        t1.tag, ;
        t2.tag ;
    from my_table t1 ;
    inner join my_table t2 ;
        on t2.aid = t1.aid ;
        and t2.tag <= t1.tag ;
    order by t1.aid, t1.tag

This code produces a table like
+ --- + ---- + ---- +
| AID | Tag1 | Tag2 |
+ --- + ---- + ---- +
| 1   | 1    | 1    |
| 2   | 2    | 2    |
| 2   | 3    | 2    |
| 2   | 3    | 3    |
| 2   | 820  | 2    |
| 2   | 820  | 3    |
| 2   | 820  | 820  |
| 2   | 821  | 2    |
| 2   | 821  | 3    |
| 2   | 821  | 820  |
| 2   | 821  | 821  |
| 3   | 2    | 2    |
| 4   | 5    | 5    |
| 4   | 18   | 5    |
| 4   | 18   | 18   |
| 4   | 2744 | 5    |
| 4   | 2744 | 18   |
| 4   | 2744 | 2744 |
| 4   | 2745 | 5    |
| 4   | 2745 | 18   |
| 4   | 2745 | 2744 |
| 4   | 2745 | 2745 |
+ --- + ---- + ---- +

We don't actually care about the data in Tag2, but now we can clearly see that the rank is the count of the Tag1 grouped by Aid and Tag1.