text:
Q: Error In FileUpload asp.net Using c# i Use This Code For File Upload But NotWorking
Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

    <title></title>

FileUpload.SaveAs Method Example

    <form id="Form1" runat="server">

Select a file to upload:

        <asp:FileUpload id="FileUpload1"
            runat="server">
        </asp:FileUpload>

        <asp:Button id="UploadButton"
            Text="Upload file"
            OnClick="UploadButton_Click"
            runat="server">
        </asp:Button>

        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>

    </form>

And This IS a Default.aspx.cs Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile)
            // Call a helper method routine to save the file.
            SaveFile(FileUpload1.PostedFile);
        else
            // Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload.";
    }

    void SaveFile(HttpPostedFile file)
    {
        // Specify the path to save the uploaded file to.
        string savePath = "~/Uploads/";

        // Get the name of the file to upload.
        string fileName = FileUpload1.FileName;

        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;

        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";

        // Check to see if a file already exists with the
        // same name as the file to upload.
        if (System.IO.File.Exists(pathToCheck))
        {
            int counter = 2;
            while (System.IO.File.Exists(pathToCheck))
            {
                // if a file with this name already exists,
                // prefix the filename with a number.
                tempfileName = counter.ToString() + fileName;
                pathToCheck = savePath + tempfileName;
                counter++;
            }

            fileName = tempfileName;

            // Notify the user that the file name was changed.
            UploadStatusLabel.Text = "A file with the same name already exists." +
                "
Your file was saved as " + fileName;
        }
        else
        {
            // Notify the user that the file was saved successfully.
            UploadStatusLabel.Text = "Your file was uploaded successfully.";
        }

        // Append the name of the file to upload to the path.
        savePath += fileName;

        // Call the SaveAs method to save the uploaded
        // file to the specified directory.
        FileUpload1.SaveAs(savePath);
    }
}

And This Error Shows Me When I Run It
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
And What am I Doing to fix This?
Thanks

A: use this simple code hope will helpfull to you for uploading an image
 string _fname,_fpath;
                if (FileUpload1.HasFile)
                {
                   _fname = FileUpload1.FileName.ToString();
                   _fpath="~/upload/"+_fname.ToString();
                    FileUpload1.SaveAs(Server.MapPath("~/upload/") + _fname);
                    SqlCommand cmd = new SqlCommand("insert into tablename(Name,Image) values('" + TextBox1.Text + "','" + _fpath + "')", con);
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        con.Open();
                        cmd.ExecuteNonQuery();
                        Label1.Text = "Data inserted successfully";
                        con.Close();
                        TextBox1.Text = "";
                    }
                    catch (Exception ex)
                    {
                        Label1.Text = ex.Message;
                    }
                }


text:
Q: How to populate a cursor during execution I am currently trying to populate a cursor in the procedure.
like that :
Function notImportantFunction
   variable nothing(20);
   Cursor notImportantCursor Is select...;
   Cursor THEcursor;
begin
    open notImportantCursor;
    open THEcursor;
    LOOP
        FETCH notImportantCursor variable;
    EXIT WHEN notImportantCursor%NOTFOUND;
        THEcursor is select ...; //trying to populate THEcursor
    end loop;
    close THEcursor;
    close notImportantCursor;
end;

i've used weird name for my variable just to show the only important one here is THEcursor.
is what i'm trying even possible? or, how would I be able to do the same in another way.
thank you in advance

A: I think what you are asking for is "Can I create a cursor based on a query that I don't have to define when I declare the cursor"
If thats what you want, then look here for information about dynamic sql.
Dynamic SQL
There is a perfect example in the section Referencing Database Objects that Do Not Exist at Compilation.
You can recreate the cursor each time, however you want.
If you need something a little more flexible, like creating a cursor that holds three values in each record and you want to populate those values in different ways, you could look for pipelined table functions

A: I'm not quite sure what you're trying to do - populate a cursor? A cursor is based on a query, so how do you plan to populate that? Maybe you want to populate a table based on a cursor? You can do that by accumulating the cursor results into a collection then using a bulk-insert to populate the table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Availability statut in product-list not showing Prestashop when I list all products from a category of my web the products show the availability statut. However, if I choose an option to filter results or I click in the next page button to see other products, this label disappears.
I don't know why it's happen? Any idea?

A: It seems that you don't have this behavior properly coded in the global.js in the
display function


text:
Q: Retrieve KeySpec Value from Certificate Using PowerShell I am attempting to verify a certificate in the machine store has KeySpec set to AT_KEYEXCHANGE.  Using certutil.exe does provide this information, but requires string parsing.  I would prefer to avoid string parsing to avoid assumptions on the output of certutil.exe that I do not know will always be true across different versions of Windows.
I have looked at the properties and methods for System.Security.Cryptography.X509Certificates.X509Certificate2 and System.Security.Cryptography.X509Certificates.RSACertificateExtensions.
How can I retrieve the KeySpec from the certificate in the certificate store?

A: I suspect the following isn't a direct equivalent of what you're looking for, but perhaps it ultimately contains the information you're looking for; it is based on applying Get-ChildItem to PowerShell's Cert: drive:
Get-ChildItem Cert:\LocalMachine -Recurse |
  Where-Object { -not $_.PSIsContainer -and $_.EnhancedKeyUsageList }
    Format-List @{
                  Name='KeyUsage'
                  Expression={ ($_.EnhancedKeyUsageList.FriendlyName) -join ', ' }
                },
                Subject,
                Thumbprint

Note: The behavior changed between Windows PowerShell and PowerShell (Core) 7.1, both in terms of the default output formatting and how many certificates report a non-null .EnhancedKeyUsageList property value: Windows PowerShell reports many more.
In PowerShell (Core) 7.1, the above yields something like:
KeyUsage   : Code Signing, Time Stamping, Encrypting File System
Subject    : CN=UTN-USERFirst-Object, OU=http://www.usertrust.com, O=The USERTRUST Network, L=Salt Lake City, S=UT, C=US
Thumbprint : 6E6D0A31B454AF8E8F06CFEB438351056204C28C

KeyUsage   : Server Authentication, Client Authentication, ,
Subject    : OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign, OU=VeriSign International Server CA - Class 3, OU="VeriSign, Inc.", O=VeriSign Trust Network
Thumbprint : 13E8AB4167D5830F9440093564AC0211C2D26E62

KeyUsage   : Code Signing, Windows Hardware Driver Verification
Subject    : CN=Microsoft Windows Hardware Compatibility, OU=Microsoft Corporation, OU=Microsoft Windows Hardware Compatibility Intermediate CA, OU=Copyright (c) 1997 Microsoft Corp.
Thumbprint : 75F7C7CDC6900B145CF9242910EC037D423F369F

KeyUsage   : Code Signing, Time Stamping, Encrypting File System
Subject    : CN=UTN-USERFirst-Object, OU=http://www.usertrust.com, O=The USERTRUST Network, L=Salt Lake City, S=UT, C=US
Thumbprint : 59E6BAC5EFE4C1A11B889146BD983F468C5103BA

KeyUsage   : Server Authentication
Subject    : CN=localhost
Thumbprint : 81F6D78B7A53AE3D03264D178A2E0FEBC978C4D8

A: I was able to find the KeySpec with the help from here and here.  The
CspKeyContainerInfo class contains a property called KeyNumber, which is what certutil refers to as KeySpec.
There are two methods I have found.  One that works for only PowerShell 5 and the other that works for both PowerShell 5 and 7.
PowerShell 5 Only
$Cert = (Get-ChildItem -Path Cert:\LocalMachine\My)[1]
$Cert.PrivateKey.CspKeyContainerInfo.KeyNumber

PowerShell 5 and 7
$Cert = (Get-ChildItem -Path Cert:\LocalMachine\My)[1]
$PrivateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Cert)
$CngProvider = [System.Security.Cryptography.CngProvider]::new($PrivateKey.Key.Provider)
$CngKey = [System.Security.Cryptography.CngKey]::Open($PrivateKey.Key.KeyName,  $CngProvider, [System.Security.Cryptography.CngKeyOpenOptions]::MachineKey)
$CspParameters = [System.Security.Cryptography.CspParameters]::New(1, $CngKey.Provider, $CngKey.KeyName)
$CspParameters.Flags = [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$CspKeyContainerInfo = [System.Security.Cryptography.CspKeyContainerInfo]::New($CspParameters)
$CspKeyContainerInfo.KeyNumber


text:
Q: Python data extraction from string page = '{"code":0,"object":{"url":"/1/0/3","deviceObjResource":[{"resourceValue":"\u0000","resourceName":"3"}]},"message":"Activity READ has Operation Completed"}'

I Want to extract resourceValue content \u0000 using Python

A: Either use regexes as suggested in the previous post, or use the json module:
import json
data = json.loads(page)
data['object']['deviceObjResource'][0]['resourceValue']

A: Use capturing groups or positive lookbehind assertion.
>>> re.search(r'(?<="resourceValue":")[^"]*', page).group()
'\x00'
>>> print(re.search(r'(?<="resourceValue":")[^"]*', page).group())

OR
>>> re.findall(r'"resourceValue":"([^"]*)', page)
['\x00']


text:
Q: DropDownListFor throws exception when user didn't select any value I got an exception when user submitted a form without selecting any value in the dropdownlistfor as follows:
    <div class="editor-field">
        @Html.DropDownListFor(
            x => x.TypeID,
            new SelectList(ViewBag.EventType, "ID", "Name"),
            "-- Select Event Type --"
            )
        @Html.ValidationMessageFor(model => model.TypeID)
    </div>

I got an exception:

Value cannot be null. Parameter name: items

I think I have to check if user selected a value or make an alert, but I'm not sure how to make it.

A: You should use a nullable type for the TypeID property on your view model if you want to handle the non-selected case in your drop down list ("-- Select Event Type --"):
public int? TypeID { get; set; }

You are getting the exception because if the user doesn't select any option in the dropdown, the default one is used:
<option value="">"-- Select Event Type --"</option>

Notice how the value is empty string. This obviously cannot be bound to a non-nullable integer  type on your model.


text:
Q: Using Realm Sync with Azure Functions I'm trying to use Realm Cloud in an Azure Function but it keeps giving me an error:
make_dir() failed: Permission denied Path: /realm-object-server/
Is there a way to configure Azure Functions to have permissions to create files? I'm new to Azure Functions, this is my first one so I'm not really sure of all the particulars.

A: I have found one solution to this. Inside Azure function, you can only create any file or folder inside the temp folder. So if you use following sync configuration, it should work. It worked for me.
var configuration = new FullSyncConfiguration(new Uri("/~/<your-realm-name>", UriKind.Relative), _realmUser, Path.Combine(Path.GetTempPath(), "realm-object-server"));
So basically, here you are passing the folder name to store the realm locally. If you don't pass the folder name, it will try to store it in a default location where you will get the access error.

A: I am not familiar with Realm, but functions has permissions to interact with the file system by default. See these links for information on the app service file system (this applies for functions too):
https://learn.microsoft.com/en-us/azure/app-service/operating-system-functionality#file-access
https://github.com/projectkudu/kudu/wiki/Understanding-the-Azure-App-Service-file-system
If the function is deployed using run from package, then the wwwroot is readonly. But since the path in the error message doesn't point to wwwroot, this is probably not the issue.
My best guess is that the code that is failing is trying to write to in an inappropriate location. The information in the links above should help resolve that. Maybe check to see if realm has a config setting that lets you specify which location it should be creating "realm-object-server" in.

A: You can use
SyncConfigurationBase.Initialize(UserPersistenceMode.NotEncrypted, basePath: Path.GetTempPath());


text:
Q: Counting unique buckets from aggregation I am trying to get the unique count for all labels used on a set of  documents.  In order to do that, and have the json returned in the bucket (cardinality doesnt return json and count together), I need to write a pipeline query.
My query gets me half way there, but I'm missing the second part that counts the number of buckets a label is in.
Here's my query
{
  "size":0,
  "aggs" : {
     unique_count : {
        "composite" : [
           "metadataId" : {
             "terms" :{"field" : "document.metadata.id"}
           },
           "label" : {
             "terms" :{"field" : "document.label"}
           }
        ]
     }
  }
}

This produces
...
"buckets" : [
  {
    "key" : {
      "metadataId" : "1",
      "label" : "label one"
    },
    "doc_count" : 2
  },
  {
    "key" : {
      "metadataId" : "2",
      "label" : "label one"
    },
    "doc_count" : 1
  },
  {
    "key" : {
      "metadataId" : "3",
      "label" : "label three"
    },
    "doc_count" : 3
  }
]
...

The problem I'm facing is that each bucket is considered unique and the sum of the unique counts is what I would like to return.  For example, in the buckets above the label "label one" is contained within two buckets, so it's doc_count should be 2, while "label three" should have a doc_count of 1.
After the last phase in the pipeline I'd like to see the following output:
"buckets" : [
  {
    "label" : "label one"
    "doc_count" : 2
  },
  {
    "label" : "label three"
    "doc_count" : 1
  }
]

I've tried all sorts of things, but they're just not getting me close to the output I need.  Can anyone point me in the right direction?

A: Try with the nested terms aggregations where first level aggs would be on label and the second level on metadataId field. The aggs block should look something like:
"aggs" : {
  "labels": {
    "terms": {
      "field": "label.keyword",
      "size": 1000
    },
    "aggs": {
      "metadata": {
        "terms": {
          "field": metadataId.keyword",
          "size": 1000
        }
      }
    }
  }
}

As output, you will get buckets of labels with key as label value and doc_count with count of docs matching that label. Each label bucket will have a nested buckets of metadataId with key as metadataId value and doc_count with count of docs matching that label and metadataId.


text:
Q: How to remove ID in URL in Laravel return Laravel 5.4, Everything works fine but one thing is bugging me,
When I edit my Data and submit and use  return view('role.index');
The URL returns this :8000/role/1, it returns a extra ID which is I don't know where it came from here is my code:-
public function edit(Role $role)
{
    return view('role.edit')->with('details', $role);
}

public function update(Request $request, Role $role)
{
    $user=auth()->user();
    $role->role=$request->get('role');;

    $role->updated_by=$user->id;

    $role->save();
    return view('role.index');

}

A: i understood it wrong but the reason that it happens because the route of the update is a "PUT request with the id" -> http://yourwebsite/role/1
you are returning a view inside this route you are still in the Role controller and update method.
The solution
instead of returning a view just
return back();

at the last of the update method


text:
Q: Error when creating a certificate using Windows SDK 7.1 Command Prompt I am a new administrator with very little experience, trying to configure my ADFS to cooperate with a single sign-on solution to cloud-based help desk software to be used internally in my organization. I have installed the Windows 7.1 SDK package on Server 2012, and am now in the process of attempting to make a certificate. The PDF guide is now instructing me to type the following commands into Windows SDK 7.1 command prompt:
makecert -r -pe -n "CN=adfs.yourdomain.com" -b 01/01/2013 -e 01/01/2014 -sky exchange Server.cer
  -sv Server.pvk

(Instead of "adfs.yourdomain.com" give the fully qualified name of the AD FS system in the above command)
pvk2pfx.exe -pvk Server.pvk -spc Server.cer -pfx Server.pfx

After entering command 1.), I enter a password upon being prompted to do so. Next, I enter 2.), at which time it gives me an error message as follows:
ERROR: File not found
Error Code = 0x80070002

My question is two-fold: firstly and most straight-forwardly, what is happening here and how do I resolve this issue? Secondly, and more generally, what resources are available to me to familiarize myself with these presently obscure commands? I mean, I don't even know what I'm typing...

A: Have a look at How to: Create Your Own Test Certificate.
The article explains what all the parameters mean.
e.g. cn is the subject name of your certificate, b is valid from, e is valid to etc.
Or refer to the full MSDN documentation - Makecert.exe (Certificate Creation Tool).
Essentially, you are creating a certificate and then transforming this into a pfx file (which is a type of certificate file that also contains the private key).
If you are using IIS for ADFS (i.e. not 2012 R2), then you can do this with IIS - How to Create a Self Signed Certificate in IIS 7

A: Thanks to nzpcmad, who provided me with a resource for understanding how the command prompt works, I was able to provide a solution to my issue that I hope others can use in the future:
The command prompt requires that all the executable files involved in the commands be in the directory that the command prompt is set to. (You can see the directory that the command prompt is set to by simply looking at the text prior to the '>' character). Therefore, in this particular situation, it requires makecert.exe and pvk2pfx.exe to be in the same directory folder, which it is not by default in Windows SDK 7.1 command prompt -- it is in the Bin folder within the default command prompt.
I created a folder in C:/ called 'MakeCert'. I then found the two executable programs needed to run their respective commands -- i.e, makecert.exe to run the command 'makecert', and pvk2pfx.exe to run the command 'pvk2pfx' -- in the file path "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin". Next, I placed these two executable files in the folder "C:/MakeCert that I created. Finally, I used the command prompt command "cd C:/MakeCert" -- which translates to change directory (cd) to the folder C:/MakeCert.
This changed the directory from the default path "C:\Program Files\Microsoft SDKs\Windows\v7.1", and provided a directory with both of my required .exe files as well as a place to house my created certificate files. There is no longer a "File Not Found" Error.


text:
Q: Page with UTF-8 encoding sends data to MySQL with UTF-8 encoding but entry is scrambled I realize there's a dozen similar questions, but none of the solutions suggested there work in this case.
I have a PHP variable on a page, initialized as:
$hometeam="Крылья Советов";    //Cyrrilic string

When I print it out on the page, it prints out correctly. So echo $hometeam displays the string Крылья Советов, as it should.
The content meta tag in the header is set as follows:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">

And, at the very beginning of the page, I have the following (as suggested in one of the solutions found in my search):
ini_set('default_charset', 'utf-8');

So that should be all good.
The MySQL table I'm trying to save this to, and the column in question, have utf8_bin as their encoding. When I go to phpMyAdmin and manually enter Крылья Советов, it saves properly in the field.
However, when I try to save it through a query on the page, using the following basic query:
mysql_query("insert into tablename (round,hometeam) values ('1','$hometeam') ");

The mysql entry looks like this:
c390c5a1c391e282acc391e280b9c390c2bbc391c592c391c28f20c390c2a1c390c2bec390c2b2c390c2b5c391e2809ac390c2bec390c2b2

So what's going on here? If everything is ok on the page, and everything is ok with MySQL itself, where is the issue? Is there something I should add to the query itself to make it keep the string UTF-8 encoded?
Note that I have set mysql_set_charset('utf8'); after connecting to the database (at the top of the page).
EDIT: Running the query SHOW VARIABLES LIKE "%character_set%" gives the following:
Variable_name   Value
character_set_client    utf8
character_set_connection    utf8
character_set_database  latin1
character_set_filesystem    binary
character_set_results   utf8
character_set_server    latin1
character_set_system    utf8
character_sets_dir  /usr/share/mysql/charsets/

Seems like there could be something here, since there are 2 latin1's in that list. What do you think?
Also, when I type a Cyrillic string directly into phpMyAdmin, it appears fine at first (it displays correctly after I save it). But reloading the table, it displays in HEX like the inserted ones. I apologize for the misinformation regarding this in the question. As it turns out, this should mean the problem is with phpMyAdmin or the database itself.
EDIT #2: this is what show create table tablename returns:
CREATE TABLE `tablename` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `round` int(11),  `hometeam` varchar(32) COLLATE utf8_bin NOT NULL,  `competition` varchar(32) CHARACTER SET latin1 NOT NULL DEFAULT 'Russia',  PRIMARY KEY (`id`)) ENGINE=MyISAM AUTO_INCREMENT=119 DEFAULT CHARSET=utf8 COLLATE=utf8_bin

A: Do you get this hex string in phpMyAdmin? I suppose when you SELECT the inserted value by e.g. PHP or the MySQL console client, you would be given the expected cyrillic UTF8 string.
If so, it's a configuration issue with phpMyAdmin, see e.g. here: http://theyouri.blogspot.ch/2010/12/phpmyadmin-collated-db-in-utf8bin-shows.html

phpMyAdmin collated db in utf8_bin shows hex data instead of UTF8 text
$cfg['DisplayBinaryAsHex'] = false;

Moreover, please don't use mysql_query that way, since you're totally open to SQL injections. I'm also not sure if you really want to use utf8_bin, see e.g. this discussion: utf8_bin vs. utf_unicode_ci or this: UTF-8: General? Bin? Unicode?
EDIT There's something weird going on. If you translate the given hex string to UTF8 characters, you get this: "ÐšÑ€Ñ‹Ð»ÑŒÑ Ð¡Ð¾Ð²ÐµÑ'ов" (see e.g. http://software.hixie.ch/utilities/cgi/unicode-decoder/utf8-decoder). If you utf8_decode this, you get the desired "Крылья Советов". So, it seems that it's at least utf8 encoded twice (besides the problem that it somewhere shows up as hex characters).
Could you please provide the complete script? Do you utf8_encode your string anywhere? If your script is this and only this (besides a valid, opened MySQL connection):
<?php
$hometeam="Крылья Советов";    //Cyrrilic string
// open mysql connection here
mysql_set_charset('utf8');
mysql_query("INSERT INTO tablename (round, hometeam) VALUES ('1', '$hometeam')");
$result = mysql_query("SELECT * FROM tablename WHERE round = '1'");
$row = mysql_fetch_assoc($result);
echo $row['hometeam'];
?>

And you call the page, what is the result (in the page source of the browser, not what is displayed in the browser)?
Also, please check what happens if you change the collation to utf8_unicode_ci, as suggested in another answer here. That at least covers phpMyAdmin issues when displaying binary data and is propably anyway what you'll want (since you probably want ORDER BY clauses to perform as expected, see discussions in the SO questions I linked above).
EDIT2 Perhaps you could also provide some snippets like SHOW CREATE TABLE tablename or SHOW VARIABLES LIKE "%character_set%". Might help.

A: 1) Try to save the entry to the database with the PhpMyAdmin and then also look at the result in PhpMyAdmin. Does it look OK? If yes, database is created and set up properly.
2) Try to use utf8_general_ci instead. This shouldn't matter, but give it a try.
3) Tune all necessary settings on the PHP side - follow this post:
 http://blog.loftdigital.com/blog/php-utf-8-cheatsheet . Especially try this trick:
echo htmlentities($hometeam, ENT_QUOTES, 'UTF-8')

A: As I saw in the comments, you don't seam to be able to update your database configuration isn't it?
I guess you have a misconfiguration of the encoding because I saw that in the official documentation MySQL Documentation
I can propose you a PHP solution. Because of a lot of encoding problem you can transform the string before inserting it inside database. You have to find a common language to talk between PHP and the database.
The one I tried in an other project consist in transform string using url_encode($string) and url_decode($string).

A:
Also, when I type a Cyrillic string directly into phpMyAdmin, it
  appears fine at first (it displays correctly after I save it). But
  reloading the table, it displays in HEX like the inserted ones.

This almost certainly looks like there is a problem in your table! Run show create table tablename. I bet there is latin1 instead of utf8, because you have it set as the default in the character_set_database variable.
To change this, run the following commmand:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

This will convert all your varchar fields to utf8. But be careful with the records you already have in the table, as they are already malformed, if you converted them to UTF8 they will stay malformed. Maybe the best idea is to create the database again, just add the following commands at the end of table definition:
CREATE TABLE `tablename` (
    ....
) ENGINE=<whatever you use> DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci


text:
Q: Angular Array.push is pushing only last object in the array when the mat-checkbox is checked I have two components item-list and item . The item-list component display a list of items with checkboxes. I have been trying to push the items to a new Array when checked in the checkbox, but the Array holds only the last item when logged.
Below is the code I tried,
item-list.component.html

  <mat-form-field appearance="outline">
  <input matInput placeholder="Add a Task" (keyup.enter)="addTask()"autocomplete="off"[formControl]="nameControl"/>
  </mat-form-field>

<app-item
  [value]="value"
  *ngFor="let value of data; index as index"
  >
</app-item>

item.component.html

  <mat-checkbox color="secondary" [(ngModel)]="IsChecked" (change)="onChange($event)">
  </mat-checkbox>

  {{ value.task | uppercase }}

item.component.Ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.scss'],
})

export class ItemComponent implements OnInit {

  @Input()
  value: any;

  IsChecked: boolean;
  public ArrayChecked: any[] = [];

  constructor() {
    this.IsChecked = false;
  }

  ngOnInit(): void {}

  onChange($event: any) {
     if ($event.checked) {
       this.ArrayChecked.push(this.value.task);

       console.log('the task is added', this.ArrayChecked);
     }
     else console.log('the task is removed');
  }
  }

In the above code for component item, I tried pushing the items to a new array 'ArrayChecked' inside the onChange(), but when I log the result, the array holds only the last item that I checked. I would like to get the list of all items that were checked in the checkboxes.
Can someone help me fix my code , so all the checked items are inside 'ArrayChecked[]'. Thanks in advance!

A: The problem here is that ArrayChecked is initialized in every item component, which means that each component is only going to push values to its own ArrayChecked variable. Therefore, only the value of the last checked checkbox is logged.
This can be fixed by initializing ArrayChecked in the item-list component instead of the item component. Then, the item component should fire an event when its checkbox's value changes with the item's task. You can then listen to this event in item-list and push the task to ArrayChecked.
item.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-item',
  templateUrl: './item.component.html',
  styleUrls: ['./item.component.scss'],
})

export class ItemComponent implements OnInit {

  @Input()
  value: any;

  // Emitted when the task is checked
  @Output()
  checkTask = new EventEmitter<any>;

  IsChecked: boolean;

  constructor() {
    this.IsChecked = false;
  }

  ngOnInit(): void {}

  onChange($event: any) {
     if ($event.checked) {
       // We now emit the checkTask event instead of directly pushing it to the array
       this.checkTask.emit(this.value.task);

       console.log('the task is added', this.ArrayChecked);
     }
     else console.log('the task is removed');
  }
}

item-list.component.html
<app-item
  [value]="value"
  (checkTask)="addCheckedTask($event)"
  *ngFor="let value of data; index as index"
  >
</app-item>

item-list.component.ts
addCheckedTask($event: any): void {
  this.ArrayChecked.push($event);
}


text:
Q: Can we use different storage engine in SQL Server I MySql proving different types of storage engine like InnoDB etc. And every storage engine have different features then others.
I want know if we have such a type of mechanism in SQL Server also? If yes then how can we use these engines in SQL Server?
And it is possible that SQL Server will provide any NoSql types storage engine in future?


text:
Q: DBSet dynamically register using interface I want to create a code block which register DBsets dynamically.
I decide to use an empty Interface to catch classes which implement the interface.
Here is my code block.
 var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var entityTypes = assembly
                    .GetTypes()
                    .Where(t =>
                        t.GetInterfaces().Contains(typeof(IBaseEnt))).toList();

                foreach (var type in entityTypes)
                {
                    entityMethod.MakeGenericMethod(type)
                      .Invoke(modelBuilder,  null);
                }
            }

But my seed methods can't handle my dbsets. Please help me.
I also tried this code block.
var entityTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where t.GetInterfaces().Contains(typeof(IBaseEnt))
                                           && t.GetConstructor(Type.EmptyTypes) != null
                                  select t;

A: Here is the solution. It is working on EF 6.1.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var entityTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where t.GetInterfaces().Contains(typeof(IBaseEnt))
                                           && t.GetConstructor(Type.EmptyTypes) != null
                                  select t;

                foreach (var type in entityTypes)
                {
                    entityMethod.MakeGenericMethod(type)
                      .Invoke(modelBuilder, null);
                }
            }
            base.OnModelCreating(modelBuilder);
        }


text:
Q: Cubature on Wiener space Suppose $(X_t)_{t\geq 0}$ diffuses as,
$$
dX_t = \mu(X_t)\, dt + \sigma(X_t) \, dW_t
$$
and,
$$
g(t,x)=\mathbb{E}[g(T,X_T)\vert\mathcal{F}_t]
$$
By Feynman-Kac we have,
$$
\frac{\partial}{\partial t}g(t,x)=-\mathcal{L}g(t,x)
$$
Where,
$$
\mathcal{L}=\mu(X_t)\frac{\partial}{\partial x}+\frac{1}{2}\sigma^2(X_t)\frac{\partial^2}{\partial x^2}
$$
Why is it that we are allowed to approximate $X_t$ by,
$$
X_t = e^{\mathcal{L}\sqrt{t}Z}X_0
$$
Where $Z\sim N[0,1]$?
EDIT: For those interested, there was a mistake in the question. This is a notation I'm not used to, since typically one knows $X_t$ has no time derivative almost surely. First, let $g(t,X_t)=X_t$ so that,
$$
\frac{\partial}{\partial t}X_t = -\mathcal{L}X_t
$$
Now choose differential operators $V_0$ and $V_1$ so that,
$$
\mathcal{L} = V_0+\frac{1}{2}V_1^2
$$
Then apparently cubature of degree 3 is the approximation,
$$
X_t = e^{V_0 t + V_1\sqrt{t}Z}X_0
$$


text:
Q: Strange behaviour of asp.net button on Firefox of pressing twice If I have this asp.net button:
<asp:Button ID="Button_Save" Width="150px" OnClick="Button_Save_Click" runat="server" Text="Save" />

In order to prevent the user to press the button twice to insert two data records, I added this in the code behind:
Button_Save.Attributes.Add("onclick", "this.disabled='true';" + ClientScript.GetPostBackEventReference(Button_Save_Data, null) + ";");

It works fine with IE and Chrome. However, in Firefox, every time the user presses the button once, I got two data records inserted.
After some time googling, I modified the button this way by adding: UseSubmitBehavior="false":
<asp:Button ID="Button_Save" Width="150px" UseSubmitBehavior="false" OnClick="Button_Save_Click" runat="server" Text="Save" />

Then it also works with Firefox, only one data record inserted. But then I will have to add that setting for every button on my web application. It requires a lot of work.
However, I think this is really a big problem if that is the case always with asp.net app running on Firefox. Or did I implement something wrong?
Thanks in advance.

A: You would be better off adding checks to your SAVE code to prevent duplicate POSTs. I've used code like yours and still had duplicate records because someone hit the Refresh button at the wrong time.
EDIT:
Here is the code I use. Key is to match a value on the server with a value coming back in the postback.
In Page_Load:
If Not IsPostBack Then
    Session("rcdupdate") = Server.UrlEncode(System.DateTime.Now.ToString)
End If

In Page_Prerender
ViewState("rcdupdate") = Session("rcdupdate")

And in the Save routine
If Session("rcdupdate").ToString = ViewState("rcdupdate").ToString Then
   ... write the data to the database ...
   Session("rcdupdate") = Server.UrlEncode(System.DateTime.Now.ToString)
End If

A: You can extend asp:button and add your new functionality, then fine/replace all of your asp:buttons.  Going forward you can then change all your buttons in once place.


text:
Q: Accessing another cluster from a Kubernetes pod I'm running jenkins in GKE. A step of the build is using kubectl to deploy another cluster. I have gcloud-sdk installed in the jenkins container. The step of the build in question does this:
gcloud auth activate-service-account --key-file /etc/secrets/google-service-account
gcloud config set project XXXX
gcloud config set account xxxx@xxx.iam.gserviceaccount.com
gcloud container clusters get-credentials ANOTHER_CLUSTER

However I get this error (it works as expected locally though):
kubectl get pod
error: You must be logged in to the server (the server has asked for the client to provide credentials)

Note: I noticed that with no config at all (~/.kube is empty) I'm able to use kubectl and get access to the cluster where the pod is currently running.
I'm not sure how it does that, does it use /var/run/secrets/kubernetes.io/serviceaccount/ to access the cluster
EDIT: Not tested if it works yet, but adding a service account to the target cluster and using that in jenkins might work:
http://kubernetes.io/docs/admin/authentication/ (search jenkins)

A: See this answer here: kubectl oauth2 authentication with container engine fails
What you need to do before doing gcloud auth activate-service-account --key-file /etc/secrets/google-service-account is to set gcloud to the old mode of auth:
CLOUDSDK_CONTAINER_USE_CLIENT_CERTIFICATE=True
gcloud config set container/use_client_certificate True

I have not succeded however using the other env var: GOOGLE_APPLICATION_CREDENTIALS


text:
Q: Asp.Net MasterPage - Change WebContentForm body element - CssClass What it's the easiest way to change the css class name of a WebContentForm that use a MasterPage ?
Example:

*

*MasterPage : ...

*Index.aspx : I will like the rendered page to look like ...

*Other.aspx   : ...

A: I use this workaround :
On MasterPage :
On Index.cs : ((HtmlGenericControl)Page.Master.FindControl("body")).Attributes["class"] = "myClass";
It's not really elegant, but it's work


text:
Q: fluentd tag rewrite on kubernetes logs only works when appending original tag This is in relation to fluentd create tag based on key value
.
The only way it seems to work is to append the original tag to the end of the new tag like so:
<match kubernetes.**>
  @type rewrite_tag_filter
  <rule>
    key $['kubernetes']['namespace_name']
    pattern ^(.+)$
    tag $1.${tag}
  </rule>
</match>

What I'd like to do is not append the original tag to the end:
<match kubernetes.**>
  @type rewrite_tag_filter
  <rule>
    key $['kubernetes']['namespace_name']
    pattern ^(.+)$
    tag $1
  </rule>
</match>

When configured in this way nothing is logged into Elastic.
Reading the docs for fluent-plugin-rewrite-tag-filter the Kubernetes example only shows appending original tag to end of new tag.
I've tested this on non Kubernetes nginx logs and it does work using only the tag $1 to rewrite the tag.
How do I achieve this on Kubernetes example above?
Thanks.

A: I was running the above test with quite a bit of additional fluentd config including a number of filters.
I took it right back to the beginning and created a very basic fluend configuration and the above now works as expected.  I just need to understand what it is about the full fluentd configuration with the additional filters that is breaking it.


text:
Q: linqtosql will not allow updating of fields as it casts them as read only I am having an issue with linq updating in linqtosql
from the code below
Dim lqPatientTable As New lqHospitalDataContext
    Dim strPatientId As String
    strPatientId = Me.ucboPatientInfo.SelectedRow.Cells(5).Value

    Dim lqPatientName = (From lqp In lqPatientTable.Patients _
                             Where lqp.PatientID = strPatientId _
                             Select lqp.FirstName, lqp.LastName)
    For Each row In lqPatientName
        row.LastName = utxtPatientLastName.Text
        row.FirstName = utxtPatientFirstName.Text
    Next
    lqPatientTable.SubmitChanges()

Visual Studio tells me that row.LastName is readonly I have not made that asignment anywhere, and I cannot see where the issue is.

A: When you select just individual fields you are creating an anonymous type on the fly that is no longer part of the ORM's change tracking/update mechanism.
You will need to change the select part to be "Select lqp" for this to work.

A: You assign to row.LastName in the first line of the "For Each" loop.
Are you copmiling with option strict/explicit on or off?  If option strict is on that line should not compile.
The reason you are seeing this is when creating an anonymous type for queries which contain an explicit Select clause, all properties on the resulting type will be readonly.  It has the same effect as if all of the properties were declared on an anonymous type using the Key field.  For Example
Dim x = New With { Key .Name ="foo" }

A: When you created the dbml file for your data context, did it create the LastName property as a readonly field?  Open the dbml find the field and check the property to see if it's set to readonly...

A: Readonly on both is set to false
Option Explicit and Option strict are also both off

A: That's the one thing entity framework has better than Linq2Sql (really the only thing!). You can select various fields from different tables, and yet it can still be updateable. With Linq2Sql, if you select from multiple tables (even though here you aren't but when you create a new anonymous type, it's the same idea) it becomes read-only.


text:
Q: Local administrator privilege is required to update the Farm Administrators' group I perform an upgrade of SP from WSS SP2 to SPF 2010 SP1.
In WSS SP2, I was able to update the farm administrators. In SPF 2010 SP1, I keep receicing the following in the ULS logs:

Local administrator privilege is required to update the Farm
  Administrators' group.

*

*I have tried multiple accounts. All with the same error message.

*I have also ran the updatefarmcredentials command. Still same error.

Update:
I was able to resolve this issue after running the SP Products Configuration Wizard several times.
Also, currently MS does not support installing SharePoint 2010 on Windows Server 2012. These issues I am noticing could be the result of unsupported environment.
Update: MS is now saying the installation of SharePoint 2010 on Windows Server 2012 will be supported once SP 2010 SP2 is released. Reference

A: I had the same problem when running IE on the server and opening the Central Admin URL.  Went to all Programs/Microsoft SharePoint 2010 Products/SharePoint 2010 Central Administration and ran that as an Administrator and had no problems adding users.
I was also able to add users when I used a workstation to add users via the URL.

A: SP2013 and 2012 Server:
I have noticed that if I start CA via browser, it won't give me add Farm Administrators with the error:Local administrator privilege is required to update the Farm Administrators' group. Even though I use a farm account.
To resolve the issue make sure that you start Central Administration from start menu.

A: I had this problem trying to add a Farm Admin to a new SharePoint Server 2010 Trial Version on Windows 2008r2. Without going too far down the avenues suggested above, I found a PowerShell script over here that does the heavy lifting, reproduced below. I ran this from a SharePoint 2010 Management Shell run as administrator (may not be necessary to run with elevated permissions).
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

# Creates a new Farm Administrator
$newFarmAdministrator = Read-Host -Prompt 'Please provide the name of the new Farm Administrator in the form of DOMAIN\Username'

$caWebApp = Get-SPWebApplication -IncludeCentralAdministration | where-object {$_.DisplayName -eq "SharePoint Central Administration v4"}
$caSite = $caWebApp.Sites[0]
$caWeb = $caSite.RootWeb

$farmAdministrators = $caWeb.SiteGroups["Farm Administrators"]
$farmAdministrators.AddUser($newFarmAdministrator, "", $newFarmAdministrator, "Configured via PowerShell")

$caWeb.Dispose()
$caSite.Dispose()

$caDB = Get-SPContentDatabase -WebApplication $caWebApp
Add-SPShellAdmin -Database $caDB -Username $newFarmAdministrator


text:
Q: How do I select a random element from an ets set in Erlang/Elixir? I have a large number of processes that I need to keep track of in an ets set, and then randomly select single processes. So I created the set like this:
:ets.new(:pid_lookup, [:set, :protected, :named_table])

then for argument's sake let's just stick self() in it 1000 times:
Enum.map 1..1000, fn x -> :ets.insert(:pid_lookup, {x, self()}) end

Now I need to select one at random. I know I could just select a random one using :ets.lookup(:pid_lookup, :rand.uniform(1000)), but what if I don't know the size of the set (in the above case, 1000) in advance?
How do I find out the size of an ets set? And/or is there a better way to choose a random pid from an ets data structure?

A: *

*If keys are sequential number

tab = :ets.new(:tab, [])
Enum.each(1..1000, & :ets.insert(tab, {&1, :value}))
size = :ets.info(tab,  :size)
# size = 1000
value_picked_randomly = :ets.lookup(tab, Enum.random(1..1000))

:ets.info(tab, :size) returns a size of a table; which is a number of records inserted on given table.

*

*If you don't know that the keys are

first = :ets.first(tab)
:ets.lookup(tab, first)
func = fn key->
    if function_that_may_return_true() do
        key = case :ets.next(tab, key) do
         :'$end_of_table' -> throw :reached_end_of_table
         key -> func.(key)
        end
    else
        :ets.lookup(tab, key)
    end
end
func.()

func will iterate over the ets table and returns a random value.
This will be time consuming, so it will not be an ideal solution for tables with large number of records.

A: As I understood from the comments, this is an XY Problem.
What you essentially need is to track down the changing list and pick up one of its elements randomly. ETS in general and :ets.set in particular are by no mean intended to be queried for size. They serve different purposes.
Spawn an Agent within your supervision tree, holding the list of PIDs of already started servers and use Kernel.length/1 to query its size, or even use Enum.random/1 if the list is not really huge (the latter traverses the whole enumerable to get a random element.)


text:
Q: SlidingTabs with only 2 tabs How can i do that with only 2 tabs and each tab view with 50% screen width? like the current Youtube apps. please help.
The following screenshot (Left) is sample from android (right) is current Youtube app:

A: Only way it's modify source code of SlidingTabLayout.
To get current window size you could use this method:
public static Point getWindowSize(Activity ac) {
    Point size;
    Display display = ac.getWindowManager().getDefaultDisplay();
    display.getSize(size);
    return size;
}

Than in populateTabStrip method add layout params to
mTabStrip.addView(tabView);

method.
Smth like this
width = getWindowSize().x;
mTabStrip.addView(tabView,
    new LinearLayout.LayoutParams(width/2, ViewGroup.LayoutParams.WRAP_CONTENT));

A: Try overriding this method in your PagerAdapter (I assume you're using ViewPager): http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#getPageWidth%28int%29

A: This works perfect for me.
mTabStrip.addView(tabView);

from populateTabStrip() in SlidingTabLayout to
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
mTabStrip.addView(tabView,
            new LinearLayout.LayoutParams(width/2, ViewGroup.LayoutParams.WRAP_CONTENT));

I guess there is no need to create method getWindowSize(Activity ac) as suggested in the previous answer.

A: in case anyone else needs this, I published the SlidingTab classes as a library and it has a method that solves this by calling setDistributeEvenly(true);. Here's an example of how to use it:
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);

The library is at https://github.com/nispok/slidingtabs. To install it via Gradle just include:
compile 'com.nispok:slidingtabs:1.0.0'

Hope it helps!


text:
Q: R: Tidying and summarising a paired comparison dataset in the tidyverse style I have a dataset with features {a,b,c...} belonging to a pair of players taken form the set {a, b, c}. Each row represents the outcome of a matchup, columns name_1, name_2 represent player names, and all other columns a1, a2, b1, b2, c1, c2, etc.. represent numeric features corresponding to the player in the matchup.
Below is the example of a dataset:
set.seed(17)
df <- tibble(
  name_1 = sample(letters[1:3], length(letters), replace = TRUE),
  name_2 = sample(letters[1:3], length(letters), replace = TRUE),
  a1 = rnorm(length(letters)),
  a2 = rnorm(length(letters)),
  b1 = rnorm(length(letters)),
  b2 = rnorm(length(letters)),
  c1 = rnorm(length(letters)),
  c2 = rnorm(length(letters))) %>%
  filter(!(name_1 == name_2))

What I need is to find a summary statistic for each feature grouped by player. The trouble is that the same player, for example, a, can be located sometimes under name_1, sometimes under name_2, hence his features can be located at feature1 or feature2.
Here is my feeble attempt to do this for one player (namely, a) and one feature (namely, a):
df %>%
  mutate(feature_a_joined = case_when(df$name_1 == "a" ~ a1,
                                      df$name_2 == "a" ~ a2)) %>%
  summarise(mean = mean(feature_a_joined, na.rm = TRUE))

I am fairly new to R, but the examples that I`ve seen in multiple vignettes refer to more standard datasets. Is there an efficient way to make a summary for each player  and each variable?
Update
My expected result would be something like this:
# A tibble: 3 x 4
  player feature_a_mean feature_b_mean feature_c_mean
  <chr>           <dbl>          <dbl>          <dbl>
1 a              -0.330          2.38           0.960
2 b              -0.482          1.30           0.207
3 c              -0.482         -0.477         -1.71

A: We can use map.  Get the unique column names ('un1') from the data.  Loop over those (map), apply the OP's code with case_when and get the mean
library(dplyr)
library(purrr)
library(stringr)
un1 <- unique(str_remove(names(df)[-(1:2)], "\\d+"))
map_dfc(un1, ~
       df %>%
         summarise(!! str_c('mean_', .x) :=
         mean(case_when(name_1 == .x ~ !! rlang::sym(str_c(.x, '1')),
                        name_2 == .x ~ !! rlang::sym(str_c(.x, '2'))),
          na.rm = TRUE)))

-output
# A tibble: 1 x 3
#    mean_a mean_b  mean_c
#     <dbl>  <dbl>   <dbl>
#1 -0.00673  0.186 -0.0632

Update
Based on the OP's expected output (assuming the output values are placeholders), we reshape the multiple blocks of columns to 'long' format with pivot_longer, do a group by to get the summarise across columns 'a' to 'c'
library(tidyr)
df %>%
   pivot_longer(everything(), names_to = c('.value', 'grp'),
          names_sep= '(?<=[a-z])_?(?=[0-9])')  %>%
   group_by(player = name) %>%
   summarise(across(a:c, mean, na.rm = TRUE), .groups = 'drop')

-output
# A tibble: 3 x 4
#  player        a      b       c
#  <chr>     <dbl>  <dbl>   <dbl>
#1 a      -0.00673  0.197  0.126
#2 b      -0.0455   0.186 -0.138
#3 c      -0.118   -0.468 -0.0632


text:
Q: why does gcc auto-vectorization for tigerlake use ymm not zmm registers I wanted to explore auto-vectorization by gcc (10.3). I have the following short program (see https://godbolt.org/z/5v9a53aj6) which computes the sum of all elements of a vector:
#include <stdio.h>
#define LEN 1024

// -ffast-math -march=tigerlake -O3 -fno-unroll-loops

int
main()
{
  float v[LEN] __attribute__ ((aligned(64)));
  float s = 0;
  for (unsigned int i = 0; i < LEN; i++) s += v[i];
  printf("%g\n", s);
  return 0;
}

I compile with the options -ffast-math -march=tigerlake -O3 -fno-unroll-loops. Since tigerlake processors have avx512, I would expect that gcc autovectorization uses zmm registers, but it actually uses ymm registers (avx/avx2) in the innermost loop:
vaddps  ymm0, ymm0, YMMWORD PTR [rax]

If I replace -march=tigerlake with -mavx512f, zmm registers are used:
vaddps  zmm0, zmm0, ZMMWORD PTR [rax]

Why aren't zmm registers used, if I just specify -march=tigerlake?

A: -march=tigerlake defaults to -mprefer-vector-width=256 because there are tradeoffs to actually using 512-bit vectors, unlike other AVX-512 features like masking and new instructions.
For a program that you hope might benefit, try compiling with -mprefer-vector-width=512.  (And all the same other options, like -march=native -O3 -flto -ffast-math or -fno-math-errno -fno-trapping-math, and ideally -fprofile-generate / -fprofile-use.)
In your case, you're mostly going to bottleneck on page faults because you loop over some uninitialized stack memory, only once without warm-up.  (Or your loop will be too short to time.)  I hope that was just to demo how it auto-vectorized, not a micro-benchmark.
Idiomatic way of performance evaluation?

Most programs spend significant fractions of their time in code that doesn't auto-vectorize, so lowering max turbo isn't worth it by default.  See SIMD instructions lowering CPU frequency
The frequency downside is small on Ice Lake client (non-server) CPUs, but does still exist on most so there's still at least a short stall while frequency transitions, if it had been running at max turbo.  And at least a few percent downside in frequency for the whole program, including non-vectorized code, and for anything else running on the CPU.
The benefit of 512-bit vectors isn't as big as you'd hope for FP throughput: Ice/Tiger Lake client CPUs only have 1/clock throughput for 512-bit FMA/add/mul (combining the two halves of the normal 256-bit FMA/add/mul units), not having the extra 512-bit FMA unit on port 5 that some Skylake-X and Ice Lake Xeon CPUs have.
(Integer SIMD throughput could sometimes benefit more, since most integer instructions do have 2/clock throughput at 512-bit.  Not 3/clock like you get with 256-bit vectors; having any 512-bit uop in the pipeline disables the vector ALUs on port 1, not just the FMA unit.  So SIMD uop throughput is reduced, which can reduce the speedup for code with good computational intensity that doesn't spend a lot of time loading/storing.)
512-bit vectors are more sensitive to alignment, even for loops that bottleneck on DRAM bandwidth (where 256-bit vectors could easily keep up with available off-core bandwidth).  So you can get maybe a 10
to 15% regression vs. 256-bit vectors in a loop over a big unaligned array that's not cache blocked.  With 256-bit vectors, misaligned data only costs maybe 1 or 2% vs. aligned when looping over a big array.  At least that was true on SKX; I haven't heard if that changed on ICL / ICX.
(Misalignment isn't great when data is hot in L1d cache; every other load being misaligned does hurt cache throughput.  But some real-world code isn't well tuned with cache-blocking, or has parts that weren't amenable to it, so performance with cache-miss loads matters, too.)
Glibc's default malloc likes to do big allocations by grabbing some fresh pages from the OS and using the first 16 bytes for bookkeeping info about them, so you always get the worst case for alignment, ptr % 4096 == 16.
The required alignment is 64, or 32 if you only use 256-bit vectors.

See also some specific discussions of compiler tuning defaults, at least for clang where they adopted the same -mprefer-vector-width=256 default for -march=icelake-client as GCC.

*

*https://reviews.llvm.org/D111029#3674440  2021 Oct and 2022 Jun - discussion of (not) bumping up the vector width on Ice Lake client or server because the frequency penalty is smaller.  Still turned out not to be worth it, 1% regression on SPEC CPU 2017 on Icelake Server, in Intel's testing of clang -mprefer-vector-width=512 vs. the current default 256.

*https://reviews.llvm.org/D67259 2019 discussion of deciding to follow GCC's lead and limit to 256, for skylake-avx512, icelake-client, and icelake-server, etc.  (But not of course KNL which doesn't even have AVX-512VL.)


text: Q: How can I make the search bar in my wordpress site search all of the pages rather than just the blog posts? When I type a word in my search bar it only returns articles from the blog section rather than pages on the site which also contain the word. How can I change that?


text:
Q: Merging 2 formulae We have to solve:
$ \sin(\dfrac{1}{2}x + \pi) $ = $\dfrac{1}{2}\sqrt{2}$
I get these answers:
$ x = -1\frac{1}{2}\pi + k2\pi\quad \lor\quad x =-\frac{1}{2}\pi + k2\pi$
Both these answers can be merged into this answer right?:
x = $\frac{1}{2}\pi + k\pi$
Also, are these 2 mergable (and have I merged them correctly or not?):
$ x = -\frac{1}{2}\pi+k6\pi\quad$ and  $\quad x = 3\frac{1}{2}\pi+k6\pi$
=
$ x = 1\frac{1}{2}\pi+k3\pi$

A: There is no value of $k$ for which $(1/2)\pi+2\pi k$ evaluates to $-(1/2)\pi+2\pi k$, so your merge doesn't work.

A: $\sin(\frac{x}{2}+\pi)=\frac{\sqrt 2}{2}$
Substition
$\frac{x}{2}+\pi=t$ we have:
$\sin t=\frac{\sqrt 2}{2}$
The elementary trigonometrics equation is $\sin x=a$, $a\in R$. If $0<a<1$ solve the equation is $x=x_0+2k\pi$ and $x=\pi-x_0+2k\pi$ where $x_0=\arcsin|a|$.
$0<a=\frac{\sqrt 2}{2}<1$ $\Rightarrow$ $t_0=\arcsin\frac{\sqrt 2}{2}$ $\Rightarrow$ $t_0=\frac{\pi}{4}$.
Definitly: $t=\frac{\pi}{4}+2k\pi$, and $t=\frac{3\pi}{4}+2k\pi$.
From here we have:
$\frac{x}{2}+\pi=\frac{\pi}{4}+2k\pi$ $\Rightarrow$ $x=-\frac{3\pi}{2}+4k\pi$, and $\frac{x}{2}+\pi=\frac{3\pi}{4}+2k\pi$ $\Rightarrow$ $x=-\frac{\pi}{2}+4k\pi$, $k\in Z$


text:
Q: Can someone please explain to me the quickest and easiest way to share one link on facebook from an Android activity? Long story short: I have an android app, from which I want users to be able to share the play store link of my app on their facebook walls.
I don't care about fancy logins with custom user pictures, or taking over the user's news feed, or having facebook take over my app...
I don't need this to happen automatically; a simple redirect to facebook.com or the facebook app with the link already typed in the field the user can submit is all I require.
Is there any way to accomplish this without implementing facebook login or open graph?
If so... HOW?
Thank you!

A: Use the Android share intent like this:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

More info can be found here:
http://developer.android.com/training/sharing/send.html


text:
Q: How to unintegrate jprofile with netbeans I installed jprofile to investigate a memory leak and also clicked the integrate IDE with netbeans 6.9.1. Runing my Web application worked well when clicking the Profile Project, However, when I want to debug again the project the jprofile is still being run when I just want to debug [i.e. Clicking the debug button instead of Profile]. This causes the debugging to fail all the time.
Glassfish Server Output Console.
JProfiler> Protocol version 33
JProfiler> Using JVMTI
JProfiler> JVMTI version 1.1 detected.
JProfiler> 32-bit library
JProfiler> Listening on port: 33200.
JProfiler> Instrumenting native methods.
JProfiler> Can retransform classes.
JProfiler> Can retransform any class.
JProfiler> Native library initialized
JProfiler> VM initialized
JProfiler> Waiting for a connection from the JProfiler GUI ...

I did not said to profile but still this log shows in the console. I tried to look at any uninstall or unintegrate option within the jprofile and there is non. But the jprofile is also not registered as a plugin when looking at the Tools > Plugins menu. Is there a way to unintegrate jprofile?
Note: I already grepped the whole "C:\Program Files\Netbeans 6.9.1\" folder and already removed the xml config of jprofile plus the jar inside the "modules\" folder. But after restarting netbeans and clicking debug button. It still shows the JProfiler prompt.
1. \NetBeans 6.9.1\ide\config\Modules\com-jprofiler-integrations-netbeans.xml
2. \NetBeans 6.9.1\ide\update\backup\netbeans\config\Modules\com-jprofiler-integrations-netbeans.xml

A: Debugging should not append the VM parameter for profiling (-agentpath) to the java command, even if the JProfiler integration is installed, so this sounds kind of strange.
Look into the %USERPROFILE%.netbeans\6.9\modules directory and delete com-jprofiler-integrations-netbeans.jar. If that file does not exist either, the -agentpath parameter is added in a different way, maybe explicitly in your debug configuration.


text:
Q: Strange logic for choosing properties file for spring boot application I am working on a multi-module Maven project where each module is a spring boot application (i.e. packaged as an executable jar). Some modules have dependencies on others. The project uses platform-bom version 1.1.4.RELEASE.
I've discovered what I believe is strange logic for deciding which application properties files to use - although not explicitly contrary to the information at https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html, it still seems unintuitive at best.
The situation was discovered with the following set of circumstances:

*

*Module A has an application.properties file in its resources folder, so this is packaged into the root of the spring boot jar.  This application.properties defines a standard Spring JPA datasource.

*Module B depends on A, but has its own application.yml properties file in it (as well as a profile-specific .properties file e.g. application-foo.properties).  This file does not have entries for the JPA datasource, but the code does expect a datasource to be injected.
Unexpectedly, it seems that the application.properties from A are read when B's tests run in the Maven build, and used to configure the datasource used by B.  From the link above, it could be inferred that this is correct behaviour ("the classpath root" in 24.3 could be taken to mean in the root of a jar on the classpath, which A's jar will be when running tests for B).  NB the .yml properties are also processed.
However, if I provide an empty application.properties in B's resources alongside the .yml file, it seems this takes precedence during the tests, and the application.properties from A is no longer processed at all.  The .yml file is still processed.
I would have thought from the documentation that all eligible properties files should be processed i.e. if A's application.properties is read, then it still should be if B provides its own file (with B's taking precedence). It also seems that .properties and .yml files are not treated identically (the existence of the application.yml did not stop A's application.properties being read, but having application.properties in B did).
Please could someone clarify what the expected behaviour is, and comment whether the documentation (linked above) is correct?  In particular:
1) When the documentation states that properties files can be loaded from "the classpath root", should that include the root of any jars on the classpath too?
2) Should providing an application.properties in B stop A's being found?
3) Should the .yml properties be treated differently in regard to this behaviour?

A: The classpath root is just a flattened representation of all the files in all the archives it contains. You could consider it like unzipping anything in a directory and then reading it (physically it is different but that is comparable to what happens when reading files). Files closest to you will be read before any other files. Hence when you provide your own application.properties that will override the ones included in jar files.
So yes that will stop the reading of files shipped in jars. Why well imagine 20 jars all containing an application.properties how should an order be guaranteed, which one should win? Especially if they contain overlapping properties. So only one will be read.
.properties and .yml are different files and as such are both read (I even believe .properties are read before .yml files but not sure). So yes that is also expected behavior.


text:
Q: C# PictureBox and Timer don't work together so I am trying to make a simple game in C# using PictureBox for painting and timer for update functions, but what I noticed is that when I start painting on my picturebox my timer stops working.. I have no idea why..
Here is the picturebox code:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        Console.WriteLine("PicBox running!");
        if (this.MyGame.InGame)
        {
            this.pictureBox1.Refresh();
            e.Graphics.Clear(Color.White);
            MyGame.CurrentMap.Draw(e.Graphics);
            //e.Graphics.Dispose(); <- if I uncomment this, then the whole programm just freezes
        }
    }

Here is the timer code:
private void timer1_Tick(object sender, EventArgs e)
    {
        Console.WriteLine("Timer running!");
        if (this.MyGame.InGame)
        {
            MyGame.CurrentMap.Update();
            MyGame.UpdateTime();
        }
    }

Here is a method called by MyGame.CurrentMap.Draw(e.Graphics); :
public void Draw(Graphics g)
    {
        foreach(Planet item in Entities){
            item.Draw(g);
        }
    }

Any help would be greately appreciated. I come from javascript, so I don't really know if I am doing something terribly wrong here.

A: When a timer tick occurs, you want to repaint your PictureBox. To do this, you should make it so that the PictureBox receives a Paint event. This is what Refresh() does, so the call to this.pictureBox1.Refresh(); goes in the end of timer1_Tick.
It doesn't make sense for the Paint event to contain a call to Refresh, because this, in turn, generates a Paint event.


text:
Q: Разделить строку по символу ; не разделяя по ; внутри слова окружённого кавычками Здравствуйте.
Как написать выражение re.split, которое будет делить строку по символу ; (точка с запятой) при условие, что этот символ не есть частью одного слова?
Пример:
Название;"Дат;а";Человек;
Грив;22,14;"Пе;тя"

Должно поделить на:
Название, Дат;а, Человек,
Грив, 22,14, Пе;тя

Я понимаю, что пример очень фантастичен ( нет слов, в которые входит символ ; ), но, надеюсь, понятно обьяснил.
Спасибо.

A: В таких случаях удобно cvs модуль использовать:
>>> import csv
>>> lines = 'Название;"Дат;а";Человек;\nГрив;22,14;"Пе;тя"'.splitlines()
>>> list(csv.reader(lines, delimiter=';'))
[['Название', 'Дат;а', 'Человек', ''], ['Грив', '22,14', 'Пе;тя']]

Для вывода также можно csv можно использовать:
>>> rows = csv.reader(lines, delimiter=';')

>>> import sys
>>> csv.writer(sys.stdout).writerows(rows)
Название,Дат;а,Человек,
Грив,"22,14",Пе;тя

Обратите внимание, что во второй строчке автоматически используются кавычки, чтобы заэкранировать запятые. Можно другой разделитель использовать, к примеру, пробел:
>>> csv.writer(sys.stdout, delimiter=' ').writerows(rows)
Название Дат;а Человек
Грив 22,14 Пе;тя

или использовать специальный экранирующий символ:
>>> csv.writer(sys.stdout, escapechar='\\', quoting=csv.QUOTE_NONE).writerows(rows)
Название,Дат;а,Человек,
Грив,22\,14,Пе;тя

В данном случае backslash используется, чтобы заэкранировать запятую (разделитель полей) внутри поля.
Не смотря на простоту, в таком формате могут быть тонкие места, в которых легко ошибиться,  если пытаться самостоятельно распознавать подобный формат, используя свой парсер -- если нет особых причин, лучше уже существующий формат с уже реализованным оттестированным парсером использовать.

A: В данном случае лучше использовать другие модули. Такие, как csv или json
Но если вы хотите разделить строку по символу с помощью регулярных выражений, вы можете использовать знак отрицания ^. Примеры:
Разобьём строку по пробелам:
Паттерн: r'[^ ]+'
result = re.findall(r'[^ ]+', 'Это тестовая строка, чтобы показать как можно разбивать строку по символам')
print(result) # ['Это', 'тестовая', 'строка,', 'чтобы', 'показать', 'как', 'можно', 'разбивать', 'строку', 'по', 'символам']

Разобьём строку по запятым:
result = re.findall(r'[^,]+', 'Это тестовая строка, чтобы показать как можно разбивать строку по символам')
print(result) # ['Это тестовая строка', ' чтобы показать как можно разбивать строку по символам']

Теперь давайте перейдём к вашей строке. У вас очень интересная задача: нужно игнорировать скобки. Но и тут можно справиться, добавив или(|) в условие поиска нашего паттерна:
import re

data = []
lines = ['Название;"Дат;а";Человек;', 'Грив;22,14;"Пе;тя"']

for line in lines:
    result = re.findall(r'(".+?"|[^;]+)', line)
    data.extend(result) # обратите внимание на то, какой у нас вывод
    # когда мы используем функцию extend

print(data) # ['Название', '"Дат;а"', 'Человек', ' Грив', '22,14', '"Пе;тя"']

Чтобы избавиться от кавычек можно воспользоваться функцией sub из того же модуля re. Чтобы не делать кучу списков и не получить ошибку во время замены значений, перед перебором скопируем его. В общем виде у нас получится такой код:
import re

data = []
lines = ['Название;"Дат;а";Человек;', 'Грив;22,14;"Пе;тя"']

for line in lines:
    result = re.findall(r'(".+?"|[^;]+)', line)
    result = [re.sub(r'"(.+)"', r'\1', x) for x in result]
    data.append(result) # посмотрите какой вывод при использовании функции append

print(data) # [['Название', 'Дат;а', 'Человек'], ['Грив', '22,14', 'Пе;тя']]

Обратите внимание на то, что в примерах, при добавлении списка использовались разные функции: extend и append, которые дали разный аутпут.

Подробнее с регулярными выражениями вы можете ознакомиться тут и тут.


text:
Q: aiogram как отправить файл? на русском Stack Overflow уже есть подобный вопрос отправка файлов ботом вTelegram | Aiogram . Но когда я пытаюсь вызвать message.answer_document, который вызывает bot.send_document, я получаю ошибку
future: <Task finished name='Task-6' coro=<Dispatcher._process_polling_updates() done, defined at /home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/dispatcher.py:409> exception=BadRequest('Wrong http url specified')>
Traceback (most recent call last):
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/dispatcher.py", line 417, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/dispatcher.py", line 238, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/dispatcher.py", line 259, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/bigcubecat/__folder__/Bears/bot/handlers/bear.py", line 28, in download_document
    await message.answer_document(savepath)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/types/message.py", line 688, in answer_document
    return await self.bot.send_document(
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/bot/bot.py", line 653, in send_document
    result = await self.request(api.Methods.SEND_DOCUMENT, payload, files)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/bot/base.py", line 208, in request
    return await api.make_request(self.session, self.server, self.__token, method, data, files,
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/bot/api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/bot/api.py", line 115, in check_result
    exceptions.BadRequest.detect(description)
  File "/home/bigcubecat/.local/lib/python3.9/site-packages/aiogram/utils/exceptions.py", line 141, in detect
    raise cls(description)
aiogram.utils.exceptions.BadRequest: Wrong http url specified

Что я делаю не так?

A: Нужно посылать не имя файла, как я пытался, а файл
Например:
message.answer_document(open("file.png", "RB"))

A:  doc = open('Имя') + '.pdf', 'rb')
 await message.reply_document(doc)

A: Мой вариант с использованием InputFile из aiogram.
from aiogram.types import InputFile

example_path = "filename.ext" # или "folder/filename.ext"

await message.answer_photo(InputFile(path))
await message.answer_document(InputFile(path))
await message.answer_...(InputFile(path))


text:
Q: Login screen shown just once i'm making app based on tab bar with two tabs. My problem is that i have to implement authentication view "loginView" on one of tabb's view, and when the credentials are saved i want show another data everytime tab is tapped. what's the best way to do it ?

A: Store a boolean in your user defaults, something like 'loginShown', then, in your appplicationDidFinishLaunching method, check if the 'loginShown' is set, and if not, present a modal view controller which is your login view.

A: You can use a modalViewController for Login so you can have some other view beneath it. For saving credentials for Login so that the user does not have to log back in, you can store it in the KeyChain.
Use this reference: http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code


text:
Q: Crashlytics not sending events on iOS I've migrated our app from react-native-firebase to @react-native-firebase/crashlytics and managed to get crash reports from Android, but no luck with iOS.
I've done all the following:

*

*removed react-native-fabric and all of it's references

*installed @react-native-firebase/app

*installed @react-native-firebase/crashlytics

*added GoogleServices-info.plist in xCode as described in the manual

*added firebase.json in the root of the app with crashlytics_debug_enabled: true (this solved Android)

But still no success, not from the simulator nor from appCenter deployed app.
I think it's good to mention that we have 3 schemes (dev, staging, production).
Any idea how to make this work?

A: Chintan from Firebase. Can you reach out to Firebase Support with the bundle ids of all 3 variant? You can also reference this SO post in there. It might just need manual activation.


text:
Q: EVP_MD_CTX "error: storage size of 'ctx' isn't known" My system is Ubuntu16.04 LTS. when I use the OpenSSL EVP_MD_CTX, this error appeared. Can anyone help me?

CODE:
#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
int main()
{
    int ret,inlen,outlen=0;
    unsigned long e=RSA_3;
    char data[100],out[500];
    EVP_MD_CTX md_ctx, md_ctx2;
    ...
}

ERROR:
root@ubuntu:/work/test# gcc evp_openssl_test.c -I/usr/local/include -L/usr/local/lib -lssl -lcrypto -o
evptestevp_openssl_test.c: In function 'main':
evp_openssl_test.c:13:19: error: storage size of 'md_ctx' isn't known
    EVP_MD_CTX md_ctx,md_ctx2;

A: I had a similar error but with EVP_CIPHER_CTX
error: storage size of 'ctx' isn't known
       EVP_CIPHER_CTX ctx;

I solved with this:
EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();

I hope this helps somebody with the same problem I had.

A: You are using OpenSSL 1.1.0 which made this structure (and many others) opaque - which means you cannot stack allocate it. Instead do this:
EVP_MD_CTX *md_ctx;

md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL)
    ...
...
EVP_MD_CTX_free(md_ctx);


text:
Q: Why is Vec::len a method instead of a public property? I noticed that Rust's Vec::len method just accesses the vector's len property. Why isn't len just a public property, rather than wrapping a method around it?
I assume this is so that in case the implementation changes in the future, nothing will break because Vec::len can change the way it gets the length without any users of Vec knowing, but I don't know if there are any other reasons.
The second part of my question is about when I'm designing an API. If I am building my own API, and I have a struct with a len property, should I make len private and create a public len() method? Is it bad practice to make fields public in Rust? I wouldn't think so, but I don't notice this being done often in Rust. For example, I have the following struct:
pub struct Segment {
    pub dol_offset: u64,
    pub len: usize,
    pub loading_address: u64,
    pub seg_type: SegmentType,
    pub seg_num: u64,
}

Should any of those fields be private and instead have a wrapper function like Vec does? If so, then why? Is there a good guideline to follow for this in Rust?

A: The  Vec struct looks something like this[1]:
pub struct Vec<T> {
    ptr: *mut T,
    capacity: usize,
    len: usize,
}

The idea is that ptr points at a block of allocated memory of size capacity. If the size of the Vec needs to be bigger than the capacity then new memory is allocated. The unused portion of the allocated memory is uninitialised and could contain arbitrary data.
When you call mutating methods on Vec like push or pop, they carefully manage the Vec's internal state, increase capacity when necessary, and ensure that items that are removed are properly dropped.
If len was a public field, any code with an owned Vec, or a mutable reference to one, could set len to any value. Set it higher than it should be and you'll be able to read from uninitialised memory, causing Undefined Behaviour. Set it lower and you'll be effectively removing elements without properly dropping them.
In some other programming languages (e.g. JavaScript) the API for arrays or vectors specifically lets you change the size by setting a length property. It's not unreasonable to think that a programmer who is used to that approach could do this accidentally in Rust.
Keeping all the fields private and using a getter method for len() allows Vec to protect the mutability of its internals, make strong memory guarantees and prevent users from accidentally doing bad things to themselves.

[1] In practice, there are abstraction layers built over this data structure, so it looks a little different.

A: One reason is to provide the same interface for all containers that implement some idea of length. (Such as std::iter::ExactSizeIterator.)
In the case of Vec, len() is acting like a getter:
impl<T> Vec<T> {
    pub fn len(&self) -> usize {
        self.len
    }
}

While this ensures consistency across the standard library, there is another reason underlying this design choice...
This getter protects from external modification of len. If the condition Vec::len <= Vec::buf::cap is not ever satisfied, Vec's methods may try to access memory illegally. For instance, the implementation of Vec::push:
pub fn push(&mut self, value: T) {
    if self.len == self.buf.cap() {
        self.buf.double();
    }
    unsafe {
        let end = self.as_mut_ptr().offset(self.len as isize);
        ptr::write(end, value);
        self.len += 1;
    }
}

will attempt to write to memory past the actual end of the memory owned by the container. Because of this critical requirement, modification to len is forbidden.

Philosophy
It's definitely good to use a getter like this in library code (crazy people out there might try to modify it!).
However, one should design their code in a manner that minimizes the requirement of getters/setters. A class should act on its own members as much as possible. These actions should be made available to the public through methods. And here I mean methods that do useful things -- not just a plain ol' getter/setter that returns/sets a variable. Setters in particular can be made redundant through the use of constructors or methods. Vec shows us some of these "setters":
push
insert
pop
reserve
...

Thus, Vec implements algorithms that provide access to the outside world. But it manages its innards by itself.


text:
Q: Heroku push failing with error regarding sqlite3 I am trying to push to master but it's not working. I used
git push heroku master

The error I'm getting is
       An error occurred while installing sqlite3 (1.3.9), and Bundler cannot continue.
       Make sure that `gem install sqlite3 -v '1.3.9'` succeeds before bundling.
 !
 !     Failed to install gems via Bundler.
 !
 !     Detected sqlite3 gem which is not supported on Heroku.
 !     https://devcenter.heroku.com/articles/sqlite3
 !

enter code here

 !     Push rejected, failed to compile Ruby app

To git@heroku.com:jmatharu.git enter code here
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:jmatharu.git'

Can anyone help me in this case.

A: That would be because Heroku does not support SQLite.  See this Heroku Documentation on how to set up your application for PostgreSQL, which is pretty clear.
In a nutshell you must pick a PostgreSQL plan and then provision your application to connect to it.  This is mostly just using the pg gem rather than SQLite3.
But very soon you will want to run PostgreSQL in your development environment, too.  SQLite and Postgres dialects of SQL differ in many ways.  Setting up Postgres for development can be a bit tedious, particularly for anything other than Linux.  And the exact procedure changes over time.  Your best bet is to Google "Rails Postgresql setup for [your operating system]".


text:
Q: Mail send-receive in Google App Engine (reply_to field) I am reading about mail send/receive in GAE and I have a question about how to use reply_to and the form of the email address replied to.
My register.py simply writes message.sender to database:
class User(db.Model):
    userEmail = db.StringProperty()
    userEmailContent = db.StringProperty()

class Register(InboundMailHandler):
    def receive(self, message):
        newUser = User(userEmail = message.sender)
        db.put(newUser)

application = webapp.WSGIApplication([
  Register.mapping()
], debug=True)

def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()

From incoming.py I am replying to an applicant's mail with this email:
mail.send_mail(sender="<az@example.com>",
               to=message.sender,
               body="reply to this email to register"
               reply_to=/_ah/mail/register@hello-1-world.appspotmail.com)

I am imagining that when the applicant replies to this email register.py will handle the email and write the applicant's email address to the database. I am not sure how to test this in dev server. Before deploying the app I wanted to ask advice about the correct email address to assign to reply_to and if this is the correct way of handling this. Thanks.

A: The reply_to address should be a canonical email address without the /_ah/mail/ prefix  and it follows the same restriction of the sender mail address.

The sender address of a message must be the
  email address of an administrator for
  the application, the Google Account
  email address of the current user who
  is signed in, or any valid email
  receiving address for the app.

To test it on your dev server, you could configure sendmail and send a mail from your program.
Once received, clicking reply from your mail client should show the reply_to mail address set in your code.

A: mail.send_mail(sender="<az@example.com>",
           to=message.sender,
           body="reply to this email to register"
           reply_to="register@hello-1-world.appspotmail.com")


text:
Q: Scrollbar shows up at the bottom of the page I'm creating an HTML document and after adding a new section a scrollbar appears at the bottom of the page probably something pushing the layout to the right.
I managed to scale down what causes the issue. It happens after I add the following code:
HTML

Szolgáltatásaink

CSS:
.content-title {
    padding-top: 4rem;
}

.content-title h3 {
    color: #333333;
    text-transform: uppercase;
    position: relative;
    padding-bottom: 2rem;
}

.content-title h3:after {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    width: 15%;
    height: .4rem;
    background:  #ff5f06;
    margin: 0 auto;
}

Here is the live app: https://avrasys.hu/

A: I looked at your live site https://avrasys.hu/ and found that removing margin-left: -15px; and margin-right: -15px; from the .row class fixes the issue.


text:
Q: iTextSharp issues wherein null reference exception I am using iTextSharp with C# to fill an editable PDF. Everything was working fine, but suddenly I am getting an error on the PdfStamper line.
PdfReader pdfReader = new PdfReader(File.ReadAllBytes(pdfTemplatePath));
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create,FileAccess.Write));
AcroFields pdfFormFields = pdfStamper.AcroFields;

The error is
System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=itextsharp
  StackTrace:
   at iTextSharp.text.Version.GetInstance()

I have checked the file paths and everything - that is all correct. I have also made sure there are no permission issues.
Can someone please let me what might be causing this to throw a null reference exception.
Thanks in advance.


text:
Q: What happens in `pandas.DataFrame.hist`? What happens under the hood when we run pandas.DataFrame.hist on a DataFrame?
Can we get the data out as a DataFrame instead of plotting a graph?

A: I think what you are looking for is
df.value_counts()

Or, in case you are more interested in the values of a special column:
df.COLUMN_NAME.value_counts(bins=5)


text:
Q: Named pipes for client server implementation-How will server distinguish between two request from the same client I have tried to implement client server model using named pipe. Now when client sends only one message to server the server is able to identify what was the message sent and prints it out. Now if client sends multiple message to same server, the server is not able to distinguish between the messages and prints out the both the client messages together instead of separately printing out both message. This is the code I am using:
  Server.c:
    int main(void)
    {
         FILE *fp;
        char readbuf[80];

  /*Create the FIFO if it does not exist */
  umask(0);
  mknod(FIFO_FILE, S_IFIFO|0777, 0);
  while(1)
  {
   fp=fopen(FIFO_FILE, "r");
   fgets(readbuf,80, fp);
   fprintf(stderr,"Received string: %s\n", readbuf);
   fclose(fp);
   fprintf(stderr,"Finished iteration\n");
  }

 return(0);
 }

   Client.c:
     int main()
     {
       FILE *fp;
        char * message1="message1";
        char * message2="message2";
         if((fp = fopen(FIFO_FILE, "w+")) == NULL) {
                perror("fopen");
                     exit(1);
      }

  fprintf(stderr,"Trying to transfer the first message\n");
  fputs(message1, fp);
  fprintf(stderr,"Transferred the first message\n");
  fprintf(stderr,"Trying to transfer the second message\n");
  fputs(message2, fp);
  fprintf(stderr,"Trying to transfer the second message\n");
  fclose(fp);
  return(0);
   }

Now, I know in the server end I am trying to read 80 bytes at a time which makes it to read all the characters together but whenever I am trying to read 5 bytes at a time in the server end it goes into infinite loop. There must be something wrong in my concept.
I have one doubt can when I am modifying the server side to read 5 bytes at a time.It goes into infinite loop why does not it block after it has read all the messages that has been sent by client.

A: There is no knowledge at pipe/stream level about what constitutes an application protocol message. There are, however, two most common ways to delimit messages in a stream:

*

*prefix messages with their size and read that many bytes, or

*read till a certain sequence of bytes is found (often \n (new-line symbol) for text-based protocols).

Use one of these methods to delimit messages in your stream.


text:
Q: Any way to set Min,Max Limits for Slider in Google Maps ( Flex )? I wan to set minimum ans maximum zoom limit for slider in Google Maps , but in Flex Implementation.
Same question is asked here before . But the question as well as answers are for Javascript implementation .
I interpreted in Flex , but got error :

Cannot assign to a method getMinimumResolution on com.google.maps.wrappers.IMapTypeWrapper.

what i did:
var mt:Array = gmap.getMapTypes();

                for (var i:int=0; i<mt.length; i++) {
                    mt[i].getMinimumResolution = function() {return 6;}
                }

how to set it in Flex ?

A: I have tweaked it a liitle bit and here's the soln:
gmap.addEventListener(MapZoomEvent.ZOOM_CHANGED, onZoomChanged);

And the Eventlistener :
public function onZoomChanged(e:MapZoomEvent):void
            {
                var inProcess:Boolean = false;
                if (inProcess) return;

                if (e.zoomLevel > 16)
                {
                    inProcess = true;
                    gmap.setZoom(16);
                    inProcess = false;
                    return
                }
                else if (e.zoomLevel < 13)
                {
                    inProcess = true;
                    gmap.setZoom(13);
                    inProcess = false;
                    return;
                }   }


text:
Q: Get string from PartialViewResult WITHOUT .ControllerContext How can I render a string with HTML code from PartialViewResult WITHOUT having to use ControllerContext
(because in my controller object .ControllerContext is null, and making fakes nor trying to hack it wasn't working. .ControllerContext isn't null from INSIDE of Contorller, but I need to use it OUTSIDE of this Contorller).
public string RenderRazorViewToString(string viewName, object model) {
    ViewData.Model = model;
    using (var sw = new StringWriter()) {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

(broader explaination)--------------------------------------------------------------------------------
I have tried:

*

*making fakes

*trying to call it from anther Controller (success, but I dont have specific .cshtml inside this controller)

*trying to make non-null ControllerContext in various, even most stupid ways

*just trying to "make plain string" from this PartialViewResult (.ToString())

*Even copy-paste code from 1 Controller to 2nd Controller. It won't work, because I got these controller objects from DependencyRegistrar (IoC), and then I ofc can use them, but they always have null .ControllerContext.
I just have PartialViewResult from some ActionResult method that have 100% valid and working HTML code.
I had done a hard search toward this topic, but all I found were answers that use ControllerContext (btw. THIS piece
of code is mentioned on at least 20 different websities. I also have this in my project and I have to say, it
works excellent, but I have a PartialViewResult outside controller).

A: Class ActionFilterAttribute constains a method OnActionExecuted() with one argument of type ActionExecutedContext  and name filterContext.
Yes, filterContext already contains initialized and valid .ControllerContext that I was missing.
This attribute can be atached directly to controller, action (only these that returns ActionResult) or indirectly via inheriting IFilterProvider with its one method GetFiltres
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
    if ((actionDescriptor.ControllerDescriptor.ControllerType == typeof(GemStoneProject.GemStoneController)) &&
        (actionDescriptor.ActionName.Equals("GemStoneAction")) && controllerContext.HttpContext.Request.HttpMethod == "POST")
    {
        return new List<Filter>() { new Filter(this, FilterScope.Action, 0) };
    }

    return new List<Filter>() { };
}

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
    /*your code, that replaces previous View to new View.
You have available and valid .ControllerContext inside "filterContext" argument*/
    }

You will need also this line, if you want to all
builder.RegisterType().As();
Effect: after execution of GemStoneAction, the OnActionExecuted will be called. With valid .ControllerContext of GemStoneController.


text:
Q: @TypeChecked failure over generic type argument I have a mixed groovy/java environment with a simple Manager hierarchy:
public abstract class HomeBean<T extends BaseEntity> {
    private T instance;

    public T getInstance() {
        if (instance == null) {
            if (id != null) {
                instance = loadInstance();
            } else {
                instance = createInstance();
            }
        }
        return instance;
    }

    protected void setInstance(T instance) {
        this.instance = instance;
    }
}

and in TaskManager.groovy:
@TypeChecked
class TaskManager extends HomeBean<Task> implements Serializable {
    void doSomething() {
        instance.compute()
    }
}

The problem I'm seeing is that the groovy compiler assumes that instance is of type BaseEntity and simply ignores the restriction made by TaskManager.
Is this by design or can I somehow make the compiler aware of the additional type information?
Edited to add: I've verified this is still happening with groovy-2.1.7, despite my hope it would be fixed in GROOVY-5981.
Edited to add: As a workaround, I'm casting the instance like this:
@TypeChecked
class TaskManager extends HomeBean<Task> {
    void doSomething() {
        currentTask.compute()
    }

    Task getCurrentTask() { instance as Task }
}

But that's a needless piece of duplication I'd like to get rid of.


text:
Q: Using lodash to sort an array of objects on a floating point number I have a Javascript array like this:
var list = [{Name: 'X', Value: 140.000},
{Name: 'Y', Value: 200.000},
{Name: 'Z', Value: 50.000}]

(it has many more properties, but has been omitted for brevity).
I've created a function that sorts this list using the name of the property passed into the function. I've done this easily with lodash, but if I sort on Value, the values seem to be treated a strings and get sorted wrong.
This is my sort function (so far)
function sortByField(fieldName)
    {
        list = _.sortBy(list, fieldName);

        //afterwards I call reverse() if the sortDirection is descending, but I omitted this part for brevity
    }

After sorting on Value I get the following array:
var list = [{Name: 'X', Value: 140.000},
{Name: 'Y', Value: 200.000},
{Name: 'Z', Value: 50.000}]

You can see it treated the Values like strings, even though they are decimal numbers. The 'Z'-object should have been first. How can I solve this?
I've been searching through the lodash documentation but couldn't seem to find anything related to this problem. Any help please? It'll be much appreciated.
EDIT: I just realized that the Value-property is filled in through a web page (an input control) so Javascript actually adds it to the array as a String, which probably causes the problem. Can I somehow cast this to a float? Or do I have to resort to the built in sort function of Javascript and create my own Compare?

A: What you posted:
var list = [{Name: 'X', Value: 140.000},
   {Name: 'Y', Value: 200.000},
   {Name: 'Z', Value: 50.000}];

list = _.sortBy(list, 'Value');
console.log(list);

should work as expected.
http://jsbin.com/fegifibasu/edit?js,console
Now if for some reason (as you mentioned), the Value field contains string instead of float, then you would need to write your 'custom' sort function.  For example:
var list = [{Name: 'X', Value: '140.000'},
  {Name: 'Y', Value: '200.000'},
  {Name: 'Z', Value: '50.000'}];

list = _.sortBy(list, function(o) {
  return parseFloat(o.Value);
});
console.log(list);

http://jsbin.com/gagelipuza/edit?js,console

A: You could use Array#sort with a custom compareFunction and replace unwanted characters like '.' with '' and a possible decimal separator ',' with dot.

var list = [{ Name: 'X', Value: '140.000' }, { Name: 'Y', Value: '200.000' }, { Name: 'Z', Value: '50.000' }];

list.sort(function (a, b) {
    function getValue(v) {
        return parseFloat(v.replace('.', '').replace(',', '.'));
    }
    return getValue(a.Value) - getValue(b.Value);
});

console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }