text:
Q: Unable to mount EFS to ECS on fargate trying to mount EFS to ECS Fargate but getting below error while task is being executed. it looks as though it is an IAM issue but crosschecked all the roles and unable to identify the issue. Checked security groups as well.i allowed 2049 port and attached ecs security group to it.

"ResourceInitializationError: failed to invoke EFS utils commands to set up EFS volumes: stderr: b'mount.nfs4: access denied by server while mounting 127.0.0.1:/' : unsuccessful EFS utils command execution; code: 32"

Terraform 0.12 and Fargate 1.4.0
resource "aws_efs_file_system" efs {
  creation_token   = "${var.prefix}-${var.appName}-ecs"
  encrypted        = true
  kms_key_id       = data.aws_kms_key.efs_kms_key.arn
  performance_mode = var.performance_mode
  throughput_mode  = var.throughput_mode
  tags            = var.tags
}

resource "aws_efs_mount_target" efs_mount {

  count           = length(module.vpc_presets.subnet_ids)
  file_system_id  = aws_efs_file_system.efs.id
  subnet_id       = flatten(module.vpc_presets.subnet_ids)[count.index]
  security_groups = data.terraform_remote_state.remote_state_sg.outputs.efs_sg

}
resource "aws_efs_access_point" this  {
  file_system_id = aws_efs_file_system.efs.id
}

data "template_file" jenkins_container_def {
  template = file("${path.module}/templates/jenkins.json.tpl")

  vars = {
    name                = "${var.prefix}-${var.appName}-${var.env}"
    jenkins_controller_port = var.jenkins_port
    jnlp_port           = var.jnlp_port
    source_volume       = "${var.appName}-efs"
    jenkins_home        = "/var/jenkins_home"
    container_image     = var.image
    region              = var.deployment_region
    account_id          = var.account
    log_group           = data.terraform_remote_state.remote_state_ecs.outputs.logs_name
    memory              = var.jenkins_memory
    cpu                 = var.jenkins_cpu
  }
}

resource "aws_ecs_task_definition" jenkins_controller {
  family = var.appName
  task_role_arn            = data.terraform_remote_state.remote_state_iam.outputs.master_task_arn
  execution_role_arn       = data.terraform_remote_state.remote_state_iam.outputs.jenkins_execution_arn
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = var.jenkins_cpu
  memory                   = var.jenkins_memory
  container_definitions    = data.template_file.jenkins_container_def.rendered

  volume {
    name = "${var.appName}-efs"

    efs_volume_configuration {
      file_system_id     = data.terraform_remote_state.remote_state_efs.outputs.efs_fs_id
      transit_encryption = "ENABLED"

      authorization_config {
        access_point_id = flatten(data.terraform_remote_state.remote_state_efs.outputs.efs_access_point_id)[0]
        iam             = "ENABLED"
      }
    }
  }

  tags = var.tags
}

resource "aws_ecs_service" jenkins_controller {
  name = "${var.prefix}-${var.appName}-controller-service"

  task_definition  = aws_ecs_task_definition.jenkins_controller.arn
  cluster          = data.terraform_remote_state.remote_state_ecs.outputs.ecs_cluster_id
  desired_count    = 1
  launch_type      = "FARGATE"
  platform_version = "1.4.0"

  // Assuming we cannot have more than one instance at a time. Ever.
  deployment_maximum_percent         = 100
  deployment_minimum_healthy_percent = 0

  service_registries {
    registry_arn = aws_service_discovery_service.controller.arn
   }

  load_balancer {
    target_group_arn = data.terraform_remote_state.remote_state_alb.outputs.tg_arn
    container_name   = "${var.prefix}-${var.appName}"
    container_port   = 8080
  }

  network_configuration {
    subnets          = flatten([module.vpc_presets.subnet_ids])

    security_groups  = data.terraform_remote_state.remote_state_sg.outputs.ecs_sg
    assign_public_ip = false
  }
  tags           = var.tags
}

A: I had a related problem because the directory has not yet been created, there is a property in root_directory that allows creating the directory with proper permissions.
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/efs_access_point#creation_info
In the example I use root, but you can set another gid.
resource "aws_efs_access_point" this  {
  file_system_id = aws_efs_file_system.efs.id
  root_directory {
    path = "/desired-directory"
    creation_info {
      owner_gid = 0
      owner_uid = 0
      permissions = "755"
    }
  }
}

A: this WORKED for me!

*

*delete and recreate EFS via AWS CLI as below.

*create 2 mount points inside EFS

*add security group flag to compose (--security-groups sg-0x1578xxxxdbc94x4)

Delete old and re-Create file system programatically
export AWS_EFS_FILESYSTEM_ID=$( \
  aws efs create-file-system \
    --creation-token hello-world-efs \
    --no-encrypt \
    --throughput-mode bursting \
    --performance-mode generalPurpose \
    --region us-west-2 \
    | jq --raw-output ".FileSystemId"
)

Create mount targets
aws efs create-mount-target \
  --file-system-id ${AWS_EFS_FILESYSTEM_ID} \
  --security-groups ${AWS_EC2_SECURITY_GROUP} \
  --subnet-id ${AWS_SUBNET_ID_1}

aws efs create-mount-target \
  --file-system-id ${AWS_EFS_FILESYSTEM_ID} \
  --security-groups ${AWS_EC2_SECURITY_GROUP} \
  --subnet-id ${AWS_SUBNET_ID_2}

This solution is from: https://github.com/aws/amazon-ecs-cli/issues/1083

A: It was an IAM policy issue. issues got fixed after changing the policy.


text:
Q: Does $f^{-1}(Y)$ make sense if $Y$ is "bigger" than $X$ My textbook asks me to decide whether or not this expression is true:

Given the function $f: X \to Y$ with $B_1 \subseteq Y $.
  $ f^{-1}(Y $ \ $ B_1) = X $ \ $f^{-1}(B_1) $

I was confused because there is no assumption that the function $f$ is onto. Hence there might be an element $y \in Y$ such that for no $x \in X$, $f(x) = y$. I actually don't know if in this case the expression $f^{-1}(Y)$ makes sense.

A: One Interpretation (probably wrong):
If $f: X \rightarrow Y$ and you assume that   $f^{-1}$ exists as a mapping at element level from $Y \rightarrow X$, then $f$ must be not only surjective but also injective. From that you can then show $f^{-1}(Y \setminus B_1) = X \setminus f^{-1}(B_1)$.
Another Interpretation (probably correct):
Using the suggested notataion in comments, $f^{-1} [B_1] = \{x \in X\colon f(x) \in B_1\}$ and $f^{-1} [Y] = \{x \in X\colon f(x) \in Y\}= X$ (assuming that $f$ is follows the normal definition of a fucntion from $X$).
$$\begin{align}
f^{-1} [Y \setminus  B_1] &=  \{ x \in X\colon f(x) \in Y  \setminus  B_1\}\\
&=\{ x \in X\colon f(x) \in Y  \land f(x) \notin B_1\}\\
&= \{  x \in X\colon x \in X \land x \notin f^{-1} [B_1]\}\\
&= X  \setminus f^{-1} [B_1].
\end{align}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: This code works, but breaks the media uploader. How do I integrate it in a way that won't? I wrote some custom code which I've stuck into the media upload panel using a filter. It does a couple of things. First, it changes the text for the "submit" button for users who add things through the uploader. Second, it makes it so that the contents of the File URL field automatically enters the image upload input for a form I created when an image for it is uploaded through the media uploader. (that's the JQuery). Finally, there's CSS to hide elements of the media uploader that users don't need to see.
When this function is in the functions.php file, it causes the media library to stall in loading up the images. It just hangs on the spinning grey ball. But it also works.
How can I integrate this code into the site in a way that doesn't keep the media uploader from working?
add_filter('attachment_fields_to_edit', 'my_plugin_action_button', 20, 2);

function my_plugin_action_button($form_fields, $post) {

  $send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Use Photo' ) . "' />";

  $form_fields['buttons'] = array('tr' => "\t\t
	$send
\n");
  ?>

  <?php
  return $form_fields;
}

A: Check if media html elements have previous classes, probably You removed some class from media window (button i guess) and some js functions can not be triggered like hide().

A: I think you have to change only two places (see arrows):
....
$form_fields['buttons'] = array('tr' => "\t\t
	$send
\n");
?>
                                                                                ⇧⇧⇧


text:
Q: How to make a clean .htaccess? i have problem with htaccess and not quite good at it. I want to know how to make a url clean.
Here is the original

http://site.com/page.php?p=index1/index2

and i want this type of url

http://site.com/page/index/index2

and how do i get the p value which is index1/index2 if i what to $_get it from the database?

A: The pattern ([^/]+) matches everything up to but not including / into $1 and the remainder is captured in (.*) into $2.
RewriteEngine On
# Don't rewrite real existing files & directories (like css,js,img)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Add .php to the first group (like page.php) and stick the rest into p
RewriteRule ^([^/]+)/(.*)$ $1.php?p=$2

Inside of PHP, retrieve the value of p via:
$_GET['p']


text:
Q: How can I modify the protected values of a variable of a base class in a derived class function? class abc{
protected:
    int x;
};
class b: public abc{
public :
    void something(abc a){ a.x = 1;}
};

I get an error in the second last line stating that I cannot access member x of variable a.

Error: Protected Member "abc::x" is not accessible through a "abc" point or object.

Is there another way to modify the x-value of variable a?

A: You can do simply as follows in derived class
void something(){ x = 1;}

Demo: http://coliru.stacked-crooked.com/a/b0f6153abfe6b783

A: Within something() you are in object scope, so you have a pointer to the current object with the this keyword. In C++, however, the default resolution within object scope, is the object's own scope, so you don't need to prefix it at all. Simply referring the property's name is enough to have the resolution succeed.

A: When inheriting, b can modify the values of the base class "it" inherited, but the base abc protected class attributes of other objects are still protected and reserved for themselves. In this case the abc a object you pass through the function something is another object not associated with an object b.
Access modifiers work on class level, meaning within an object b the private attributes of another object b can be accessed. However, this inheritance shown is basically saying that "b is an abc, but abc isn't necessarily b". In the function void something(abc a){ a.x = 1;}, if you change it to something(b a) instead, it would work, because a b can access another b.
However, remember that if:
int main(){
    abc data;
    abc data2;

    data.x = data2.x; //This won't work becuase you are outside the class
}

What you can do is declaring class b a friend of class abc, so that any object b can access the protected members of any other object abc.
Example:
class abc{
protected:
    int x;

friend class b;
};

A: One way to do what you are asking is to have a function setX() in class ABC like such:
class abc
{
    public:
        void setX(int x){ this->x = x; }
    protected:
        int x;
};

Then declare something inside of class B like this:
class b: public abc
{
    public :
        void something(abc a){ a.setX(1); }
};

At that point though you might as well not have class B at all, but rather from the scope you are calling b.something(myABCObj) just call myABCObj.setX(1) instead.
The point of 'protected' is that class b has access to 'x' in class abc not through the parameter you are passing it but rather inside of itself.
For example, your class b could look like this:
class b: public abc{
    public :
        void something(){ x = 1; } //HA- I inherited a value from class abc that wasn't public and changed it!
};

So in a different scope you could create object b myB; and myB.x won't be allowed but myB will have access to 'x' inside of itself from its parent class.


text:
Q: Create gradle sample project for eclipse (java web) I use gradle for some time and I want to create my own sample projects for eclipse like those IDE already contains 'Java Quickstart', 'flat-java-multiproject'. Is it possible to do it? If yes, how can I do it? WHy I want to do it? Because it is annoying to create new project manually everytime.

A: For those who are interested in I solved this problem in this way http://github.com/pepuch/gradleTemplatesCreator. Project was created for my own usage so it's not clear and finished.


text:
Q: Why do the child widgets of my custom UITableViewCell stack on top of each other? I have a custom UITableViewCell that I've designed in a storyboard. The custom cell contains a label and a text field. The label should be on the left side of the cell and the text field should be on the right side. But no matter what combination of constraints I try (constraining the right side of the text field to the right side of the cell, spacing the left side of the text field 300 pixels from the label, etc...) the text field always ends up stacked on the label when I run my app.
Here's a screenshot of a portion of the storyboard

In this image, the trailing edge of the text field is set to the trailing margin of its parent.
This is what it looks like in the app.

This is my code for the custom table cell class:
class ItemRowCell: UITableViewCell {
@IBOutlet weak var itemDescription: UILabel!
@IBOutlet weak var quantity: UITextField!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

A: You've set something incorrectly... I suggest, start fresh.
Delete the current Label and Text Field.
Add a new label to your cell prototype, and set the Leading Constraint to 0 and the Vertical Constraint to Centered - should look like this:

Add a new Text Field, and set the Trailing Constraint to 0, the Vertical Constraint to Centered, and the Width Constraint to 80:

Re-connect your @IBOutlets, and run the app.


text:
Q: How to hide user dashboard details in WordPress? I'm trying to hide details from the backend user (not admin) WordPress dashboard like Recently Published From our Blog WordPress Events and News Admin Colour Scheme Help Activity Screen Options
I haven't been able to locate the html (php/javascript?) for any of it but located some html for the colour scheme picker as follows:

Personal Options

Admin Color Scheme

<fieldset id="color-picker" class="scheme-list">
<legend class="screen-reader-text">Admin Color Scheme.
</legend>
<input type="hidden" id="color-nonce" name="color-nonce"
value="98ec68455d" />

<input name="admin_color" id="admin_color_fresh" type="radio"
value="fresh" class="tog"  checked='checked' />
<input type="hidden" class="css_url" value="" />
<input type="hidden" class="icon_colors" value="{"icons":
{"base":"#a0a5aa",
"focus":"#00a0d2","
current":"#fff"}}" />
Default

<input name="admin_color" id="admin_color_light" type="radio"
value="light" class="tog"  />
<input type="hidden" class="css_url" value="https://adsler.co.uk/wp-
admin/css/colors/light/colors.min.css" />
<input type="hidden" class="icon_colors" value="{"icons":
{"base":"#999","focus"
:"#ccc","current":"#ccc"}}" />
Light

Tried css:
 #tab-panel-overview {visibility: hidden;}

.help-tab-content active {visibility: hidden;}

.form-table {visibility:hidden; display:none;}

.user-admin-color-wrap {visibility: hidden; display: none;}

Also tried:
.scheme-list {visibility:hidden;}

Nothing.

A: You mean the admin dashboard widgets?
You can hide them with following wordpress action.
function remove_dashboard_widgets() {
    global $wp_meta_boxes;

    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']);
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

}

add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );

A: Please add this through a plugin or add the code to your functions.php.
This is tested and will work.See screenshot attached
function stackinnerflow_remove_dashboard_widgets() {
    global $wp_meta_boxes;

    // Remove At a glance
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
    // Remove Activity
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity']);
    // Remove News and Events
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
}

add_action('wp_dashboard_setup', 'stackinnerflow_remove_dashboard_widgets' );

// removes the `profile.php` admin color scheme options
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );

// Remove thanks WP
add_action('admin_head', 'stackinnerflow_footer_remove');

function stackinnerflow_footer_remove() {
  echo '';
}

// remove the Help Tab use

add_action('admin_head', 'stackinnerflow_remove_help_tabs');
function stackinnerflow_remove_help_tabs() {
    $screen = get_current_screen();
    $screen->remove_help_tabs();
}

//remove the Screen Options Tab
add_filter('screen_options_show_screen', '__return_false');

If your wrap all the code for users below the level of administrator capabilities any user as editor or lower will not see this apart from the administrators.
if (current_user_can('editor')) {}
If you want to loop over a number of other capabilities, check this question: https://wordpress.stackexchange.com/questions/131814/if-the-current-user-is-an-administrator-or-editor


text:
Q: WINAPI/Winapi C++, отрисовка Bitmap При отрисовке изображения Bitmap оно накладывается на само себя, а если выносить вне, то происходит мерцание изображения.
void DrawBitmap(HDC hDC, int x, int y, HBITMAP hBitmap)
{
    HBITMAP hbm, hOldbm;
    HDC hMemDC;
    BITMAP bm;

    // Создаем контекст памяти, совместимый
    // с контекстом отображения
    hMemDC = CreateCompatibleDC(hDC);

    // Выбираем изображение bitmap в контекст памяти
    hOldbm = (HBITMAP)SelectObject(hMemDC, hBitmap);

    // Если не было ошибок, продолжаем работу
    if (hOldbm)
    {

        // Определяем размеры изображения
        GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);

        // Рисуем изображение bitmap
        TransparentBlt(hDC, x, y, bm.bmWidth, bm.bmHeight,
            hMemDC, 0, 0, bm.bmWidth, bm.bmHeight, RGB(0, 0, 0));

        // Восстанавливаем контекст памяти
        SelectObject(hMemDC, hOldbm);
    }

    // Удаляем контекст памяти
    DeleteDC(hMemDC);
}

void Draw(HDC* hdc)
{
    HDC hMem = CreateCompatibleDC(*hdc);
    SelectObject(hMem, BGround);
    AddPlanets(&hMem);
    BitBlt(*hdc, 0, 0, sizeX, sizeY, hMem, 0, 0, SRCCOPY);
    DeleteDC(hMem);
}

void AddPlanets(HDC * hdc)
{
    DrawBitmap(*hdc, MovementPlanet(150).first, MovementPlanet(150).second, Planets[0]);
}

Вызываю Draw в WM_PAINT + есть Timer, который вызывает InlidateRect
Как сделать, чтобы не накладывался?

A: Вам надо просто использовать теневой буфер.
void Paint(PAINTSTRUCT &ps)
{
    HDC hMemDC, hTempDC;
    HGDIOBJ hMemBmp, hSysBmp;
    int cx, cy;

    // создаем теневой буфер
    cx = ps.rcPaint.right - ps.rcPaint.left;
    cy = ps.rcPaint.bottom - ps.rcPaint.top;
    hMemDC = CreateCompatibleDC(ps.hdc);
    hMemBmp = CreateCompatibleBitmap(ps.hdc, cx, cy);
    hSysBmp = SelectObject(hMemDC, hMemBmp);
    SetViewportOrgEx(hMemDC, ps.rcPaint.left, ps.rcPaint.top, nullptr);

    hTempDC = CreateCompatibleDC(ps.hdc);

    // закрашиваем фон
    SelectObject(hTempDC, hBkBitmap);
    BitBlt(hMemDC, ps.rcPaint.left, ps.rcPaint.top, cx, cy, hTempDC, ps.rcPaint.left, ps.rcPaint.top, SRCCOPY);

    // накладываем прозрачный растр
    SelectObject(hTempDC, hTransparentBitmap);
    TransparentBlt(hMemDC, ps.rcPaint.left, ps.rcPaint.top, cx, cy, hTempDC, ps.rcPaint.left, ps.rcPaint.top, cx, cy, RGB(0, 0, 0));

    SelectObject(hTempDC, hSysBmp);
    DeleteDC(hTempDC);

    // выводим содержимое теневого буфера на экран
    BitBlt(ps.hdc, ps.rcPaint.left, ps.rcPaint.top, cx, cy, hMemDC, ps.rcPaint.left, ps.rcPaint.top, SRCCOPY);

    SelectObject(hMemDC, hSysBmp);
    DeleteObject(hMemBmp);
    DeleteDC(hMemDC);
}

Для примера, я накидал похожий по функционалу проект
на основе стандартной болванки vs:
Готовый exe
Архив с проектом


text:
Q: malloc pointer to array int (*p)[2];
p=(int(*))malloc(sizeof(int[2])*100);

What is the right way to malloc a pointer to an array?
I can't figure out the part with (int(*))

A: Posting comments as answer:
In C you should not to cast the return value of malloc. Please refer this post on SO for more information regarding why typecasting return value of malloc is not a good idea in C. And if for some reason you really really want to cast, it should be (int(*)[2]). (int(*)) is int *. The size passed to malloc looks fine (allocating size for 100 pointers to array of 2 ints). So you should be doing
int (*p)[2];
p=malloc(sizeof(int[2])*100);

Hope this helps!

A: It's not clear what you want here.  If you want 100 int pairs, for example, arranged as an array of pointers to int (where each pointer points to exactly two ints), then you need to call malloc 100 times on 100 pointers to int, allocating two integers each time.
It just doesn't' make sense to "malloc a pointer to an array".  You can malloc an array, and assign that address to a pointer though, or you can malloc an array of pointers.  But what you've asked is not clear.


text:
Q: How to confirm the payment was success in 2checkout integration I created a test demo account in 2checkout.And i tested  some code to do a demo payment in 2checkout.
in the account , i set 'demo setting' 'On'
Everything goes correctly,and i am  getting hash match on the return page.
Following is my code.
index.php
<form action='https://www.2checkout.com/checkout/spurchase' method='post'>
<input type='hidden' name='sid' value='123456' >
<input type='hidden' name='mode' value='2CO' >
<input type='hidden' name='li_0_type' value='product' >
<input type='hidden' name='li_0_name' value='Test' >
<input type='hidden' name='li_0_price' value='2.00' >
<input type='hidden' name='li_0_quantity' value='4' >
<input type='hidden' name='li_0_tangible' value='N' >
<input type='hidden' name='currency_code' value='INR' >
<input name='submit' type='submit' value='Checkout' >
</form>

return.php
if ($_REQUEST['demo'] == 'Y')
{
    $order_number = 1;
}
else
{
    $order_number = $_REQUEST['order_number'];
}
$hashSecretWord = '2checkout';
$compare_string = $hashSecretWord . $_REQUEST['sid'] . $order_number . $_REQUEST['total'];
$compare_hash1 = strtoupper(md5($compare_string));
$compare_hash2 = $_REQUEST['key'];

if ($compare_hash1 != $compare_hash2)
{
    echo "Hash Mismatch";
}
else
{
    echo "Hash Matched";
}

How to confirm that whether the payment was success or not ?
i can't  see the demo orders in my account
But I am getting mails about each orders .Also iam getting "HAsh Matched" in return.php page.
I also created a API username  & password.
How to do these payment process using the API details?

A: Your script is validating the hash correctly. 2Checkout demo sales will not show in your account as they do not actually create a sale in 2Checkout's system. When placing a live sale, the sale record will show in your account under the sales tab.
2Checkout's back office API can be used for retrieving or updating live sales that have already been placed but it cannot be used to create a sale. Sales need to be passed in along with the buyer to 2Checkouts secured server to complete the payment.
Feel free to reach out to 2Checkout's integrations department at techsupport@2co.com if you would like additional assistance with your integration.


text:
Q: Can we add putImageData to fabric canvas instead of fromURL fabric.Image.fromURL(hc.toDataURL(), function(img) {
             // add image onto canvas
            Canvas.add(img);
            img.hasControls = false;
            img.hasBorders = false;
            img.hasControls = false;
            img.hasRotatingPoint = false;
            img.selectable = false;
        });
Above code helps in rendering a image to canvas but I want to use something like putImageData/drawImage because I have to draw the image from another canvas . And as per real time operation using toDataURL for more than 5 MB images is very bad when performance comes to picture.
I also want to render the image on the middle of the canvas .
Fabricjs just takes the image toDataURL and renders it as it is.
Any help will be appreciated.

A: fabric.Image() just like the row ctx.drawImage accepts a canvasElement as imageSource.
So you can just call it like
canvas.add(new fabric.Image(yourCanvasToDraw));

And if you want it centered in the canvas :
canvas.add(new fabric.Image(c, {left: canvas.width/2-c.width/2, top: canvas.height/2-c.height/2}));

Note that ctx.getImageData+ctx.putImageData is at least as slow as ctx.toDataURLwhich both are incredibly slower than ctx.drawImage


text:
Q: get YouTube videoID from gdata.youtube.com/feeds/api/videos (YouTube api) Using jQuery and YouTube api.
I've been trying for a while to simply get the ID's of the searched videos, seems like or either i'm blind or the guys from youtube wants us to work more than necessary ;-)
#search = 'mad max';

$.ajax({
    url: "http://gdata.youtube.com/feeds/api/videos?q=" + escape($("#search").val()) + "&alt=json&max-results=30&format=5",
    dataType: "jsonp",
    success: function (data) {showVideoList(data)}
});

function showVideoList(data) {
    console.log(data);
}

I get lots of information but the videos ID's. Ok I can get it from:
data.feed.entry[0].entrymedia$group.media$player[0].url

But will have to use regExp and might change in the future. There is no property in this object where I can get just the videoID ?

A: Try this:
var id = data.feed.entry[0].id.$t.split('/').reverse()[0];

A: To add on to Šime's answer, you can use 'pop' instead of reversing the whole array:
var id = data.feed.entry[0].id.$t.split('/').pop();

A: Since this is highly ranked on google it's worth noting that now youtube returns the videoid as:
feed.entry[0].media$group.yt$videoid.$t


text:
Q: How to set timestamp on update event in SQL Server? While creating a table or alter the table using the below command getting the below error

Incorrect syntax near the keyword 'on'

Please help me - how to set on update timestamp?
create table my_table
(
    index1 char(32) not null primary key,
    title varchar(50),
    my_timestamp timestamp not null
         default current_timestamp on update current_timestamp
);

A: The datatype Timestamp is auto generated by SQL Server it self, you cannot specify a default constraint on it.
See documentation
Timestamp is deprecated and rowversion should be used.

A: TIMESTAMP in SQL Server is NOT  something to store date & time values. It's an internal, binary counter - aptly renamed ROWVERSION by now.
If you need to store date and time, use DATEITME2(n) instead.
create table my_table
(
    index1 char(32) not null primary key,
    title varchar(50),
    my_timestamp datetim2(3) not null
);

Unfortunately, to get the "last date & time row was modified" functionality, you'll need to use a trigger - you cannot do this using a DEFAULT constraint...


text:
Q: What exactly is the toggle option for Pages in Settings > [your name] > Pages for? It apparently does not good If you have the iCloud Drive turned on, the Pages files get stored on iCloud Drive and if it is off, they are stored locally. This is decided on the option set in Settings > Pages and there you select where to save. What exactly is the toggle option for Pages in Settings > [your name] > Pages for? (It's right below the iCloud Drive toggle)
This is the toggle option I'm talking about (also, personal info has been removed, in case the picture looks weird) :


text:
Q: What type of server Django runserver uses? What type of server Django uses when "runserver" command is ran? Documentation says more or less that it's "lightweight development Web server". Is it for example Apache? Thanks in advance.

A: It's exactly what it says on the tin - a simple, lightweight web server implemented in Python that ships with Django and is intended for development purposes only. It's not a free-standing web server in its own right and is intended purely for developing applications with Django - you should never use it in production because it simply doesn't offer all the functionality you need in a production web server.
A web server can be implemented in virtually any programming language, and so it makes sense to ship one implemented in Python with Django in order that you can get working with it immediately without having to install something like Apache as well. Most web servers that might be used in production, such as Apache and Nginx, are written in C so it wouldn't really be practical to ship them with Django.
Also, shipping your own development server cuts down on complexity. Apache and Nginx are both complex pieces of software that require a fair amount of configuration, and while there are ways to automate that during development, it's not something you really want to have to deal with when you'd rather be writing code. All you need to get you started is something that will serve static and dynamic content - you don't need a lot of the other functionality required. It's notable that even PHP now ships with a development server.
When you go live with a Django project, you should use of course use a proper web server. It's generally recommended that with Django, in production you should use two web servers, one to serve static content, the other to serve dynamic content, because involving Django in serving static content will slow it down. This sounds odd at first, but it actually makes a lot of sense, because what you do is set one web server to serve all the static content, then have it reverse proxy to the other server, which is running on a non-standard port, and serves all the  dynamic content. The setup I have for my current project is Nginx for the static content, with Gunicorn for the dynamic content.


text: Q: is it necessary to call `enable_irq()` after `devm_request_threaded_irq()` Trying to understand when one should call enable_irq(), and would like to know is it really necessary to call enable_irq() after devm_request_threaded_irq() call that register and interrupt handler for Linux interrupt number, and there must be always disable_irq() for a enable_irq() call?


text:
Q: ClassPathXmlApplicationContext return FileNotFoundException exception when try to open beans xml file i'v got an error exception :
INFOS: Loading XML bean definitions from class path resource [ma/openbook/www/beans/perons.xml]
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [ma/openbook/www/beans/perons.xml]; nested exception is java.io.FileNotFoundException: class path resource [ma/openbook/www/beans/perons.xml] cannot be opened because it does not exist
i did not understand wath should i do to resolve this issue, i though that's the code is correct
could someone help me please. i will be thankful
http://i.stack.imgur.com/d78ZK.jpg

A: Maven, by default, does not move non-.java files from /src/main/java into the target build. Instead move your persons.xml resource to /src/main/resource, in the appropriate package.
Also, you seem to have a typo: perons.xml vs persons.xml.


text:
Q: Return pointer to array I'm trying to return a pointer to an array for my function prototype.
class NAV
{
    string date;
    float nav;
public:
    NAV(const string&);
};

const int HistorySize = 300;

class MutualFund
{
    string ticker;
    NAV* history[HistorySize];
public:
    MutualFund(const string& ticker_, const string& historyFile);
    ~MutualFund();
    NAV** getArray() const{return history;}
    void report() const;

};

For NAV** getArray() const{return history;}, I'm getting a compiler error:
error: invalid conversion from 'NAV* const*' to 'NAV**' [-fpermissive]
Any ideas?

A: In NAV** getArray() const{return history;} const means the programmer promises that calling this function will not cause changes to the state of the MutualFund. By returning a non-const pointer, NAV**, you are opening up the possibility for the state to be changed through use of the returned pointer. The compiler will not allow this and is telling you that it can only return a pointer to constant data: NAV* const*.

A: Your getter is a const method, so during its execution, all data members are considered const as well.  That's why the conversion error says it is converting from const to non-const, since your return value is non-const.


text:
Q: Can you bypass a category's behavior in Objective-C? I have a category on UINavigationBar, the drawRect function of which draws a custom logo in the nav bar. There is one view controller in my app which i would not like to draw the custom logo for.
Is there a way to bypass the category's drawRect function?

A: Use two different subclasses of UINavigationBar and put the category on one of the two subclasses.

A: Nope; you can't.   Or, you can (through swizzling), but you shouldn't.   Namely, you are modifying system behavior, which is a good way to either cause crashes in the future or potentially have your app rejected.
Typically, if you want to customize a class's behavior, you do so by subclassing and using instances of the subclass.

A: You're probably doing something wrong, against the HIG, if you need to do this.
Matt Gallagher wrote an article about invoking the 'supersequent' implementation which may be used in this case.
Note that this not the proper way to achieve such a thing, even if it works now it's very likely to break in the future, I'd advise not to use such techniques!

A: This is a problem you will no longer face in ios5 as using a category to "override" drawRect in the navigation bar is not supported any more.
You should look into the new UIAppearance changes, or as Daniel says, use multiple subclasses of UINavigationBar.


text:
Q: Is there a way to create a new shared drive through PowerShell script? How do I create a new shared drive with the provided credentials on the computer that is running the script?
Is there a PowerShell cmdlet that does that?

A: Just use "net use" inside your powershell scripts:

new use z: \\server\share /user:domain\username password

A: This powershell function should work:
Function NEW-SHARE ($Foldername, $Sharename) {
   # Test for existence of folder, if not there then create it
   #
   IF (!(TEST-PATH $Foldername)) {
       NEW-ITEM $Foldername -type Directory }
   # Create Share but check to make sure it isn't already there
   #
   If (!(GET-WMIOBJECT Win32_Share -filter "name=$Sharename") {
       $Shares.Create($Foldername,$Sharename,0)}
}

The following article on technet provides more information:
http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/16/how-to-use-powershell-to-create-shared-folders-in-windows-7.aspx


text:
Q: Android: error inflating extended class I know you'll have seen this question before. I know I have :-). But still, combing all the answers I have found I still get the inflating class error. My layout has an extended webView as I want to be able to swipe left and right in order to load previous and next html pages.
I include the entire layout as I find that most of the answers I have found present a solution in a somewhat abstract manner dealing with just the webView and not as a part of a larger picture. Hopefully when this is answered it will help others to get the bigger picture as well.
The scrollview at the bottom wil contain buttons as an alternative means of navigating the html pages. The view imageView2 will contain a transparent header partly obscuring the underlying webView. The textView helloText will display the chapter titles. I had all of this working until I had to extend the webView to deal with the left right swipes.
Here's the layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.8"
        android:orientation="vertical" >

        <com.example.test.MyWebView
            android:id="@+id/webView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" />

        <View
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:background="#88FF0000"/>
    </RelativeLayout>

    <TextView
        android:id="@+id/helloText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.05"
        android:gravity="center_horizontal"
        android:text="Hello World" />

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.15"
            android:background="#0000FF" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:orientation="horizontal" >

             <Button
            android:id="@+id/button1"
            android:layout_width="110dp"
            android:layout_height="45dp"
            android:background="#00FF00" />

        </LinearLayout>
    </HorizontalScrollView>

</LinearLayout>

and this is the code:
package com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends Activity {

int currentPage = 2; // page number for current html file

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

    //get a pointer to the webview
    MyWebView webview = (MyWebView) findViewById(R.id.webView1);

    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setSupportZoom(true);
    webview.getSettings().setBuiltInZoomControls(true);

    // put html page in the webView
    webview.loadUrl("file:///android_asset/chapter" + currentPage + ".html");
}

public void changePage(int page) {

    Log.v("test", "change page to " + page);

    //get a pointer to the webview
    MyWebView webview = (MyWebView)findViewById(R.id.webView1);

    // put html page in the webView
    webview.loadUrl("file:///android_asset/chapter" + page + ".html");

    }

class MyWebView extends WebView {
     Context context;
     GestureDetector gd;

    public MyWebView(Context context, AttributeSet attrs) {
    super(context, attrs);

    this.context = context;
         gd = new GestureDetector(context, sogl);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return (gd.onTouchEvent(event)
                || super.onTouchEvent(event));
    }

     GestureDetector.SimpleOnGestureListener sogl = new GestureDetector.SimpleOnGestureListener() {
      public boolean onDown(MotionEvent event) {
       return false;
      }
      public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
       if (event1.getRawX() > event2.getRawX() && StrictMath.abs(event1.getRawY()-event2.getRawY())<100) {
        show_toast("swipe left");
        currentPage += 1;
        if (currentPage >= 19) currentPage = 19;
        changePage(currentPage);
       } else if(event1.getRawX() < event2.getRawX() && StrictMath.abs(event1.getRawY()-event2.getRawY())<100){
        show_toast("swipe right");
        currentPage -= 1;
        if (currentPage <= 1) currentPage = 1;
        changePage(currentPage);
       } else {
         return false;
       }
    return true;
      }
     };

     void show_toast(final String text) {
      Toast t = Toast.makeText(context, text, Toast.LENGTH_SHORT);
      t.show();
     }
    }
}

The actual error reads:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class com.example.test.MyWebView
Thanks in advance for your help. Much appreciated.
Mr. Jigs
As requested the full error trace:
01-23 10:21:51.980: E/AndroidRuntime(29514): FATAL EXCEPTION: main
01-23 10:21:51.980: E/AndroidRuntime(29514): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class com.example.test.MyWebView
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.os.Looper.loop(Looper.java:137)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at java.lang.reflect.Method.invokeNative(Native Method)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at java.lang.reflect.Method.invoke(Method.java:511)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at dalvik.system.NativeStart.main(Native Method)
01-23 10:21:51.980: E/AndroidRuntime(29514): Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class com.example.test.MyWebView
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:749)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:308)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.Activity.setContentView(Activity.java:1924)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at com.example.test.MainActivity.onCreate(MainActivity.java:21)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.Activity.performCreate(Activity.java:5206)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
01-23 10:21:51.980: E/AndroidRuntime(29514):    ... 11 more
01-23 10:21:51.980: E/AndroidRuntime(29514): Caused by: java.lang.ClassNotFoundException: com.example.test.MyWebView
01-23 10:21:51.980: E/AndroidRuntime(29514):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.createView(LayoutInflater.java:552)
01-23 10:21:51.980: E/AndroidRuntime(29514):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
01-23 10:21:51.980: E/AndroidRuntime(29514):    ... 22 more

A: Make sure you add all these constructors in your custom webview class.
    public CustomWebView(Context context) {
        super(context);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

And also don't forget to use this CustomWebView class in xml layout file with your complete package name.
 <com.kittykitty.meowmeow.CustomWebView
                android:id="@+id/my_webview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />

A: MyWebView class is internal of MainActivity class. Inflater does not see this class. Make your WebView in defferent .java file.
Also you can try to use that name in your layout file <com.example.test.MainActivity.MyWebView/>, but i'm not sure about it.

A: // try this way
1. Custom WebView Class
public class MyWebView extends WebView {
    Context context;
    GestureDetector gd;
    OnPageChangleListener listener;
    private int currentPage=1;
    private int startPageIndex;
    private int lastPageIndex;

    public MyWebView(Context context) {
        super(context);
       init(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        gd = new GestureDetector(context, sogl);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return (gd.onTouchEvent(event)
                || super.onTouchEvent(event));
    }

    public void setOnPageChangeListener(OnPageChangleListener listener){
        this.listener = listener;
    }

    public void setStartPageIndex(int startPageIndex){
        this.startPageIndex = startPageIndex;
    }

    public int getStartPageIndex(){
        currentPage = startPageIndex;
        return startPageIndex;
    }

    public int getLastPageIndex(){
        return lastPageIndex;
    }

    public void setLastPageIndex(int lastPageIndex){
        this.lastPageIndex = lastPageIndex;
    }
    GestureDetector.SimpleOnGestureListener sogl = new GestureDetector.SimpleOnGestureListener() {
        public boolean onDown(MotionEvent event) {
            return false;
        }
        public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
            if (event1.getRawX() > event2.getRawX() && StrictMath.abs(event1.getRawY()-event2.getRawY())<100) {
                currentPage += 1;
                if (currentPage > lastPageIndex){
                    currentPage = lastPageIndex;
                    show_toast("Last Page");
                }else{
                    show_toast("swipe left");
                    listener.onPageChange(currentPage);
                }
            } else if(event1.getRawX() < event2.getRawX() && StrictMath.abs(event1.getRawY()-event2.getRawY())<100){
                currentPage -= 1;
                if (currentPage < startPageIndex) {
                    currentPage = startPageIndex;
                    show_toast("First Page");
                }else{
                    show_toast("swipe right");
                    listener.onPageChange(currentPage);
                }
            } else {
                return false;
            }
            return true;
        }
    };

    void show_toast(final String text) {
        Toast t = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        t.show();
    }

}

2. Custom Interface for you Custom WebView page change listener.
public interface OnPageChangleListener {
    public void onPageChange(int pageNo);
}

3. Use Custom WebView in your Activity.
 MyWebView myWebView;

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

        myWebView = (MyWebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setUseWideViewPort(true);
        myWebView.getSettings().setSupportZoom(true);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.setStartPageIndex(2);
        myWebView.setLastPageIndex(4);
        myWebView.setOnPageChangeListener(new OnPageChangleListener() {
            @Override
            public void onPageChange(int pageNo) {
                System.out.println(String.valueOf(pageNo));
                myWebView.loadUrl("file:///android_asset/" + pageNo + ".html");
            }
        });

        myWebView.loadUrl("file:///android_asset/" + myWebView.getStartPageIndex() + ".html");

}
4.main.xml
<?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">
    <com.example.Demo.MyWebView
        android:id="@+id/myWebView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>


text:
Q: Recursively Totaling File Content I am trying to write a Python script that will take a directory as input and look through that directory recursively and output the file names and their sizes to a file. At the end it totals the entirety of the directory. The output is okay and fits what I need but all file sizes are being listed at 4096 when I run this code on the /var directory. Below is code:
#!/usr/bin/python
import os

#print usage for input directory and accepts input

print("Example: /home/cn")
input_file = raw_input("Enter the name of the directory: ")

#prints usage for output file and accepts input

print("Example: /home/cn/Desktop/output_test.txt")
output_file = raw_input("Enter the name of the output file: ")

#opens output file for writing, sets variable for directory size to 0

of = open(output_file, "w")
start_path = input_file
total_size = 0

#loops recursively, calculates directory size

for (path,dirs,files) in os.walk(start_path):
    of.write(format(path))
    of.write(" " + str(os.path.getsize(path)) + "\n")
    for file in files:
        fstat=os.stat(os.path.join(path,file))
        size = os.stat(path).st_size
        total_size = total_size + size

#writes output to file

of.write("\n" + "Directory: " + input_file + "\n")
of.write("The total size of the directory is: " + str(total_size))

And also a screenshot of the output file when this is run on the /var directory:

A: You're not producing the file path at all. You need to join the file name with the current path in order to get the file path and only then get the size of the file in question:
for path, dirs, files in os.walk(start_path):
    full_path = os.path.abspath(os.path.realpath(path))  # just to cover symlinks
    of.write("{} {}\n".format(full_path, os.path.getsize(full_path)))  # not a real size!
    for file in files:
        file_path = os.path.join(full_path, file)  # get the file path
        size = os.stat(file_path).st_size  # get the actual file stats
        of.write(" {} {}\n".format(file_path, size))  # write the file path and size
        total_size += size

A: It is because you are just checking for root path size.
Instead try below code
for (path,dirs,files) in os.walk(start_path):
    of.write(format(path))
    of.write(" " + str(os.path.getsize(path)) + "\n")
    for dir in dirs:
        dir_path = os.path.join(path, dir)
        of.write(format(dir_path))
        of.write(" " + str(os.path.getsize(dir_path)) + "\n")

Try this !


text:
Q: Gravity contradicting conservation of energy? If we could utilize gravitational force to create energy, could gravity, being unlimited, generate unlimited energy?
Consider electricity generation from tides. Since tides are due to gravity, aren't we creating energy from an unlimited source and thus generating unlimited energy?
This seems highly contradictory to conservation of energy.
What am I missing?

A: Tides gradually reduce the internal kinetic energy and gravitational potential energy of the Earth-Moon system, that is, the speed and height of the Moon's orbit.
Whether or not humans extract some electricity from it along the way, the same amount of energy per tide ends up as random thermal internal energy in the materials that make up the Earth and the Moon. The Earth and Moon are doing work on each other; harvesting tidal energy lets us redirect a tiny fraction of this work to our own purposes before it ends up dissipated as heat.
The energies available are exceedingly large relative to the energies dissipated.
Our Moon is actually on a (very, very slow) outward spiral. The energy dissipated by tides on Earth and on the Moon (which lacks water, of course, but rock still deforms a little bit) acts to counteract this. If the Earth-Moon system were left alone forever, tidal energy dissipation would eventually stop the outward spiral and begin an inward spiral, eventually ending either with the Moon crashing into the Earth or perhaps developing an orbital eccentricity that eventually would result in the moon being captured by another body's gravity and leaving Earth forever. I haven't seen the calculation, but the estimate I've seen projected for time at which the outward spiral would stop and the inward spiral would begin is about fifty billion years from now, with collision or ejection at about 65 billion years. https://en.wikipedia.org/wiki/Timeline_of_the_far_future

A: You are missing the fact that the tidal energy you convert into electricity comes from the relative motion of the Moon and the Earth. Very gradually, that motion is slowing down as energy is lost through tidal effects. So energy is conserved, as the gain in tidal energy is offset by the loss of kinetic energy of the Earth and the Moon.


text:
Q: How to access elements within array of arrays in Angular 4 based on indexing? I want to iterate only the first element of the array in a table in Angular 4 (for TV AD 1, for weeks ranging from 2/10/2017 to 29/1/2018).But I am facing challenge as it is iterating over all the elements of the table(for all TV ads 1,2,3,4).
Please find my code below:
JSON:
      public calendarTable = [
      { name: "TV AD1",
          weeks: [
          { period: "2/10/2017", price: "400" },
          { period: "9/10/2017", price: "800" },
          { period: "16/10/2017", price: "200" },
          { period: "23/10/2017", price: "500" },
          { period: "30/10/2017", price: "600" },
          { period: "6/11/2017", price: "800" },
          { period: "13/11/2017", price: "700" },
          { period: "20/11/2017", price: "800" },
          { period: "27/11/2017", price: "900" },
          { period: "4/12/2017", price: "400" },
          { period: "11/12/2017", price: "800" },
          { period: "18/12/2017", price: "200" },
          { period: "25/12/2017", price: "500" },
          { period: "1/1/2018", price: "600" },
          { period: "8/1/2018", price: "800" },
          { period: "15/1/2018", price: "700" },
          { period: "22/1/2018", price: "800" },
          { period: "29/1/2018", price: "900" }
          ]
      },
      { name: "TV AD2",
          weeks: [
            { period: "2/10/2017", price: "500" },
            { period: "9/10/2017", price: "600" },
            { period: "16/10/2017", price: "700" },
            { period: "23/10/2017", price: "800" },
            { period: "30/10/2017", price: "900" },
            { period: "6/10/2017", price: "100" },
            { period: "13/10/2017", price: "200" },
            { period: "20/10/2017", price: "300" },
            { period: "27/10/2017", price: "400" },
            { period: "4/12/2017", price: "400" },
            { period: "11/12/2017", price: "800" },
            { period: "18/12/2017", price: "200" },
            { period: "25/12/2017", price: "500" },
            { period: "1/1/2018", price: "600" },
            { period: "8/1/2018", price: "800" },
            { period: "15/1/2018", price: "700" },
            { period: "22/1/2018", price: "800" },
            { period: "29/1/2018", price: "900" }
            ]
          },

      { name: "TV AD3",
          weeks: [
            { period: "2/10/2017", price: "500" },
            { period: "9/10/2017", price: "600" },
            { period: "16/10/2017", price: "700" },
            { period: "23/10/2017", price: "800" },
            { period: "30/10/2017", price: "900" },
            { period: "6/10/2017", price: "100" },
            { period: "13/10/2017", price: "200" },
            { period: "20/10/2017", price: "300" },
            { period: "27/10/2017", price: "400" },
            { period: "4/12/2017", price: "400" },
            { period: "11/12/2017", price: "800" },
            { period: "18/12/2017", price: "200" },
            { period: "25/12/2017", price: "500" },
            { period: "1/1/2018", price: "600" },
            { period: "8/1/2018", price: "800" },
            { period: "15/1/2018", price: "700" },
            { period: "22/1/2018", price: "800" },
            { period: "29/1/2018", price: "900" }
            ]
          },

      { name: "TV AD4",
        weeks: [
          { period: "2/10/2017", price: "500" },
          { period: "9/10/2017", price: "600" },
          { period: "16/10/2017", price: "700" },
          { period: "23/10/2017", price: "800" },
          { period: "30/10/2017", price: "900" },
          { period: "6/10/2017", price: "100" },
          { period: "13/10/2017", price: "200" },
          { period: "20/10/2017", price: "300" },
          { period: "27/10/2017", price: "400" },
          { period: "4/12/2017", price: "400" },
          { period: "11/12/2017", price: "800" },
          { period: "18/12/2017", price: "200" },
          { period: "25/12/2017", price: "500" },
          { period: "1/1/2018", price: "600" },
          { period: "8/1/2018", price: "800" },
          { period: "15/1/2018", price: "700" },
          { period: "22/1/2018", price: "800" },
          { period: "29/1/2018", price: "900" }
            ]
          }
   ]

HTML:

                        {{data.period}}

Please assist me in this regard

A: Just add [0] to your calenderTable... check the code below...

                    {{data.period}}

or you could go like this...

                    {{data.period}}

A: Extract the array & keep it in a variable before looping.Since calendarTable is an array of object calendarTable[0] will give first object & calendarTable[0].weeks will give value of the week key from that object
var toLoop = calendarTable[0].weeks;

A: Take the first item of an array(calendarTable) and loop through weeks.

           {{data.period}}

A: If you need to dynamically select each of the table's object, you can do like this:
In your service:
private calendarTable = [
  // this is the table you already have
];

getAdsNames(): string[] {
  return Array.from(this.calendarTable, ad => ad.name);
}

getAd(adName: string): any {
  return this.calendarTable.filter(ad: => ad.name === adName)[0];
}

In your component:
availableAds: string[];
activeAd: any;

ngOnInit() {
  this.availableAds = this.myService.getAdsNames();

  // Loads the first ad from the list
  this.activeAd = this.setActiveAd(this.availableAds[0]);
}

setActiveAd(adName: string) {
  this.activeAd = this.myService.getAd(adName);
}

In your template:

    {{week.period}}

<select [(ngModel)]="selectedAd" (ngModelChange)="setActiveAd($event)">
  <option *ngFor="let ad of availableAds" [ngValue]="ad">
    {{ ad }}
  </option>
</select>

If you don't need to dynamically change the ads, you should still use a service to handle your data and simply request the value when you need it (e.g. On component's init - within the ngOnInit method) and making it available for the template.
P.S.: You should avoid using any as I have used (to simplify the example) and create a model for your ads.
Cheers


text:
Q: How to update new value field on customer_entity table? I am new to magento 2, and I would like to know how to update an added field in the customer_entity table, I have created a popup form with sending the information through post jquery, and the controller receives the information to be able updated in the database.
But the consumer field is not updated in the database, any suggestions?
Below the code:

/app/code/ElTiempo/ModalOverlay/Setup/UpgradeSchema.php

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

/**
 * Class UpgradeSchema
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    /**
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        if (version_compare($context->getVersion(), '1.0.1', '<')) {
            $this->addHabeasDataField($setup);
        }
    }

    /**
     *  table
     *
     * @param \Magento\Framework\Setup\SchemaSetupInterface $setup
     */
    protected function addHabeasDataField($setup)
    {
        $setup->startSetup();

        // Get module table
        $tableName = $setup->getTable('customer_entity');

        // Check if the table already exists
        if ($setup->getConnection()->isTableExists($tableName) == true) {
            // Declare data
            $columns = [
                'accept_habeas_data_datetime' => [
                    'type' => Table::TYPE_TIMESTAMP,
                    null,
                    'nullable' => true,
                    'comment' => 'Accept Habeas Data Datetime'
                ],
            ];

            $connection = $setup->getConnection();

            foreach ($columns as $name => $definition) {
                $connection->addColumn($tableName, $name, $definition);
            }
        }

        $setup->endSetup();
    }
}

/app/code/Vendor/Module/view/frontend/templates/view.phtml

date_default_timezone_set("America/New_York");
        $currentDateTime = date("Y-m-d H:i:s");
        $currentDateTimeStamp = strtotime($currentDateTime);
        if ($currentDateTimeStamp >= strtotime("2020-12-17 16:00:00")) {
            if ($content = $block->getContent('popup-habeas-data')) {
        ?>
            <div id="modal-habeas-data" style="display:none;">
                <form action="<?php  echo $block->getBaseUrl() . 'accepthabeasdata/index/update';?>"
                    method="post"
                    id="form-validate"
                    enctype="multipart/form-data"
                    autocomplete="off"
                    data-mage-init='{"validation":{}}'
                    data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
                    <?php echo $content ?>
                    <input type="hidden" name="accept_habeas_data_datetime" value="<?php echo $currentDateTime ?>">
                </form>
            </div>
            <script type="text/x-magento-init">
                {
                    "*": {
                        "Magento_Ui/js/core/app": {
                            "components": {
                                "modal_habeas_data": {
                                    "component": "Vendor_Module/js/modal_habeas_data"
                                }
                            }
                        }
                    }
                }    </script>
        <?php
            }
        }

/app/code/Vendor/Module/view/frontend/web/js/modal_habeas_data.js

initialize: function () {

        this._super();
        var options = {
            type: 'popup',
            responsive: true,
            innerScroll: false,
            title: false,
            clickableOverlay: false,
            opened: function($Event) {
                $('.modal-header button.action-close', $Event.srcElement).hide();
            },
            buttons: [{
                text: $.mage.__('Aceptar'),
                class: 'btn btn-primary',
                click: function () {
                    var form_data = $("#form-validate").serialize();
                    console.log(form_data);

                    $.ajax({
                        url: "accepthabeasdata/index/update",
                        type: 'POST',
                        data: form_data,
                        success: function(data) {
                            console.log(data);
                        },
                        error: function(result) {
                            console.log('no response !');
                        }
                    });

                    this.closeModal();
                }
            }]
        };

        var modal_habeas_data_element = $('#modal-habeas-data');
        var popup = modal(options, modal_habeas_data_element);

        modal_habeas_data_element.css("display", "block");

        this.openModalHabeasDataModal();

    },

/app/code/Vendor/Module/etc/frontend/routes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="acceptHabeasData" frontName="accepthabeasdata">
            <module name="Vendor_Module"/>
        </route>
    </router>
</config>

/app/code/Vendor/Module/Controller/Index/Update.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Controller\Index;

class Update extends \Magento\Framework\App\Action\Action
{
    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerSession;
    protected $customerRepository;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    )
    {
        $this->customerSession = $customerSession;
        $this->customerRepository = $customerRepository;
        return parent::__construct($context);
    }

    public function execute()
    {
        $customerId =  $this->customerSession->getCustomer()->getId(); //Get Current customer ID
        echo $customerId;
        $data = $this->getRequest()->getParams('accept_habeas_data_datetime');
        var_dump($data);
        $customer = $this->customerRepository->getById($customerId);
        $customer->setCustomAttribute('accept_habeas_data_datetime', $data);
        $this->customerRepository->save($customer);
    }
}

A: I have the solution, I needed to create before the attribute with the same name of the field. With this I have been able to update the data in the customer_entity table

/app/code/Vendor/Module/Setup/UpgradeData.php

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Quote\Setup\QuoteSetupFactory;
use Magento\Sales\Setup\SalesSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Customer\Api\CustomerMetadataInterface;

/**
 * @codeCoverageIgnore
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * @var SalesSetupFactory
     */
    private $salesSetupFactory;

    /**
     * @var QuoteSetupFactory
     */
    private $quoteSetupFactory;

    /**
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * UpgradeData constructor.
     * @param CustomerSetupFactory $customerSetupFactory
     * @param SalesSetupFactory $salesSetupFactory
     * @param QuoteSetupFactory $quoteSetupFactory
     * @param \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
     * @param \Magento\Eav\Model\Config $eavConfig
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        SalesSetupFactory $salesSetupFactory,
        QuoteSetupFactory $quoteSetupFactory,
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->salesSetupFactory = $salesSetupFactory;
        $this->quoteSetupFactory = $quoteSetupFactory;
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    /**
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {

        $installer = $setup;
        $installer->startSetup();

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        if (version_compare($context->getVersion(), '1.0.1') < 0) {

            $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

            $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
            $attributeSetId = $customerEntity->getDefaultAttributeSetId();

            $attributeSet = $this->attributeSetFactory->create();
            $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

            $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'accept_habeas_data_datetime', [
                'type' => 'static',
                'label' => 'Accept Habeas Data',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'user_defined' => true,
                'sort_order' => 1000,
                'position' => 1000,
                'system' => 0,
            ]);

            $eavSetup->addAttributeToSet(
                CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
                CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
                null,
                'accept_habeas_data_datetime');

            $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'accept_habeas_data_datetime')
                ->addData([
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId,
                    'used_in_forms' => ['adminhtml_customer','customer_address_edit','adminhtml_customer_address', 'customer_register_address','customer_account_edit', 'customer_account_create']
                ])->save();;

        }

        $installer->endSetup();
    }
}


text:
Q: MySQL find_in_set() function skips an item in the set I'm having a very strange issue with the MySQL find_in_set() function.  Three tables, as follows.  The query at the bottom is looking for all users whose positions are listed in activity_assoc for the particular activity.  In other words: "Which people have this activity?".
It should find all three users; but for some reason it skips the position in the middle, and only returns user 1 and 3. (Actual data has more people. It is clearly skipping a particular position -- as though "DOP" were not on the list in activity_assoc.positions.)
users_master
id    first_name        last_name        position_id
-----------------------------------------------------------
1     Eblis             O'Shaugnessy     13
2     JimmyJojo         Shamadou         20
3     Bob               Justbob          25

positions
id    position              abbreviation
---------------------------------------------
13    Director of Stuff     DOS
20    Director of Peoples   DOP
25    Director of Ideas     DOI

activity_assoc
id    activity              positions
----------------------------------------------
47    Make Things Happen    DOS,DOP,DOI

SELECT DISTINCT `users`.`id`, `users`.`first_name`, `last_name`, `position`, `activity_assoc`.`positions`
FROM `activity_assoc`,
    (
        SELECT `users_master`.*, `positions`.`abbreviation` AS `position`
        FROM `users_master` LEFT JOIN `positions` ON `users_master`.`position_id` = `positions`.`id`
    ) AS `users`
WHERE
    `activity_assoc`.`activity` = 'Make Things Happen' AND
    find_in_set( `users`.`position`, `activity_assoc`.`positions` )

If I change the find_in_set line to the following, it works fine.
`users`.`position` IN ( 'DOS','DOP','DOI' )

UPDATE: The below part is now fixed:
You may have noticed the cast() function. If I leave that off I get an "illegal mix of collations" error.  Most tables in the DB are utf8_general_ci, but the activity_assoc table was utf8_unicode_ci. I ran the following in it yesterday to try and fix this:
ALTER TABLE `activity_assoc` COLLATE `utf8_general_ci`;

The Table Inspector in MySQL Workbench now shows it as utf8_general_ci collation, but actually running the query seems to act as though it's still utf8_unicode_ci. (To be clear: Table Inspector currently shows all three tables to be utf8_general_ci collation.)  I can't tell if these are two separate problems or the same problem.

A: @BillKarwin resolved one issue I was having, and the main issue of the find_in_set() not working properly suddenly started working after I manually altered the record (probably not for the first time).  Can't say why or how -- some sort of glitch at the DB or system level. :-/


text:
Q: Issues creating list from list of dictionaries in python I have a file with json data in it like this:
data = [
            {
                "id": 12345678,
                "list_id": 12345,
                "creator_id": 1234567,
                "entity_id": 1234567,
                "created_at": "2020-01-30T00:43:55.256-08:00",
                "entity": {
                    "id": 123456,
                    "type": 0,
                    "first_name": "John",
                    "last_name": "Doe",
                    "primary_email": "john@fakemail.com",
                    "emails": [
                        "john@fakemail.com"
                    ]
                }
            },
            {
                "id": 12345678,
                "list_id": 12345,
                "creator_id": 1234567,
                "entity_id": 1234567,
                "created_at": "2020-01-30T00:41:54.375-08:00",
                "entity": {
                    "id": 123456,
                    "type": 0,
                    "first_name": "Jane",
                    "last_name": "Doe",
                    "primary_email": "jane@fakemail.com",
                    "emails": [
                        "jane@fakemail.com"
                    ]
                }
            }
        ]

I managed to extract the "first_name" values as well as the "primary_email" with the following code
for record in data:
    first_names = record.get('entity',{}).get('first_name', None)
    email = record.get('entity',{}).get('primary_email', None)
    print(first_names)
    print(email)

which produces following output:
John
john@fakemail.com
Jane
jane@fakemail.com

I am struggling however to create two separate lists for names and email like this:
(John,Jane)
(john@fakemail.com,jane@fakemail.com)

Any help with this is much appreciated.

A: import json

first_names = [record.get('entity',{}).get('first_name', None) for record in data]
email = [record.get('entity',{}).get('primary_email', None) for record in data]
print(first_names)
print(email)

or in the same loop:
first_names = []
email = []
for record in data:
    first_names.append(record.get('entity',{}).get('first_name', None))
    email.append(record.get('entity',{}).get('primary_email', None))
print(first_names)
print(email)


text:
Q: Skewness of Von mises distribution using two different methods I want to use skewness of circular data using circ_skewness code  in MATLAB. I know there are two methods for this:

*

*Pewsey, Metrika, 2004

*Statistical analysis of circular data, Fisher, p. 34

However, it seems the results are very different from each other. For instance, when I test for a Von Mises distribution (which should have a skewness of 0), the first method returns a skewness of zero while the second method returns a skewness of the order of thousands. What is causing this problem?
Here is an example of what I do:
I generate a Von Mises distribution with mean 1 and kappa 10 with size 10 (values are in radians):
b=[0.8149    0.8456    0.3600    0.6513    0.9229    1.3470    0.5658    1.3099    1.1366    0.6194]

I try to find its skewness:
Based on the code , b is the skewnss using Pewsey method and b0 is the skewness using Fisher method. These are the results:
b=-0.0061

b0=-78.8672

Why do we have this difference?


text:
Q: ImageMagick can't handle mixed font rendering This is an example from Imagemagick that will render the chinese characters in the file if using the ZenKaiUni font.
convert -background lightblue -fill blue -pointsize 48 -font ZenKaiUni label:@chinese_words.utf8   label_utf8.gif
I have a situation where a Chinese font is mixed with English and would like to render it with the above command. Imagemagick is rendering the English text with "?" symbols. Is it possible to provide an English font also to the same command above or any other way to render the mixed languages text ?
Thanks .

A: Imagemagick is not a text editor and so its text functions are basic. Later versions come with Pango and you may be able to use that.


text:
Q: Turn off visibility with a redirection or something I would like to make a global switch off for my website like when the user click on a button in the admin side of the website, the homepage turns off to public.
How can I figure it out? Maybe with a redirection on a custom page or something like that?

A: First suggestion would be extending the default controller and making the __construct() check for this flag (in the database, in a flat file or whatever) and making the __construct() show the view or redirect to the custom page that you wan't to show your visitors.


text:
Q: Is there a less redundant way to load/save an entity? Currently, we have this pattern a lot in our project. Loading an entity and saving it afterwards is a really common task. Is there a more concise and less redundant way in Kotlin?
userRepository.findByIdOrNull(1L)?.let {
    userRepository.save(it.apply {
        firstName = "Jon"
        lastName = "Doe"
    })
} ?: throw NoSuchElementException("User not found")

A: There is no official way to make it more concise that I know of, but you could create an extension function on JpaRepository like that:
inline fun <reified T : Any, ID : Serializable> JpaRepository<T, ID>.update(id: ID, modify: T.() -> Unit) = findByIdOrNull(id)?.let {
    modify(it)
    saveAndFlush(it)
} ?: throw NoSuchElementException("There is no ${T::class.simpleName} with id $id!")

and use it like this:
userRepository.update(1L) {
    firstName = "Jon"
    lastName = "Doe"
}

This will make the call site really clean and concise.
update could of course return null instead of throwing the exception. This depends on your use-case.

In case you wonder why I asked and answered this question right away, take a look here.


text:
Q: How to prioritize tags orders in Head in Next.js? I have a Next.js application that each page renders a tag in its head.
my problem is that tags in _app.js are at the top of all tags.
how can i move others pages tags above _app.js tags?


text:
Q: How to put ads on every web page? I am wondering how to put ads like the software Hotspot Shield does.  It puts ads on the top of every web page.  I don't want in a specific language like vb or c++ i just want how in any language.
Examples:

*

*http://ishtechnology.com/wp-content/uploads/2010/10/Blog-Ad-added-by-Hotspot-Shield-e1288306756847.png

*http://www.raymond.cc/images/hotspot-shield-advertisements.png

A: Beside from the obvious evilness of this, the solution is quite simple : install a transparent http proxy on the machine and decorate each and every page with the html code required to display add.
Did I say that kind of behaviour was simply bad ? It indeed defaces web pages, for the sole purpose of displaying adds that will rarely be clicked.


text:
Q: Salesforce lightning input's element.set not working anymore after summer 18 release I am using below snippet to check for valid phone number format and then trying to set the formatted value to the current input element. But after summer 18 release I'm unable to set input with new formatted value.
TestApp
<aura:application extends="force:slds">
   <lightning:input type="text" label="Num" aura:id="ele" onchange="
    {!c.changeNum}" />
 </aura:application>

Controller:
({
    changeNum : function(component, event, helper) {
       helper.changeNum(component, event);
    }
})

Helper:
({
changeNum : function(component, event) {
    var element = event.getSource();
    var phonenumber = element.get("v.value");
    if(phonenumber){
            var updatedValue = phonenumber.replace(/-/g, "");
            if(/^\d{10}$/.test(updatedValue)){
                phonenumber = updatedValue.match(new RegExp('\\d{4}$|\\d{3}', 'g')).join("-");
            }
            else{
                var x = phonenumber.replace(/[^0-9._-]/g, "").replace(/ +/, " ");
                phonenumber = x;
               if(!/^[0-9-]+$/.test(phonenumber.slice(-1))){
                    phonenumber = phonenumber.slice(0, -1);
                }
            }
        }
    console.log(phonenumber);
    element.set('v.value', phonenumber);
}
})

element.set is not able to update the formatted value. The lightning input element is still able to accept alphabets.

A: We can solve the issue by using Promise
({
handleInputChange : function(component, event) {
    try {
        var element = event.getSource();
        var inputValue = element.get("v.value");
        var formattedValue;
        var chkPattern = new Promise(
            function (resolve, reject) {
                if (inputValue) {
                    formattedValue = inputValue.replace(/[^0-9-]/g, "").replace(/ +/, " ");
                    resolve(formattedValue); // fulfilled
                } else {
                    var reason = new Error('kitten is not happy');
                    reject(reason); // reject
                }

            }
        );

        chkPattern.then(function (fulfilled) {
            element.set('v.value', fulfilled);
        }).catch(function (error) {
            console.log(error.message);
        });
    } catch(e) {
        this.consoleLog(e.stack, true)
    }
}

})


text:
Q: How to change the reference anchor Image dynamically in RealityKit I want to use an image load from the network as an anchor to attach my object in the real world.
However, I found that reality kit only provides using the image in the asset folder as an anchor, which seems can't be added by code.
AnchorEntity(.image(group: "", name: ""))

So is there a possible way for ARKit to do such things?

A: I found a way to load ARreferenceImage in the code:
//create a CIImage
let image = UIImage(named: "refimage.jpg",
                                        in: Bundle(for: type(of:self)),
                                        compatibleWith: nil)
        let ciimage = CIImage(image: image!)
        let cgimage = convertCIImageToCGImage(inputImage: ciimage!)!
        let arReference = ARReferenceImage(cgimage, orientation: .up, physicalWidth: 0.05)
//add this image into ARReferenceImage<Set>
        refImage.insert(arReference)
//add this set to the ARView Tracking Config
        let config = ARImageTrackingConfiguration()
        config.trackingImages = refImage
//run the config
        arView.session.run(config)

Then you can get notified when the system detects the image in your ARSessionDelegate
 func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
        for i in anchors{
            if let a = i as? ARImageAnchor{
                DispatchQueue.main.async {
                    print("find anchor")
                    let imageAnchor = AnchorEntity(anchor: a)
                    self.boxEntity = ModelEntity(mesh: MeshResource.generateBox(size: 0.005),materials: [SimpleMaterial(color: .green, isMetallic: true)])
                    imageAnchor.addChild(self.boxEntity)
                    self.arView.scene.addAnchor(imageAnchor)
                }
            }
        }
    }


text:
Q: Python C extension with data file I'm trying to write and install a C Extension for Python which has to load a 120MB data file.  Using distutils package_data argument I've got it installing the data file correctly to the same folder as the extension module.  However, the C code doesn't know how to find the data file.
I can hard code the path to the installed data file in the C extension (that works), but that's obviously not going to work on systems with different installation directories.  I'll need to install this extension both under Linux and Windows.
I've tried using PyModule_GetFilename() to get the path to the module, and then build the path to the datafile from that, but that function raises SystemError: module filename missing.  Possibly the error is because I'm trying to call it inside my module init function?
If necessary I can load the data file manually outside of module initialization, though I would much rather load the file automatically on import.
EDIT: So, I found a workaround.  I wrote an initialization function which can take the file's path as an argument.  From Python, I can access the module's __file__ attribute and figure out the path to the data file from there.  Then, everything works if I run the initialization function in __init__.py.  While this works, I'm still hoping that someone out there can give me a more elegant solution, because this feels pretty backwards to me!

A: So I came up with a somewhat better solution on my own and thought I'd post it in case it helps anyone else.
My project consists of a package (my_module) with a C extension.  The installation contains _my_extension.so, __init__.py, and datafile.dat.  In relevant part, __init__.py looks like:
import os

def datafile_path():
    return os.path.join(os.path.dirname(__file__), "datafile.dat")

import _my_extension

My C extension initialization functions looks like:
PyMODINIT_FUNC
init_my_extension(void)
{
    PyObject *m, *fileobj, *pModule, *pFunc;

    m = Py_InitModule3("_my_extension", _my_extension_methods, "A docstring");
    if (m == NULL)
        return;

    pModule = PyImport_ImportModule("my_module");
    pFunc = PyObject_GetAttrString(pModule, "datafile_path");
    fileobj = PyObject_CallFunction(pFunc, NULL);
    Py_DECREF(pFunc);

    LoadDataFile(PyString_AS_STRING(fileobj));

    Py_DECREF(fileobj);
    Py_DECREF(pModule);
}

I'll need to add some error handling obviously, and this still seems a little off, but at least it loads the data file at module initialization time, and works.  Obviously I could do much of the datafile_path computation in C, but since I needed to import the module anyway, and since I want cross-platform compatibility, it seemed easier to just use the os module.
Anyway, I'd still be happy if anyone could tell me how to do this better, so I'll leave this open, but I thought I'd put up an answer both to help anyone with the same problem in case no better answer is forthcoming, and because I thought it might clarify the problem.


text:
Q: Pass id user to view function I try pass id by template to view but I have

MultiValueDictKeyError at /accounts/profile/1

{{request.user}}

path('accounts/profile/<int:id>', views.profile, name="profile"),

def profile(request, id):
user = User.objects.get(id=int(request.POST[id]))
return user

A: Since the id is passed as URL parameter, you filter with:
from django.shortcuts import get_object_or_404

def profile(request, id):
    user = get_object_or_404(User, pk=id)
    # …
You can furthermore not return user, since that is a User object, not a HttpResponse, you thus need to return for example the result of rendering a template, etc.


text:
Q: Firebase - Structuring Data For Efficient Indexing I've read almost everywhere about structuring one's Firebase Database for efficient querying, but I am still a little confused between two alternatives that I have.
For example, let's say I want to get all of a user's "maxBenchPressSessions" from the past 7 days or so.
I'm stuck between picking between these two structures:

In the first array, I use the user's id as an attribute to index on whether true or false. In the second, I use userId as the attribute NAME whose value would be the user's id.
Is one faster than the other, or would they be indexed a relatively same manner? I kind of new to database design, so I want to make sure that I'm following correct practices.
PROGRESS
I have come up with a solution that will both flatten my database AND allow me to add a ListenerForSingleValueEvent using orderBy ONLY once, but only when I want to check if a user has a session saved for a specific day.

I can have each maxBenchPressSession object have a key in the format of userId_dateString. However, if I want to get all the user's sessions from the last 7 days, I don't know how to do it in one query.
Any ideas?

A: I recommend to watch the video. It is told about the structuring of the data very well.
References to the playlist on the firebase 3
Firebase 3.0: Data Modelling
Firebase 3.0: Node Client

A: As I understand the principle firebase to use it effectively. Should be as small as possible to query the data and it does not matter how many requests.
But you will approach such a request. We'll have to add another field to the database "negativeDate".
This field allows you to get the last seven entries. Here's a video -
https://www.youtube.com/watch?v=nMR_JPfL4qg&feature=youtu.be&t=4m36s

.limitToLast(7) - 7 entries
.orderByChild('negativeDate') - sort by date

Example of a request:
const ref = firebase.database().ref('maxBenchPressSession');
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })

A: Then add the user, and it puts all of its sessions.

const ref = firebase.database().ref('maxBenchPressSession/' + userId);
ref.orderByChild('negativeDate').limitToLast(7).on('value', function(snap){ })


text:
Q: Regex - "['!@#$%*][()=_+{}:\";?,.\/A-Za-z0-9\s-]" is allowing < and > characters Below RegEx is allowing < >
functionA = function ()
{
    var value = "sdfhf$#%##<>*";
    var val = new RegExp("['!@#$%*\]\[()=_+{}:\";?,.\/\A-Za-z0-9\s-]");
    return val.test(value);
}

A: val.test(value) tests whether the regexp matches anywhere in the string. It returns true because the regexp matches the first character of the string. It doesn't match the <> characters, see here.
If you want to test the whole string, you need to repeat the regexp and anchor it at both ends:

functionA = function ()
{
    var value = "sdfhf$#%##<>*";
    var val = /^['!@#$%*\]\[()=_+{}:\";?,.\/\A-Za-z0-9\s-]*$/;
    return val.test(value);
}
console.log(functionA());

or you can invert the character set and the sense of the test:

functionA = function ()
{
    var value = "sdfhf$#%##<>*";
    var val = /[^'!@#$%*\]\[()=_+{}:\";?,.\/\A-Za-z0-9\s-]/;
    return !val.test(value);
}
console.log(functionA());


text:
Q: how to avoid callback hell in my program of calculation using promise and then i tried to avoid call back hell in my program using promise and then.
` function opertion(a, b, callback) {
callback(a, b);
}
    opertion(2, 3, function (a, b) {
        console.log(a + b);
        opertion(3, 5, function (a, b) {
            console.log(a * b);
            opertion(13, 5, function (a, b) {
                console.log(a - b);
                opertion(null, null, function () {
                    console.log("api calling is here");
                });

            });
        });
    });;`


text:
Q: Can I make a scheduled auto-scaling policy in AWS to have 1 EC2 instance during specific hours? I need to practice AWS for my job but I would like to reduce my personal costs as much as possible. I will only be working on my personal EC2 instance from noon to 11:00pm generally for the most part. Can I have an autoscaling group that will bring up the instance at noon and bring it down at 11:00pm? Saving me 13 hours of uptime a day, would this save on costs if it is possible?
I know about scheduled scaling options but I do not know if there is a configuration for 0 instances during down times. Desired 0? Minimum 0? Max 1? Unsure

A: You can use scheduled scaling and define actions for start and stop at specific hours. For example:
Start:
Recurrence: 0 8 * * *
Desired capacity: 1
Stop:
Recurrence: 0 11 * * *
Desired capacity: 0


text:
Q: Problem on a quotient group of a matrix Let $G=\left\{\begin{bmatrix}a & b \\ c & d\end{bmatrix}:a,b,c,d\in\mathbb{Z}\right\}$ be the group under matrix addition and $H$ be the subgroup of $G$ consisting of matrices with even entries. Find the order of the quotient group $G/H$.
How should I solve this problem?

A: $G\simeq \mathbb Z^4$ (the isomorphism is given by $\begin{bmatrix}a & b \\ c & d\end{bmatrix}\mapsto (a,b,c,d)$) and $H\simeq (2\mathbb Z)^4$ $\Rightarrow$ $G/H\simeq ({\mathbb Z}/2\mathbb Z)^4$ and this shows that $|G/H|=16$.

A: First way: Try to prove that the set
$$\left\{\;\begin{pmatrix}\alpha&\beta\\\gamma&\delta\end{pmatrix}\;\;;\;\;\alpha,\beta,\gamma,\delta\in\{0,1\}\;\right\}$$
is a complete set of representatives of the different cosets in $\,G/H\,$ (this implies that you also must prove these represent all the different elements in the quotient group). How many are there?
Second way: Define
$$\,\phi: G\to K:=C_2\times C_2\times C_2\times C_2\,\,,\,\,\phi\begin{pmatrix}a&b\\c&d \end{pmatrix}:=\left(a,b,c,d\right)\pmod 2\in K\,$$
Check the above is a group homomorphism...what is its kernel?


text:
Q: problem when using multiple AurahandledException I'm trying to use multiple AurahandledExceptions in the apex controller to show correct message based on where the error occurred.
Controller:
public static void updateRecord(String recordId, String fieldValue){
   try{
       if(String fieldValue == null){
          throw new AurahandledException('No field value specified');
       }else{
          //update Record here
       }
   } catch(Exception e){
         throw new AurahandledException('Error occurred while updating record');
   }
}

Now, if I pass fieldValue parameter as null, it still throws the error message : Error occurred while updating record.
I'm not able to understand why No field value specified is not displayed even though it enters the enclosing if.

A: The catch catches the initial error, and then you throw a second one. You might consider changing your logic:
public static void updateRecord(String recordId, String fieldValue){
    try{
        if(String fieldValue == null){
            throw new AurahandledException('No field value specified');
        }else{
            //update Record here
        }
    }
    catch(AurahandledException e) {
        throw e;
    }
    catch(Exception e) {
        throw new AurahandledException('An error occurred: '+e.getMessage());
    }
}

With this design, if you specifically throw an exception, it will be passed through to the client, otherwise you'll send the other message.
Note that catch blocks are evaluated in order, so the generic exception must come after all specific exceptions in order for this design to work.


text:
Q: Wordpress - ACF: list titles of all articles associated with a certain post type and custom field? I am using wordpress in combination with advanced custom fields plugin.
I am trying to achieve something – which I guess is probably pretty simply or have been covered already. Unfortunately I do not really know for what to search, so it would be great to receive some help from you guys.
I have a custom post type with the name "test". This custom post type has a custom field with a multiple select field "multiple" – this field contains two possible values "value1" and "value2".
Now I have a common page where I want to alphabetically(!) list the title of all(!) articles of the custom post type "test" which have the value "value1" selected.
My question: how to achieve this?! :)
Really looking forward to your help and answers!
$loop = new WP_Query( array( 'post_type' => 'test', 'posts_per_page' => 99 ) );

while ( $loop->have_posts() ) : $loop->the_post();

if( get_field('multiple')=='value1') {
    echo ''.get_the_title().'';
}

endwhile;