text:
Q: Js file as fixture in cypress not loaded How do you use js files as fixtures? any examples on this?
I tried this in user-details.js:
data = {
  email: function () {
    const currentTimestamp = new Date().getTime();
    return `test${currentTimestamp}@test.com`
  },
  firstName: 'Max',
  lastName: 'Mustermann',
  street: 'Some Street',
}

Then in my spec file I do this:
beforeEach(function () {
    cy.fixture(env + '/user-details').as('userDetails');
  });

And in the it block of the test in the same spec file:
const userDetails = this.userDetails.data;
actions.insertStreet(userDetails.street);

But it says it cannot read property 'street' of undefined. Any ideas how to do it properly? :sweat_smile:

A: I had the same question, and couldn't quite square the accepted answer with what I saw happening (in Cypress 9.2.1).
It turns out that when a .js file is given as a fixture, cypress eval()s the content of the file (actually, it uses eval-with-parentheses), and uses whatever object this results in.
So it is possible to have a file user-details.js, which looks like
[{name: "Bob", age: 30 + 5}]

or even execute some "real" code:
["Bob", "Rob", "Job"].map((name, index) => ({user: name, age: 20 + index}))

or
(() => {
    const users = ....
    return users
})()

It should be noted that it's not as flexible as you might want (e.g. you cannot import code, do asynchronous things, etc), but it's more than nothing.
The question is, should you....
Quite honestly, I think this is a great way to allow making your fixtures slightly more human readable, being able to add comments, and easy conversions. And you're not bothered by JSON's comma-stictness E.g
[
  // have a single user, because blah blah
  {name: "Bob", date_of_birth: new Date(1979, 5, 3).valueOf() / 1000},
]

(Date(1979, 5, 3) is much better human-readable than some unix timestamp (even though it means 5th of June, not 5th of May....))
I fully think that the .js fixture is a good way to do this (and would be even happier if it would just import the fixture as a module and use the default export as item or something, but eval is acceptable....), as long as the thing you're producing is constant! If you want something dynamic (or, probably, something constant that takes a bit more complexity to make), you're much better of with @seth-lutske 's suggestion (meaning that in your case, the accepted answer is what you need, however I wanted to document how .js fixtures work in case someone else came by).
Having said all this, it's questionable why cypress uses an eval() here, even though the suggested way is to use window.Function(); in addition, I wonder if you want to run the risk that down the line, some other developer (which includes future-you) decides to build a system that downloads your fixtures from some external website, which means that you created a nice security hole....
It's very informative to read the github issue on Javascript fixtures (I wish I had before I dove into all this myself); if you're looking for a good workaround, see this and this comment.

As a concrete answer to the question asked, the problem is that
eval(`data = {
  email: function () {
    const currentTimestamp = new Date().getTime();
    return \`test\${currentTimestamp}@test.com\`
  },
  firstName: 'Max',
  lastName: 'Mustermann',
  street: 'Some Street',
} `)

will return exactly that object, which should be accessible on this.userDetails. Therefore this.userDetails.data points to the data-field in this object, which is undefined.
The following would work:
user-details.js:
{
  data: {
    email: function () {
      const currentTimestamp = new Date().getTime();
      return `test${currentTimestamp}@test.com`
    },
    firstName: 'Max',
    lastName: 'Mustermann',
    street: 'Some Street',
  }
}

(or, in case you want email to be a string rather than a function:
{
  data: {
    email: (function () {
      const currentTimestamp = new Date().getTime();
      return `test${currentTimestamp}@test.com`
    })(),
    firstName: 'Max',
    lastName: 'Mustermann',
    street: 'Some Street',
  }
}

)

A: From the cypress docs:

Load a fixed set of data located in a file.

What you are trying to load is not a fixed set of data.  It is an object that contains a dynamic function that returns data that will be unique every time the function is run.  You are trying to apply a json-like attitude towards something that is definitely not json. You need to think of a fixture as something that a real api call would return - a JSON, an image, binary, etc.  An api call would likely not return a raw text/javascript file like your user-details.js file and expect the front end to know what to do with it.
Your options:

*

*Make it a true JSON and use a hard-coded value for the date

*Do an export data = { ... }, then import that value into your .spec.js file and use it

*Just include the values inline, or create a function at the top of the .spec file that creates them for you

Sorry if that's not what you were hoping to hear
Edit: as per request, here's an example of option 3:
// any.spec.js

function createUserDetails(){
  return {
    email: `test${new Date().getTime()}@test.com`,
    firstName: 'Max',
    lastName: 'Mustermann',
    street: 'Some Street',
  }
};

describe('your test block', => {

  it('tests some stuff', () => {
    const userDetails = createUserDetails();
    actions.insertStreet(userDetails.street);
  });

  it('tests some other stuff', () => {
    const userDetails = createUserDetails();
    actions.insertEmail(userDetails.email);
  });

});

So you define your data creator in a single place, but can reuse it in may places.


text:
Q: How to fail back to the first region in amazon aurora global database I am following the official documentation here
https://aws.amazon.com/getting-started/hands-on/aurora-global-database/
which says:
Note: After failover, the newly promoted cluster in Europe (Paris) Region becomes a Regional aurora cluster. Once promoted you cannot add the new DB cluster back to the old Aurora Global Database as a secondary region. If you want to fail back to original region US-East (N. Virginia) or add a secondary cluster in different AWS Region, you need to repeat the steps 6 to 8 by creating a new Aurora Global Database with the newly promoted cluster as the primary cluster. See Failover for Aurora Global Database.

I am wondering about the following:

*

*On what basis does the failover happen to secondary region? Does it happen only when the primary region is down? If I have a custom failover strategy then, can that be tied to amazon aurora global database failover as well?

*When the failover happens, does it promote the secondary region's aurora to master automatically?

*After failover, if I need to fail back to the primary region then, can I flip the the direction of replication back to primary from secondary somehow? Is there an automated way to do that?

A: Unfortunately at the moment the Aurora service does not perform the failover itself (although you could automate this through CloudWatch and Lambda triggers).

Q: Will Aurora automatically fail over to a secondary region of an Aurora Global Database?
No. If your primary region becomes unavailable, you can manually remove a secondary region from an Aurora Global Database and promote it to take full reads and writes. You will also need to point your application to the newly promoted region.

When the failover occurs the promoted instance becomes separated from the cluster, and it will become its own cluster with its own reads and writes. At this point there is no relationship between the clusters anymore your application would need to be retargeted to use this endpoint instead.
To flip back you would need to recreate an Aurora cluster in the previous region (or copy the DB changes back to the previous cluster). The simpler route might be to create a global database back to the original region then failover and retarget your application at this one.
Amazon has recently enabled write forwarding for global databases so in theory you could retarget the application back to the original region before you failover.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple_form hidden field breaks Devise validation in rails 3.2 app I'm using devise for authentication and have users associated with buildings.  I can create new users appropriately associated with the right building but devise validation breaks if a new user doesn't have all required inputs.
The code:
app/models/user.rb
class User < ActiveRecord::Base
  belongs_to :building
  attr_accessible :building_id
  ...
end

(I known that having building_id attr_accessible is not ideal but I'm not sure how to create the association without using a hidden field for the building_id in the new user registration form...)
class Building < ActiveRecord::Base
  has_many :users
  ...
end

In my routes, user registration is nested within buildings:
devise_for :users, controllers: { :registrations => "registrations" }, skip: [:registrations]

resources :users, except: [:new, :create] do
  resource :approvals, only: [:update]
end

match '/:building', to: "buildings#landing"
resources :buildings, except: [:new, :create, :destroy] do
  as :user do
    get '/signup' => 'registrations#new', as: :new_user_registration
    post '/signup' => 'registrations#create', as: :user_registration
  end
  ...
end

app/views/devise/registrations/new.html.erb
<%= simple_form_for(resource, :as => resource_name, :url => building_user_registration_path(), :html => {:class => 'form-inline', :multipart => true }) do |f| %>

    <%= render 'fields', f: f %>

    <%= f.input :role, collection: User::ROLES.collect %>
    <%= f.input :password, :required => true %>
    <%= f.input :password_confirmation, :required => true %>

    <%= f.button :submit, "Create my account", class: "btn btn-large btn-primary" %>

<% end %>

And then, finally, the offending line of code in app/views/devise/registrations/_fields.html.erb
...
 <%= f.hidden_field :building_id, value: @building.id %>
...

If all of the required fields for the new user are filled in correctly a new user is created  that is appropriately associated with the right building.  If any of the required fields is blank or invalid, Devise throws the following error in the browser:
RuntimeError in Registrations#create

Showing .../app/views/devise/registrations/_fields.html.erb where line #7 raised:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

Line #7 is: <%= f.hidden_field :building_id, value: @building.id %>
Any thoughts would be greatly appreciated.  I'm sure that I'm doing several suboptimal things here...

A: You can do
<%= f.hidden_field :building_id, value: @building.try(:id) %>

but I would rather not include this field at all if there's no @building set

A: I got it working with the help of a friend.  I already had a custom registration controller (referred to in my routes) and I added a before filter to find the building:
class RegistrationsController < Devise::RegistrationsController

  before_filter :find_building, only: [:new, :create]

  ...

  private

  def find_building
    @building = Building.find_by_slug(params[:building_id])
  end

end


text:
Q: How does this C multiply function correspond to assembly, and what integer type is it using? Okay, so I have a function:
void store_prod(num_t *dest, unsigned x, num_t y){
 *dest = x*y;
}

now, according to the book, GCC generates the following assembly code
(dest at %ebp+8, x at %ebp+12, y at %ebp+16)
1. movl 12(%ebp), %eax
2. movl 20(%ebp),%ecx
3. imull %eax,%ecx
4. mull 16(%ebp)
5. leal (%ecx, %edx), %edx
6. movl 8(%ebp),%ecx
7. movl %eax, (%ecx)
8. movl %edx, 4(%ecx)

I need to find out what kind of data type is num_t and to describe the algorithm used to compute the product and argue that it is correct.
Mind you, this isn't homework, just a practice problem in a book. However, I'd be glad to have some insight, as unsigned vs signed division is getting hazy.


text:
Q: Angular - Difference between two dates wrong timezone I'm trying to obtain the duration of something. I have the start and end time in ms so I do the diff between the two values. But when I try to show it in HH:mm:ss format the timezone is different.
Start time : 1658150216000 | 18.07.2022 15:16:56
End time  : 1658160216000 | 18.07.2022 18:03:36
Diff : 10000000 | (should be) 02:46:40 | (shows) 03:46:40
The first two dates are created with GMT+0200 but the diff time is created with GMT+0100, and I don' get to modify this timezone.
I also tried to parse just the number but gets the same result {{ 10000000 | date:'HH:mm:ss' }}


text:
Q: Why is the directory listing different between Filezilla and Putty? Help I'm new to bash
So I log into my hosting account ftp at Godaddy with Filezilla and my directory structure is this:
..
access (directory)
cgi (directory)
js (directory)
kml (directory)
stats (directory)
test (directory)
(and a bunch of files)

then I log in with Putty and from the -bash-3.25$ prompt ls:
data  error logs  htconfig  html  site  tmp

The home directory is /var/chroot/home/content/48/10443756
Can someone explain why these are different?  Thanks

A: the reason must be: you are listing different directories (or on different hosts)
execute pwd on both (ssh & ftp) you will see difference


text:
Q: Why Browsable(false) does not hide columns in DataGrid In my WPF apllication I want to hide column in DataGrid with binding ItemsSource  by adding [Browsable(false)] to some properties
But, with or without Browsable(false) all columns are visible.
My model:
public class Room : INotifyPropertyChanged
{
    private int id;
  ...
    [Browsable(false)]
    public int Id
    {
        get
        {
            return this.id;
        }
        set
        {
            this.id = value;
            this.OnPropertyChanged("Id");
        }
    }
    ...
    public Room()
    {
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged;
        if (propertyChangedEventHandler != null)
        {
            propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

View:
<DataGrid Grid.Row="1" ItemsSource="{Binding Rooms}" SelectedItem="{Binding SelectedRoom, Mode=TwoWay}" />

How can I use Browsable(false) to hide columns?

A: You can hide them by hooking up the AutoGeneratingColumn Event on your DataGrid (see https://stackoverflow.com/a/3794324/4735446).
public class DataGridHideBrowsableFalseBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        AssociatedObject.AutoGeneratingColumn += AssociatedObject_AutoGeneratingColumn;
        base.OnAttached();
    }

    private void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (((PropertyDescriptor)e.PropertyDescriptor).IsBrowsable == false)
            e.Cancel = true;
    }
}

<DataGrid
    ItemsSource="{Binding Path=DataGridSource, Mode=OneWay}"
    AutoGenerateColumns="true">
        <i:Interaction.Behaviors>
            <behaviors:DataGridHideBrowsableFalseBehavior>
             </behaviors:DataGridHideBrowsableFalseBehavior>
        </i:Interaction.Behaviors>
</DataGrid>

A: You can't, I'm afraid. The Browsable attribute only affects the Properties view of the visual designer, it has NO effect during runtime...
For more info, check the MSDN page about BrowsableAttribute.

A: Don't call this.OnPropertyChanged("Id"); in your code.


text:
Q: Remove existing log file and create new log file in sql server I have log file which is grown to 1TB. I have no need of log file. Just want to delete the old log file and create a new one instead of old log file.
How can I achieve that ? will it cause any other problem? pleas help.

A: Right mouse button on the database and
TASKS -> SHRINK -> FILES

Then choose the option that interests you
More :
https://learn.microsoft.com/en-us/sql/relational-databases/databases/shrink-a-file?view=sql-server-2017

A: I made a backup of the database (very important just in case something fails or trying something else you brake up things!) and then I detached and reatached the database, but deleting the ldf file from the reataching window. This creates a new ldf file as expected in the original database but empty.

More details here:
https://inapp.com/delete-sql-server-database-transaction-log-file/

A: Brought database to offline and deleted log file manually from file system. And bring database back to online. Thats worked out.

A: use this :
create database cmsdb on
(filename = 'd:\programfiles\microsoft sqsl server \msql12.mssqlserver\mssql\data\cmsdb.mdf')
for attach_rebuild_log
go


text:
Q: How to Login in Web Application using REST APIs through JMETER I am trying a Performance scenario where single user logs in to web application.
For that i am using Jmeter and REST-APIs
Here i have to call REST-APIs for that i have used "HTTP Request Defaults", I have created one thread group and added one "HTTP Request Default".
From APIs i have to pass two parameters:
1) User Name
2) Password
What would be the syntax of parameters in HTTP Request Defaults? or what sampler i should use for this?
I have one API link from which we can trigger those parameter, which will get applied on web application.

A: *

*First of all you'll need a HTTP Header Manager configured to send the following header:

*

*Name: Content-Type

*Value: application/json
Elsewise your request may not be processed as needed

*The sampler you need to use is generic HTTP Request sampler. The easiest way to provide JSON payload is to switch to Body Data tab and put your JSON there as below:

*Optionally you may with to use JSON Path Extractor for correlation

See Testing SOAP/REST Web Services Using JMeter guide for a quick ramp-up on the RESTful web services testing domain.

A: for ease of use

*

*In your Jmeter click on File, select Templates

*In the opened window/dialog, select "Building a SOAP web-service test plan"

*Click on Create.

It will open a test plan, which should give you a fare idea on how to achieve your scenario.
Hope this will help.


text:
Q: Patch section command fails I'd like to patch the section command to add at the end a simple \label in a way that is as generic as possible (I don't want to assume the number of arguments of the section command for instance, so I can't use \let and redefine \section directly).
However, the patched version moves the title outside of the section:

\documentclass{article}

\usepackage{etoolbox}

\ifdef{\section}{
  \ifpatchable*{\section}{
    \apptocmd{\section}{{\label{DEF}}}{}{}%
  }{}
}

\usepackage{hyperref}
\usepackage{cleveref}
\begin{document}

\section{Name of my section}

Hello everybody. \cref{DEF}

\end{document}

A: You assume that \section is the command that sets a numbered section. But that's not the case. Look at the definition of \section in article.cls:
\newcommand\section{\@startsection {section}{1}{\z@}%
                                   {-3.5ex \@plus -1ex \@minus -.2ex}%
                                   {2.3ex \@plus.2ex}%
                                   {\normalfont\Large\bfseries}}

\section, in fact, calls \@startsection with a bunch of other arguments.
If you want to add a generic label to a numbered section, you can use your patch but for \@sect:

\documentclass{article}

\usepackage{etoolbox}

\makeatletter
\apptocmd{\@sect}{\label{DEF}}{}{}%
\makeatother

\usepackage{hyperref}
\usepackage{cleveref}

\begin{document}

\section{Name of my section}

Hello everybody. \cref{DEF}

\end{document}

Unnumbered section use \@ssect internally, so this will only hold for numbered sections. But that makes complete sense. What doesn't make sense in your request if fixing the \label independent of the \section. It will result in multiply-defined labels if you have more than one section.


text:
Q: RactiveJS: Filtering DIV elements based on text input value I've been trying to find an example on how to filter a container of divs based on a search text box using RactiveJS.
I know how to get the key pressed events using Ractive but unsure on how to filter the model the RactiveJS way. Keeping copies / history of the data during key press event seems like a bad idea. What am I missing here?

A: You can let Ractive manage it (http://jsfiddle.net/nnbww/):

  <input name="search" type="text" value="{{searchTerm}}"/>
  {{#items}}
     {{#(..indexOf(searchTerm)===0)}}

{{.}}

     {{/}}
 {{/items}}

You can use this instead of . if you prefer:
{{# this.indexOf(searchTerm)===0 }}

And put the function on your data, rather than inline:
{{# filter(this) }}

This would allow you to change the filter as well. Check out http://examples.ractivejs.org/todos for a good example of this.
If you need to track other info about the filtered list (for example display a count of matched items), it's a bit more difficult to use a purely reactive approach (see version /1/ of above jsfiddle), which probably makes it simpler to use an observer:
 <input name="search" type="text" value="{{searchTerm}}"/>
 {{#filtered}}

{{.}}

 {{/filtered}}
 Matching {{filtered.length}} of {{items.length}}

set in complete method:
var ractive = new Ractive({
    el: 'container',
    template: '#container',
    data: {
        searchTerm: 'foo',
        items: [ 'foo', 'bar', 'biz', 'bah' ]
    },
    complete: function(){
        var r = this
        r.observe('searchTerm', function(search){
            var filtered = r.get('items').filter(function(item){
                return item.indexOf(search)===0
            })
            r.set('filtered', filtered)
        })
    }
})

(see version /2/ of jsfiddle link)

A: If your searchable div's are static, then you can put an observer on your search term:
http://jsfiddle.net/fLd86/10/
ractive = new Ractive({
el: 'container',
template: '#container',
data: { searchTerm: 'foo' }
});

observer = ractive.observe( 'searchTerm', function ( newValue, oldValue, keypath ) {
    $( 'div.searchable:contains("' + newValue +'")').show();
    $( 'div.searchable:not(:contains("' + newValue +'"))').hide();
});

If the divs are part of your model, you'll need to put something in the template to inject them into the html, but the same sort of logic should work.


text:
Q: Docker Redis start with persistent storage using -v gives error (chown: changing ownership of '.': Permission denied) I'm using following system version/spec for the docker-redis setup using default redis.conf.
Redhat version: 7.6 (Red Hat Enterprise Linux Server)
Redis Version: 5.0.4
Docker Version:  1.13.1, build b2f74b2/1.13.1

When I run following command it's working perfectly fine.
sudo docker run -d -v $PWD/redis.conf:/usr/local/etc/redis/redis.conf --name redis-persistance --net tyk -p 7070:6379 redis redis-server /usr/local/etc/redis/redis.conf --appendonly yes

I need to get redis data (which is in /data inside the container) to the host directory (/usr/local/etc/redis/data) (-v $PWD/data:/data). So when I run following command I'm getting the below error.
Note $PWD = /usr/local/etc/redis/
sudo docker run -d -v $PWD/redis.conf:/usr/local/etc/redis/redis.conf -v $PWD/data:/data --name redis-persistance --net tyk -p 7070:6379 redis redis-server /usr/local/etc/redis/redis.conf --appendonly yes

Error in docker logs:
journal: chown: changing ownership of '.': Permission denied
level=warning msg="05ce842f052e28566aed0e2eab32281138462cead771033790266ae145fce116 cleanup: failed to unmount secrets: invalid argument"

Also I tried changing the ownership of the data folder in the host to following as well. chown redis:redis data
drwxrwxrwx. 2 redis redis     6 May  3 07:11 data

Can someone help me out on this. Thanks.

A: First create a volume:
docker volume create redis_data

Check the volume is created (note the Mountpoint):
docker volume inspect redis_data

Then use this volume to start your container:
sudo docker run -d -v $PWD/redis.conf:/usr/local/etc/redis/redis.conf -v redis_data:/data --name redis-persistance --net tyk -p 7070:6379 redis redis-server /usr/local/etc/redis/redis.conf --appendonly yes

You can then check the contents of the "Mountpoint" that should be the redis data.


text:
Q: PHP: embed text in image when uploading it I followed this example to embed text in image while uploading it but it's not working.
This is my code:
header('Content-type: image/jpeg');
$img = $_FILES['mainImage']['name'];
list($txt, $ext) = explode(".", $img);
$imgName = "ac_".time().".".$ext;
$tmp = $_FILES['mainImage']['tmp_name'];

$textToImage = imagecreatefromjpeg($tmp);
// Allocate A Color For The Text
$white = imagecolorallocate($textToImage, 255, 255, 255);
// Set Path to Font File
$font_path = '../assets/fonts/font.ttf';
// Set Text to Be Printed On Image
$text = "Test text";
// Print Text On Image
imagettftext($textToImage, 25, 0, 75, 300, $white, $font_path, $text);

$imageUploaded = move_uploaded_file($tmp, 'images_path/'.$imgName);
if(!$imageUploaded){
    die('Error upload image!');
}

The image is uploaded but wihout text in it !

A: For this we are working with GD library.

"PHP is not limited to creating just HTML output. It can also be used
  to create and manipulate image files in a variety of different image
  formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more
  convenient, PHP can output image streams directly to a browser. You
  will need to compile PHP with the GD library of image functions for
  this to work. GD and PHP may also require other libraries, depending
  on which image formats you want to work with."

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.
The following code sample demonstrates the use of GD library to watermark images on the fly. The method demonstrated here to watermark an uploaded image is to overlay the original image with another image, preferably a transparent PNG image.
PHP provides a rich set of functions to create and alter images on the fly. These functions require the GD library, which is bundled with PHP since version 4.3.
The HTML form needs a file upload element: <input type="file">. You must also specify the correct encoding type: enctype="multipart/form-data" for the form.
 / link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;

function create_image($user){

global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";

// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {

// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");

// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);

// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;

// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;

}
// create the image
imagejpeg($im, $file, $quality);

}

return $file;
}

function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}

$user = array(

array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),

array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),

array(
'name'=> 'SlimenTunis@webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);

// run the script to create the image
$filename = create_image($user);

here we have two functions to make it as simple as possible. To run the code simply pass the $user array data to the function and it'll save the new image in the folder 'covers' on your server. The function returns the file url so you just need to echo it into an image tag as shown below. Check out the demo where you can create your own.
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>

A: You can try using the Intervention library. I use it for doing what you're asking about. It is quite simple to understand and the documentation is is well-written.


text:
Q: Print Java enum to lower case by default keeping enum constants in uppercase I have an enum in Java I'd like to serialize, so that when I call it from anywhere in the code, I get the lowercase representation of the name.
Let's say I have the following enum:
public enum Status {
    DRAFT, PENDING, COMPLETE;
}
println ("Status=" + Status.DRAFT);

I'd like to get the following:
Status=draft

[Note]: I want to use the enum constants in uppercase, and when requesting the value get the lowercase representation.

A: If you want lower case, you could just use lower case, or mixed case, or whatever makes more sense to you.
public enum Status {
    draft, pending, complete;
}

println ("Status=" + Status.draft);

prints
Status=draft

A: I am replying this question myself as i found the solution interesting and could not find a reply in the site. Just in case somebody else looks for a way to solve this.
The solution is simple, just override the Enum toString method like this:
public enum Status {
    DRAFT, PENDING, COMPLETE;

    @Override
    public String toString() {
        return name().toLowerCase();
    }
}
println ("Status=" + Status.DRAFT);

This would output the name in lower case.

A: Another solution could be:
public enum Status {
  DRAFT, PENDING, COMPLETE;

  public String nameLowerCase(){
        return name().toLowerCase();
    }
}

A: You can use the following Enum class which contains constructor with name and ordinal for each enum constant. You can assign values you need for the enum constant.
public enum Status {

DRAFT(0,"draft"), PENDING(1,"pending"), COMPLETE(2,"complete");

private int key;
private String value;

Status(int key, String value){
    this.key = key;
    this.value = value;
}

public int getKey() {
    return key;
}

public void setKey(int key) {
    this.key = key;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

@Override
public String toString(){
    return this.value;
}

}

Since we override the toString method, the value which is lowercase is returned.
Using
System.out.print("Status = "+Status.DRAFT);

would print,
Status = draft

and
System.out.print("Status = "+Status.DRAFT.name());

would print
Status = DRAFT


text:
Q: DNS SRV records for IMAP are not seen or used To the best of my knowledge, the below DNS records should work as a failover for my mail servers:
example.com     A   192.0.2.1       3600
www.example.com A   192.0.2.1       3600
ftp.example.com A   192.0.2.1       3600
example.com TXT "v=spf1 a mx a:spf.batchsmtp.com ip4:198.51.100.1 ip4:203.0.113.2 -all"     86400
example.com     MX  srv1.batchsmtp.com  10  86400
example.com     MX  srv2.batchsmtp.com  10  86400
srv1.example.com    A   198.51.100.1        3600
srv2.example.com    A   203.0.113.2         3600
_smtp._tcp.example.com  SRV 2 25 srv1.example.com   10  3600
_smtp._tcp.example.com  SRV 1 25 srv2.example.com   10  3600
_imaps._tcp.example.com SRV 2 993 srv1.example.com  10  3600
_imaps._tcp.example.com SRV 1 993 srv2.example.com  10  3600
_imap._tcp.example.com  SRV 2 143 srv1.example.com  10  3600
_imap._tcp.example.com  SRV 1 143 srv2.example.com  10  3600
_submission._tcp.example.com    SRV 2 587 srv1.example.com  10  3600
_submission._tcp.example.com    SRV 1 587 srv2.example.com  10  3600

I've turned srv1.example.com off but my email clients just time out and never seem to contact srv2.example.com (short TTLs are for testing).
Online DNS tools never seem to show my SRV records, but I believe that is normal behavior.

*

*Am I doing something wrong here?

*Or does it maybe take a long time before mail clients start using these records (as in 48 hours)?

*Do I need to put something specific in my email client? (which target host)

Email clients tried: Mozilla Thunderbird, iOS Mail
This is what a dig gives:
;; QUESTION SECTION:
;_imaps._tcp.example.com.      IN      SRV

;; ANSWER SECTION:
_imaps._tcp.example.com. 3600  IN      SRV     10 2 993 srv1.example.com.
_imaps._tcp.example.com. 3600  IN      SRV     10 1 993 srv2.example.com.

;; AUTHORITY SECTION:
example.com.           86400   IN      NS      ns3.nsdomain.com.
example.com.           86400   IN      NS      ns2.nsdomain.com.
example.com.           86400   IN      NS      ns1.nsdomain.com.

;; ADDITIONAL SECTION:
srv2.example.com.      2502    IN      A       203.0.113.2
srv1.example.com.      3600    IN      A       198.51.100.1

A: The world is not ready for SRV records. Sigh, they only exist since 1996...
https://www.rfc-editor.org/rfc/rfc2052


text:
Q: Prevent updateUIView to update view when @State var changes After reading other questions and google around, i think its safe to say that updateUIView will be triggered as soon as any @state/@Binding var is changed in UIViewRepresentable no matter what. In my case i don't want to trigger updateUIView on one specific @State var.
I'm using Google maps in my app where I'm using @state/@Binding var to pass some location list data to UIViewRepresentable, the updateUIView do the list iteration and shows the location markers on mapView with GMSCameraUpdate.fit(bounds,withPadding: 15.0).
Now i'm using coordinator to use GMSMapViewDelegate methods like drag and willMove and idleAt. I want to pass a bool which is a @State var back to my content view as soon as the idleAt is triggered after camera move. The bool is sent back to the contentView and i can trigger my API to get new list of location data and pass it in @State var. But since the bool was a @State var and it got updated, the updateUIView is triggered still with the old list of data and move the camera back to old location bounds. This updateUIView is triggered even before the API call is fired.
How can i send the bool back to my contentView without triggering updateUIView?
UIViewRepresentable code
struct MapsView: UIViewRepresentable {

@Binding var list : [LocationObj]
@Binding var shouldRefresh: Bool

func makeUIView(context: Context) -> GMSMapView

func updateUIView(_ mapView: GMSMapView, context: Context){
    var bounds = GMSCoordinateBounds()
    for location in list{}

    mapView.animate(with: GMSCameraUpdate.fit(bounds,withPadding: 15.0))

}

func makeCoordinator() -> Coordinator {
    Coordinator(owner: self, refresh: $shouldRefresh)
}

class Coordinator: NSObject, GMSMapViewDelegate {

    let owner: MapsView
    var mShouldRefresh: Binding<Bool>

    init(owner: MapsView, refresh: Binding<Bool>) {
        self.owner = owner
        self.mShouldRefresh = refresh
    }

func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition){
   // after moving camera and calculating the difference
    mShouldRefresh.wrappedValue = true
}

Now back in contentView
@State var shouldRefresh = true

MapsView(list: $locationList, shouldRefresh: $shouldRefresh)

A: Here is a sketch of possible approach (written inline, not tested, so might by typo - compiler error fixing is on you):
struct MapsView: UIViewRepresentable {

    @Binding var list : [LocationObj]
    var callback: (Bool) -> Void           // << here !!

    func makeUIView(context: Context) -> GMSMapView

    func updateUIView(_ mapView: GMSMapView, context: Context){
        var bounds = GMSCoordinateBounds()
        for location in list{}

        mapView.animate(with: GMSCameraUpdate.fit(bounds,withPadding: 15.0))

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(owner: self)
    }

    class Coordinator: NSObject, GMSMapViewDelegate {

        let owner: MapsView

        init(owner: MapsView) {
            self.owner = owner
        }

        func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition){
            // after moving camera and calculating the difference
            owner.callback(true)      // << here !!
        }
    }
}

and usage like
@State var shouldRefresh = true

MapsView(list: $locationList) {
    self.shouldRefresh = $0
}


text:
Q: Computer Sometimes Hangs During Startup and Always Hangs After Sleeping I just built a new rig (full specs and BIOS snapshots at bottom) and I'm having a problem with it experiencing what appears to be random CPU hangs during startup.
My board is an MSI B450I Mini-ITX and it has 4 "EZ Debug" LED's. They are CPU, DRAM, VGA, and BOOT. (I am not the most experienced PC builder so I apologize if I'm providing unnecessary OR insufficient information.) When it fails to boot, the CPU EZ debug light is on. When this happens, there is no output to the monitor or the keyboard or mouse (they don't light up). There is one exception here, when I put the computer to sleep and try to resume Windows the mouse (and probably keyboard but can't say for sure) will receive power but the monitor still receives nothing and the computer will not boot (CPU EZ debug light on again).
The computer fails to resume 100% of the time after being put to sleep and after the power supply has been disconnected and reconnected. Other than that, it seems pretty random with failures about 1/2 to 2/3 of the time. I haven't actually recorded any tests, this is just my feeling after working with it for a week. Basically I have to start it, hold the power button to shut it off, and then repeat once or twice before it takes. I have not had it randomly shut off once I've had it up and running (maybe once at the very beginning before I even had Windows 10 installed, but really couldn't say) and It has run for days at a time.
I just uninstalled, cleaned, and reinstalled the CPU. I'm 99.99% sure it's irrelevant, but I had to modify the heat sink by chopping off the AMD badge that sticks out on the fan portion if you're familiar with the Ryzen 5 heat sinks (google images will show you what I'm talking about).
Thank you very much for reading this and any information you are able to provide.
Complete Hardware

*

*MSI B450I

*AMD Ryzen 5 2600

*Ballistix Sport LT 16GB (8GBx2) DDR4 2666

*CORSAIR SF450

*GIGABYTE GeForce GTX 1050 Ti

*Running Windows 10 on a Samsung 850 EVO 500GB SSD

2018-12-27 Update:
Initially, the BIOS was 3 months old. I performed a BIOS update to a version released just a few weeks ago and the problem persists. Although, when testing the problem a few minutes ago, I did successfully boot back up after putting the computer to sleep. This contradicts where I said it fails 100% of time when put to sleep. To my knowledge, that's the only time that has worked. I got all excited and tried it again after a restart and it failed.
Initial BIOS Snapshot
Updated BIOS Snapshot


text:
Q: Boto3 errors out with 'Could not connect to the endpoint URL: "https://ec2.us-west-2.amazonaws.com/"' I am running some python code on an AWS EC2 instance. The IAM role for this EC2 instance has adequate privileges to describe and create new EC2 instances.
My code calls ec2_client.describe_instances() and checks whether a specific instance is alive. If that instance is terminated, it will call ec2_client.run_instances and create a new instance.
However, when I call ec2_client.run_instances(), I get an error Could not connect to the endpoint URL: "https://ec2.us-west-2.amazonaws.com/".
ec2_client is a boto3 EC2 client object.
In some other examples, I've seen people getting this error because they had an incorrect region. That is not the case here. I've made sure that the region is correct.
Any ideas why this happens?
I am using boto3 (1.4.4).


text:
Q: Como organizar aplicação multi-nível MVC Estou desenvolvendo uma aplicação seguindo o padrão MVC, e terá 2 níveis de usuários, o normal e o admin, no que se refere as opções do que cada usuário pode fazer, é melhor fazer uma lógica no controller para mostrar determinada view ou alguma ação de outro controller ou criar alguns "blocos if" numa view padrão para "esconder" menus somente do admin ou vice/versa?

Exemplo de situação:
Um usuário normal acessa a dashboard depois do login, o ideal seria
mostrar uma view (views/user_normal) específica para ele, que só tem os menus/links do seu
nível, ou usar uma view (views/all_users) para ambos os níveis e esconder menus/links
com validações?

A: Um controller pode ter N views. Se acha melhor uma view para cada caso (user normal e admin), não tem problema. Mas tanto faz usar uma só view com condicionais ou múltiplas views.
Particularmente prefiro views separadas se houver muitas condicionais.
Há quem prefira um padrão estrito, ou seja, não importa se tem apenas 1 condicional, deve seguir o padrão de múltiplas views.
Quem define o padrão é o gerente do projeto.

A: Para fugir de (if/elses) desnecessários pelo controller, eu prefiro fazer da maneira pelo qual você citou:
view/user_normal
view/user_diferenciado
É questão de boas práticas de código, mas nesse caso, pra mim é questão pessoal de quem está desenvolvendo.


text:
Q: Pandas Create Percentages from Category Sums I have a dataset of website traffic, for about 2000 websites over a period of a month, tabulated by the type of device from which the traffic originated:
In [12]: df.sample(10)
Out[12]:
         date                  device  nb_uniq_visitors  site_id
11 2017-10-31                     Tv               0.0   3331.0
6  2017-10-22            Car browser               0.0    503.0
7  2017-10-22                 Camera               0.0   3259.0
7  2017-10-08            Car browser               0.0    630.0
3  2017-10-23                 Camera               0.0    118.0
0  2017-10-12                Desktop               1.0   4769.0
11 2017-10-31                     Tv               0.0    361.0
5  2017-10-12                Phablet               0.0   2999.0
9  2017-10-17  Portable media player               0.0   1725.0
0  2017-10-13                Desktop            2410.0   1004.0
4  2017-10-13                all                 900.0   1271.0

Note that the all category of the device column represents the total of all devices, therefore it could serve as the denominator of the percentage calculation.
I want to see the percentages of device types for each website, I'm imagining the output looking like this (I manually calculated the below for example):
                               nb_uniq_visitors
site_id device
74.0    Camera                         0.00
        Car browser                    0.00
        Console                        0.00
        Desktop                        0.56
        Feature phone                  0.00
        Phablet                        0.01
        Portable media player          0.00
        Smart display                  0.00
        Smartphone                     0.37
        Tablet                         0.05
        Tv                             0.00
        Unknown                        0.00
        all                            1.00
96.0    Camera                         0.00
        Car browser                    0.00
        Console                        0.00
        Desktop                        0.64
        Feature phone                  0.00
        Phablet                        0.01
        Portable media player          0.00
        Smart display                  0.00
        Smartphone                     0.29
        Tablet                         0.06
        Tv                             0.00
        Unknown                        0.01
        all                            1.00

I used groupby to group by site_id and device:
In [23]: sl = df.groupby(['site_id', 'device']).sum()

In [24]: sl.head(25)
Out[24]:
                               nb_uniq_visitors
site_id device
74.0    Camera                              0.0
        Car browser                         0.0
        Console                             1.0
        Desktop                         10534.0
        Feature phone                       0.0
        Phablet                           178.0
        Portable media player               4.0
        Smart display                       0.0
        Smartphone                       6955.0
        Tablet                           1022.0
        Tv                                  1.0
        Unknown                            62.0
        all                             18757.0
96.0    Camera                              0.0
        Car browser                         2.0
        Console                             6.0
        Desktop                        118157.0
        Feature phone                       0.0
        Phablet                          1061.0
        Portable media player              73.0
        Smart display                       0.0
        Smartphone                      53292.0
        Tablet                          11060.0
        Tv                                  2.0
        Unknown                          1717.0
        all                            185370.0

How do I translate the above from aggregate values to percentages? Or is there a better way entirely?

A: Use DataFrame.xs for select all rows with dividing by DataFrame.div:
sl = df.groupby(['site_id', 'device']).sum()
a = sl.div(sl.xs('all', level=1))
print (a)
                               nb_uniq_visitors
site_id device
74.0    Camera                         0.000000
        Car browser                    0.000000
        Console                        0.000053
        Desktop                        0.561604
        Feature phone                  0.000000
        Phablet                        0.009490
        Portable media player          0.000213
        Smart display                  0.000000
        Smartphone                     0.370795
        Tablet                         0.054486
        Tv                             0.000053
        Unknown                        0.003305
        all                            1.000000
96.0    Camera                         0.000000
        Car browser                    0.000011
        Console                        0.000032
        Desktop                        0.637412
        Feature phone                  0.000000
        Phablet                        0.005724
        Portable media player          0.000394
        Smart display                  0.000000
        Smartphone                     0.287490
        Tablet                         0.059664
        Tv                             0.000011
        Unknown                        0.009263
        all                            1.000000

Detail:
print (sl.xs('all', level=1))
         nb_uniq_visitors
site_id
74.0              18757.0
96.0             185370.0


text:
Q: Write Array with List to csv I have an array with multiple lists inside and want to write the values to an CSV
unfortunately I cannot figure out how to write the Array.mapi.
Any ideas?
   let temp = [|title;body;ordinariePris;extraPris;inkopPris;images;allValues|]

   let lines2 =
            temp
            |> Array.mapi (fun idx (t,b,op,ep,ip,i,av) ->
                sprintf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s" title body ordinariePris extraPris inkopPris images allValues
                       )
        let header = "title\tbody\tordinariePris\textraPris\tinkopPris\tallValues"

        System.IO.File.WriteAllLines("test.csv",
            Array.append [| header|]lines2, Encoding.UTF8)

thanks in advance

A: The problem with your code is that mapi indexes over the elements of temp, which means that you're only getting one column at a time.  You want to retrieve one row at a time.
The following instead transposes your list of lists, so that indexing does what you want.  It's also a little more generic-- you don't actually need to know the number of columns ahead of time.  It does, however, assume that every column has the same number of elements in it.
let col1 = ["a"; "b"; "c"]
let col2 = ["1"; "2"; "3"]
let col3 = ["x"; "y"; "z"]

let cols = [col1; col2; col3]

let transpose(xs: string list list) : string list list =
  [0 .. xs.[0].Length - 1] |> List.map (fun i ->
    xs |> List.rev |> List.fold (fun acc col -> col.[i] :: acc) []
  )

let stringify_rows(xs: string list list) : string list =
  xs |> List.map (fun row -> System.String.Join(",", row))

System.IO.File.WriteAllLines("test.csv", cols |> transpose |> stringify_rows)

Note that this approach does not use an array of lists, since there was no obvious reason that you had to use an array. WriteAllLines will happily accept any IEnumerable.
If you do a lot of CSV writing, I recommend using a library like CsvHelper, since correctly handling when to quote or escape cell contents can be tricky.


text:
Q: Adding a Script tag in a DIV element I have a code like this:
var myscript = document.createElement('script');
myscript.setAttribute('src','codescript.js');
document.head.appendChild(myscript);

The result is:

Well, how do I change the code.I'm hoping to put the script into a DIV tag which will be more specific.
For example:

A: Try this:
var myscript = document.createElement('script');
myscript.setAttribute('src','codescript.js');

var div = document.getElementById('this');
div.appendChild(myscript);

document.getElementById: Get the element with the specified id which is passed to that function as the first parameter.

A: With jQuery, you can simply use $.getScript('codescript.js'); to load code.
See https://api.jquery.com/jQuery.getScript/


text:
Q: Запуск jar файла на linux сервере Я написал маленький скрипт на java, необходимо запустить на сервере который работает на linux. Я создаю jar файл с помощью IntelliJ IDEA делаю это так (File | Project Structure | Artifacts,  artifact, jar --> From modules with dependencies Потом Build | Build artifacts) после через программу putty подключаюсь к серверу и запускаю jar файл, скрипт работает нормально пока окно в котором я запустил jar открыто, но после закрытия окна  программы putty, скрипт перестает работать,почему так может происходить ?  За ранние прошу прошения за такой странный вопрос я новичок в программировании.

A: Как вариант, сделайте следующее:

*

*Напишите sudo nano /etc/systemd/system/myapplication.service

*Вставьте следующий код, отредактировав его под вашу программу:

[Unit]
Description= # можете тут добавить описание программы, если нужно
After=syslog.target
After=network.target[Service]
User= # напишите какой пользователь может пользоваться данной функцией, к примеру root
Type=simple

[Service]
ExecStart=/usr/bin/java -jar /path/to/file/myapplication.jar
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier= # Короткое название вашей программы, например 'myapplication'

[Install]
WantedBy=multi-user.target

*Закрываем nano командами Ctrl+x далее пишем y или Y и жмем Enter.

*Пишем следующюю строку для запуска проекта:

sudo systemctl start myapplication

Для завершения проекта:
sudo systemctl start myapplication

Для перезагрузки файла (в случае остановки/ошибки/обновлении файла):
sudo systemctl restart myapplication

Для просмотра статуса запуска:
sudo systemctl status myapplication


text:
Q: Is java.util.Observable in Android thread-safe? Is java.util.Observable in Android thread-safe? The documentation says that only deleteObserver() and deleteObservers() are synchronized methods. What about addObserver(), set/clear/hasChanged()? Can I safely call addObserver() from different threads without locking around the Observable object?

A: AFAIK, Android is based on Apache Harmony. I found the source code of the the Observable implementation of Harmony here : http://www.java2s.com/Open-Source/Java-Document/Apache-Harmony-Java-SE/java-package/java/util/Observable.java.htm.
It seems to me that the tried to make it thread-safe, but failed : they forgot to synchronize the countObservers method, as well as the set/has/clearChanged methods.


text:
Q: Tool or code for Cache and Memory Bus performances I am facing a performance issue on a multi-core (8+) architecture with software written in C++ / VistualStudio / WindowsXP.
Suddenly I realized that I have no idea of the performances of my L1 and L2 cache and CPU->to->Memory bandwidth.
I have tested several tools (including VTune, Glowcode, etc, etc) but all of them fails when tested on load in a multicore architecture (which is the very reason why I need them!).
Can you suggest any other tool which is not so fancy in doing graphs but can give me at least few indications of my cache/memory performances or can suggest snippets of code to manually instrument my application?
Thanks!

A: Maybe Memtest86+ is what you are looking for.

A: I believe the EVEREST test suite will check your memory/cpu/cache performance. You may want to look into this site. Lavalys' Everest Page

A: you can use hardware counters to measure the L1 and L2 miss rate; however, I am not too sure which library package to use with a windows platform.

A: Did you try cachegrind ? Its a simulator, of course, but still, it will let you catch most of the real problems.


text:
Q: What does $SL_2(\mathbb{F}_q)/\{I,-I\}$ look like? I am not sure what the elements of
$$SL_2(\mathbb{F}_q)\big/\left\{ \begin{pmatrix}1&0\\0&1\end{pmatrix},\begin{pmatrix}-1&0\\0&-1\end{pmatrix}\right\}$$
 look like for an arbitrary prime $q$.
Could someone write down explicitly this group for a small $q$ (or explain it if that's not feasible)? I think that would help me understand how it behave for any arbitrary prime $q$.
I ask this in the context of Ramanujan graphs. Lubotzky, Phillips and Sarnark showed that when taking the Cayley graph of this group with respect to a family of suitably chosen generator of order $p+1$ (with $p$ prime and $p\neq q$) then we get an infinite family of d-regular Ramanujan graphs. But to see what those families look like I have to understand the shape of the group above.


text:
Q: Font not well rendered with freetype and Opengl ES 2 (IPhone device) I'm using freetype for writing text in an IPhone device, the result are rare. As you can see in the image same characters(like 'b', 'n' or 'u') aren't rendered equally.
The texture is always the same. Any idea where is the problem or what's going on?
http://craneossgd.files.wordpress.com/2011/10/image_freetype1.png
Code:
FT_New_Face(getFTLibrary(), _filename, 0, &(_face))
FT_Select_Charmap( _face, FT_ENCODING_UNICODE );
FT_Set_Char_Size( _face, _pt<<6,_pt<<6, _dpi, _dpi);
for (i=0; i<255; i++)
{
    if (!createGlyphTexture(i))
    {
        clean();
    }
}
.....

createGlyphTexture(unsigned char ch){
    ....
    FT_Load_Glyph(_face, FT_Get_Char_Index(_face,ch), FT_LOAD_DEFAULT)
    FT_Get_Glyph(_face->glyph, &glyph)
    ....
    // *** Transform glyph to bitmap
    FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);

    // *** Get bitmap and glyph data
    bitmap_glyph = (FT_BitmapGlyph)glyph;
    bitmap = bitmap_glyph->bitmap;
    // ***
    width = pow2(bitmap.width);
    height = pow2(bitmap.rows);

    // *** Alloc memory for texture
    expanded_data = (GLubyte *)malloc( sizeof(GLubyte)*2*width*height );
    for (j=0; j<height;j++)
{
    for (i=0; i<width; i++)
    {
        if ( (i>=(CRuint)bitmap.width) || (j>=(CRuint)bitmap.rows) ){
            expanded_data[2*(i+j*width)] = 0;
            expanded_data[2*(i+j*width)+1] = 0;
        } else {
            expanded_data[2*(i+j*width)] = bitmap.buffer[i+bitmap.width*j];
            expanded_data[2*(i+j*width)+1] = bitmap.buffer[i+bitmap.width*j];
        }
    }
}
    // *** Load texture into memory
    glBindTexture(GL_TEXTURE_2D, _textures[ch]);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_LUMINANCE_ALPHA, width, height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, expanded_data);
    ....
}

Thanks!!

A: In freetype reference:
http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html
FT_LOAD_TARGET_LIGHT.
A lighter hinting algorithm for non-monochrome modes. Many generated glyphs are more fuzzy but better resemble its original shape. A bit like rendering on Mac OS X. As a special exception, this target implies FT_LOAD_FORCE_AUTOHINT.
FT_RENDER_MODE_LIGHT.This is equivalent to FT_RENDER_MODE_NORMAL. It is only defined as a separate value because render modes are also used indirectly to define hinting algorithm selectors. See FT_LOAD_TARGET_XXX for details.
It works using next configuration:
FT_Load_Glyph(_face, FT_Get_Char_Index(_face,ch), FT_LOAD_TARGET_LIGHT)
...
FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);


text:
Q: Alert me a message if i enter the same name or word in one search bar or text box twice using jQuery or javascript div class="container">

                <input type="text" id="medicineSearchBar" class="form-control" placeholder="Search..." >

Alert me a message if i enter the same name or word  in one search bar or text box  using jQuery or javascript
The word or name is coming from json file


text:
Q: Add different numbers in each row in the Gridview hi i have a Gridview that load from the database and i create a column in the Gridview name lblImportanceRatio and i need this column to generate those number in every row 25,20,35,20
this is the Gridview:
enter image description here
and the column name SymbolicRate i wanna just generate those number  25,20,35,20 in every row i tried to add the generate number in the Grirdview row data bound in for loop but it only give me the last number in the all column i'm Using Asp.net C#
this the Gridview:

    <asp:GridView ID="gvRptBattalion" runat="server" AutoGenerateColumns="False" CssClass="table" OnRowDataBound="gvRptBattalion_RowDataBound" Visible="false">
                            <Columns>

                                <asp:BoundField DataField="ReadinessTypeName" HeaderText="Type" />
                                <asp:BoundField DataField="SymbolicRate" HeaderText="Rate" />

                                <asp:TemplateField>
                                    <HeaderTemplate>
                                        <asp:Label runat="server" Text="SymbolicRate"></asp:Label>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblImportanceRatio" runat="server"></asp:Label>
                                    </ItemTemplate>
                                    <ItemStyle Width="50px" />
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <HeaderTemplate>
                                        <asp:Label runat="server" Text="Total"></asp:Label>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblTotal" runat="server"></asp:Label>
                                    </ItemTemplate>
                                    <ItemStyle Width="50px" />
                                </asp:TemplateField>

                                <asp:BoundField DataField="BattalionDate" HeaderText="#">
                                    <FooterStyle CssClass="hide_identity" />
                                    <HeaderStyle CssClass="hide_identity" HorizontalAlign="Right" />
                                    <ItemStyle CssClass="hide_identity" />
                                </asp:BoundField>

                                <asp:BoundField DataField="SUnitId" HeaderText="#">
                                    <FooterStyle CssClass="hide_identity" />
                                    <HeaderStyle CssClass="hide_identity" HorizontalAlign="Right" />
                                    <ItemStyle CssClass="hide_identity" />
                                </asp:BoundField>

                                <asp:TemplateField>

                                    <HeaderTemplate>
                                        <asp:Label runat="server" Text="TotalAll"></asp:Label>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblFormla" runat="server"></asp:Label>
                                    </ItemTemplate>
                                    <FooterStyle CssClass="lbl" />
                                    <HeaderStyle CssClass="lbl" HorizontalAlign="Right" />
                                    <ItemStyle CssClass="lbl" />
                                </asp:TemplateField>

                                <asp:TemplateField>

                                    <HeaderTemplate>
                                        <asp:Label runat="server" Text="TotalALL2"></asp:Label>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblG" runat="server"></asp:Label>
                                    </ItemTemplate>
                                    <FooterStyle CssClass="lbl" />
                                    <HeaderStyle CssClass="lbl" HorizontalAlign="Right" />
                                    <ItemStyle CssClass="lbl" />
                                </asp:TemplateField>

                            </Columns>
 </asp:GridView>


text:
Q: Can I inject @RootContext in ViewModel class? I create MVVM android app, and I need context in my ViewModel class. I know that a ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context. But...
does it apply also inject Context by @RootContext annotation?
I'm also wondering if I can use the context from a view object in the onClick method when I use DataBinding in ViewModel class.

A: so you can pass clicked view add your onclick param.
<View
...
android:onClick="@{(v)-> viewModel.modelOnClick(v)}"
...
/>

class ViewModel
class ViewModel{
   public void modelOnClick(View v){
   }
}

so you have your clicked view in your model and can use it's context


text:
Q: Why did we get auto-upgraded to 14.7-gke.14? Why is the latest 1.14.8-gke.2 not working at all… Seems like our master got auto-upgraded this morning without prior warning from an earlier 1.14.x version to 1.14.7-gke.14 but we've disabled auto-upgrade before so it's completely odd especially given that 1.14.7-gke.14 is breaking workload identity which quite a few of us in the GKE world rely on.
Moreover, I'm seeing a new version in the list 1.14.8-gke.2 which at the time of writing this question was not even mentioned in the GKE release notes at all. Our cluster was created before release channels became a thing so AFAIK we're not enrolled in any of those.
Wondering if someone pulled the release trigger prematurely (again as this is not the first time).
Since there was no option to go back to a stable version where workload identity was working fine, we went ahead and upgraded to 1.14.8-gke.2 in a hope it would fix the problem. This was a clear gamble that did not pay off at all because it resulted in a colossal clusterfuck where some services did not come up at all due to all kinds of container and networking issues. Specifically:

*

*kube-dns's container prometheus-to-sd is throwing the following error: http://169.254.169.254/computeMetadata/v1/project/project-id: dial tcp 169.254.169.254:80: getsockopt: connection refused

*readiness and liveness probes are failing due to some sort of internal networking issue for some of our services
Now on to the main question. What would you guys suggest? Recreate a cluster and go back to v1.13.x and also enroll in a stable release channel? What other options do we have? Would like to get some insight into what the heck is going on here.
EDIT: we're currently hosted in europe-west1-d, it's a zonal cluster that comprises 1 standard pool w/ 3 auto-scaled nodes and 1 preemptible pool for dynamic workloads.
EDIT2: just noticed in the release notes from Oct 30 that 1.14.6-gke.2 was going to be wound down, I must have missed it before. Either way the question is still why there's an undocumented version and why it's not working + if anyone knows when workload identity will work again in the regular channel? This forces us to downgrade to a 1.13.x
EDIT3: turns out kube-dns is using a 1.15.4 image version on a 1.14.x cluster, this almost looks like a broken release, when i downgrade it works for a brief moment until the cluster controller decided to revert the change so we're going to recreate the cluster
EDIT4: after a few hours it turns out that cos_containerd image was the main culprit, switching the image helped resolve all issues it seems, we'll keep monitoring


text:
Q: How to rename a Testcase or Teststep using Groovy in SoapUi I am re factoring large sets of tests in SoapUi.
Is there a way to automate creation and renaming of test cases/test steps through Groovy?
Thanks.

A: Possibly not what you're looking for but I've had some success manually editing the test suite xml using find and replace in a text editor. You need to be careful and make sure to back up a copy.

A: There is really not so much information in the question about what you really need to achieve, but given the little you provided, one way to go would be to directly modify the soapUI project XML file. I have done this with some success in the past. The last I used soapUI, it UI did not come with massive refactoring functionality.

A: You can run Groovy code within SoapUI using SoapUI Groovy Console plugin. This way, you can change any property you want programmatically (within API constraints of course).
As for technical details on how to solve your actual problem, I can only refer you to this blog post and SoapUI's javadoc. Based on the blog post, you need to figure out what's given to you, and based on the API, you need to figure out how to achieve what you need.
In my case, I started with my project being bound as a project variable, and moved on from there.


text:
Q: AWS Glue ETL Integration with Spark and Scala I created a database called "glue-demo-db" and created a catalog for table "orders". Now, I am planning to write my own Scala script to execute ETL. The job is simple, read data from the glue-demo-db.orders table and write that as CSV into a S3 bucket. For some reason, 1) The diagram cannot be generated for Scala, and 2) The job keeps on running continuously without ending or creating the output file. Any help will be much appreciated.
Code:
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import java.util.Calendar
import org.apache.spark.SparkContext
import org.apache.spark.sql.Dataset
import org.apache.spark.sql.Row
import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.from_json
import org.apache.spark.sql.streaming.Trigger
import scala.collection.JavaConverters._

object ordersDataCapture {
  def main(sysArgs: Array[String]) {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    val sparkSession: SparkSession = glueContext.getSparkSession

    // @params: [JOB_NAME]
    val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME").toArray)
    Job.init(args("JOB_NAME"), glueContext, args.asJava)

    // @type: DataSource
    // @args: [database = "glue-demo-db", table_name = "orders", redshift_tmp_dir = args["TempDir"], transformation_ctx = "<transformation_ctx>"]
    // @return: <output>
    // @inputs: []
    val read_data = glueContext.getCatalogSource(database = "glue-demo-db", tableName = "orders", redshiftTmpDir = args("TempDir"), transformationContext = <transformation_ctx>).getDynamicFrame()

    #Convert dynamic frame to data frame to use standard pyspark functions
    val sourceDF = read_data.toDF()
    sourceDF.printSchema()
    sourceDF.show(false)

    sourceDF.write                           // joined.write returns type DataFrameWriter
          .mode(SaveMode.Append)
          .format("csv")
          .save("s3://nvs-ordersdata/output")

    Job.commit()
  }
}


text:
Q: SocketCAN C# using mono I am really new to mono and C# but I want to use sockets to open a communication via CAN. The problem is that a lot of protocol an adress families are implemented but CAN ist not supported by mono so far. The system kernel supports it but it is not possible for me to patch the files in this way to get down to the SystemCall Level. So if someone reads this who is part of the really nice mono developing community please help me and a lot of other guys out there who needs this function. Since three weeks I googled anything and tried to find my own workaround to get it on but until now no success. Even if my problem won't be solved with this question here at stackvoerflow I hope to motivate someone who is better in improving mono and hard code than me, so that other guys will be able to work easy with CAN and mono. S I think the base problem is, that the Variables AF_CAN and PF_CAN are not implemented in mono. I tried my best by adjusting these files by adding PF_CAN and AF_CAN with Value 29 but it does not work for me
.../mono-3.2.8/mono/metadata/socket-io.c
.../mono-3.2.8/mcs/class/System/System.Net.Sockets/AddressFamily.cs
.../mono-3.2.8/mcs/class/System/System.Net.Sockets/ProtocolFamily.cs

I hope for help because its all there but I am not able to put it all together. With C it is easy to open a socket this way and the CAN bus works fine but with mono a small stone is missing to get it all to work.
best regards
Ben

A: The easiest workaround would be to write a library in C, that handles SocketCAN stuff and then just invoke the library calls from C# code. See this tutorial.
Alternative you can take a look at socketcand and implement its TCP based API.


text:
Q: tesseract-ocr use ascii only? I have been using tesseract-ocr (in .NET) which has been working well. The images i feed it are ascii only (A-z0-9). Is there a way i can tell it not to use special characters?

A: There's a new thread about this question over at the Google forum linked above. The first answer concludes that it probably isn't possible.
As far as I know, this is correct, if you're using the language data files that are packaged with Tesseract. You can, however, very easily limit the output characters if you're training on your own box files. It's practically automatic: if unicharset_extractor doesn't find any non-ASCII characters in the box files, you'll never see non-ASCII characters in the output.
I was similarly frustrated by all the interpuncts and other unusual characters in my output when I first started using Tesseract, and training on my own box files solved the problem. You can even use the Tesseract training data as a starting point.

A: use the tessedit_char_whitelist config option.


text:
Q: Shared Preferences for list As a an inexperienced Android programmer I need some help. I'm designing this app for a church that needs an Activity that can record prayer requests (similar to making a to-do list). At this point I can type items into a list, but they don't seem to save and come back after closing using the Shared Preferences excerpt from below, also looking around this site it looks like I can do this without a physical button to press to save.
SharedPreferences prayerRequests = getPreferences(Activity.MODE_PRIVATE);
ListView myListViewa = (ListView)findViewById(R.id.myListView);

SharedPreferences.Editor editor = prayerRequests.edit();

editor.putString("prayers", myListViewa.toString());

editor.apply();

The entire class is here:
   package com.direction.investor.prayerjournal;

   import java.util.ArrayList;

   import android.annotation.TargetApi;
   import android.app.Activity;
   import android.os.Build;
   import android.os.Bundle;
   import android.view.KeyEvent;
   import android.view.View;
   import android.widget.ArrayAdapter;
   import android.widget.EditText;
   import android.widget.ListView;
   import android.widget.TextView;
   import android.content.SharedPreferences;
   import android.content.SharedPreferences.Editor;

 public class prayerRequests extends Activity {

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.prayerrequest);

ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);

final ArrayList<String> prayers = new ArrayList<String> ();

final ArrayAdapter<String> aa;

aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, prayers);

myListView.setAdapter(aa);

SharedPreferences prayerRequests = getPreferences(Activity.MODE_PRIVATE);

ListView myListViewa = (ListView)findViewById(R.id.myListView);

SharedPreferences.Editor editor = prayerRequests.edit();

editor.putString("prayers", myListViewa.toString());

editor.apply();

myEditText.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
            if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                    (keyCode == KeyEvent.KEYCODE_ENTER)) {

                prayers.add(0, myEditText.getText().toString());
                aa.notifyDataSetChanged();
                myEditText.setText("");
                return true;

            }
        return false;
    }
});

}

}

A: I would suggest to use database instead of sharedpreferences
seee http://developer.android.com/guide/topics/data/data-storage.html#db


text:
Q: Как сделать GridView прокручиваемым? Заполнил GridView.
Скриншот
Но почему-то он не прокручивается. Ровно под размер экрана. По скриншоту видно, что картинки обрублены. И не сдвинуть ни на пиксель. Причем если стиль сделать с экшн баром, то можно будет крутить, но чуть-чуть (в высоту экшн бара, т.е. картинки будут так же обрублены).
Обновление
Содержимое, очевидно, не влезает в экран. Хочется свайпом прокрутить его, чтобы увидеть нижний край. А оно не прокручивается. Совсем. Хотя если добавить ActionBar в стиль сверху, то можно чуть-чуть двигать, но не достаточно.

A: Суть была такова, что нижней границей (до которой можно прокрутить экран) считается нижняя граница последнего вставленного View в сетку. А, как видно на скриншоте, в последней ячейке (самая правая в нижней строке) нет картинки (оказывается, сервер null присылал, поставил свою дефолтную), поэтому ячейка оказалась короткая. Поэтому экран и не прокручивался.


text:
Q: InputQuery on IOS Rad Studio 11 Modal Response Reversed I am working with RAD Studio Delphi 11 Version 28.0.44500.8973 with Update 1 and the PAServer update on Windows 10.
When I use the TDialogServiceAsync.InputQuery() method under iOS, the modal response from the Input query is reversed.
When the OK button is pressed, the modal result (AResult) is 2 (mrCancel) and the resulting response is not updated.
When the Cancel button is pressed, the modal result (AResult) is 1 (mrOK) and the resulting response is returned.
This is completely opposite to the way it is supposed to work.
When the method is used under Android or Windows, the modal result and response are correct.
This was working properly in RAD Studio 10.4, and I believe was working properly when I first installed RAD Studio 11. However, I since had to reload RAD Studio 11, so I downloaded the latest install that had Patch 1 included and then loaded the PA Server Patch.
I have attached the code to a very simple project that demonstrates the behaviour.
I haven't been able to find any posts on this issue other than one back in 2017 where the Cancel button wasn't working under Windows, but I'm pretty sure that is not relevant here.
Just wondering if anyone else is experiencing the same issue, or if it is something from my install or setup. I duplicated the RAD Studio 11 install on my development laptop, and I'm getting the same issue.
I am attaching code to a very simple project that recreates the issue.
Unit:
unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.DialogService.Async,
  FMX.Controls.Presentation, FMX.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    chkFlipIOSResponse: TCheckBox;
    Label2: TLabel;
    Label3: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure OnInputQuery_Close(const AResult: TModalResult; const AValues: array of string);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
begin
  TDialogServiceAsync.InputQuery('Enter Text', ['Enter Text:'], [label1.Text], Self.OnInputQuery_Close)

end;

procedure TForm1.OnInputQuery_Close(const AResult: TModalResult; const AValues: array of string);
var Response: String;
begin
  Label2.Text := 'Modal Response = ' + IntToStr(AResult);

  Response := AValues[0];

{$IFDEF IOS}
  if AResult = 1 then
     Label3.Text := 'Cancel Button Pressed'
   else
     Label3.Text := 'OK Button Pressed';
{$ELSE}
  if AResult = 1 then
     Label3.Text := 'OK Button Pressed'
   else
     Label3.Text := 'Cancel Button Pressed';
{$ENDIF}

  Label1.Text := Response.Trim;
end;

end.

Form:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 282
  ClientWidth = 338
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Button1: TButton
    Position.X = 118.000000000000000000
    Position.Y = 190.000000000000000000
    TabOrder = 0
    Text = 'Button1'
    OnClick = Button1Click
  end
  object Label1: TLabel
    Position.X = -8.000000000000000000
    Position.Y = 145.000000000000000000
    Size.Width = 338.000000000000000000
    Size.Height = 17.000000000000000000
    Size.PlatformDefault = False
    TextSettings.HorzAlign = Center
    Text = 'Message Response'
    TabOrder = 3
  end
  object chkFlipIOSResponse: TCheckBox
    Position.X = 96.000000000000000000
    Position.Y = 24.000000000000000000
    Size.Width = 234.000000000000000000
    Size.Height = 19.000000000000000000
    Size.PlatformDefault = False
    TabOrder = 4
    Text = 'Flip IOS Response'
  end
  object Label2: TLabel
    Position.X = -8.000000000000000000
    Position.Y = 107.000000000000000000
    Size.Width = 338.000000000000000000
    Size.Height = 17.000000000000000000
    Size.PlatformDefault = False
    TextSettings.HorzAlign = Center
    Text = 'Modal Response'
    TabOrder = 2
  end
  object Label3: TLabel
    Position.Y = 75.000000000000000000
    Size.Width = 338.000000000000000000
    Size.Height = 17.000000000000000000
    Size.PlatformDefault = False
    TextSettings.HorzAlign = Center
    Text = 'Button Pressed'
    TabOrder = 1
  end
end

A:
Just wondering if anyone else is experiencing the same issue

Yes, I have seen several people report a similar issue.  And I found several Quality Portal tickets related to it:
RSP-11101: InputQuery on iOS wrong value for ModalResult
RSP-37702: InputQuery result problem on iOS
RSP-38143: iOS inputQuery returns wrong button
RSP-38454: FMX: TDialogServiceAsync.InputQuery ModalResult wrong


text:
Q: volume attachment on for_each ec2 creation I am new to terraform and been trying to figure out how to attach a volume when doing a for_each on ec2 creation.
resource "aws_instance" "test_directory_controller" {
    for_each = aws_network_interface.test_directory_controller

ami = local.test_ami_id
key_name = var.test_instance_key_name
instance_type = var.test_instance_type

iam_instance_profile = module.test_manager.test_instance_profile_name

network_interface {
    network_interface_id = each.value.id
    device_index         = 0
}

root_block_device {
    volume_size = 120
    encrypted = true
}

ebs_block_device  {
    device_name = "/dev/sdh"
    volume_size = 40
    encrypted = true
}

Here is the new code that I have added :
resource "aws_ebs_volume" "test_directory_d_drive" {
  availability_zone = "us-east-1a"
  size = 40
  encrypted = true

  tags = {
      Name = "Local Disk"
      DriveLetter = "D"
  }
}

resource "aws_volume_attachment" "test_volume_attachment" {
  device_name = "xvdf"
  volume_id = aws_ebs_volume.test_directory_d_drive.id
  instance_id = aws_instance.test_directory_controller.id
}

The error states that because of the "for_each" set, it requires a aws_instance.test_directory_controller[each.key].id to resolve it but that seems to cause more errors. What am I missing?

A: If you need to use a for_each in the aws_instance resource you will have to use it on the volume as well, it is easy to reference those using the key
Here is an example:
data "aws_ami" "suse12" {
  owners      = ["amazon"]
  most_recent = true
  filter {
    name   = "name"
    values = ["*suse*"]
  }
}

locals {
  instances = toset(["one", "two"])
}

resource "aws_instance" "suse12" {
  for_each          = local.instances
  ami               = data.aws_ami.suse12.id
  instance_type     = "m5d.large"
  availability_zone = "us-east-1a"
  tags              = { Name = each.value }
}

resource "aws_ebs_volume" "data-ndj" {
  for_each          = local.instances
  type              = "gp2"
  size              = 110
  availability_zone = "us-east-1a"
}

resource "aws_volume_attachment" "data-ndj" {
  for_each    = local.instances
  device_name = "/dev/sdj"
  instance_id = aws_instance.suse12[each.key].id
  volume_id   = aws_ebs_volume.data-ndj[each.key].id
}


text:
Q: Switch rendering according to headers, application-wide This question is a case in hand.
Let's imagine a website page that displays a filtered products list :

*

*If I request /products?foo=bar in my browser, I get a full page wrapped in a layout, the layout contains a header with a form allowing to change search criterias.

*If I change foo value to baz and submit the form, it reloads dynamically the results (with a jQuery $.load(), for example), calling /products?foo=baz in Ajax.

*If I enter the  same criteria into my iPhone app, the app requests /products?foo=bar to the server, which replies with a json object.
All 3 calls refer to the same resource ("the products list", resource is intended as in REST resource), but all need different rendering.

*

*In the first case, I need a full HTML page (with layout)

*In the second case, I need a partial HTML page (without layout)

*In the third case, I need a plain json response

This rendering switch can be triggered by the headers X-Requested-With (with or without layout) and Accept (html/json).
In Phalcon, the given example could be implemented as :
class ProductsController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
        // Build data
        $products = Products::find(array(
            'foo' => $this->request->get('foo')
        ));

        // JSON is identified
        if ($this->request->getBestAccept() == 'application/json')
        {
            // JSON rendering (case 3)
            $this->response->setContentType('application/json');
            $this->response->setJsonContent($products);
            $this->view->disable();
            return $this->response;
        }
        // Otherwise, defaults to HTML
        else
        {
            // Passing data to the view
            $this->view->products = $products;

            // Ajax call is identified
            if ($this->request->isAjax())
            {
                // Partial rendering (case 2)
                $view->disableLevel(array(
                    View::LEVEL_LAYOUT => true,
                    View::LEVEL_MAIN_LAYOUT => true
                ));
            }
            // Defaults to normal rendering
            else
            {
                // Layout rendering (case 1)
            }
        }
    }

}

How could I implement this mechanism application-wide, rather than duplicate this behavior in every single action ?

A: The easiest would be to get your data together in a unified format (if it isn't already) and pass it to a method in your base controller to handle that logic in pretty much the same way you showed in your example.
abstract class AbstractController extends \Phalcon\Mvc\Controller
{

    protected function prepareResponse($data)
    {

        // JSON is identified
        if ($this->request->getBestAccept() == 'application/json')
        {
            // JSON rendering (case 3)
            $this->response->setContentType('application/json');
            $this->response->setJsonContent($data);
            $this->view->disable();
            return $this->response;
        }

        // Otherwise, defaults to HTML

        // Passing data to the view
        $this->view->setVars($data);

        // Ajax call is identified
        if ($this->request->isAjax())
        {
            // Partial rendering (case 2)
            $view->disableLevel(array(
                View::LEVEL_LAYOUT => true,
                View::LEVEL_MAIN_LAYOUT => true
            ));
        }
        // Defaults to normal rendering
        else
        {
            // Layout rendering (case 1)
        }

        return null;
    }
}

class ProductsController extends AbstractController
{

    public function indexAction()
    {
        // Build data and prepare response
        return this->prepareResponse(array(
            'products' => Products::find(array(
               'foo' => $this->request->get('foo')
            ))
        ));
    }
}

Otherwise, it might be a bit tricky. I see the following alternative scenarios.
Extend your base controller with, say, renderJson and renderPartial methods, to handle those bits of logic (default otherwise), but in your action you still would need to check which one to call. Duplication…
Do some crazy shit with the router to go to different action, e.g., indexJsonAction and indexPartialAction (default otherwise), depending on the conditions. But you'd end up with bloated controllers.


text:
Q: Keras 2 Deconv2D layer Trying to follow this implementation of a fully-convolutional densenet in Keras 2.  I updated the function calls for some layers and updated the concatenate layer from
def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconvolution2D(ch, 3, 3, (None,r*2,c*2,ch), init='he_uniform',
                           border_mode='same', subsample=(2,2), W_regularizer=l2(wd))(x)

to
def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)

but an input doesn't double like it should after the down path. Here's the full code to create the model with Keras 2.
def conv(x, nf, sz, wd, p, stride=1):
    x = Conv2D(nf, (sz, sz), strides=(stride, stride), padding='same',
               kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)
    return dropout(x, p)

def conv_relu_bn(x, nf, sz=3, wd=0, p=0, stride=1):
    return conv(relu_bn(x), nf, sz, wd=wd, p=p, stride=stride)

def dense_block(n, x, growth_rate, p, wd):
    added = []
    for i in range(n):
        b = conv_relu_bn(x, growth_rate, p=p, wd=wd)
        print('x:', x, 'b:', b)
        x = concat([x, b])
        added.append(b)
    return x, added

def transition_dn(x, p, wd):
    return conv_relu_bn(x, x.get_shape().as_list()[-1], sz=1, p=p, wd=wd, stride=2)

def down_path(x, nb_layers, growth_rate, p, wd):
    skips = []
    for i, n in enumerate(nb_layers):
        x, added = dense_block(n, x, growth_rate, p, wd)
        skips.append(x)
        x = transition_dn(x, p=p, wd=wd)
    return skips, added

def transition_up(added, wd=0):
    x = concat(added)
    _, r, c, ch = x.get_shape().as_list()
    return Deconv2D(ch, (3, 3), input_shape=(r*2, c*2, ch), padding='same',
                    kernel_initializer='he_uniform', kernel_regularizer=l2(wd)) (x)

def up_path(added, skips, nb_layers, growth_rate, p, wd):
    for i, n in enumerate(nb_layers):

        x = transition_up(added, wd)
        x = concat([x, skips[i]])
        x, added = dense_block(n, x, growth_rate, p, wd)
    return x

def reverse(x):
    return list(reversed(x))

def create_tiramisu(nb_classes, img_input, nb_dense_block=6, growth_rate=16, nb_filter=48,
                    nb_layers_per_block=5, p=None, wd=0):
    if type(nb_layers_per_block) is list or type(nb_layers_per_block) is tuple:
        nb_layers = list(nb_layers_per_block)
    else:
        nb_layers = [nb_layers_per_block] * nb_dense_block

    x = conv(img_input, nb_filter, 3, wd, 0)
    skips, added = down_path(x, nb_layers, growth_rate, p, wd)
    x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
    x = conv(x, nb_classes, 1, wd, 0)
    _, r, c, f = x.get_shape().as_list()
    x = Reshape((-1, nb_classes)) (x)
    return Activation('softmax') (x)

input_shape = (224, 224, 3)
img_input = Input(shape=input_shape)
x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)

This is the stacktrace when the it tries to create the model with Keras 2 syntax. One of the inputs to the concatenate layer doesn't get doubled from (None, 7, 7, 656) when it should be like (None, 14, 14, 656) at the beginning of the upsampling path. This doesn't happen with Keras 1 syntax, which I can also post.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-133-fb96a61666a1> in <module>()
----> 1 x = create_tiramisu(12, img_input, nb_layers_per_block=[4, 5, 7, 10, 12, 15], p=0.2, wd=1e-4)

<ipython-input-131-f58faf58b799> in create_tiramisu(nb_classes, img_input, nb_dense_block, growth_rate, nb_filter, nb_layers_per_block, p, wd)
     62     print('p', p)
     63     print('wd', wd)
---> 64     x = up_path(added, reverse(skips[:-1]), reverse(nb_layers[:-1]), growth_rate, p, wd)
     65     x = conv(x, nb_classes, 1, wd, 0)
     66     _, r, c, f = x.get_shape().as_list()

<ipython-input-131-f58faf58b799> in up_path(added, skips, nb_layers, growth_rate, p, wd)
     38         print('up path', 'i:', i, 'n:', n)
     39         x = transition_up(added, wd)
---> 40         x = concat([x, skips[i]])
     41         x, added = dense_block(n, x, growth_rate, p, wd)
     42     return x

<ipython-input-130-c6d2942be960> in concat(xs)
      5 def bn(x): return BatchNormalization(axis=-1)(x)
      6 def relu_bn(x): return relu(bn(x))
----> 7 def concat(xs): return concatenate(xs, axis=-1)

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in concatenate(inputs, axis, **kwargs)
    389         A tensor, the concatenation of the inputs alongside axis `axis`.
    390     """
--> 391     return Concatenate(axis=axis, **kwargs)(inputs)
    392
    393

/home/clu/anaconda3/lib/python3.6/site-packages/keras/engine/topology.py in __call__(self, inputs, **kwargs)
    528                     self.build(input_shapes[0])
    529                 else:
--> 530                     self.build(input_shapes)
    531                 self.built = True
    532

/home/clu/anaconda3/lib/python3.6/site-packages/keras/layers/merge.py in build(self, input_shape)
    158                              'inputs with matching shapes '
    159                              'except for the concat axis. '
--> 160                              'Got inputs shapes: %s' % (input_shape))
    161
    162     def call(self, inputs):

ValueError: `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 7, 7, 240), (None, 14, 14, 656)]

A: Use a stride of 2 in the deconvolutional layer.


text:
Q: Iterating through constructor's arguments I often find myself writing class constructors like this:
class foo:
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pythonic way to loop through the constructor's arguments list and assign attributes accordingly. I'm working with Python 2.7, so ideally I'm looking for help with that version.

A: The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:
class foo:
    def __init__(self, **kwargs):
        vars(self).update(kwargs)

A: You can do that both for positional and for keyword arguments:
class Foo(object):
    def __init__(self, *args, **kwargs):
        for arg in args:
            print arg
        for kwarg in kwargs:
            print kwarg

* packs positional arguments into a tuple and ** keyword arguments into a dictionary:
foo = Foo(1, 2, 3, a=4, b=5, c=6) // args = (1, 2, 3), kwargs = {'a' : 4, ...}

A: How about this?
class foo:
    def __init__(self, arg1, arg2, arg3):
        for _prop in dir():
            setattr(self, _prop, locals()[_prop])

This uses the builtin python dir function to iterate over all local variables.
It has a minor side effect of creating an extraneous self reference but you could filter that if you really wanted.
Also if you were to declare any other locals before the dir() call, they would get added as constructed object's attributes as well.

A: Provided answers rely on *vargs and **kargs arguments, which might not be convenient at all if you want to restrict to a specific set of arguments with specific names: you'll have to do all the checking by hand.
Here's a decorator that stores the provided arguments of a method in its bound instance as attributes with their respective names.
import inspect
import functools

def store_args(method):
    """Stores provided method args as instance attributes."""
    argspec = inspect.getargspec(method)
    defaults = dict(zip( argspec.args[-len(argspec.defaults):], argspec.defaults ))
    arg_names = argspec.args[1:]
    @functools.wraps(method)
    def wrapper(*positional_args, **keyword_args):
        self = positional_args[0]
        # Get default arg values
        args = defaults.copy()
        # Add provided arg values
        list(map( args.update, ( zip(arg_names, positional_args[1:]), keyword_args.items() ) ))
        # Store values in instance as attributes
        self.__dict__.update(args)
        return method(*positional_args, **keyword_args)

    return wrapper

You can then use it like this:
class A:
    @store_args
    def __init__(self, a, b, c=3, d=4, e=5):
        pass

a = A(1,2)
print(a.a, a.b, a.c, a.d, a.e)

Result will be 1 2 3 4 5 on Python3.x or (1, 2, 3, 4, 5) on Python2.x

A: class foo:
    def __init__(self, **kwargs):
        for arg_name, arg_value in kwargs.items():
            setattr(self, arg_name, arg_value)

This requires arguments to be named:
obj = foo(arg1 = 1, arg2 = 2)

A: What about iterating over the explicit variable names?
I.e.
class foo:
    def __init__(self, arg1, arg2, arg3):
        for arg_name in 'arg1,arg2,arg3'.split(','):
            setattr(self, arg_name, locals()[arg_name])

f = foo(5,'six', 7)

Resulting with
print vars(f)

{'arg1': 5, 'arg2': 'six', 'arg3': 7}

My suggestion is similar to @peepsalot, except it's more explicit and doesn't use dir(), which according to the documentation

its detailed behavior may change across releases

A: As others have noted, you should probably stick to your original 'pythonic' method in most cases.
However, if you really want to go the whole nine yards, here's some code that neatly deals with args, keyword args if desired, and avoids boilerplate repetition:
def convert_all_args_to_attribs(self, class_locals):
    class_locals.pop('self')
    if 'kwargs' in class_locals:
        vars(self).update(class_locals.pop('kwargs'))
    vars(self).update(class_locals)

class FooCls:
    def __init__(self, foo, bar):
        convert_all_args_to_attribs(self, locals())

class FooClsWithKeywords:
    def __init__(self, foo, bar, **kwargs):
        convert_all_args_to_attribs(self, locals())

f1 = FooCls(1,2)
f2 = FooClsWithKeywords(3,4, cheese='stilton')

print vars(f1) #{'foo': 1, 'bar': 2}
print vars(f2) #{'cheese': 'stilton', 'foo': 3, 'bar': 4}

A: For python >= 3.7 take a look at the @dataclass class decorator.
Among other things, it handles your __init__ boilerplate coding problem.
From the doc:
@dataclass
class InventoryItem:
    name: str
    unit_price: float
    quantity_on_hand: int = 0

Will automatically add an __init__ like that:
def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

A: the *args is a sequence so you can access the items using indexing:
def __init__(self, *args):
        if args:
            self.arg1 = args[0]
            self.arg2 = args[1]
            self.arg3 = args[2]
            ...

or you can loop through all of them
for arg in args:
   #do assignments


text:
Q: Mongodb: how to give multiple conditions? I need to check the status of my condition.I need to check both "completed" and "stopped" status.
So how do I give the condition here my query:
var query = { };
    query.status = { $ne: "Stopped" };
            query.status = { $ne: "Completed" };

I give condition like this means it will take either only one condition only. I need to check both conditions.
what can i do?

A: Use operator $and, for example:
var query = {$and:[{status:{ $ne: "Stopped" }}, {status:{ $ne: "Completed" }}] };


text:
Q: api retrieve points of interest nearby city I am looking for a API/web service for me to retrieve a list of landmarks, points of interest (and their GPS coordinates) near a given city. I tried google places including the query Place Search and type point_of_interest, but the results do not seem satisfactory.
For example, to Paris, I need an answer:
Eiffel Tower, Arc de Triomphe, Champs Elysees, ...
What would you advise me to find such information.

A: A couple options:

*

*Foursquare Venues Platform

*Factual Places API

A: Google places has the flag "point_of_interest" but only to show, not for search (see Table 2 in https://developers.google.com/places/documentation/supported_types)
Google Earth on the other hand has what you need. See the icons for Tourist destination, Monument and Historical Place in https://support.google.com/earth/answer/180709?hl=en#what
However I am not sure if there is an API for this data, or if you need to  find a way to extract it from GE.