text:
Q: Cross controllers test in Rails In a rails 6.1.3.1 API, I would like to implement an unusual test. Basically, a user can create a team with a many-to-many relational model. A team creation automatically triggers a new entry in the table JoinedTeamUser with two references (user_id and team_id), and a boolean can_edit in order to know whether the user can update/delete or not a team details.
What I would like to test is if a user accessing the update or destroy method of the team controller has the right to do so (meaning, the right entry in a model depending of another controller).
To give you a better view of the process, here is the file seed.rb.
3.times do |i|
  team = Team.create(name: Faker::Company.name, description: Faker::Company.catch_phrase)
  puts "Created TEAM ##{i+1} - #{team.name}"
end

10.times do |i|
  name = Faker::Name.first_name.downcase
  user = User.create! username: "#{name}", email: "#{name}@email.com", password: "azerty"
  puts "Created USER ##{i+1} - #{user.username}"

  joined_team_users = JoinedTeamUser.create!(
    user_id: user.id,
    team_id: Team.all.sample.id,
    can_edit: true
  )
  puts "USER ##{joined_team_users.user_id} joined TEAM ##{joined_team_users.team_id}"
end

Edit:
As requested, here is the team controller (the filter of authorized to update user has still not been implemented) :
class Api::V1::TeamsController < ApplicationController
  before_action :set_team, only: %i[show update destroy]
  before_action :check_login

  def index
    render json: TeamSerializer.new(Team.all).serializable_hash.to_json
  end

  def show
    render json: TeamSerializer.new(@team).serializable_hash.to_json
  end

  def create
    team = current_user.teams.build(team_params)

    if team.save
      if current_user&.is_admin === false
        JoinedTeamUser.create!(
          user_id: current_user.id,
          team_id: team.id,
          can_edit: true
        )
        render json: TeamSerializer.new(team).serializable_hash.to_json, status: :created
      else
        render json: TeamSerializer.new(team).serializable_hash.to_json, status: :created
      end
    else
      render json: {errors: team.errors }, status: :unprocessable_entity
    end
  end

  def update
    if @team.update(team_params)
      render json: TeamSerializer.new(@team).serializable_hash.to_json, status: :ok
    else
      render json: @team.errors, status: :unprocessable_entity
    end
  end

  def destroy
    @team.destroy
    head 204
  end

  private

  def team_params
    params.require(:team).permit(:name, :description, :created_at, :updated_at)
  end

  def set_team
    @team = Team.find(params[:id])
  end

end

and the team controller tests :
require "test_helper"

class Api::V1::TeamsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @team = teams(:one)
    @user = users(:one)
  end

  # INDEX
  test "should access team index" do
    get api_v1_teams_url,
    headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
    as: :json
    assert_response :success
  end

  test "should forbid team index" do
    get api_v1_teams_url, as: :json
    assert_response :forbidden
  end

  # SHOW
  test "should show team" do
    get api_v1_team_url(@team),
    headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
    as: :json
    assert_response :success
  end

  # SHOW
  test "should forbid show team" do
    get api_v1_team_url(@team),
    as: :json
    assert_response :forbidden
  end

  # CREATE
  test "should create team" do
    assert_difference('Team.count') do
      post api_v1_teams_url,
      params: { team: { name: "Random name", description: "Random description" } },
      headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
      as: :json
    end
    assert_response :created
  end

  test "should not create team when not logged in" do
    assert_no_difference('Team.count') do
      post api_v1_teams_url,
      params: { team: { name: "Random name", description: "Random description" } },
      as: :json
    end
    assert_response :forbidden
  end

  test "should not create team with taken name" do
    assert_no_difference('Team.count') do
      post api_v1_teams_url,
      params: { team: { name: @team.name, description: "Random description" } },
      headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
      as: :json
    end
    assert_response :unprocessable_entity
  end

  test "should not create team without name" do
    assert_no_difference('Team.count') do
      post api_v1_teams_url,
      params: { team: { description: "Random description"} },
      headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
      as: :json
    end
    assert_response :unprocessable_entity
  end

  # UPDATE
  test "should update team" do
    patch api_v1_team_url(@team),
    params: { team: { name: "New name", description: "New description" } },
    headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
    as: :json
    assert_response :success
  end

  test "should not update team " do
    patch api_v1_team_url(@team),
    params: { team: { name: "New name", description: "New description" } },
    as: :json
    assert_response :forbidden
  end

  # DESTROY
  test "should destroy team" do
    assert_difference('Team.count', -1) do
      delete api_v1_team_url(@team),
      headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
      as: :json
    end
    assert_response :no_content
  end

  test "should forbid destroy team" do
    assert_no_difference('Team.count') do
      delete api_v1_team_url(@team), as: :json
    end
    assert_response :forbidden
  end
end

Thanks !

A: I would start by actually fixing the models.
class Team < ApplicationRecord
  has_many :memberships
  has_many :members, through: :memberships
end

class Membership < ApplicationRecord
  belongs_to :team
  belongs_to :member, class_name: 'User'
end

class User < ApplicationRecord
  has_many :memberships,
     foreign_key: :member_id
  has_many :teams,
     through: :memberships
end

Joins should never be a part of the name of your model. Name your models after what they represent in your domain, not as peices of plumbing.
Whatever is_admin is should be admin?.
If you want to create a team and make the user who created the team a member at the same time you want to do:
# See https://github.com/rubocop/ruby-style-guide#namespace-definition
module Api
  module V1
    class TeamsController < ApplicationController
      def create
        @team = Team.new(team_params)
        @team.memberships.new(
          member: current_user,
          can_edit: current_user.admin?
        )
        if team.save
          # why is your JSON rendering so clunky?
          render json: TeamSerializer.new(team).serializable_hash.to_json, status: :created
        else
          render json: {errors: team.errors }, status: :unprocessable_entity
        end
      end

      # ...
    end
  end
end

This will insert the Team and Membership in a single transaction and avoids creating more code paths in the controller.
require "test_helper"

module API
  module V1
    class TeamsControllerTest < ActionDispatch::IntegrationTest
      setup do
        @team = teams(:one)
        @user = users(:one)
      end

      # ...
      test "when creating a team the creator is added as a member" do
        post api_v1_teams_url,
          # add valid parameters to create a team
          params: { team: { ... } },
          # repeating this all over your tests is very smelly
          headers: { Authorization: JsonWebToken.encode(user_id: @user.id) },
          as: :json
        assert @user.team_memberships.exist?(
          team_id: Team.last.id
        ), 'expected user to be a member of team'
      end
    end
  end
end

As for actually adding the authorization checks I would recommend that you look into Pundit instead of reinventing the wheel, this also has a large degree of overlap with Rolify which is a much better alternative then adding a growning of can_x boolean columns.


text:
Q: Reset Count - If different value in specific column using C# lambda expression Is there a way to reset count after select? Here is sample in Fiddle.
This is the result I'm getting,
{groupRowId: 1, monthYear: '2020-08', projectName: 'Project 1'}
{groupRowId: 2, monthYear: '2020-08', projectName: 'Project 2'}
{groupRowId: 3, monthYear: '2020-08', projectName: 'Project 3'}
{groupRowId: 4, monthYear: '2021-08', projectName: 'Project 4'}
{groupRowId: 5, monthYear: '2021-08', projectName: 'Project 5'}
{groupRowId: 6, monthYear: '2021-08', projectName: 'Project 6'}

This is what I've tried.
public List<object> GenerateDynamicCalendar(List<ProjectResult> result) {
            int row = 1;
     var queryAug = result.Where(c => c.LiveDate != Convert.ToDateTime("1900-01-01 00:00:00.000") && c.LiveDate.Month == 8)
              .GroupBy(c => new { c.Month, c.Name})
              .Select(g => new DynamicProjectCalendarAug
              {
                  GroupRowId = row++,
                  MonthYear = g.Key.Month,
                  ProjectName = g.Key.Name,
                  Aug = g.Where(c => c.LiveDate != Convert.ToDateTime("1900-01-01 00:00:00.000") && c.LiveDate.Month == 8).Max(c => c.Name)
              }).ToList();

            List<object> query = otherMonthResult.Cast<object>()
                .Concat(queryAug)
            return query;
    }

And this is what I want to achieve. Since MonthYear value is different I want to reset count back to 1
{groupRowId: 1, monthYear: '2020-08', projectName: 'Project 1'}
{groupRowId: 2, monthYear: '2020-08', projectName: 'Project 2'}
{groupRowId: 3, monthYear: '2020-08', projectName: 'Project 3'}
{groupRowId: 1, monthYear: '2021-08', projectName: 'Project 4'}
{groupRowId: 2, monthYear: '2021-08', projectName: 'Project 5'}
{groupRowId: 3, monthYear: '2021-08', projectName: 'Project 6'}

A: If you group by only month, you could use the .GroupBy()'s resultSelector to create a DynamicProjectCalendarAug object for each group item. The resultSelector takes advantage of the .Select() overload that provides the index of the source element. It would look like the following:
var queryAug = result
    //.Where( ... )
    .GroupBy(
        resultItem => resultItem.Month,
        ( _, itemsInMonth ) => itemsInMonth
             .Select(( item, i ) => new DynamicProjectCalendarAug {
                 GroupRowId = i + 1,
                 MonthYear = item.Month,
                 ProjectName = item.Name,
                 //Aug = ...
             }))
    .SelectMany(_ => _)
    .ToList();

For a simplified implementation of your classes, this example input:
List<ProjectResult> result = new()
{
    new() { Month = "2020-08", Name = "Project 1"},
    new() { Month = "2020-08", Name = "Project 2"},
    new() { Month = "2020-08", Name = "Project 3"},
    new() { Month = "2021-08", Name = "Project 4"},
    new() { Month = "2021-08", Name = "Project 5"},
    new() { Month = "2021-08", Name = "Project 6"}
};

will have the following output:
1  |  2020-08  |  Project 1
2  |  2020-08  |  Project 2
3  |  2020-08  |  Project 3
1  |  2021-08  |  Project 4
2  |  2021-08  |  Project 5
3  |  2021-08  |  Project 6

Example fiddle here.

A: Created an example to show how you can solve this.
https://dotnetfiddle.net/b9mnau

A: Having
record WithRowId(int GroupRowId, MyDto MyDto);
record MyDto(int X, string Val);

var list = new []{
    new MyDto(X: 1, Val: "a"),
    new MyDto(X: 1, Val: "b"),
    new MyDto(X: 2, Val: "c"),
    new MyDto(X: 2, Val: "d"),
};

you could add group row id the following ways:
var list2 = new List<WithRowId>();
foreach( var group in list.GroupBy( c => c.X ))
{
    int i = 0;
    foreach(var r in group)
    {
        list2.Add(new WithRowId(1 + i++, r));
    }
}

// Method 2
var list2B = list
 .GroupBy( c => c.X)
 .SelectMany( g => g.Select((x, i) => new WithRowId(GroupRowId: i+1, MyDto: x)));

The second method uses the lesser known variant of Select which provides an index.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I load data from an external URL using JSON? I want to display a name from this url http://api.open-notify.org/astros.json/
Here is my code,
var astrosAPI = "http://api.open-notify.org/astros.json/";

$.getJSON(astrosAPI, function (json) {
    var name = json.results[0].formatted_name;
    console.log('Name : ', name);
});

I want to display it with my h3 tag. I'm new to JSON and jQuery. I keep getting
index.html:631 Uncaught TypeError: Cannot read property '0' of undefined error

A: You have to use the success() or done() function.
var url = "http://api.open-notify.org/astros.json/";
$.getJSON(url).success(function (json) {
  var name = json.people[0].name
  console.log('Name : ', name)
})

A: If you are able to reach out to the specific endpoint and not be blocked by CORS it must be the format of the data.
Looking at the data, there is no property called results in your data.  Try debugging that line to see the proper format of the variable json.  It may be a string and you would need to call JSON.parse(json); in order to format it properly as an object.
You should be able to do:
var astrosAPI = "http://api.open-notify.org/astros.json/";

$.getJSON(astrosAPI, function (json) {
    var name = json.people[0].name;
    console.log('Name : ', name);
});


text:
Q: how to reload calling fragment with the previous state and set the result got as a callback from the dialog fragment it initiated This is how my application runs.
The application has several fragments as view pager connecting through main activity. From Second Fragment, I launched custom fragment dialog and upon ok button click inside that fragment dialog, I am fetching the result into main activity. I am using android.support.v4 library.
public class MainActivity extends FragmentActivity implements MyDialog.Communicator {

private static String callBackMessage;
    @Override
    public Fragment getItem(int pos) {
        switch (pos) {
            case 0:
                return FirstFragment.newInstance();
            case 1:
                return SecondFragment.newInstance(MainActivity.this);
            default:
                return ThirdFragment.newInstance();
        }
    }

@Override
public void onDialogMessage(String callBackMessage) {
    MainActivity.callBackMessage = callBackMessage;
}

public static String getCallBackMessage() {
    return callBackMessage;
}

This is my MyDialog Fragment class, here I am creating some rows and giving checkboxes to be selected.
private void performOKButtonFunctionality() {
    String msg = checkedBoxesCount + "";
    communicator.onDialogMessage(msg);

    SecondFragment secondFragment = new SecondFragment();
    secondFragment.testFunction(row);
    dismiss();
}

Now because of my very early days into android and its fragment life cycle, I am calling a method on Second fragment after instantiating it. the row parameter just passes the row number.
Now inside the Second Fragment Class I have some thing like,
public void testFunction(String callBackRow) {
    callBackRowNo = Integer.parseInt(callBackRow);
    String callBackMessage = MainActivity.getCallBackMessage();
    getTableData(callBackMessage + "");
}

In order to save the SecondFragment previous state, I am saving its context by making it static like this,
private static Context activityContext;

public static SecondFragment newInstance(Context context) {
    activityContext = context;
    SecondFragment f = new SecondFragment();
    Bundle b = new Bundle();
    f.setArguments(b);
    return f;
}

Now doing so, I am able to use my Second Fragment only one time after clicking the ok button from Fragment Dialog. but upon clicking again, the app crashes at this point.
FragmentManager myDialogManager = getActivity().getSupportFragmentManager();

The raised exception is:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference

Now, my questions are:

*

*How do we reenter into the oncreate method of the fragment where it just restores its previous state rather than saving it explicitly before launching
fragment dialog.

*How does the fragment dialog pass parameter to the fragment which can be used to update the fragment field.
Is there some easy way to achieve this?
Before asking I searched the SO but could not find anything where this scenario was asked or explained.
I am badly stuck here and any solution/direction is much appreciated.

A: try getChildFragmentManager() instead of getSupportFragmentManager()
when do you make fragment with newInstace, you can put argsments like this.
public static MyFragment newInstance(int value) {
    MyFragment f = new MyFragment();

    Bundle args = new Bundle();
    args.putInt("value", value);
    f.setArguments(args);
    return f;
}

it also needs constructor MyFragment()
public MyFragment() {}

get values from args like this
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getArguments() != null) {
        value = getArguments().getInt("value");
    }
    return inflater.inflate(R.layout.your_layout, container, false);
}


text:
Q: Angular&rxjs testing performance of API with multiple requests I want to check response time for multiple requests sent to API, than display it on chart with help of chart.js I already have done it, but I am not sure if I am doing it right, because responses could not come and my code is adding point on chart only when client receive equal amount of responses that user entered.
here is function responsible for sending request to API and returning response time and data weight:
testRequests(numOfRequests, numOfRecords, db): Subject<any> {

const subject = new Subject();

for (let i = 1; i <= numOfRequests; i++) {
  const start_time = performance.now();
  this.http.get(BASE_URL + DATABASE + db + LIMIT + numOfRecords, {observe: 'response'}).subscribe((response) => {
    subject.next({
      time: performance.now() - start_time,
      weight: response.headers.get('Content-Length')
    });
  });
}

return subject;

}

and here is func, that receives results and when it have same amount responses that user requested it adds point to chart:
makeTest(requestsAmount = 1, requestDB = 'aurora') {
const arrOfResults = [];
this.subscription = this.api.testRequests(requestsAmount, 5, requestDB).subscribe(
  result => {
    arrOfResults.push(result);
    if (arrOfResults.length === +requestsAmount) {
      this.lineChartData[0].data.push(arrOfResults[arrOfResults.length - 1].time);
      this.lineChartData[1].data.push(arrOfResults[arrOfResults.length - 1].weight * arrOfResults.length / 1024);
      this.lineChartLabels.push(arrOfResults.length + ' - ' + (requestDB === 'aurora' ? 'Aurora' : 'DynamoDB'));
      this.chart.chart.update();
    }
  },
  err => console.error(err),
  () => console.log('completed')
);

}

as I heard that there is no guarantee that request will produce response, and responses can get lost, I would like to improve my code, so its generate point on chart in case there are some responses missing.

A: The subscribe method is not called when there is an unhandled error. You need to use a catch listener for error events.
The below example catches all errors and converts them into a null value. Now subscribe will receive either a response or null.
 this.http.get(BASE_URL + DATABASE + db + LIMIT + numOfRecords, {observe: 'response'})
       .catch((error, resp) => null)
       .subscribe((response) => {
             subject.next({
                  time: performance.now() - start_time,
                  weight: response ? response.headers.get('Content-Length') : 0
             });
       });


text: Q: Is there a way to boot from ISO file in rEFInd Boot Manager? I am wonder if there is such feature in rEFInd - to run ISO file located on the USB stick. I can not use any superuser utilities such as dd to write an ISO directly. I can only repack it.


text:
Q: Javascript Nested Array Return Even Numbers I am trying to write a function that prints only the even numbers from a nested array. Here is my attempt and it keeps returning "undefined".
function printEvents(){

 var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]];

  for (var i = 0; i<nestedArr.length; i++) {
    for (var j = 0; j<nestedArr[i]; j++) {
      var evenNumbers = nestedArr[i][j]
    }
  }

  if (evenNumbers % 2 == 0) {
    console.log(evenNumbers)
  }

 }

 printEvents();

A: You could use a recursive approach, if the item is an array. You need to move the test for evenness inside of the for loop.

function printEvents(array) {
    var i;
    for (i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            printEvents(array[i]);
            continue;
        }
        if (array[i] % 2 == 0) {
            console.log(array[i]);
        }
    }
}

printEvents([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]);

Solution with a callback

function getEven(a) {
    if (Array.isArray(a)) {
        a.forEach(getEven);
        return;
    }
    if (a % 2 == 0) {
        console.log(a);
    }
}

getEven([[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12], [[[13, [14]]]]]);

A: You just have a couple issues. You need to check the length of your nested arrays and you need to move your code that checks whether a number is even or not inside the array.

 var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]];

  for (var i = 0; i<nestedArr.length; i++) {
    for (var j = 0; j<nestedArr[i].length; j++) {
      var evenNumbers = nestedArr[i][j]
      if (evenNumbers % 2 == 0) {
        console.log(evenNumbers)
      }
    }
  }

A: You can do this more easy using filter method which accepts a callback method.

var nestedArr = [[1,2,3],[4,5,6],[7,8],[9,10,11,12]];
var mergedArray=[].concat.apply([], nestedArr);
console.log(mergedArray.filter(a => a%2 == 0));

A: You can use reduce with every for something quick.

var nestedArr = [ [1, 2, 3],[4, 5, 6],[7, 8],[9, 10, 11, 12]];

var sift = nestedArr.reduce(function(r,o) {
    o.every(i => i % 2 === 0 ? r.push(i) : true)
    return r;
}, []);

console.log(sift);

If you want a one-liner you can use ReduceRight with Filter

var nestedArr = [[1, 2, 3],[4, 5, 6],[7, 8],[9, 10, 11, 12]];

var sift = nestedArr.reduceRight((p, b) => p.concat(b).filter(x => x % 2 === 0), []);

console.log(sift)


text:
Q: Как можно реализовать этот вариант с использованием ACF на WordPress? Подскажите пожалуйста как можно реализовать такой пример используюя ACF на Wordpress.
Я этот вариант наверстал и реализовал с помощью jQuery-ui-tabs но как посадить на WP с помощью ACF пока не могу понять, подскажите пожалуйста.
Нет принципиальной разницы слайдером или табами, желательно вариант который будет проще реализовать и удобнее использовать с админки.
Спасибо !

$(function () {
  $("#tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
  $("#tabs li").removeClass("ui-corner-top").addClass("ui-corner-left");
  $("#tabs").tabs({
    active: 0,
  });
});
.tabs__descr {
  background-color: #003333;
}

.ui-tabs-vertical {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.ui-tabs-vertical .ui-tabs-nav {
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -webkit-box-flex: 0;
  -ms-flex: 0 1 27%;
  flex: 0 1 27%;
  margin-right: 40px;
}

.ui-tabs-vertical .ui-tabs-nav:before {
  position: absolute;
  content: "";
  width: 12px;
  height: 95%;
  top: 5px;
  bottom: -10px;
  background-color: #fff;
}

.ui-tabs-vertical .ui-tabs-nav li {
  position: relative;
  clear: left;
  width: 100%;
  border-bottom-width: 1px !important;
  border-right-width: 0 !important;
  margin: 0 -1px 0.2em 0;
}

.ui-tabs-vertical .ui-tabs-nav li:before {
  position: absolute;
  content: "";
  width: 30px;
  height: 30px;
  left: -10px;
  background-color: #003333;
  border-radius: 50%;
  border: 9px solid #fff;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active:before {
  width: 104px;
  height: 104px;
  left: -48px;
  border: 12px solid #fff;
  background-image: url(../img/svg/ichtab.svg);
  background-repeat: no-repeat;
  background-position: center;
  background-color: #33cccc;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.ui-tabs-vertical .ui-tabs-nav li a {
  display: block;
  font-size: 26px;
  line-height: 33px;
  color: #fff;
  font-weight: 600;
  padding: 0 15% 0 65px;
}

.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  padding-bottom: 0;
  padding-right: 0.1em;
  border-right-width: 1px;
  padding-left: 60px;
}

.ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active a {
  color: #33cccc;
  padding-left: 35px;
}

.ui-tabs-panel.ui-corner-bottom.ui-widget-content:before {
  position: absolute;
  content: "";
  border: 40px solid transparent;
  border-left-color: #fff;
  margin: 0 0 0 -150px;
  -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  transform: rotate(180deg);
}

.ui-tabs-vertical .ui-tabs-panel {
  -webkit-box-flex: 0;
  -ms-flex: 0 1 73%;
  flex: 0 1 73%;
  padding: 70px;
  position: relative;
  background-color: #fff;
}

.ui-tabs-vertical .ui-tabs-panel p {
  margin-bottom: 35px;
  color: #003333;
  font-size: 20px;
  line-height: 26px;
  font-weight: 500;
}

.tab__description__bottom {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.tab__description__bottom p {
  padding-left: 100px;
  background-size: contain;
  background-position: center left;
  background-repeat: no-repeat;
}

.tab__description__bottom p:first-child {
  background-image: url(../img/svg/ab-i1.svg);
}

.tab__description__bottom p:nth-child(2) {
  background-image: url(../img/svg/ab-i2.svg);
}

.tab__description__bottom p:last-child {
  background-image: url(../img/svg/ab-i1.svg);
}

.tab__button {
  position: absolute;
  bottom: -29px;
  left: 50%;
  margin-left: -105px;
}

.tab__button .button {
  background-color: #33cccc;
  color: #fff;
}

.tab__button .button:hover {
  background-color: #fff;
  color: #003333;
}

Citizenship of Ukraine

Temporary residence permit

Permanent residence permit

Invitation to Ukraine

Registration in Kiev

Extension of the period of stay

Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

2Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

1Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

1Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

1Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

1Temporary residence permit

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                At the bottom of the slider are the slider control buttons.
                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. At the bottom of the slider are the slider control
                buttons. At the bottom of the slider are the slider control
                buttons. Picture with a title and a button to go to the
                corresponding page.

                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.
                Slider images automatically switch at 3-5 second intervals. At
                the bottom of the slider are the slider control buttons. At the
                bottom of the slider are the slider control buttons. Picture
                with a title and a button to go to the corresponding page.

                Picture with a title and a button to go to the corresponding
                page. Slider images automatically switch at 3-5 second
                intervals. Picture with a title and a button to go to the
                corresponding page. Slider images automatically switch at 3-5
                second intervals.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                  At the bottom of the slider are the slider control buttons.

                contact

fidle
Возможно есть способ который будет добавлять ссылку с id и соответственно id табу при клонирование поля?

A: Вы можете сделать это при помощи repeater поля. Все что вам нужно, просто прогнать цикл 2 раза, чтобы не заморачиваться особо и все. Будет что-то вроде:
<?php if ( have_rows( 'your_repeater' ) ) : ?>

                    <?php while ( have_rows( 'your_repeater' ) ) : the_row(); ?>
                        <?php // Тут просто текстовое поле заголовка + id таба если нужно, можно сделать отдельным полем и подставить его в href ?>
                        <?php // Учтите что the_row_index() было добавлено в ACF с версии 5.8.8 вроде как, если более ранняя версия, используйте echo get_row_index(); ?>

<a href="#tabs-<?php the_row_index(); ?>"><?php the_sub_field( 'title' ); ?>

                    <?php endwhile; ?>

                <?php while ( have_rows( 'your_repeater' ) ) : the_row(); ?>
                    <?php // Тут просто WYSIWYG ?>
                    <div id="tabs-<?php the_row_index(); ?>">
                        <?php the_sub_field( 'text' ); ?>
                        <?php if ( get_sub_field( 'description' ) ) : ?>

                                <?php // Тоже просто WYSIWYG ?>
                                <?php the_sub_field( 'description' ); ?>

                        <?php endif; ?>
                        <?php
                        // Relational -> Link
                        $button = get_sub_field( 'button' );

                        if ( $button ) : ?>

                                <a href="<?php echo esc_url( $button['url'] ); ?>" target="<?php echo ( $button['target'] ) ?: '_self'; ?>" class="button"><?php echo esc_html( $button['title'] ); ?>

                        <?php endif; ?>

                <?php endwhile; ?>

<?php endif; ?>


text:
Q: Bad Input Shape Sklearn Error After HashingVectorizer I have 204567 words of which 21010 are unique. Each word is associated with a unique tag. In total, there are 46 unique tags.
I have used feature hashing to map the 204567 words using HashingVectorizer(). I have one-hot encoded the tags and used Perceptron() model for this multi-class classification problem.
from keras.utils import np_utils
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import Perceptron
from sklearn.preprocessing import LabelEncoder

vect = HashingVectorizer(decode_error='ignore', n_features=2**15,
                          preprocessor=None)
X = vect.transform(X_train)

encoder = LabelEncoder()
y = encoder.transform(y_train)
target = np_utils.to_categorical(y)

ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0)
ppn.fit(X, target)

However, I receive the following error: ValueError: bad input shape (204567, 46)
Is there a better way to encode the tags?
P.S. Please, explain the error and a possible solution

A: I changed my code as follows and now its working:
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import np_utils
from numpy import array

vec = HashingVectorizer(decode_error = 'ignore', n_features = 2**15)
X = vec.fit_transform(X_train)

values = array(y_train)

label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)

encoded = np_utils.to_categorical(integer_encoded)
print(X.shape)
print(encoded.shape)

clf = MLPClassifier(activation = 'logistic', solver = 'adam',
                    batch_size = 100, learning_rate = 'adaptive',
                    max_iter = 20, random_state = 1, verbose = True )
clf.fit(X, encoded)
print('Accuracy: %.3f' %clf.score(X, encoded))

I changed my model from Perceptron to Multi Layer Perceptron Classifier though I am not completely sure how this is working. Explanations are welcome.
Now I have to approach the same problem using n-gram model and compare the results.

A: the function np_utils.to_categorical() expects an class vector as parameter, you gived a shape
See docs:
to_categorical
to_categorical(y, num_classes=None)

Converts a class vector (integers) to binary class matrix.
E.g. for use with categorical_crossentropy.
Arguments
y: class vector to be converted into a matrix (integers from 0 to num_classes).
num_classes: total number of classes.
Returns
A binary matrix representation of the input.
so
target = np_utils.to_categorical(y)

gives you an error type


text:
Q: Move constructor and move assignment operator vs. copy elision Related questions:

*

*Why this move constructor is not called wtih rvalue temporary? [duplicate]

*Move Constructor vs Copy Elision. Which one gets called?

*move Constructor is not called
I'm posting this question because this thing of the move semantics is really puzzling me. At first they seemed quite clear to me, but when I tried to demostrate the use of those to myself, then I realized that maybe I've misunderstood something.
I've tried to arrange the following file to be a not-so-trivial implementation of a vector-like class making use of move semantics (actually the main function is there as well, together with a free function to make printing to screen easier, ...). It is not really a minimal working example, but the output it produces to screen is reasonably readable, imho.
Still, if you thing it's better to slim it down, please suggest me what to do.
Anyway the code is the following,
#include<iostream>
using namespace std;

int counter = 0; // to keep count of the created objects

class X {
  private:
    int id = 0; // hopefully unique identifyier
    int n = 0;
    int * p;
  public:
    // special member functions (ctor, dtor, ...)
    X()           : id(counter++), n(0),   p(NULL)       { cout << "default ctor (id " << id << ")\n"; }
    X(int n)      : id(counter++), n(n),   p(new int[n]) { cout << "param ctor (id " << id << ")\n"; };
    X(const X& x) : id(counter++), n(x.n), p(new int[n]) {
      cout << "copy ctor (id " << id << ") (allocating and copying " << n << " ints)\n";
      for (int i = 0; i < n; ++i) {
        p[i] = x.p[i];
      }
    };
    X(X&& x)      : id(counter++), n(x.n), p(x.p) {
      cout << "move ctor (id " << id << ")\n";
      x.p = NULL;
      x.n = 0;
    };
    X& operator=(const X& x) {
      cout << "copy assignment (";
      if (n < x.size() && n > 0) {
        cout << "deleting, ";
        delete [] p;
        n = 0;
      }
      if (n == 0) {
        cout << "allocating, and ";
        p = new int[n];
      }
      n = x.size();
      cout << "copying " << n << " values)";
      for (int i = 0; i < n; ++i) {
        p[i] = x.p[i];
      }
      cout << endl;
      return *this;
    };
    X& operator=(X&& x) {
      this->n = x.n;
      this->p = x.p;
      x.p = NULL;
      x.n = 0;
      cout << "move assignment (\"moving\" " << this->n << " values)\n";
      return *this;
    };
    ~X() {
      cout << "dtor on id " << id << " (array of size " << n << ": " << *this << ")\n";
      delete [] p;
      n = 0;
    }
    // getters/setters
    int size() const { return n; }

    // operators
    int& operator[](int i) const { return p[i]; };
    X operator+(const X& x2) const {
      cout << "operator+\n";
      int n = min(x2.size(), this->size());
      X t(n);
      for (int i = 0; i < n; ++i) {
        t.p[i] = this->p[i] + x2.p[i];
      }
      return t;
    };

    // friend function to slim down the cout lines
    friend ostream& operator<<(ostream&, const X&);
};

int main() {
    X x0;
  X x1(5);
  X x2(5);
  x1[2] = 3;
  x2[3] = 4;
  cout << "\nx0 = x1 + x2;\n";
  x0 = x1 + x2;
  cout << "\nX x4(x1 + x2);\n";
  X x4(x1 + x2);
  cout << x4 << endl;
  cout << '\n';
}

// function to slim down the cout lines
ostream& operator<<(ostream& os, const X& x) {
  os << '[';
  for (int i = 0; i < x.size() - 1; ++i) {
    os << x.p[i] << ',';
  }
  if (x.size() > 0) {
    os << x.p[x.size() - 1];
  }
  return os << ']';
}

When I compile and run it with
$ clear && g++ moves.cpp && ./a.out

the output is the following (#-comments are added by hand)
default ctor (id 0)
param ctor (id 1)
param ctor (id 2)

x0 = x1 + x2;
operator+
param ctor (id 3)
move assignment ("moving" 5 values)
dtor on id 3 (array of size 0: [])

X x4(x1 + x2);
operator+
param ctor (id 4)
[0,0,3,4,0]

dtor on id 4 (array of size 5: [0,0,3,4,0])
dtor on id 2 (array of size 5: [0,0,0,4,0])
dtor on id 1 (array of size 5: [0,0,3,0,0])
dtor on id 0 (array of size 5: [0,0,3,4,0])

From the first part of the output, I guess that I really demonstrated the intended use of the move assignment operator. Am I right, in this respect? (From the next output, it seems I'm not, but I'm not sure.)
At this point, if my deduction that copy elision prevented the call to the copy ctor is right, then one question comes natural to me (and not only me, see OP's comment here):
Isn't that situation of creating an object based on another temporary object (e.g. x4 based on the result of x1 + x2 in X x4(x1 + x2);) exactly the one for which move semantics where supposed to be introduced? If not, what is a basic example to show the use of the move ctor?
Then I read that copy elision can be prevented by adding a proper option.
The output of
clear && g++ -fno-elide-constructors moves.cpp && ./a.out

however, is the following:
default ctor (id 0)
param ctor (id 1)
param ctor (id 2)

x0 = x1 + x2;
operator+
param ctor (id 3)
move ctor (id 4)
dtor on id 3 (array of size 0: [])
move assignment ("moving" 5 values)
dtor on id 4 (array of size 0: [])

X x4(x1 + x2);
operator+
param ctor (id 5)
move ctor (id 6)
dtor on id 5 (array of size 0: [])
move ctor (id 7)
dtor on id 6 (array of size 0: [])
[0,0,3,4,0]

dtor on id 7 (array of size 5: [0,0,3,4,0])
dtor on id 2 (array of size 5: [0,0,0,4,0])
dtor on id 1 (array of size 5: [0,0,3,0,0])
dtor on id 0 (array of size 5: [0,0,3,4,0])
+enrico:CSGuild$

where it looks like the call to the move ctor I expect is now there, but both that call and the call to the move assignment are preceded by another call to the move ctor each.
Why is this the case? Have I completely misunderstood the meaning of move semantics?

A: You appear to have two questions here:

*

*why is the move constructor not called for X x4(x1 + x2)?

*why, when copy elision is disabled, is the move constructor called twice?

The first question

Isn't that situation (X x4(x1 + x2);) exactly the one for which move
  semantics where supposed to be introduced?

Well, no.  In order to use move semantics you're effectively suggesting that we should choose to construct an X in operator+, and then move it to the result x4, which is clearly inefficient compared to a copy-elided construct the final result (x4) in place during operator+.
The second question
Having disabled copy-elision, why do we see two calls to the move constructor during X x4(x1 + x2)?  Consider that there are three scopes in play here:

*

*the operator+ scope, where we construct an X and return it;

*the main scope where we are calling X x4(x1 + x2);

*the X constructor where we are constructing an X from x1 + x2;

Then, in the absence of elision, the compiler is:

*

*moving the result from operator+ to main (into x1 + x2); and

*moving the content of x1 + x2 into x4.


text:
Q: How to change the width of CF7? I am having trouble changing the width of a form field to 100 %. I think it's because it is in corruption with the themes code...
so here is my code:
.wpcf7-text, .wpcf7-textarea, .wpcf7-captchar, .wpcf7-form-control-wrap {
background-color:rgba(255, 255, 255) !important;
border: none !important;
width: 100% !important;
border-radius: 0 !important;
font-size: 16px;
font-weight: 500;
color: #1c1c1c !important;
padding: 16px !important;
box-sizing: border-box;
}
.wpcf7-submit {
color: #fff;
background-color: #414141 !important;
margin: 8px auto 0;
font-family: Francois One, latin;
font-size: 30px;
font-weight: 500;
border-color: #414141 !important;
border-bottom: 3px solid rgb(163, 163, 163)!important;
border-left: #414141 !important;
border-right: #414141 !important;
border-radius: 8px;
padding: 6px 60px;
line-height: 1.7em;
box-shadow: 0px 8px 30px rgba(0, 0, 0, 0.4);
}
.wpcf7-submit:hover {
background-color:rgba(78, 78, 78) !important;
border-width: 2px !important;
border-color:  #494949 !important;
border-bottom: 3px solid rgb(163, 163, 163)!important;
border-left: #4e4e4e !important;
border-right: #4e4e4e !important;
border-radius: 8px;
padding: 6px 0px !important;

}
span.wpcf7-list-item { display: block; }

And here is the link to the site:
https://ptbydimitri.de/so-geht-es-weiter/
As you can see, the form fields are not with a width of 100% like the send button.
I hope someone can help!

A: Your input tag is inside the label tag, you have to change the width of label to 100% to make it work.
.wpcf7 .wpcf7-form label {
    width: 100%;
}


text:
Q: Run extension command on save I use the Sorting HTML and Jade attributes extension which offers the command attrsSorter.execute.  I would like to setup my workspace settings.json so that "editor.codeActionsOnSave" section runs this every time before saving, then formatting / linting so that we get the sorted benefit.
Have looked all over the place and cannot figure out how to simply execute this each time save is performed.  Appreciate the help!

A: I just lost way too many hours of my life figuring out how to run the command test-explorer.run-all defined by this plugin. If you substitute editor.codeActionsOnSave for test-explorer.run-all everywhere below I think that should work.
What I've hacked together is to first of all install the Trigger Task on Save extension
which, instead of bash commands as per the other answer, runs VS code tasks on save.
As per the VS code docs
you can then define a custom task to wrap the command. For me, this looks like
{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "mocha-explorer",
      "command": "${command:test-explorer.run-all}",
    }
  ]
}

Here mocha-explorer is my own arbitrary label for this.
Finally, configure the settings.json file to run your task on save by its label, which for me looks like:
    "triggerTaskOnSave.tasks": {
        "mocha-explorer": ["*.js"]
    }

I'm a total newb to all this VS code config but I hope that helps someone.
A related useful answer that may be helpful for more complex tasks: Is there a way to run a command with VS Code tasks?

A: I needed to format CSS files on save by executing the PostCSS Sorting extension and I found this tutorial: Automatic CSS sorting in VS Code
According to it you have to install the extension:  ryuta46.multi-command and then modify the keybindings.json file. (F1 + Preferences: Open Keyboard Shortcuts (JSON))
Mine looks like this:
// Place your key bindings in this file to override the defaults
[
    {
        "key": "ctrl+s",
        "command": "extension.multiCommand.execute",
        "args": {
          "sequence": ["postcssSorting.execute", "workbench.action.files.save"]
        },
        "when": "editorLangId == css"
      }
]

I hope it helps someone! :)

A: You can use this extension
Run On Save for Visual Studio Code
This extension allows configuring commands that get run whenever a file is saved in vscode.


text:
Q: PHP get base64 decoding xml array and encode it to pdf I need to convert XML array (contained base64 decoding) and encode it to PDF.
This is the array:
<response>
<xmlArray>
<blabla>TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gTnVuYyB2ZW5lbmF0aXMsIGp
1c3RvIHV0IGF1Y3RvciBzZW1wZXIsIHB1cnVzIGxlY3R1cyBlbGVtZW50dW0gbGliZXJvLCBhYyBwZWxsZW50ZXNxdWUgYW50ZSBqdXN0b
yBldCB0dXJwaXMuIE51bmMgYmliZW5kdW0gZWdlc3RhcyBkb2xvciB2b2x1dHBhdCBlZ2VzdGFzLiBTdXNwZW5kaXNzZSBkYXBpYnVzIHN
lbSBvZGlvLCBpbiBmYXVjaWJ1cyBsZWN0dXMgcHVsdmluYXIgdml0YWUuIE5hbSBtYXR0aXMgZXVpc21vZCBhdWd1ZSwgZWdldCBmaW5pY
nVzIGxlbyBoZW5kcmVyaXQgbmVjLiBDbGFzcyBhcHRlbnQgdGFjaXRpIHNvY2lvc3F1IGFkIGxpdG9yYSB0b3JxdWVudCBwZXIgY29udWJ
pYSBub3N0cmEsIHBlciBpbmNlcHRvcyBoaW1lbmFlb3MuIE51bmMgaWQgbnVuYyBsZWN0dXMuIFBlbGxlbnRlc3F1ZSBsYWN1cyB1cm5hL
CB2aXZlcnJhIGNvbnZhbGxpcyBlZmZpY2l0dXIgdmVsLCBhbGlxdWFtIHNpdCBhbWV0IGRpYW0uIEluIGEgYWxpcXVldCBtYXNzYS4gU2V
udCwgdGVtcHVzIGhlbmRyZXJpdCBlbmltIGZhdWNpYnVzLiBEb25lYyBtYXR0aXMgZWxpdCBub24gbWFzc2EgaW50ZXJkdW0gZmF1Y2lid
XMuIEFlbmVhbiBub24gbWF1cmlzIGluIHVybmEgbWFsZXN1YWRhIGx1Y3R1cy4=
</blabla>
</xmlArray>
</response>

My attempt up until now is
<?php

// 1st. convert xml array; get the blabla array information

$blabla2 = $xml->xmlArray->blabla;

// remove CR, new lines and whitespace on blabla2

$blabla3 = str_replace(array("\n", "\t", "\r"), '', $blabla2);

// 2nd. encode it to PDF

header('Content-type: application/pdf');

$blabla4 = base64_decode($blabla3 );

echo $blabla4 ;
?>

The result is a pdf, but not the way I expected as it shows this line on pdf:
%PDF-1.410obj<</Title(þÿ)/Creator(þÿwkhtmltopdf0.12.2.4) ...
Would you mind to tell me how to show the pdf properly?
Thanks a lot!


text:
Q: RegExp capturing non-match I have a regex for a game that should match strings in the form of go [anything] or [cardinal direction], and capture either the [anything] or the [cardinal direction]. For example, the following would match:
go north
go foo
north
And the following would not match:
foo
go
I was able to do this using two separate regexes: /^(?:go (.+))$/ to match the first case, and /^(north|east|south|west)$/ to match the second case. I tried to combine the regexes to be /^(?:go (.+))|(north|east|south|west)$/. The regex matches all of my test cases correctly, but it doesn't correctly capture for the second case. I tried plugging the regex into RegExr and noticed that even though the first case wasn't being matched against, it was still being captured.
How can I correct this?

A: Try using the positive lookbehind feature to find the word "go".
(north|east|south|west|(?<=go ).+)$

Note that this solution prevents you from including ^ at the start of the regex, because the text "go" is not actually included in the group.

A: You have to move the closing parenthesis to the end of the pattern to have both patterns between anchors, or else you would allow a match before one of the cardinal directions and it would still capture the cardinal direction at the end of the string.
Then in the JavaScript you can check for the group 1 or group 2 value.
^(?:go (.+)|(north|east|south|west))$
                                   ^

Regex demo
Using a lookbehind assertion (if supported), you might also get a match only instead of capture groups.
In that case, you can match the rest of the line, asserting go  to the left at the start of the string, or match only 1 of the cardinal directions:
(?<=^go ).+|^(?:north|east|south|west)$

Regex demo


text:
Q: AngularJS: table edit data + update server I have managed to create a table using AngularJS. In this table I show products from my datbase which can be filtered on category or some other keywords. Now the user should be able to alter this data in this table to update the data in the database.
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
    $scope.search = "";
    $scope.products = [];
    $scope.categories = [];

    store.getCategories().then(function(data){
        $scope.categories = data;
    })
    store.getProducts().then(function(data){
        $scope.products = data;
    })

    $scope.filterProductsByCats = function(category){
    $scope.search = category;
    };
}])

categorieFilter.factory('store', function($http, $q){
    function _getCategory (){
        var deferred = $q.defer();
        $http.get('api/categories').success(function (data) {
                deferred.resolve(data);
            })
        return deferred.promise;
    }

    function _getProducts (){
        var deferred = $q.defer();
        var prods = [];
        $http.get('api/products').success(function (data) {
            for(var i = 0;i<data.length;i++)
            {
                prods[i] = {name: data[i][0], category: data[i][2], price: data[i][1]};
            }
            deferred.resolve(prods);
        })
        return deferred.promise;
    }
        return {
         getCategories: _getCategory,
         getProducts : _getProducts
        };
});

HTML table

 <input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>

 <button class="btn btn-sm btn-default">

 </button>

 <input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">

   Category
   Product
   Price

  {{product.category}}
  {{product.name}}
  {{product.price}}

Any ideas or reccomendations to get this done?

A: A library I like to use to achieve the editing of data, is angular xeditable. http://vitalets.github.io/angular-xeditable/
Then save it by posting it back to the webapi


text:
Q: Error booting after fresh install - Kernel Panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) I installed Ubuntu on my Windows 10 laptop (Dell, trying to dual boot) and am unable to start Ubuntu.  On startup I get the following error:
Kernel Panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)

Steps I've already taken:

*

*Change SATA to ACHI in the BIOS

*Run initramfs

*start from the live DVD to check I'm not running out of space in my boot partition

and I still get the same error.
Any thoughts on next steps to solve this issue?


text:
Q: Tornado: How to handle POSTs when using method based routing I'm using the following handlers, based on finding a project that also uses this style of method-based routing for Tornado:
import threading

from concurrent.futures import ThreadPoolExecutor
from tornado.process import cpu_count
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from tornado.concurrent import run_on_executor
from tornado.escape import recursive_unicode
from tornado.gen import coroutine

class BaseHandler(RequestHandler):

    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)
        self.io_loop = IOLoop.current()
        self.executor = ThreadPoolExecutor(cpu_count())

    @run_on_executor
    def route(self, function, **kwargs):
        threading.currentThread().setName('webUI')
        kwargs = recursive_unicode(kwargs)
        for arg, value in kwargs.items():
            if len(value) == 1:
                kwargs[arg] = value[0]
        return function(**kwargs)

class WebHandler(BaseHandler):

    @coroutine
    def prepare(self, *args, **kwargs):
        res = getattr(
                self,
                self.request.path.strip('/').split('/')[::-1][0].replace('.', '_'),
                getattr(self, 'index', None)
            )

        if res:
            view = yield self.route(res, **self.request.arguments)
            self.finish(view)

class Route():

    routes = []

    def __init__(self, uri, name=None):
        self.uri = uri
        self.name = name

    def __call__(self, _handler):
        '''Called when routes are decorated'''
        name = self.name and self.name or _handler.__name__
        self.routes.append((self.uri, _handler, name))
        return _handler

    @staticmethod
    def get_routes(webroot='/'):
        try:
            routes = [tornado.web.url(webroot + _uri, _handler, name=name)
                for _uri, _handler, name, in Route.routes]
            routes.reverse()
            return routes
        except Exception as e:
            print(e)
            return None

def route_redirect(src, dest, name=None):
    Route.routes.append(tornado.web.url(
        src, tornado.web.RedirectHandler,
        dict(url=dest),
        name=name
    ))

Which allows me to do something like the following:
@Route('config(/?.*)')
class Config(WebHandler):

    def __init__(self, *args, **kwargs):
        super(Config, self).__init__(*args, **kwargs)

    def index(self):
        <do some things and return an index page>

    def general(self):
        <do some thing and return a different page>

And thus when a GET is received for /config/, Config.index() is run and the index page is returned. Similarly, if I navigate to /config/general, a different page is returned.
However, I am unsure how to handle POST requests now. If I have a form that POSTs to /config/update for example, then when Config.update() is executed, it behaves exactly like the other methods for GET requests. The POSTed data is not passed to the method. Further, if I look at the request within either BaseHandler, I do not see the POSTed data there either - request.body is entirely empty, and trying to call self.data_received in the handlers results with the request not be handled at all (the browser will get a ERR_EMPTY_RESPONSE).
I'm obviously missing something, perhaps quite obvious, but I cannot find any reference to this in the tornado docs, nor anywhere else online as everything revolves around having a separate handler for each page and get and post methods for each - which is cumbersome and inefficient.
How do I properly handle POSTs when using this style of routing?


text:
Q: What Type of Firebase Data Structure Is Better? I'm seeing mixed tutorials in Firebase that recommends to structure data like this:
posts: {
  post_1: {
    title: 'Some Title',

    comments: {
      comment_1: true,
      comment_2: true,
      ...
      comment_x: true
    }
  }
}

comments: {
  comment_1: {
    name: 'Foo'
  },

  comment_2: {
    name: 'Bar'
  },

  ...

  comment_x: {
    name: 'X'
  }
}

and
posts: {
  post_1: {
    title: 'Some Title',
  }
}

comments: {
  post_1: {
    comment_1: {
      name: 'Foo'
    },

    comment_2: {
      name: 'Bar'
    },

    ...

    comment_x: {
      name: 'X'
    }
  }
}

I think the latter is better in terms of speed when querying, bulk writing, and security flexibility. Especially that when you have the 1st data structure and you query over the blogs just to find out it's title. It's gonna load tons of data if you have a million comments even if the value is just true (unless I'm missing something here).
My question is, for heavy data like those in social networks, is the 2nd data structure really that better compared to the 1st one? I'm not even convinced that the 1st one is better at any area than the 2nd one at all.
I'm torn because some Firebase tutorial uses the 1st data structure and I'm using the Emberfire web library from Firebase which enforces it if you want to completely embrace the library.

A: The second example is shallow(er) which is good for Firebase. The data is separated, again a good thing. The only downside (which really isn't a downside) is if you want to hit the database only once for the post and associated comments, instead of twice as in the second example; once for the post and again for the comments. Obviously #1 wins there but other than that #2 is the way to go.


text:
Q: Filter out string from result set I have this SPARQL script meant to work on Wikidata:
SELECT
  ?game
  (group_concat(distinct      ?gameLabel ; separator = ", ") AS      ?gameLabels)
  (group_concat(distinct     ?genreLabel ; separator = ", ") AS     ?genreLabels)
  WHERE {
    ?game wdt:P31 wd:Q7889;
    wdt:P136 wd:Q744038.
    OPTIONAL {?game wdt:P136     ?genre}
    SERVICE wikibase:label {
      bd:serviceParam wikibase:language "en".
           ?game rdfs:label      ?gameLabel.
          ?genre rdfs:label     ?genreLabel.
    }
} GROUP BY $game
ORDER BY ASC (?gameLabel)

You can test the code here:
https://query.wikidata.org/
Currently, I am filtering for a genre named "role-playing video game". However, I do not want this string to appear in the result set. How do I filter out just this string but not the actual records? Thanks.

A: SPARQL is pretty simple, just add the FILTER to the OPTIONAL clause:
SELECT
  ?game
  (group_concat(distinct      ?gameLabel ; separator = ", ") AS      ?gameLabels)
  (group_concat(distinct     ?genreLabel ; separator = ", ") AS     ?genreLabels)
  WHERE {
    ?game wdt:P31  wd:Q7889 ;
          wdt:P136 wd:Q744038.
    OPTIONAL {?game wdt:P136 ?genre . FILTER(?genre != wd:Q744038)}
    SERVICE wikibase:label {
      bd:serviceParam wikibase:language "en".
           ?game rdfs:label      ?gameLabel.
          ?genre rdfs:label     ?genreLabel.
    }
} GROUP BY ?game
ORDER BY ASC (?gameLabel)

Note, this doesn't filter out the genre "action role-playing game". If you also want to omit this one (since it looks like a sub-genre) you have to add this as a second condition to the FILTER:
FILTER(?genre != wd:Q744038 && ?genre != wd:Q1422746)

or if you more resource, it's more compact to
FILTER(?genre NOT IN (wd:Q744038, wd:Q1422746))


text:
Q: Extracting Multiple Relation Triples from Stanford CoreNLP I'm trying to extract relation triples from Stanford CoreNLP, and it's working very well for single relation triples in a sentence but doesn't seem to work for multiple ideas in the same sentence.
For example: I drink water, and he eats a cake.
I would expect there to be two triples. (I, drink, water), (he, eats, cake), but only one will show up.
Here's what I'm currently working with:
with corenlp.CoreNLPClient(annotators="tokenize ssplit lemma pos ner depparse natlog openie".split()) as client:
      ann = client.annotate(text)
sentence = ann.sentence[0].openieTriple
for x in ann.sentence:
    print(x.openieTriple)

I would assume I"m doing something wrong here. Changing max_entailments doesn't fix the problem.

A: You must do:
for x in ann.sentence:
   for triple in x.openieTriple
     print(triple)`

Discovered this today thanks to your question, so thanks!


text:
Q: Invalid Geojson Object Angularjs &Leafletjs In my project i try to synchronize filters with geojson displayed in table and on map. To achieve this i used angular and previously angular-leaflet-directive, but performance was to slow for my purposes so i decide to make my own directive for leaflet.js.
In my case i can pass data from controller to my directive, but it makes map static, when i try to pass data after filtering in order to make my map dynamic, map is not showing any markers and i get Error from leaflet, Invalid Geojson Object.
Here Fiddler with my example: http://jsfiddle.net/ior88/5ea8yxwo/4/
 $scope.FilteredGeojson = function () {

    var result;

    result = $filter('filter')($scope.data, $scope.search);

    $scope.geojson = result;
    return result;
};

If you will look into console there you will see error.
I don't get it because when i display geojson or geojson_watch in {{}} it looks the same as geojson in data, So assume the problem here is filtering? I will be really thankful to somebody who will tell me where i make errors

A: First off, what you are showing is not a GeoJSON object. That Leaflet's L.GeoJSON accepts just an array of features, doesn't make it a valid GeoJSON object, so you shouldn't call it a GeoJSON object. It's an array of GeoJSON feature objects. In a valid GeoJSON featurecollection object the feature array is contained like this:
{
    "type": "FeatureCollection",
    "features": [
        // The features
    ]
}

Next, you're trying to filter some complex objects in a way that doesn't work. Here is how $filter('filter') works:
var simpleArray = [{
  'name': 'Foo'
}, {
  'name': 'Bar'
}];

$filter('filter')(simpleArray, {'name': 'Foo'}); // Returns array with Foo object
$filter('filter')(simpleArray, {'name': 'Bar'}); // Returns array with Bar object
$filter('filter')(simpleArray, {'name': 'Foobar'}); // Returns empty array

Example on Plunker: http://plnkr.co/edit/I7OGfoJLwaCz0XibcTDB?p=preview
What you are trying to do with $filter('filter'):
var complexArray = [{
  'properties': {
    'name': 'Foo'
  }
}, {
  'properties': {
     'name': 'Bar'
  }
}];

$filter('filter')(complexArray, {'name': 'Foo'}); // Returns empty array
$filter('filter')(complexArray, {'name': 'Bar'}); // Returns empty array
$filter('filter')(complexArray, {'name': 'Foobar'}); //Returns empty array

Example on Plunker: http://plnkr.co/edit/rUtseKWCeyLiewDxnDDn?p=preview
Why? Because the objects in the array do not have a property called name. They only have a property called properties, that contains an object and that does have a name property. You can't expect the filter to recursivily go searching through your object untill it finds a name property. It doesn't. It only does when you explictly tell it to do so:
$filter('filter')(complexArray, {'properties': {'name': 'Foo'}}); // Returns with Foo
$filter('filter')(complexArray, {'properties': {'name': 'Bar'}}); // Returns with Bar
$filter('filter')(complexArray, {'properties': {'name': 'Foobar'}}); // Returns empty

Example on Plunker: http://plnkr.co/edit/LpOvr7Zxw5C5A3Tt5umQ?p=preview
So you'll need to setup your logic a bit different, say you want to search for two properties, id and name In your scope you would have:
$scope.search = {
  'properties': {}
};

$scope.$watch('search', function (newVal, oldVal) {
  if (newVal !== oldVal) {
    $scope.data = $filter('filter')($scope.source, $scope.search);
  }
}, true);

And in your template:
<input ng-model="search.properties.id" placeholder="ID" />
<input ng-model="search.properties.name" placeholder="Name" />

Now everytime you use one of the inputs, the watch on the search property gets fired, which filters the source and updates the data. To reflect that change in your directive also, you've also got to put a watch on the data object in the link method of your directive. In there you can update the layer with the new data:
scope.$watch('data', function (newVal, oldVal) {
    if (newVal !== oldVal) {
        geojsonLayer.clearLayers();
        geojsonLayer.addData(scope.data);
    }
}, true);

Entire code in a working example on Plunker: http://plnkr.co/edit/CmfBdmt7BYKPmE22HLvl?p=preview

A: This error comes from here in the Leaflet code, and indicates that the GeoJSON contained a Geometry object without a valid type property. You'll need to investigate why your code is generating such an object.


text:
Q: Use a function with an argument of a derived type (F#) I've got a class in my application - for simplicity let's assume it's defined like this:
type baseType() =
    member this.A = 5.

Also, I've got a lot of functions that take objects of this type as an argument. Moreover, some of them take an array of this type:
let myFun (xArr : baseType[]) =
    // ... do something inspirig ;)

Now I realized, that it would be nice to have another class which derives from "baseType". e.g.:
type inhType() =
    inherit baseType()
    member this.B = 8.

However, I can't use the arrays of inherited type with the functions like "myFun"
let baseArr = [| baseType() |]
let inhArr = [| inhType() |]

myFun baseArr
myFun inhArr // won't work

which would be "nice to have". Is there a simple way to re-use my functions without applying so many changes ?
I guess one of the solution is to map my array using e.g. the function (fun (d : inhType) -> d :> baseType), but I'm wondering if there's anything else could be done.

A: You can also populate an array of A with instances of a subtype, B, by using a type annotation:
let bArr: A[] = [| B() |]

This could be useful for one-off usage or if the function is in a third party library. Another common usage is creating boxed arrays (obj[]).

A: You need to annotate your function as accepting a flexible type.
type A() = class end
type B() = inherit A()

let aArr = [| A() |]
let bArr = [| B() |]

// put # before type to indicate it's a flexible type
let f (x : #A[]) = ()

f aArr
f bArr  // works!


text:
Q: Odd error when capturing function parameter in Swift call to animateWithDuration:Animations: I'm writing some simple animation code to make a button get taller and then shorter using UIView animations. The code is a little long, but fairly simple:
func animateButton(aButton: UIButton, step: Int)
{
  let localStep = step - 1

  let localButton = aButton
  let halfHeight = aButton.bounds.height / 2

  var transform: CGAffineTransform
  switch step
  {
  case 2:
    //Make the center of the grow animation be the bottom center of the button
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 1.2)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        //------------------------------------
        //--- This line throws the error ---
        animateButton(aButton, step: 1)
        //------------------------------------
    })
  case 1:
    //In the second step, shrink the height down to .25 of normal
    transform = CGAffineTransformMakeTranslation(0, -halfHeight)

    //Animate the button to 120% of it's normal height.
    transform = CGAffineTransformScale( transform, 1.0, 0.25)
    transform = CGAffineTransformTranslate( transform, 0, halfHeight)
    UIView.animateWithDuration(0.5, animations:
      {
        aButton.transform = transform
      },
      completion:
      {
        (finshed) in
        animateButton(aButton, step: 0)
    })
  case 0:
    //in the final step, animate the button back to full height.
    UIView.animateWithDuration(0.5)
      {
        aButton.transform = CGAffineTransformIdentity
    }
  default:
    break
  }
}

The completion blocks for the animation methods are closures. I'm getting an error "Call to method animateButton in closure requires explicit self. to make capture semantics explicit.
The thing is, the parameter aButton is a parameter to the enclosing function. There is no reference to an instance variable.
It looks to me like this is compiler bug. Am I missing something here?

A: Calling methods in the same class are called with an implied self.  In this case because of the closure you have to make it explicit:
self.animateButton(aButton, step: 1)


text:
Q: how to deploy python app on iis windows server? hi i am trying to deploy my python app on windows2012 server with iis .
i follow the process of add application in website on specific folder than changing handler mapping settings in adding handler script putting python path in it.
when i am trying to open it code show me text of app.py instead of running it.
only difference when i tried is that in his python code he started with
 #!iusr
and i started directly have my python code.
source where i tried
https://www.youtube.com/watch?v=7whncKjSXK0
anyone have any clue
thanks for help

A: First, create python site for example mine is hello.py and place it under C:\pythonsite folder:
print('Content-Type: text/plain')
print('')
print('Hello, world!')

*

*now open iis manager.

*add a new site. select your python site folder and add bindings.

*

*now click on the handler mapping from the middle pane.

*

*in the handler mapping window select "add script map" from the action pane.

 - add below details:
request path: *.py
executable: C:\Python37-32\python.exe %s %s
name:python
"C:\Python37-32\"  is your python folder.

*

*click request restrictions and make sure that the checkbox is unchecked.

*

*when you click on ok it will open a prompt click "yes".

Note: make sure directory browsing is enabled and your python and site folder has iis_iusrs and iusr permission assigned with full control. you install iis CGI feature.

*

*browse the site.


text:
Q: Vector radius with triangle and inscribed circle Can you give me hints on how to solve this one: Knowing the radius-vectors  r1, r2 and r3, of vertex of triangle, find radius vector of center of circle inscribed inside that triangle.
So basically I should somehow represent that radius vector of center of that circle with r1, r2 and r3?
What should I use to express in terms of them?

A: Let $a = |\mathbf{r_2} - \mathbf{r_3}|, b = |\mathbf{r_3} - \mathbf{r_1}|, c = |\mathbf{r_1} - \mathbf{r_2}|$. Then the position vector $\mathbf{r}$ of the incenter is given by
\begin{align*}
\mathbf{r} = \frac{a\mathbf{r_1} +b\mathbf{r_2}+c\mathbf{r_3}}{a+b+c}
\end{align*}

A: Observe first of all that if $|B-A|=|C-A|$ then vector $(B-A)+(C-A)$ is parallel to the bisector of $\angle BAC$. For a generic triangle $ABC$ we can then construct a vector $v_A$ parallel to the bisector of $\angle BAC$ as follows:
$$
v_A={B-A\over|B-A|}+{C-A\over|C-A|}.
$$
Any point $P$ on that bisector can be then represented as $P=A+tv_A$, where $t$ is any real number. In the same way, you can construct $v_B$ and represent any point $Q$ on the bisector of $\angle ABC$ as $Q=B+sv_B$, where $s$ is any real number.
The incenter you are after is the intersection of those two bisectors. To find it, just solve for $t$ and $s$ the equation: $A+tv_A=B+sv_B$.


text:
Q: Dynamic creation of forms.ImageField in Django Sorry for my English.
I have a problem with the forms.ImageField. The problem is, that I want to set initial value to this field dynamically and widget ClearableFileInput will display the "Current link" and checkbox. I read somewhere, that I have to pass dictionary File with  attribute url, and then, widget knows to display it. But I don't know how pass it properly...
if attr.type == "Img":
    self.fields [title] = forms.ImageField (required = bool(required))

    # Where here, I have to assign an initial value.
    # Thank you.

A: You can assign value to ImageField while rendering the form such as
initialValues={
'textField1':'value for text field 1',
'textField2':'value for text field 2',
'imageField': someModel.objects.get(id=someId).logo
}

form = myForm(initial=initialValues)

A: it's work , i just need to assign to initial value , object of type ImageFieldFile
self.fields[title].initial = ImageFieldFile (file)


text:
Q: What kind of verb is do when people say "I do"? I was reading The Wolf's Side of the Story. On the third paragraph, it says

Everybody knows the story of the Three Little Pigs. Or at least they think they do.

How is "they do" used in this sentence? Why wouldn't you use "they do know" to make the sentence clearer instead?

A: In this case, "do" is echoing the original verb without actually using it.

I heard the car alarm go of... or I thought I did.
  They see a mysterious floating object in the sky... or they think they do.

Repeating the verb is also an option, though without do/did.

I heard the car alarm go off... or I thought I heard it/the alarm.
  They see a mysterious floating object in the sky... or they think they see one/a mysterious floating object.
  Everybody knows the story of the Three Little Pigs. Or at least they think they know it/the story.

By using do/did, you avoid having to repeating both the verb and a pronoun or the noun itself.
Your recommended version would likely be understandable but non-standard.


text:
Q: Using a dynamic precision value in number_to_currency based on the decimal value Thoughout our app we use number_to_currency(value, :precision => 2).  However, we now have a requirement whereby the value may need displaying to three or more decimal places, e.g.
0.01  => "0.01"
10    => "10.00"
0.005 => "0.005"

In our current implementation, the third example renders as:
0.005 => "0.01"

What's the best approach for me to take here?  Can number_to_currency be made to work for me?  If not, how do I determine how many decimal places a given floating point value should be displayed to?  sprintf("%g", value) comes close, but I can't figure out how to make it always honour a minimum of 2dp.

A: The following will not work with normal floats, because of precision problems, but if you're using BigDecimal it should work fine.
def variable_precision_currency(num, min_precision)
  prec = (num - num.floor).to_s.length - 2
  prec = min_precision if prec < min_precision
  number_to_currency(num, :precision => prec)
end

ruby-1.8.7-p248 > include ActionView::Helpers

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("10"), 2)
$10.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("0"), 2)
$0.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.45"), 2)
$12.45

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.045"), 2)
$12.045

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("12.0075"), 2)
$12.0075

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-10"), 2)
$-10.00

ruby-1.8.7-p248 > puts variable_precision_currency(BigDecimal.new("-12.00075"), 2)
$-12.00075


text:
Q: Creating Tkinter widgets with Objects Button and Window - how to put button created using Button class onto window created with Window class UIconstruction.py
import tkinter

class Window:

    def __init__(self):
        self.height = None
        self.width = None
        self.title = None

    def setDimensions(self, height, width):
        self.height = height
        self.width = width

    def setTitle(self, title):
        self.title = title

    def GetDimensions(self):
        dimensionsDict = {
            "Height": self.height,
            "Width": self.width
        }

        return dimensionsDict

    def getTitle(self):
        return self.title

    def startWindow(self):
        Window.tk = tkinter.Tk()
        Window.tk.geometry(f"{self.width}x{self.height}")
        Window.tk.title(self.title)
        Window.tk.mainloop()

class Button:

    def __init__(self):
        self.height = None
        self.width = None
        self.label = None
        self.container = None

    def setDimensions(self, height, width):
        self.height = height
        self.width = width

    def GetDimensions(self):
        dimensionsDict = {
            "Height": self.height,
            "Width": self.width
        }

        return dimensionsDict

    def setLabel(self, labelText):
        self.label = labelText

    def getLabel(self):
        return self.label

    def createButton(self):
        button = tkinter.Button(text = self.label, width = self.width, height = self.height)

main.py
from UIconstruction import Window, Button

background = Window()
button1 = Button()

background.setDimensions(500, 500)
background.setTitle("Test")
background.startWindow()

button1.setDimensions(100, 100)
button1.setLabel("test")
button1.createButton()

What I want is for 'button1' is to be in the window 'background', but I have not been able to figure out how to do this (incorrect attempts omitted)
Is there a way to do this with this setup - if so, how?
If there is not a way to do this like this, how should I be doing it optimally.
I'm a relative python beginner, so I don't know much more than the basics past object oriented support.
Thanks!

A: This code has many mistakes - and this can make big problem.
First: you should keep tk.Tk() as self.tk instead of Window.tk
Second: you need backgroud.tk to assign button. But this makes problem. You have to create tk.Tk() before you create Button() (to use it as parent for for Button()), but you have to run mainloop() after adding Button() to Window() (because mainloop() blocks rest of code)

You should send it as parameter
button1 = Button(background.tk)

and keep it in __init__
class Button:

    def __init__(self, parent):
        self.height = None
        self.width = None
        self.label = None
        self.container = None

        self.parent = parent

and use it when you create real tk.Button
    def createButton(self):
        button = tkinter.Button(self.parent, text=self.label, width=self.width, height=self.height)   # PEP8: inside `()` use `=` without spaces

Eventually you could send it directly to createButton()
    def createButton(self, parent):
        button = tkinter.Button(parent, text=self.label, width=self.width, height=self.height)   # PEP8: inside `()` use `=` without spaces

and run it as
button1.createButton(background)

And you have to also use .pack(), .grid() or .place() to show widget in window.
    def createButton(self):
        button = tkinter.Button(self.parent, text=self.label, width=self.width, height=self.height)   # PEP8: inside `()` use `=` without spaces
        button.pack()

Full working code
import tkinter

class Window:

    def __init__(self):
        self.height = None
        self.width = None
        self.title = None

    def setDimensions(self, height, width):
        self.height = height
        self.width = width

    def setTitle(self, title):
        self.title = title

    def GetDimensions(self):
        dimensionsDict = {
            "Height": self.height,
            "Width": self.width
        }

        return dimensionsDict

    def getTitle(self):
        return self.title

    def create(self):
        self.tk = tkinter.Tk()
        self.tk.geometry(f"{self.width}x{self.height}")
        self.tk.title(self.title)

    def startWindow(self):
        self.tk.mainloop()

class Button:

    def __init__(self, parent):
        self.height = None
        self.width = None
        self.label = None
        self.container = None
        self.parent = parent

    def setDimensions(self, height, width):
        self.height = height
        self.width = width

    def GetDimensions(self):
        dimensionsDict = {
            "Height": self.height,
            "Width": self.width
        }

        return dimensionsDict

    def setLabel(self, labelText):
        self.label = labelText

    def getLabel(self):
        return self.label

    def create(self):
        self.button = tkinter.Button(self.parent, text=self.label, width=self.width, height=self.height)
        self.button.pack()

#from UIconstruction import Window, Button

background = Window()

background.setDimensions(500, 500)
background.setTitle("Test")
background.create()

button1 = Button(background.tk)

button1.setDimensions(100, 100)
button1.setLabel("test")
button1.create()

background.startWindow()

EDIT:
Code would be more useful if you would create window and button in __init__ and you would use special function to set values in  widgets because in current code you can't use setLabel to change text in button after creating it.


text:
Q: How to reduce few minutes for current date in Swift 2.0 How can I  reduce 5 or 10 minutes from current time and then store it as date format in Swift 2.0 ?
let now = NSDate()
var reducedTime = ???? \\ Here I want 10 minutes reduced from current time.

If current time is  02:20:00, then reducedTime should be 02:10:00
How can I do this in a simplest way ???

A: You can use calendar method dateByAddingUnit and subtract 10 minutes fro the date.
let now = NSDate()

let reducedTime = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)?.dateByAddingUnit(.Minute, value: -10, toDate: now, options: NSCalendarOptions())


text:
Q: Obtaining the last elements of an array I have a string that looks like this:
Current working dir is /usr/local/Cellar/clamav/0.99.4/share/clamav
Max retries == 5
ERROR: Can't create temporary directory /usr/local/Cellar/clamav/0.99.4/share/clamav/clamav-07bc3bfeabec6a3bd40e8c2fdf126323.tmp
Hint: The database directory must be writable for UID 501 or GID 20

Running data=$(echo $string | grep -o -E '[0-9]+') it provides a variable that looks like this: 0 99 4 5 0 99 4 07 3 6 3 40 8 2 126323 501 20. I'm assuming this is an array because when I run the following:
for el in "${data[@]}"
do
  echo "${el}"
done

It will output:
...
99
4
07
...
501
20

What I need to do is get the last two numbers in this array (?) and put them into a command. How can I successfully extract the last two numbers from the given array?

A: You don't have an array, you need more parentheses :
$ data=( $(echo $string | grep -o -E '[0-9]+') )
$ echo "${data[-1]}"
20

A: use
./my-script.sh | tail -2 | my-next-command

or write it to a temp file

A: As mentioned by Giles I do not have an array. I was however able to get the UID and GID into separate variables using the following:
data=$(echo $string | grep -o -E '[0-9]+')
usersUID=${data: -2}
echo $usersUID
#<= 20
usersGID=$(echo $data | tail -c 7 | cut -c1-3)
echo $usersGID
#<= 501


text:
Q: Passing dictionary values in python as command line inputs to c++ code I have a wrapper file that is reading a JSON file into a dictionary.
I am using the os.system("command") command to run a C++ code in this python file.
The C++ code takes command line inputs which are key values in the parsed dictionary.
How can i pass a python variable as a command line input for a C++ code using the os.system("command") instruction?

A: You can't do that unless you relax one of the restrictions.
Relax the python dict requirement:  The command line has a well defined text arguments interface, which can easily handle all the info.  You can pass the json filename, the str representation of the dict, or pass name-value pairs as command line arguments.
Relax the system call requirement: Rather than building an executable from the c++ code, you can build a python c++ extension.  The c++ code can export functions that take a python dict.
Relax the c++ requirement: Obviously you could code it in python.


text:
Q: Multiple listview in a activity programatically populated from database I have created listviews programatically and added them into horizontal scrollview as shon in image

And My Activity
    package com.example.dynamiclistviewtest;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ScrollView;

public class MainActivity extends ActionBarActivity {
    //LinearLayout llListView;
    LinearLayout llMain;
    ListView[] listView;
    private HorizontalScrollView scrollListView;
    private int counter = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scrollListView = (HorizontalScrollView)findViewById(R.id.scrollListView);
        //llListView = (LinearLayout) findViewById(R.id.llListView);
        llMain = (LinearLayout)findViewById(R.id.llMain);
        listView = new ListView[5];

        //Onclick listener
        Button.OnClickListener btnpayClick = new Button.OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter++;
                Button button = (Button) v;
                button.setText("Button "+counter);
            }

        };

        LayoutInflater inflator = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        ArrayList<ArrayList<HashMap<String, String>>> arr = new ArrayList<ArrayList<HashMap<String, String>>>();

        for (int pages = 0; pages <10 ; pages++) {
            LinearLayout llViewHolder = new LinearLayout(this);
            llViewHolder.setOrientation(LinearLayout.VERTICAL);
            llViewHolder.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT,1.0f));
            for (int page_row = 0; page_row < 2; page_row++) {
                LinearLayout row = new LinearLayout(this);
                row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT,1.0f));
                llViewHolder.addView(row);
                for (int sale = 0; sale< 3; sale++) {
                    View item = inflator.inflate(R.layout.view_inflate, null);
                    ListView listofItems = (ListView) item.findViewById(R.id.listView1);
                    Button btnpay = (Button)item.findViewById(R.id.btnpay);
                    btnpay.setOnClickListener(btnpayClick);
                    btnpay.setText("pay "+sale);
                    LayoutParams lpll = new LinearLayout.LayoutParams(300,300,1.0f);
                    lpll.setMargins(30, 10, 10, 10);
                    listofItems.setLayoutParams(lpll);
                    String[] data = new String[]{"Ashok","Shaishavi","jatin","Akansha","Aditi","Bhavesh","Rajesh","Roshni","Heema"};
                    ArrayAdapter<String> arrAdapater = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
                    listofItems.setAdapter(arrAdapater);

                    /*listView[i] = new ListView(this);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200,100);
                    lp.setMargins(10, 10, 10, 10);
                    listView[i].setLayoutParams(lp);
                    listView[i].setBackgroundColor(getResources().getColor(R.color.red));
                    llListView.addView(listView[i]);*/

                    row.addView(item);
                }

                //listView[3].setVisibility(View.INVISIBLE);
            }
            llMain.addView(llViewHolder);
        }

    }

}

and xml layout  file activity_main  which contains horizontal scrollview and a linear layout to hold all views and code for this layout file as below:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <HorizontalScrollView
        android:id="@+id/scrollListView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/llMain"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="1" >
        </LinearLayout>
    </HorizontalScrollView>
    <!--<LinearLayout
        android:id="@+id/llListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </LinearLayout>-->

</LinearLayout>

and view that I have inflated from view_inflate.xml file it's code is as:
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="540dp"
        android:layout_weight="1"
        android:background="@color/paybtn_lgreen" >
    </ListView>

    <Button
        android:id="@+id/btnpay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Payment" />

</LinearLayout>

Now I want to populate all listviews that I have added from local database sqlite, How can I achieve   this?