text:
Q: Repository error - The context cannot be used while the model is being created I'm getting the following exception when trying to retrieve data from my registry:

An exception of type 'System.InvalidOperationException' occurred in
  OHR.Repository.dll but was not handled in user code
Additional information: The context cannot be used while the model is
  being created. This exception may be thrown if the context is used
  inside the OnModelCreating method or if the same context instance is
  accessed by multiple threads concurrently. Note that instance members
  of DbContext and related classes are not guaranteed to be thread safe.

This error occurs on the first database query that I'm running in the method called MovieExists:
MovieRepository.cs:
private readonly ApplicationDbContext _context;

public MovieRepository(ApplicationDbContext context)
{
    this._context = context;
}

public bool MovieExists(string MovieUrl)
{

    try
    {
        bool result;
        using (_context)
        {
            // The next line causes the exception
            result = _context.Movies.Any(p => p.Url == MovieUrl);
        }
        return result;
    }
    catch (Exception e)
    {
        throw;
    }
}

My context.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet<Movie> Movies { get; set; }

}

I'm using EF6, and while I have async EF tasks, this very first one is not using any async calls so I don't think I'm trying to use the context on multiple threads.
I assume I'm not instantiating the context properly, but can't see how to fix the problem.
Thanks

A: Fixed, the problem was that I made the ApplicationDbContext _context readonly.  Removing readonly fixed the issue.


text:
Q: Working with dynamic types on Google Cloud Datastore Our application is currently working on MongoDb. Our plan is to make it work with Datastore. In our application, there are some API calls and we don't know how its response is structured. So, we work with dynamic types. We get response and put it to Mongodb as is.
As far as we examined, Google.Cloud.Datastore.V1 .Net SDK pushes developers to work with structured type. We have to create an entity which has certain properties with predefined key names.
As shown below:
        MapField<string, Value> fields = new MapField<string, Value>();
        fields.Add("d1", "string value");
        fields.Add("d2", 30);
        fields.Add("d3", 55);

        var entity = new Entity
        {
            Key = key,
            Properties = { fields }
        };

What I've already tried is to set API response to a field. Unfortunately it ended up saving response as a string.
Is there anyway to achive it?

A: I believe the problem is simplified if you take int account that you don't need to use the Properties  entity key.
I did the following, basing this in your examples. Note that i'm not a C# expert as you will see, but this did the trick:
string projectId = "MY-PROJECT";
string kind = "Task";
string name = "samplekey1";

DatastoreDb db = DatastoreDb.Create(projectId);

KeyFactory keyFactory = db.CreateKeyFactory(kind);

Key key = keyFactory.CreateKey(name);

var request = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

var entity = new Entity()
{
    Key = key,
};

foreach(JProperty property in request.Properties())
{
    entity[property.Name] = property.Value.ToString();
}

using (DatastoreTransaction transaction = db.BeginTransaction())
{
    transaction.Insert(entity);
    transaction.Commit();
};

Note that this will not save the type of the values for each key (all of them will be Strings). This is not an issue if you don't need the Type (i.e. Int, String...) for each value to be used later.
However this seems to be the easiest solution, and it gets the job done to create each property with each value.

A: Take a look at this page in the documentation Properties and Value Types, specially the bit named Embedded entity which will allow you to store a JSON entity, and then query its subproperties as long as it is indexed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to create this. Can someone assist? Can someone assist with this query below?
In JavaScript, define a function makeCounter which takes one optional argument defining the intial value, start, with a default value of 0. The function should return an object containing keys that define 3 methods:
- value returns the current value of the counter
- increment increments the value of the counter by 1 and returns the new value
- decrement decrements the value of the counter by 1 and returns the new value
The returned object should not allow direct modification or retrieval of the value.

Example usage:

var counter = makeCounter();
console.log(counter.value());
// 0

var counter2 = makeCounter(4);

console.log(counter2.value());
// 4

console.log(counter2.increment());
// 5
console.log(counter2.value());
// 5

counter2.decrement();
counter2.decrement();
console.log(counter2.decrement());
// 2

A: Instead of using a function makeCounter(), I suggest just using the new operator. The # prefix to the value class field makes it private.

class Counter {
  #value
  constructor(value = 0) {
    this.#value = value;
  }
  value() {
    return this.#value;
  }
  increment() {
    this.#value++;
  }
  decrement() {
    this.#value--;
  }
}

let counter = new Counter(3);
console.log(counter.value());
counter.increment();
console.log(counter.value());


text:
Q: How to detect changes in a datagridview row? I have a datagridview with 15 columns.
The rows are filled from it, what I want is an event, function or method to detect the change in the rows (not in cells).
I tried:
private void DGVPurchases_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        if (DGVPurchases.RowCount > 0)
        {
            switch (DGVPurchases.Columns[e.ColumnIndex].Name)
            {
                case "PurchaseEmisionDate":
                case "PurchaseVendorNumber":
                //others columns
                    if (!Convert.ToBoolean(DGVPurchases.Rows[e.RowIndex].Cells["PurchaseModified"].Value))
                            DGVPurchases.Rows[e.RowIndex].Cells["PurchaseModified"].Value = true;
                    break;
            }
        }
    }
    catch (Exception er)
    {
        PBLog.Save(this, er);
        Alert.Error(Error.Value, App.Purchase.Title);
    }
}

PurchaseModified is a checkbox type column that when detecting changes in cells is set to true, but it does not work quite well since the CellValueChanged event only fires when the cell leaves edit mode or the focus is changed to another cell.

A: I guess RowDirtyStateNeeded is what you are looking for. Set the DataGridView's VirtualMode property to true and add RowDirtyStateNeeded handler. When the event is fired, check if QuestionEventArgs.Respose is true.

A: Subscribe DataGridView to events:
DGVPurchases.EditingControlShowing += DGVPurchases_EditingControlShowing;
DGVPurchases.CellBeginEdit += DGVPurchases_CellBeginEdit;
DGVPurchases.CellEndEdit += DGVPurchases_CellEndEdit;

Define the fields in the form:
private int rowIndex;
private object originalValue;
private TextBox cellTextBox;

Implement event handlers:
private void DGVPurchases_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    cellTextBox = e.Control as TextBox;
    if (cellTextBox != null)
        cellTextBox.TextChanged += TextBox_TextChanged;
}
private void DGVPurchases_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    rowIndex = e.RowIndex;
    originalValue = DGVPurchases[e.ColumnIndex, e.RowIndex].Value;
}
private void DGVPurchases_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (cellTextBox != null)
        cellTextBox.TextChanged -= TextBox_TextChanged;
}
private void TextBox_TextChanged(object sender, EventArgs e)
{
    DGVPurchases["PurchaseModified", rowIndex].Value =
        cellTextBox.Text != originalValue.ToString();
}

Modify behavior as you wish.

A:
what I want is an event, function or method to detect the change in the rows

Do you want to be notified as soon as the operator finishes editing one or more cells in a row and selects a different row to edit? In that case use events DataGridView.RowValidating and DataGridView.RowValidated.
Not sure though it that would be a nice interface. Suppose half-way typing the customer's address the operator decides to copy-paste it from the text editor he has on his screen?
I think a good HMI is, that you let the operator do his task in all his peace, and you should start processing the edits only when the operator indicates that he finished editing the DataGridView.
To be able to see all changes:
Using visual studio designer you will probably have added columns. You'll need to specify which column should show which property:
class DisplayedPurchase
{
    public int Id {set; set;}
    public DateTime EmisionDate {get; set;}
    public int VendorNumber {get; set;}
    ...
}

Probably in your constructor:
public MyForm() : base()
{
    InitializeComponents();

    this.columnId.DataPropertyName = nameof(DisplayedPurchase.Id);
    this.columnEmissionDate.DataPropertyName = nameof(DisplayedPurchase.EmissionDate);
    this.columnVendorNumber.DataPropertyName = nameof(DisplayedPurchase.VendorNumber);
    ...
}

You need a procedure to fetch the Purchases that must be displayed (out of scope of this question)
public IEnumerable<DisplayedPurchase> FetchPurchases(...)
{
    ...
}

To Display the Purchases and to know about the changes: use a BindingList:
BindingList<DisplayedPurchase> DisplayedPurchases
{
    get => (BindingList<DisplayedPurchase>)this.dataGridView1.DataSource;
    set => this.dataGridView1.DataSource = value;
}

To initialize the datagrid view:
private void InitDisplayedPurchases()
{
    this.DisplayedPurchases = new BindingList<DisplayedPurchase>(
        this.FetchPurchases(...).ToList());
}

private void OnFormLoading(object sender, ...)
{
    this.InitDisplayedPurchases();
}

Now Suppose you decided that the operator clicks the Apply-Now button to notify that the edited data must be processed.
private void OnButtonApplyNow_Clicked(object sender, ...)
{
    ICollection<DisplayedPurchase> editedPurchases = this.DisplayedPurchases;
    // find out which data is changed and process them
    this.ProcessEditedPurchases(editedPurchases);
}

Because you put all data in a BindingList, all added / removed / changed rows are automatically in this.DisplayedPurchases.
You might also be interested in the current DisplayedPurchase and the selected DisplayedPurchases (if multi-select)
DisplayedPurchase CurrentDisplayedPurchase => (DislayedPurchase)
    this.dataGridView1.CurrentRow?.DataBoundItem;

IEnumerable<DisplayedPurchase> SelectedPurchases => this.datGridView1.SelectedRows
    .Cast<DatGridViewRow>()
    .Select(row => row.DataBoundItem)
    .Cast<DisplayedPurchase>();

If you really want to process rows immediately after they are edited, consider to subscribe to events RowValidating and RowValidated:
public void OnRowValidated(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGridView = (DataGridView)sender;
    DataGridViewRow row = dataGridView.Rows[e.RowIndex];
    DisplayedPurchase editedPurchase = (DisplayedPurchase)(row.DataBoundItem);
    this.ProcessEditedPurchase(editedPurchase);
}


text:
Q: Inspiration or antecedent for title of Heinlein's "The Moon Is a Harsh Mistress"? I'm fairly certain that I know the answer to this question, but I want to appeal to the collective wisdom here before I definitively file this in my mind as solved. Is there an earlier source or a similar antecedent to the title Robert Heinlein chose for his novel The Moon Is a Harsh Mistress? The title is so wonderfully evocative and for a long time I thought he must have pulled it from some earlier work, perhaps a poem, in the same way many of Shakespeare's memorable phrases have permeated the works of later writers.
I have searched on and off again for some indication of the source of Heinlein's inspiration without success. Now I think he must have created it from a blank slate.
Interestingly, Jimmy Webb used the title for his song of the same name, with permission from Heinlein's lawyers.
What do you think?

A: From Wikipedia, sourced to Heinlein's posthumous autobiography Grumbles from the Grave:

Heinlein's original title for the novel was The Brass Cannon, replaced with the final title at the publisher's request.

The title is probably inspired by the following quote from the novel (emphasis mine):

"I accept the title—nay, I glory in the title of 'jailbird.' We citizens of Luna are jailbirds and descendants of jailbirds. But Luna herself is a stern schoolmistress; those who have lived through her harsh lessons have no cause to feel ashamed. In Luna City a man may leave purse unguarded or home unlocked and feel no fear… I wonder if this is true in Denver?"
-- Professor de la Paz

A: No, the idiom that X is a Harsh Mistress or X is a Cruel Mistress is old indeed, going back at least to the 1800s for "Harsh" and the 1600s for "Cruel". You might want to look at THIS page for examples.
From the link:
A poem from 1910
Alfred Noyes

To a Pessimist

Life like a cruel mistress woos
the passionate heart of man, you say,
Only in mockery to refuse
his love at last and turn away...

Or from 1829

At MOA I found an 1829 from Michael Faraday, in which he says that in
  1813 Humphry Davy warned him that Science is a harsh mistress.

Or from 1640

Thomas Carew has a 1640 poem titled "A Cruel Mistress." The reference is to a woman.

Doubtless there are even older examples for both. It is too good a metaphor to give up.


text:
Q: AWS Lambda GoLang handler API Is it possible to implement Lambda function handler with custom API?
For aws-lambda-go the valid handler is one of following types:
//  func ()
//  func () error
//  func (TIn) error
//  func () (TOut, error)
//  func (TIn) (TOut, error)
//  func (context.Context) error
//  func (context.Context, TIn) error
//  func (context.Context) (TOut, error)
//  func (context.Context, TIn) (TOut, error)

In my case, TIn is KinesisEvent containing MySpecificType as a payload.
I'm looking for the way (maybe to overwrite lambda.Start()) to be able to create the handler of type
func(MySpecificType) error

The goal is to avoid extracting the payload from KinesisEvent in every lambda and make the handler source independent

A: Seems like the solution is quite simple. Just overwrite the lambda.Start() method:
func Start(handler func(t * MySpecificType, i int) error) {

    lambda.Start(func(kinesisEvent events.KinesisEvent) (err error) {

        for i, record := range kinesisEvent.Records {

            mySpecType := new(MySpecificType)
            if err = json.Unmarshal(record.Kinesis.Data, mySpecType); err != nil {
                logrus.Errorf("records[%d]: %s", i, err)
                continue
            }

            err = handler(mySpecType, i)
        }
        return
    })
}

and then:
// main.go
func Handler(m *MySpecificType, index int) error {
// ...
}

func main() {
    <wherever_you_put_it_package>.Start(Handler)
    // instead of lambda.Start(Handler)
}


text:
Q: Boolean Logic Regarding empty arrays. quick question:
why does this return false? Just curious.

    var myArray = [];
    var myArray1 = new Array();
    console.log(myArray === myArray1)

A: Two distinct objects are never === to one another (nor are they ==, for that matter). Object equality means that the two objects are really just one object; that is, that both sides of the === operator are references to the exact same object.
So, this will give you true:
var a = [], b = a;
console.log(a === b);

A: Every time you do

*

*new Array()
or

*= []

A new instance of the Array constructor is assigned to the variable. So when you do a equality check they aint same. Just as same as when two instance of a class aint same.


text:
Q: how to make boto3 connect to default working folder My s3 account is only woking at specific folder, like: 'A/B/C/'
When I using the following code, I still have the access deny issue:
from boto3.session import Session
session = Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
s3 = session.client('s3')
prefix = 'A/B/C/'

for x in s3.list_objects_v2(Bucket=aws_bucket, Prefix=prefix):
    print(x)

I also tried startAfter, still failed to access denied:
from boto3.session import Session
session = Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
s3 = session.client('s3')
start_after = 'A/B/C/'

for x in s3.list_objects_v2(Bucket=aws_bucket, StartAfter=start_after):
    print(x)

Here is the error:
Traceback (most recent call last):
  File "debug5.py", line 39, in <module>
    for x in s3.list_objects_v2(Bucket=aws_bucket, StartAfter=start_after):
  File "/Users/ken/PythonVM3/lib/python3.7/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/ken/PythonVM3/lib/python3.7/site-packages/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Dose the Boto3 provide a feature, that we could connect to the default working folder: A/B/C?
Note:
I could use Cyberduck to access the certain folder: A/B/C
That means the AWS Config side is expected

A: Make sure you have attached IAM policy with below permissions (S3 Full permission) to your IAM user. You can give  permissions as per your requirements.
 {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:ListAllMyBuckets",
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::<bucket-name>",
                "arn:aws:s3:::<bucket-name>/*"
            ]
        }
    ]
}


text:
Q: zsh prompt theme causing cursor to shift right upon completion request I'm trying to create a simple prompt using escape characters to define the colors of the prompt components:
PROMPT=$'\e[0;35m%n\e[0m \e[0;92m%~\e[0m \e[0;97m$ \e[0m'

This works fine except for one thing - when I go to tab-complete my cursor (and the associated command to be completed) gets shifted to the right.
A little googling led me here:
https://github.com/robbyrussell/oh-my-zsh/issues/23
Changing the prompt formatting to something like:
PROMPT='%{$fg[green]%}%n%'

fixes the problem. However, the green, magenta, blue, etc. color options are more limiting in terms of the colors that you can choose than using the escape characters along with the color codes shown above.
I cannot figure out how to format the first prompt shown above so that the tab completion issue goes away. I've a tried a few different permutation with regards to where to put the %{ and they all just end up breaking prompt string.
What is the correct way to format this? OR, is there a way to access more colors using the $fg[COLOR] scheme than red, blue, magenta, etc.?

A: You could put the %{ … %} around the escape characters.

%{...%}
Include a string as a literal escape sequence.  The string within the braces should not change the cursor position.
-- zshmisc(1) SIMPLE PROMPT ESCAPES, Visual effects

So, the below simplified erroneuos case,
PROMPT=$'\e[0;35m%n\e[0m '

could be
PROMPT=$'%{\e[0;35m%}%n%{\e[0m%} '

And why PROMPT='%{$fg[green]%}%n%' works because the escape sequences which $fg[green] produces are correctly wrapped within %{...%}.


text:
Q: xcode 6 installing -> image not recognized I'm trying to install xcode 6 but when I double tap dmg icon, the popup appears and it tells me "The following disk image couln't be opened. Image not recognized."
Please, can you help me? Where is the problem?

A: You have to download the beta version once again as downloading was stopped in between due to some issue and you might have started it again. i also faced the same issue. re downloading helped.

A: I had the same issue when trying to install Xcode 6 Mac told me that the image was not recognized. After downloading it again everything went fine.


text:
Q: How to set a PHP SESSION_ID using a MySQL Database I'm trying manage my users PHP SESSIONS using a MySQL database. I am setting the SESSION_ID() manually using the ID primary key field in the database so its unique to each user.
The API i have created is trying to retrieve the CustomerID session variable to be able to set the SESSION_ID however the SESSION_ID isnt set yet so I'm stuck in a loop.
The outcome is to get the users profile pic to be displayed
Here is the funtion to hoepfully make a little more sense... (I'm using Slim PHP framework)
$app->get('/api/getprofilepic', function(Request $request, Response $response){

    session_id($resultsess);
    session_start();

    $db = new db();
    $db = $db->connect();

     $sqlsess =  "SELECT SessionID FROM sessions WHERE CustomerID= {$_SESSION['CustomerID']} LIMIT 1";

    $stmtsess = $db->query($sqlsess);
    $resultsess = $stmtsess->fetchColumn();

    $sql =  "SELECT ProfilePic FROM login WHERE CustomerID= {$_SESSION['CustomerID']}";

        $stmt = $db->query($sql);
        $result = $stmt->fetchColumn();

The issue is obvious, the "$resultsess" isnt defined yet as i have not run the query however i need to set the sessionID before i run the query in order to get the sessionID.
If there is an easier way of doing this, please let me know.
Thank you for helping me.


text:
Q: converting string to element in page object Page object gem with ruby, and I have defined some number of page-objects for links like:
  link(:link_for_1week, text: /1 wk/)
  link(:link_for_2week, text: /2 wks/)
  link(:link_for_3week, text: /3 wks/)
  link(:link_for_4week, text: /4 wks/)
  link(:link_for_5week, text: /5 wks/)
  link(:link_for_6week, text: /6 wks/)
  link(:link_for_2months, text: /2 mo/)
  link(:link_for_3months, text: /3 mo/)
  link(:link_for_6months, text: /6 mo/)
  link(:link_for_1year, text: /1 yr/)

and I am having a method to call these links dynamically with user input:
If I give user input as '1week' it has to click on 'link_for_1week'
If I give user input as '2week' it has to click on 'link_for_2week'
and so

I don't know how to do and I even used instance_eval, but it doesn't work:
def click_link(args:)
  self.browser.instance_eval('link_for_'+args+'_element.click')
end

But am not able to click the link.
I am not sure on using this instance_eval.. apart from instance_eval also most welcomed...

A: You can use send to convert a String to method call:
def click_link(text)
  send("link_for_#{text}")
end

A: I haven't used that gem but the argument in the method is wrong. Instead of
def click_link(args:)

use
def click_link(args)

A: Below mentioned code will solve your problem:
("link_for_#{args}_element")
When you need to write/get dynamic value from any ruby variable in double quotes use "#{variable}" syntax.


text:
Q: Finding the difference between a number variable within a repeating range? I'm trying to process a numeric variable as follows-
if number is between 1-6 I want to count the difference between it and 7,
if number is between 15-20 I want to count the difference between it and 21,
if number is between 29-34 I want to count the difference between it and 35
and so on....
In other words, grouping it in multiples of 14, i need to find the difference between the first 6 numbers and the 7th number in each group.
I hope that makes sense.  i find it hard to explain in writing, my code isn't much better but i managed to get it to do what i want, but I know it isn't ideal so what I am looking for is a simpler solution to this.
$total = 'A NUMBER'; /* the input number (example: 16 )*/

    $fill =($total / 14);
    $fill = $fill - floor($fill);
    if($fill > 0 && $fill < 0.5)
    {
        $fill = $total;
        while ($fill >= 7)
        {
            $fill = ($fill - 7);
        }
        $fill = (7 - $fill);
    } else {
$fill=0;
}

echo $fill; /* the output (example answer: 5) */

A: Try the following function:
function MyProcess( $in ) {
    $quotient = (int) ($in / 7);
    if( ($quotient % 2 === 0) and ($in % 7 !== 0) )
        return 7 - ($in % 7);
    return 0;
}


text:
Q: Database change history I'm searching for a django package that would allow me to save history of my models, but only on updates. I found django-reversion, but after a quick look it doesn't seem to have such ability. Database triggers are also not an option, since my database structure is rather complicated, and writing them would be hard.

A: I had the same problem at some point.
My solution at that time was to define two models:

*

*content: which corresponds to an abstraction of content of the website. This model is what holds the current content of the website.

*action: which corresponds to an abstraction of content change on the website.

content has two pointers (OneToOneField) to actions: first edit, which is the action that created that particular content and last edit, the action that has the last modification made on the content.
action has one pointer (OneToOneField) to an actor, the user that made the action, and a pointer (ForeignField) to another action, the previous action on the particular content. It also has a TextField which saves content change. This can be for instance a diff-like text for databases, or simply a pickled dictionary.
In some sense this is equivalent to version control like git, where "action" is a commit on a specific content (and not on the whole project), and content is the source. Commits are linked via "previous commit", and save content change and user.

A: You can use south. It detects changes to your models and creates migration files that allow you to sync your database forward and backward.


text:
Q: What increases the BIOS Time? Windows 10 I recently reset my Windows 10 PC. The 'last BIOS time' when I checked first was 1.8 seconds (I kept only necessary startup items and services enabled). I used to check it frequently as I was installing more programs until recently it jumped to 2.4 seconds (after installing Adobe Photoshop I believe). I disabled all the newly appeared startup program and services. Now it reached 1.9 seconds. I just want to know where I lost the 0.1 seconds.

A: According to https://www.howtogeek.com/265623/what-is-last-bios-time-in-the-windows-task-manager/ this value is the time before booting windows, so it is not relevant for this value which software is installed or autostarting.
I would consider 100ms as a possible variation/error of measurement. The 0.6 seconds may be caused by more devices that were connected to your computer or just by a device that took slightly longer to answer the UEFI/BIOS request, for example because it did a self check.


text:
Q: Which Swing layout(s) do you recommend? There are 8 layout managers in the Java library alone, and then there's a bunch of 3rd party products as well.
The other day, I tried to use SpringLayout and... well, it ain't working out for me. See my other question. So... if you have a Swing app to design, and you want your layout just so, what are your preferred layout managers? Any interesting/useful experiences to relate?
Update: Yup, sure I'm aware that different LMs are appropriate for different layouts. But I'd expect that most of you use 1, 2 or maybe 3 for most everything you do, or you swear by a single one that's so versatile you never need anything else. With enough responses, I'd expect to see something like a bell curve, with a peak on GridBagLayout or MigLayout (for example) and a long tail of a few stragglers using (say) BoxLayout or FlowLayout.
Hopefully, the distribution of responses will reveal some trends as to what people use most to Get Stuff Done™

UPDATE and Summary
OK, after almost 2 days, MiGLayout is definitely out in front! Its fans will be happy to hear that it looks like this layout will be entering the "official" library soon.
GroupLayout, FormsLayout and TableLayout are relatively new and haven't gotten much exposure. Perhaps others will be as surprised to find out about them as I was.

A: GroupLayout is pretty decent. It was originally intended for use by GUI Builder applications but I've found it to be very straight forward to code by hand too.

A: FormLayout, part of the JGoodies Forms package has been a workhorse for me. It's not perfectly flexible in that it works hard to make your design look good. I've used it for several years on dozens of projects and it keeps on producing good looking output quickly.
You specify your layout in human-readable text, then add the components. Done.

A: I usually use border layout with gridlayout, first i design ui on paper prototype like ;

(source: usernomics.com)
After that we can split screen to gridlayout on borderlayout. In this picture we see NORTH, CENTER, SOUTH part (BorderLayout elements) and every part's layout can be gridlayout or BorderLayout, it depends on you. Same Layouts can use one within the other.

A: MiGLayout, no doubt. Honestly, it's the only Swing layout manager I know of that makes any sense.
The mere fact that there are 8 layout managers in the core JDK  is a good sign that the Swing creators had absolutely no idea about what they were trying to do. This is not to trash the rest of the Swing - it's a good GUI toolkit, except for the layout managers.

A: GridBagLayout. Does pretty much all that you need (kind of) and it's in the Java library. Admittedly it does need some help, and the API is terrible.
GroupLayout makes a real mess of your layout code. Okay, so most people's GUI code is a big ball of mud. But your's does not have to be! Perhaps a nice interface could be put onto this layout manager, but I suspect it might have to be cloned-and-owned.
I am not in favour of introducing external dependencies unless they are really necessary. Also a lot of the third-party layout managers use strings of data, which have all the usual issues.

A: There is no real answer to your question except that: it depends. It depends on what kind of frame (form) you are trying to create. I am no Swing-guru, but created a couple of (moderately advanced) GUI's and have never had the need to touch the GridBagLayout manager. I have always been able to create my GUI's using a combination of "easier" layout managers. For example, you can give your frame the BorderLayout and then place another layout in the SOUTH of that BorderLayout.

A: Use IntelliJ IDEA with its GUI designer. Makes GridBagLayout easy.
http://madbean.com/anim/totallygridbag/

A: I only use GridBagLayout, especially when doing some complex interfacing, believe me GridBagLayout can do anything. I also recommended the FlowLayout, because it is easy to use, and understandable, good for putting a group of buttons. Actually I only use this two layouts since it is part of the JDK library as for the MigLayout I haven't tried it yet so for now can't recommend it for you.

A: There are following layout options available:
MiGLayout
TableLayout
GroupLayout
FormsLayout

Out of these above MigLayout is the most recommended one as it is swing layout manager. There others have not got much exposure.

A: All of them, in combination. That's the whole point. Each layout manager fulfills different requirements, and by nesting panels with different layout managers, you can achieve almost anything.
The "do everything in a single panel" layout managers like GridBagLayout and GroupLayout (and lots of 3rd party ones) have their place, mainly when you need components in different parts of the layout to align, but with a large layout, they generally result in a huge, hard-to-handle mess.

A: I'm a Swing neophyte, but in the course of writing my first Swing application, I've tried four different layout managers: FlowLayout, BoxLayout, GridLayout and GroupLayout. In my opinion, FlowLayout and BoxLayout seems most appropriate for laying out groups of components of similar sizes. For components of varying sizes, GroupLayout seems to be the way to go. Steeper learning curve than the other two, but definitely worth it. As for GridLayout, I'd argue that you can achieve the same results you would with that layout manager by using a combination of FlowLayout and BoxLayout -- and you'd probably have more control of the placement of your components. But maybe that's just me :)
Sheldon

A: It depends on what kind of GUI you are creating.  You might use just one or two of the simple layouts, or you might need to reach for a more advanced layout.  My overall layout manager use would probably break down to something like this, although it would vary based on the project:

*

*65% GridBagLayout - The one layout that will get it done, no matter what you need to do.

*15% Box/BoxLayout - Great for quickly & easily sticking a couple components together.

*12% BorderLayout - Good for attaching a button panel or info panel to a content panel.  I almost always use it to add content to a JFrame.

*3% FlowLayout - Useful for button panels, but not much else.

*3% CardLayout - Mostly useful in programs that display different content panels for different operational modes.

*2% Other layouts - It's very rare that I need anything else, but occasionally one of the other layouts comes in handy.

Once you get the hang of GridBagLayout, it's not that bad to write initially, but it's still not pretty to work with, or to debug later on.  I tried MiGLayout for something recently and was disappointed to find that the MiGLayout actually ended up being more complicated to use than the GridBagLayout in that particular case.
Some people try to avoid GridBagLayout like the plague; but the truth is, there are some things that no combination of simple layouts will be able to handle.  It's fine to split a GUI into panels for different logical sections, but I think if you're creating a whole bunch of unnecessary extra nested panels just for the purpose of positioning components, you clearly need to learn how to use a GridBagLayout (or other similarly advanced layout, like MiGLayout).  You might get your GUI to look okay with a nasty mess of nested BorderLayouts and GridLayouts and BoxLayouts, but as soon as someone starts resizing your application windows and dialogs to be either smaller or larger than you originally designed them, your GUI will probably look horrible and your customers will start to form a negative opinion about your product since you couldn't get such a simple thing right.
Update: I've been using WindowBuilder in Eclipse for a while now, and it greatly simplifies working with many layouts, especially GridBagLayout.  I used to spend a lot of time writing layouts by hand, but with WindowBuilder or probably any similarly advanced visual editor, you can create the layouts in much less time.

A: DesignGridLayout both looks great and is easy to use through fluent interface.
just look at example:

with just a few lines of clean code:
    layout.row().grid(label("Last Name"))   .add(lastNameField) .grid(label("First Name"))  .add(firstNameField);
    layout.row().grid(label("Phone"))       .add(phoneField)    .grid(label("Email"))       .add(emailField);
    layout.row().grid(label("Address 1"))   .add(address1Field);
    layout.row().grid(label("Address 2"))   .add(address2Field);
    layout.row().grid(label("City"), 1)     .add(cityField);
    layout.row().grid(label("State"))       .add(stateField)    .grid(label("Postal Code")) .add(postalField);
    layout.row().grid(label("Country"), 1)  .add(countryField);
    layout.emptyRow();
    layout.row().center().add(newButton).add(deleteButton).add(editButton).add(saveButton).add(cancelButton);

A: It depends which kind of layout you need, that's why you have 8 of them:

*

*BorderLayout, simple and quite useful to design normal content frames (with main content in the middle and helpers on sides).

*GridLayout, useful when you have a grid of objects that should be of the same size (buttons? textfields?).

*GridBagLayout, very flexible, needs some tweaking to be fine and it is quite verbose (but I raccomend it if you want to do things well).

*FlowLayout, useless.. not a very layout: just placing item one next to another.

*CardLayout, useful for tabs or subviews that must be switched.

*BoxLayout, never used it too much.. it should be a sort of enhanced FlowLayout but it's not enough flexible to be used intensively.


text:
Q: int** matrix segmentation fault I am trying to pass a matrix by reference and then initialize it dynamically. This is just an example:
int main(int argc, char* argv[]) {
  int** matrix = NULL;

  initialize(&matrix, 8);

  return 0;
}

void initialize(int*** matrix, int size) {
  *matrix = (int**) calloc(size, sizeof(int*));

  for (int i = 0; i < size; ++i) {
    *matrix[i] = (int*) calloc(size, sizeof(int));  // cashes here with segmentation fault
  }

  for (int i = 0; i < size; ++i) {
    for (int j = 0; j < size; ++j) {
      *matrix[i][j] = 5; // some number, doesn't matter for now
    }
  }
}

I have also tried the alternative, saving the matrix in a contiguous memory space:
*matrix = (int**) calloc(size, sizeof(int*));

  *matrix[0] = (int*) calloc(size * size, sizeof(int));
  for (int i = 1; i < size; ++i) {
    *matrix[i] = *matrix[0] + size * i; // crashes here, segmentation fault
  }

Yet the same error pops. Never on index 0, always on index 1. I don't understand, what am I doing wrong?
Any kind of help will be greatly appreciated!
Kind regards,
Raul.

A: *matrix[i] = (int*) calloc(size, sizeof(int));

is interpreted as:
*(matrix[i]) = (int*) calloc(size, sizeof(int));

That's why you are seeing segmentation fault.
Use:
(*matrix)[i] = (int*) calloc(size, sizeof(int));

You have a similar error in the line:
  *matrix[i][j] = 5;

That should be:
  (*matrix)[i][j] = 5;

You can avoid some of the confusion by using a temporary variable in the function.
void initialize(int*** matrix, int size) {

   int** m = calloc(size, sizeof(int*));

   for (int i = 0; i < size; ++i) {
      m[i] = calloc(size, sizeof(int));
   }

   for (int i = 0; i < size; ++i) {
      for (int j = 0; j < size; ++j) {
         m[i][j] = 5; // some number, doesn't matter for now
      }
   }

   *matrix = m;
}


text:
Q: Issue in setup and deployment project I have the below requirements in set up and deployment project

*

*Need to find dot net version available or not

*If not we ask user to have that

*if exists we need to check two DLLs are available in GAC or not

*if not we need to register them

But I don't have any idea as how to proceed....any help!

A: Is the .Net Framework installed?:
Right-click on your setup project, hover on View, and click Launch Conditions:

You want to add .NET Framework to your launch conditions:

After that, you can right-click on .NET Framework and click Properties Window. You can choose the Version number in that window.
Install assemblies to the GAC:
Right-click on your setup project, hover on View, and click File System:

Then in that window, right-click on the root node (File System on Target Machine), hover on Add Special Folder, and click Global Assembly Cache Folder:

Drag your assemblies to this folder to have them installed on the machine. If the correct version is not already there in the GAC, the setup program will install it.


text:
Q: footnote goes over margin The second line of the footnote goes over the left margin.
How can I achieve that the second line is in a line with the first line?
\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}

@incollection{incollection,
    author       = {Peter Farindon},
    title        = {The title of the work},
    booktitle    = {The title of the book},
    publisher    = {The name of the publisher},
    year         = 1993,
    pages     ={10},
}

\end{filecontents}

\documentclass{article}
\usepackage[style=verbose]{biblatex}
\usepackage[ngerman]{babel}
\usepackage{csquotes}

\addbibresource{\jobname.bib}
\begin{document}
    Let's cite!  \footcite{incollection}
    \printbibliography
\end{document}

A: You can define the layout of the footnote with the following code added to the preamble:
\makeatletter
\renewcommand{\@makefntext}[1]{%
  \setlength{\parindent}{0pt}%
  \begin{list}{}{%
    \setlength{\labelwidth}{1.5em}% <===================================
    \setlength{\leftmargin}{\labelwidth}%
    \setlength{\labelsep}{3pt}%
    \setlength{\itemsep}{0pt}%
    \setlength{\parsep}{0pt}%
    \setlength{\topsep}{0pt}%
%   \setlength{\rightmargin}{0.2\textwidth}%
    \footnotesize}%
  \item[\@makefnmark\hfil]#1%
  \end{list}%
}
\makeatother

The command \setlength{\labelwidth}{1.5em} defines the length given to the foornote number you can change for your needs ...
The complete code
\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}

@incollection{incollection,
    author       = {Peter Farindon},
    title        = {The title of the work},
    booktitle    = {The title of the book},
    publisher    = {The name of the publisher},
    year         = 1993,
    pages     ={10},
}

\end{filecontents}

\documentclass{article}
\usepackage[style=verbose]{biblatex}
\usepackage[ngerman]{babel}
\usepackage{csquotes}

\makeatletter
\renewcommand{\@makefntext}[1]{%
  \setlength{\parindent}{0pt}%
  \begin{list}{}{%
    \setlength{\labelwidth}{1.5em}% <===================================
    \setlength{\leftmargin}{\labelwidth}%
    \setlength{\labelsep}{3pt}%
    \setlength{\itemsep}{0pt}%
    \setlength{\parsep}{0pt}%
    \setlength{\topsep}{0pt}%
%   \setlength{\rightmargin}{0.2\textwidth}%
    \footnotesize}%
  \item[\@makefnmark\hfil]#1%
  \end{list}%
}
\makeatother

\addbibresource{\jobname.bib}
\begin{document}
    Let's cite!  \footcite{incollection}
    \printbibliography
\end{document}

gives you the result:

If you do not want the second line indentend on the left change \setlength{\leftmargin}{\labelwidth} for example to \setlength{\leftmargin}{0pt} ...
Because you are writing in German please consider to use normal footnote numbers (have a look into the German Duden). To get that please add the line
\renewcommand{\@makefnmark}{\hbox{\normalfont\@thefnmark}}

after \makeatletter ...
Then you get with the complete code
\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}

@incollection{incollection,
    author       = {Peter Farindon},
    title        = {The title of the work},
    booktitle    = {The title of the book},
    publisher    = {The name of the publisher},
    year         = 1993,
    pages     ={10},
}

\end{filecontents}

\documentclass{article}
\usepackage[style=verbose]{biblatex}
\usepackage[ngerman]{babel}
\usepackage{csquotes}

\makeatletter
\renewcommand{\@makefnmark}{\hbox{\normalfont\@thefnmark}} % <==========
\renewcommand{\@makefntext}[1]{%
  \setlength{\parindent}{0pt}%
  \begin{list}{}{%
    \setlength{\labelwidth}{1.5em}% <===================================
    \setlength{\leftmargin}{\labelwidth}%
    \setlength{\labelsep}{3pt}%
    \setlength{\itemsep}{0pt}%
    \setlength{\parsep}{0pt}%
    \setlength{\topsep}{0pt}%
%   \setlength{\rightmargin}{0.2\textwidth}%
    \footnotesize}%
  \item[\@makefnmark\hfil]#1%
  \end{list}%
}
\makeatother

\addbibresource{\jobname.bib}
\begin{document}
    Let's cite!  \footcite{incollection}
    \printbibliography
\end{document}

the result

A: You could use the package footmisc package
\usepackage[flushmargin]{footmisc}

There are two options flushmarginand hang

flushmargin
This option is as option marginal, but sets the footnote marker flush with, but
  just inside the margin from, the text of the footnote.

and

hang
This option sets the footnote mark flush with the margin, and makes the body
  of the footnote hang at an indentation of \footnotemargin (if that is a positive
  distance), or the width of the marker (if \footnotemargin≤ 0). The option code
  itself leaves \footnotemargin at its default value of 1.8em.
  The footnote itself may of course be longer than one paragraph; if so, the
  paragraphs will be separated by the vertical space specified by \hangfootparskip,
  and the second and subsequent paragraphs are indented by \hangfootparindent.
  Default values are:

e.g.
\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}
@Article{article,
    author  = {Hans Zimmer},
    title   = {The title of the work The title of the work The title of the work},
    journal = {Some journal},
    year    = {2013},
    number  = {12},
    pages   = {40-41},
}

@book{book,
author    = {Peter Babington},
title     = {The title of the work The title of the work The title of the work The title of the work},
year      = 1993,
pages     ={310},
}

@incollection{incollection,
author       = {Peter Farindon},
title        = {The title of the work},
booktitle    = {The title of the book},
publisher    = {The name of the publisher},
year         = 1993,
pages     ={10},
}

\end{filecontents}

\documentclass{article}
\usepackage[style=verbose]{biblatex}
\usepackage[ngerman]{babel}
\usepackage{csquotes}

\usepackage[flushmargin]{footmisc}

\addbibresource{\jobname.bib}
\begin{document}
Let's cite! \footcite{ article} \footcite{incollection} \footcite{book}     \footcite{article} \footcite{incollection} \footcite{book}
\printbibliography
\end{document}

which produces


text:
Q: how to count the elements entered by the user in python? I have a program that appends to a list repeadly  numbers entered by the user using a while loop. My goal is to count the amount of elements entered by the user. To count the elements of the list,I used the len() function. Is there any other way to count the amount of elements entered by the user without appending them to a list? My code is below:
L=[]

while True:
    n=input('digite um numero: ')

    if n== 'done':
        break
    try:
        L.append (float(n))
    except ValueError:
        print(' erro')

A: A simple solution would be to increment a variable by one each time an input is being done, the variable should be outside of the loop - like so:
counter = 0

while True:
    user_input=input('Enter a number or type exit')

    if user_input == 'exit':
        break

    counter += 1

A: Is this what you wanted?
count = 0
while True:
    n=input('digite um numero: ')

    if n== 'done':
        break
    count = count + 1
print(count)


text:
Q: Bash Script for Moving Variable string (files) with wildcard I would like to ask some help regarding my script below:
#!/bin/bash

year=$(date +%Y)
lastyear=$((year-1))
month=$(date +%m)
log="$lastyear$month"

mkdir -p "/root/temp/$lastyear"
mkdir -p "/root/temp/$lastyear/$month"
cd /root
mv -f "*$log*" "/root/temp/$lastyear/$month"

Error Prompt is

mv: cannot stat `*201602*': No such file or directory

My target was to move all the files that has the specific "201602" string in file name to a specific location.
Sample logs files is OUTXXX-201602XXX, INXXX-201602XXX, 201602XXXX.
This will be implemented through crontab, because there are about 500k+ log files to be transferred and using find will receive a too much argument error T_T.
Any suggestions will help!

A: You have to put globbing characters outside of quotes for them to be interpreted.
Try instead:
mv -f *"$log"* …

The shell will still keep the resulting matches as one word, so this is OK even if the filenames have spaces.


text:
Q: using mfc to get process network statistics Now I'am working on a MFC program. What I want to know is the speed a process receive/send to the network. Suppose I have a process named chrome.exe, it may receive 1008B/s, send 2987B/s. I know I can get what I want in the Win 7 Resource Monitor. But how can I get those data in my program. Dose MFC or Win32api support this?

A: You can obtain this information, as well as a wealth of other performance data using WMI:
Monitoring Performance Data
This class is probably what you are looking for:
Win32_PerfFormattedData_Tcpip_NetworkInterface
From a native C++/MFC application, you'll access WMI through some COM interfaces
Have fun!


text:
Q: Is it impossible to use react dev tools in a Chrome extension dev tools?
*

*This makes the workflow a lot harder. Is there a way to use react dev tools?

*I also notice constantly that the extension dev tools take some time to load, like 1 to 2s, and because of that, it misses network requests... is there a way to speed it up? I mean, speed up the development workflow, maybe some way to let the extension use more memory? the first few requests do not show in the network tab, but they are sent to the server.

I'm talking about the dev tools that open when you click on the (service worker) link in the chrome://extensions/ tab or when you open the **
** and do right click > inspect

A: The standalone version of React Devtools works https://github.com/facebook/react/tree/main/packages/react-devtools
Since you can't load the script from localhost you will have to include it in your extension.
To do that, go to http://localhost:8097 (or wherever your react devtools is running), save the JS to a file in your Chrome extension folder and add that with a script tag to your html.
Be sure to remove it before publishing.

A:
I also notice constantly that the extension dev tools take some time to load, like 1 to 2s, and because of that, it misses network requests... is there a way to speed it up?

You can try to use the Incognito Mode. There will be no extensions used. So, it will not affect your network requests.


text:
Q: How can I silence the "Terminated" message when my command is killed by timeout? By referencing bash: silently kill background function process and Timeout a command in bash without unnecessary delay, I wrote my own script to set a timeout for a command, as well as silencing the kill message.
But I still am getting a "Terminated" message when my process gets killed. What's wrong with my code?
#!/bin/bash
silent_kill() {
    kill $1 2>/dev/null
    wait $1 2>/dev/null
}
timeout() {
    limit=$1 #timeout limit
    shift
    command=$* #command to run
    interval=1 #default interval between checks if the process is still alive
    delay=1 #default delay between SIGTERM and SIGKILL
    (
        ((t = limit))
        while ((t > 0)); do
            sleep $interval;
            #kill -0 $$ || exit 0
            ((t -= interval))
        done
        silent_kill $$
        #kill -s SIGTERM $$ && kill -0 $$ || exit 0
        sleep $delay
        #kill -s SIGKILL $$
    ) &> /dev/null &
    exec $*
}
timeout 1 sleep 10

A: There's nothing wrong with your code, that "Terminated" message doesn't come from your script but from the invoking shell (the one you launch your script
from).
You can deactivate if by disabling job control:
$ set +m
$ bash <your timeout script>

A: Perhaps bash has moved on in 4 years.  I do know you can avoid
getting Terminated by disowning a child process. You can no longer job control it though.  Eg:
$ sleep 100 &
[1] 15436
$ disown -r
$ kill -9 15436

help disown:

disown [-h] [-ar] [jobspec ...]
Remove jobs from current shell.
Removes each JOBSPEC argument from the table of active jobs.  Without
any JOBSPECs, the shell uses its notion of the current job.

*

*-a        remove all jobs if JOBSPEC is not supplied

*-h        mark each JOBSPEC so that SIGHUP is not sent to the job if the    shell receives a SIGHUP

*-r        remove only running jobs

A: Internally the shell maintains a list of children it forked and wait()s for any of them to exit or be killed. When a child's exit status was collected, the shell prints a message. This is called monitoring in shell parlance.
It seems you want to turn off monitoring. Monitoring is managed with the m option; to turn it on, use set -m (the default at startup). To turn it off, set +m.
Note that monitoring off also disables messages for asynchronous jobs, e.g. no more messages like
$ sleep 5 &
[1] 59468
$
[1]  + done       sleep 5
$


text:
Q: Measuring how long it takes to draw a view in a UIViewController and all its subviews At first I wanted to use -viewWill/DidAppear but I need to know the time for all subsequent updates in all possible view controllers so I came up with a UIView subclass that is always a root view in every controller and has an instance variable for its parent VC and does this in -drawRect:
- (void)drawRect:(CGRect)rect
{
   if (self.parentViewController)  {
      [self.parentViewController resetTime];
      [self.parentViewController performSelector:@selector(measureTimeMethod) withObject:nil afterDelay:.0];
   }
}

Seems to kind of work but can I be certain that this gets called on the next event cycle? I am sure there must be a better way to do it.

A: You could (and should) use Inspector to measure timing issues of your CoreGraphics routines to build up your user interface.
If you have heavy draw calls in your -drawRect: class method it will be slower for sure then with less calls. Which is the reason why Apple suggests to avoid the use of this method if there are no continuous changes in graphics or even if drawRect is empty. The less pixels you have to draw over and less layers and elements are in them for the next drawing cycle the faster it will be. Consider decreasing the size of your Rect for the absolute needed ranges to draw, this will fasten it very much. And rethink your design pattern if drawRect is really the way to go for your needs. Maybe you want to compose classes that draw once at initiation and only update size and positions after.
If you want to make faster UI: it is recommended to use -(void)layoutSubviews instead and update the frames of your pre-defined layout/sublayers UI elements.
If really measuring is your thing: one measurement will give you only a rough clue about improvements but being more precise than performing a selector on top of your object model.
instead use
#include <mach/mach_time.h>

mach_absolute_time();

cache the output in a global to calculate time diff on it
Traversing layout code in your -drawRect will give you wrong timing anyway.
DrawRect is for drawing. In other words you would place your if statement in -(void)layoutSubviews or -(void)layoutSublayers.
As on iOS your UI is usually running always in Main Thread you can measure before and after the allocation and initiation of your Subview containing what you want to exam. In case you want to measure changes in drawing while running you will want to figure out what of the mentioned drawing methods is called when.
Another extreme simple solution is a NSLog(@"t"); and watching the corresponding time prints in your debugger.


text:
Q: Cannot get grunt-scp, grunt-sftp, grunt----- anything to upload to my server except grunt-ftp So, I'm struggling here with getting grunt-scp to work. I'm with a huge telecom and I'm internal to their system or at home on VPN. I can ssh into the server and using WINSCP.
So here's where I got my example: Grunt SCP Example
And now my code:
Pre-requisites:
.ftppass or secret.json. Either will work

//WIN SCP
    scp: {
        qat2: {
            options: {
                host: '123.45.678.900',
                port: 443,
                username: '<%= secret.qat2.username %>',
                password: '<%= secret.qat2.password %>'
            },
            files: [{
                    cwd: allFiles.srcPath.client,
                    src: '**/*',
                    //filter: 'isDirectory',
                    dest: allFiles.uploadServer + '**/*'
                }]
        }
    },

The allFiles.srcPath.client is on my machine literal as:
/var/www/html/app/oauth2/v1

The allFiles.uploadServer = the same as above but for the server.
The loadNpmTasks
grunt.loadNpmTasks('grunt-scp');

Now the grunt register task:
//SCP
grunt.registerTask('scpThis', [
    'scp:qat2',
    'clean:qat2'
], function () {
    try {
        grunt.task.run([
            'scp:qat2',
            'clean:qat2'
        ]);
    }
    catch (e) {
        console.log("SCP Connection failed...", e);
    }
    console.log("pkg: ", pkg);
    console.log("Starting SCP SEQUENCE");
});

The CLEAN is recalled to clean out the remote server, I have a local when I
Here's that section:
 clean: {
        build: {
            src: [ //THIS IS FOR LOCAL Build
                '**/*.*',
                '/docs/*.*'
                        //,
                        //Uncomment out to use
                        //allFiles.destPath.server + '*.*'
            ]
        },
        qat2: { //Thus is for the server when it's called above
            options: {
                force: true
            },
            src: allFiles.uploadServer + '**/*'

        }
    },

Here's the result:
Starting SCP SEQUENCE

//JUST SO EVERYONE KNOWS: The server IPs are FAKE and the question in the
//comments below seems like PVG50 thinks they are REAL.  Ah, they are not.
//in any case, IF THEY were real and then the REAL IPs do connect and then
//close. Thoughts on this please?

11:54:59 - Running "scp:qat2" (scp) task
11:54:59 - ssh connect 123.45.678.90
11:54:59 - ssh close 123.45.678.90
11:54:59 -
Running "clean:qat2" (clean) task //This didn't clean the server since the connection closed...
>> 0 paths cleaned.

Done, without errors.

Execution Time (2015-12-13 19:54:57 UTC)
11:54:59 - loading tasks   1.5s  ████████████████████████████████████ 77%
scp:qat2       441ms  ███████████ 22%
Total 2s

This doesn't work
Here's my attempt with sftp:
//SFTP - SSH EXEC
    sftp: {
        deploy: {
            command: "sudo su",
            auth: {
                host: '<%= secret.qat2.ip %>',
                port: 443,
                authKey: 'key1'
            },
            files: {
                src: allFiles.destPath.client
            },
            options: {
                path: allFiles.uploadServer,
                directoryPermissions: parseInt(777, 8),
                createDirectories: true
            }
        }
    },

//SFTP DEPLOY
    'sftp-deploy': {
        build: {//SERVERS GO HERE LIKE BELOW
            command: "sudo su",
            auth: {
                host: '<%= secret.qat2.ip %>',
                port: 443,
                authKey: 'key1'
            },
            cache: 'sftpCache.json', //OMIT from Source Control Stores Locally
            expand: true,
            src: [
                allFiles.destPath.client + 'images/{,*/}*.*',
                allFiles.destPath.client + 'images/*.jpg',
                allFiles.destPath.client + 'images/*.png',
                allFiles.destPath.client + 'scripts/config/*.json',
                allFiles.destPath.client + 'tmpl/*.js',
                allFiles.destPath.client + '*.html',
                allFiles.destPath.client + 'views/*.html',
                allFiles.destPath.client + 'views/**/*.html',
                allFiles.destPath.client + 'favicon.ico',
                allFiles.destPath.client + '.htaccess'
            ],
            dest: allFiles.uploadServer,
            concurrency: 4,
            progress: true
        }
    },

Now the result when I run grunt sftpDeployThis
23:21:59 - Running "sftpDeployThis" task
23:21:59 - Starting SFTP SERVER DEPLOYMENT SEQUENCE
23:21:59 - Running "sftp-deploy:build" (sftp-deploy) task
23:21:59 - Warning: /var/www/html/app/oauth2/v1/images/{,*/}*.* is not an existing location Use --force to continue.
23:21:59 -
Aborted due to warnings.
23:21:59 -

Execution Time (2015-12-13 07:21:58 UTC)
23:21:59 - loading tasks      1.4s  ███████████████████████████████████████████ 99%
sftp-deploy:build  15ms  █ 1%
Total 1.4s

I've been using grunt for 2 years and this one's got me stumped.
What I want to do:

*

*connect to the server

*clean the deploy directory

*push the already compiled app from my machine to the server

*run the scripts I have, whichever one will work

*Receive notifications that DONE WITHOUT ERRORS actually worked

*Verify on the server that the files are indeed there with WINSCP (This works fine - viewing the directory I mean.)

Thanks all for any help that can be offered


text:
Q: Generate Downloadable PDF's from HTML Tables Can you suggest me some tools to generate downloadable PDFs from HTML tables?
If possible, compatible with Twitter Bootstrap.
Ps.: I've tried Prawn, but I'd like to know some other tools.

A: What you need to know
Basic Perl scripting, HTML, Perl module installation
Introduction
The Adobe © PDF files is one of the popular file format for transferring documents. One of the reasons for this is that it displays the document the way it will be printed (WYSIWYG). Since it does not require a word processor to browse the document, it is also a lot more convenient. You just need their reader to be able to browse the document.
Perl has a module that will allow you to convert HTML files to PDF documents. This is done by using the HTML::HTMLDoc module.
Installation
You need to download the HTMLDoc product from Easy Software Products. Install it first then you can proceed to download the HTML::HTMLDoc module from CPAN. Once you download it, install it as you would typical Perl modules.
Generating your PDF Document
First thing to do is to use the module and create your instance of the HTML::HTMLDoc package.
You can then pass a full HTML document to the package or tell it to generate the PDF document from an HTML file.
Sample code
#!/usr/bin/perl
use HTML::HTMLDoc;
use strict;
####################################################
# This script is distributed according to the terms of
# the Perl Artistic License. Use at your own risk
# © 2004 Philip L. Yuson
####################################################
my $str = '

HTML to PDF Document

Let us see how this will work

This is a row in a table

This is another row

copyright © 2004 Philip L. Yuson

';
my $html = new HTML::HTMLDoc(); # Start instance
$html->set_page_size('letter'); # set page size
$html->set_bodyfont('Arial'); # set font
$html->set_left_margin(1, 'in'); # set margin
$html->set_html_content($str); # contents to convert
my $pdf = $html->generate_pdf(); # generate document
$pdf->to_file('article.pdf'); # save document

Save this as pdf.pl and run it by starting a command line and typing this:
perl pdf.pl
This should generate a PDF file similar to this.
Generating PDF files for download on the web
to generate a PDF which can be downloaded, without saving it to a file, you can use the same script as above except that you need to change the last line. However, to make our example more interesting, we will put the date and time on the document also. So the script will look like this:
#!/usr/bin/perl
use HTML::HTMLDoc;
use Date::Calc;
use strict;
####################################################
# This script is distributed according to the terms of
# the Perl Artistic License. Use at your own risk
# © 2004 Philip L. Yuson
####################################################
my @c = Date::Calc::Today_and_Now();
my $str_temp;
foreach (@c) {
 $str_temp .= sprintf("%02d:", $_);
}
my $str = "

HTML to PDF Document

Let us see how this will work

This is a row in a table

This is another row

This document was generated:
$str_temp
copyright © 2004 Philip L. Yuson

";
my $html = new HTML::HTMLDoc(); # Start instance
$html->set_page_size('letter'); # set page size
$html->set_bodyfont('Arial'); # set font
$html->set_left_margin(1, 'in'); # set margin
$html->set_html_content($str); # contents to convert
my $pdf = $html->generate_pdf(); # generate document
# Tell browser this is a a PDF document
print "Content-Type: Application/pdf\n\n";
$pdf->to_string(); # Send the document


text:
Q: Why infinity minus infinity, 0 multiply infinity, infinity divided by infinity and 0/0 are not defined? Suppose that the arithmetic operation on extended complex plane are defined via arithmetic operations on the corresponding sequences, why $∞-∞,0*∞,∞/∞,0/0 $are not defined? Can anyone give me some example about that?
I know that ∞ + ∞ is undefined because if we have two sequences:
$1, 3, 3, 5, 5, 7, 7, 7, 9,....$    and
$-1,-2,-3,-4,-5,-6,-7,-8,....$
the sum of the above sequences will be:  $0,1,0,1,0,1,0,1,...$
which is not converging or diverging. so ∞+∞ is meaningless.
Can I use it in $ ∞-∞,0*∞,∞/∞,0/0$?
Can anyone give me some example about that?

A: *

*$[\infty-\infty]$

*

*$\lim\limits_{n\to \infty} (n+1)^2-n^2=\infty$

*$\lim\limits_{n\to \infty} (n^2+1)-n^2=1$

*$[0\cdot\infty]$, $\left[\frac{\infty}{\infty}\right]$, $\left[\frac{0}{0}\right]$

*

*$\lim\limits_{n\to \infty} \frac{1}{n}\cdot n^2=\lim\limits_{n\to \infty} \frac{n^2}{n}=\lim\limits_{n\to \infty} \frac{\frac{1}{n}}{\frac{1}{n^2}}=\infty$

*$\lim\limits_{n\to \infty} \frac{1}{n}\cdot n=\lim\limits_{n\to \infty} \frac{n}{n}=\lim\limits_{n\to \infty} \frac{\frac{1}{n}}{\frac{1}{n}}=1$


text:
Q: How to define that RPM package has a GUI in install4j? I'm using install4j and I'd like to know how I can specify that the software package has a GUI. I'm testing this with Mageia and there the packages are grouped as those with a GUI and those without a GUI.
After installing my package it's in the list of packages without a GUI. But it's a Java desktop application with a GUI. Mageia shows those with a GUI by default so my package is hard to find.
Those without a GUI are mostly libraries which get installed as dependencies of other packages. The user usually only installs software with a GUI.

A: On Installer->Screens & Actions, you can add an empty custom application whose "Default execution mode" property is set to "Unattended mode" and then add a single "Add a desktop link" action for your launcher to the "Startup" node.
In the media wizard of your RPM archive, on the "Installer options->Post install script" step, you can then call that executable.

A: For now I use this (for debian too):
Post Install:
#!/bin/bash

echo "Categories=Office;" >> XXXXX.desktop
if [ -x "$(command -v desktop-file-install)" ]; then
  desktop-file-install XXXXX.desktop
fi
if [ -x "$(command -v xdg-desktop-menu)" ]; then
  xdg-desktop-menu install --novendor XXXXX.desktop
fi

exit 0

Post Uninstall:
#!/bin/bash

if [ -f /usr/share/applications/XXXXX.desktop ]; then
  if [ -x "$(command -v xdg-desktop-menu)" ]; then
    xdg-desktop-menu uninstall --novendor XXXXX.desktop
  else
    rm "/usr/share/applications/XXXXX.desktop"
  fi
fi

exit 0

Note that I need to add Categories=Office; to the file, so Mageia/KDE would actually add it to the menu. It works without that on Ubuntu.
It's still not listed as an application with GUI, but at least it's in the menu so the user can start the application.
And you can't use variables of the script is in a file.


text:
Q: Problem with calling 4 async method paralel in constructor I have a problem with tasks in c#, and don't know how to use async await. I have 4 methods, something like:
private async Task Name(parameters) {}

How can I run all 4 methods simultaneously in the constructor, to reduce the execution time and optimize cpu usage.
I tried Parallel.Invoke(() => but this not best solution....

A: You can use this sample code:
Task[] tasks = new Task[4];
tasks[0] = Method0();
tasks[1] = Method1();
tasks[2] = Method2();
tasks[3] = Method3();
await Task.WhenAll(tasks);// If you have to wait all the tasks to be finished.
//await Task.WhenAny(tasks); //If any of them finished.

Update:
Here is the full answer:
static async Task<List<int>> MethodTest(int i)
{
    await Task.Delay(10);
    return new List<int>() { i, i, i };
}
async Task method()
{
    Task<List<int>>[] tasks = new Task<List<int>>[4];
    tasks[0] = MethodTest(0);
    tasks[1] = MethodTest(1);
    tasks[2] = MethodTest(2);
    tasks[3] = MethodTest(3);
    await Task.WhenAll(tasks);
    Console.WriteLine(tasks[0].Result);
}


text:
Q: Evaluate $7\int xe^{6x^2}dx$ using u substitution 5.3
Can somebody verify this solution for me? Thanks!
Evaluate $7\int xe^{6x^2}dx$ using u substitution

Let $u=6x^2$. Then $\frac{du}{dx}=12x$ and so $\frac{du}{12x}=dx$. Thus we have:
$7 \int xe^{6x^2}dx$
$=7 \int xe^u \frac{du}{12x}$
$= \frac{7}{12} \int e^u du$
$=\frac {7}{12} e^u + C$
$=\frac{7}{12} e^{6x^2} + C$


text:
Q: Copy Image to Local Folder Using Python Selenium How can we copy image from source to local folder using python selenium process.
Kindly help me.

A: Here you go:
import urllib
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://www.python.org/')

# get the image source
img = driver.find_element_by_xpath('//img[@class="python-logo"]')
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "python-logo.png")

driver.close()


text:
Q: Can I connect ADF V1 Self Hosted IR in ADF V2? I have some pipelines running in ADF V1, I want to run one more pipeline which involves AWS Redshift as a source, and it needs a Self hosted IR to do that, currently we dont have any option to specify the IR in AWS Redshift connection, so am wondering how this can be done if I Can connect the ADF V1 IR to ADF V2?

A: Currently we cannot reuse the ADF V1 self-hosted IR in ADF V2. You may need to create a new self-hosted IR in ADF V2, then select this IR in "Connect via integration runtime" property.


text:
Q: I have a problem with my div when I write in the text area and hit save nothing is show up I have a problem with my div when I write in the text area and hit save nothing is show up. I have a problem with my div when I write in the text area and hit save nothing is show up
 <!DOCTYPE html>

     <meta charset="utf-8">
     <meta name="Go from idea to action in seconds with wesam to do list">
    <title>wesam list to do</title>

    <form>

 Add your tasks

         <textarea id="text"></textarea>
         <button onClick="input()" id=" b " type="button "> save</button>

A: Try this. There were a few issues with this code. I added comments to the changes.
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="Go from idea to action in seconds with wesam to do list">
  <title>wesam list to do</title>

  <form>

 Add your tasks

    <textarea id="text"></textarea>
    <button onClick="input(event)" id="b" type="button"> save</button>

  </form>

Cheers!

A: *

*Your output element has both a black background, and black text, so you won't see anything change.

*You were missing a </form> tag.
It looks like you're trying to create a list of tasks, and each time you add a new task, and click "save" it adds a new task under the proceeding ones.
Here's an updated example that uses more modern JS methods that you might find useful. Links to the relevant documentation are at the bottom of the post.

// First we cache all our elements
const task = document.querySelector('textarea');
const list = document.querySelector('ul');
const button = document.querySelector('button');

// Instead of inline JS we add an event listener to
// the cached button element.
button.addEventListener('click', handleClick, false);

// `focus` the cursor in the textarea
task.focus();

function handleClick() {

  // We create a new list item
  const item = `<li>${task.value}</li>`;

  // We add that to the list
  list.insertAdjacentHTML('beforeend', item);

  // Reset the textarea value
  task.value = '';

  // And refocus on it so we don't have to
  // manually click in it to write a new task
  task.focus();
}
button { background-color: red; color: white; }
<form>

Add your tasks

  <textarea></textarea>
  <button type="button">Save task</button>
</form>

Addition documentation

*

*querySelector

*Template/string literals

*insertAdjacentHTML

*addEventListener

A: There are couple problem:

*

*You didn't close the form tag in HTML

*you write the first letter of value as capital in input function

*And you may did not look but your button background color is not coming that is because there is spaces inside the id in HTML just remove those and you're good to go.

*And make a paragraph inside the output div and give him the id of output and than stor that into a variable and do o.innerText o is you output paragraph = i.value i is your input

*I have added some features to to your application if you want to copy it i do not mined -

// ES6 Syntax
const render = () =>{
    // Getting the value from HTML DOM to inputEl variable
    const inputEl = document.getElementById('text');
    // Getting the output paragraph from HTML DOM and storig it into output
    const outputEl = document.getElementById('output-text');
    // Rendering the inputEL value into outputEl
    outputEl.textContent = inputEl.value;
}

// ES5-- Syntax
function renderES(){
    // Getting the value from HTML DOM to inputEl variable
    const inputEl = document.getElementById('text');
    // Getting the output paragraph from HTML DOM and storig it into output
    const outputEl = document.getElementById('output-text');
    // Rendering the inputEL value into outputEl
    outputEl.textContent = inputEl.value;
}
@import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');

:root{
    --primary-color: rgb(26, 26, 26);
    --secondary-color: white;
    --font-family: Nunito, sans-serif;
    --box-shadow:  rgb(0 0 0) 1px 1px 3px 0px inset, rgb(48 48 48 / 50%) -1px -1px 3px 1px inset;;
    --all-transition:transform ease-in-out 0.3s 0s;
}

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    font-family: var(--font-family);
}

.main-content{
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container{
    border-radius: 10px;
    box-shadow: var(--box-shadow);
    width: 85%;
    height: 270px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: var(--primary-color);
    flex-direction: column;
}

.container>h1{
    margin-top: 15px;
    color: var(--secondary-color);
    text-transform: uppercase;
}

form{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 5px;
    width: 100%;
    height: 75%;
}

form>textarea{
    width: 95%;
    height: 30%;
    background-color: var(--primary-color);
    border: none;
    border-radius: 10px;
    box-shadow: var(--box-shadow);
    padding: 15px;
    color: var(--secondary-color);
}

#output{
    width: 95%;
    height: 40%;
    background-color: var(--primary-color);
    box-shadow: var(--box-shadow);
    color: var(--secondary-color);
    padding: 10px;
}

form>button{
    background-color: var(--primary-color);
    box-shadow: var(--box-shadow);
    width: 95%;
    height: 30px;
    border-radius: 10px;
    border: none;
    font-weight: bold;
    margin-bottom: 10px;
    color:var(--secondary-color);
    transition: var(--all-transition);
    cursor: pointer;
}

/* NTH CHILD */
form>textarea::placeholder{
    color: var(--secondary-color);
}

/* Animations */
form>button:hover{
    transform: scale(1.02)
}

form>button:active{
    border: 1px solid var(--secondary-color);
}
<!doctype HTML>

        <title>codedamn HTML Playground</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="/style.css" />

 Add your tasks

                <form>
                    <textarea id="text" placeholder="Enter you task here.."></textarea>

                    <button
                    type="button"
                    id="addtask-btn"
                    onclick="render()">
                    Save
                    </button>
                <form>

A: It seems that you haven't ended the
<form>

tag


text:
Q: How to select just an array from MongoDB using PHP? How to select just an array from MongoDB using PHP?
For example, I have data like:
db.articles.insert({name: "topic1", images: ["img1", "img2", "img3"]})

So, how I can select and print it just names of images?

A: We know so little of what you want. You are not even using valid PHP syntax.
The question is vague and doesn't make much sense.
However this should help:
// Make our doc
$doc = array('name' => "topic1", 'images' => array("img1", "img2", "img3"));

// insert our doc
$db->collection->insert($doc);

// Find out inserted doc
$doc = $db->collection->findOne(array('name' => 'topic1'));

// echo out a comma deliminated list of images.
echo implode(',', $doc['images']);


text:
Q: CocoaPods unable to update ScoutMaps-iOS-SDK pod The current (installed) version of ScoutMaps-iOS-SDK is 2.4 and I'm trying to updated to the latest version 2.5.
However it is not updating neither failing.
I've run the command:
pod update

The output was:
Downloading dependencies
Using AFDownloadRequestOperation (2.0.1)
Installing AFNetworking 2.5.4 (was 2.5.3)
Using HMSegmentedControl (1.5.1)
Using MBProgressHUD (0.9.1)
Using Reachability (3.2)
Using SWRevealViewController (2.3.0)
Using ScoutMaps-iOS-SDK (2.4.0)
Using ScoutMaps-iOS-SDKTools (2.4.0)
Using ZipArchive (1.4.0)
Generating Pods project
Integrating client project

If I run the command:
pod outdated

The output is (Even after executing pod update):
Updating spec repositories
Analyzing dependencies
The following pod updates are available:
- ScoutMaps-iOS-SDK 2.4.0 -> 2.4.0 (latest version 2.5)

The contents of my Podfile is the following:
platform :ios, '7.1'

inhibit_all_warnings!

target 'MyTarget' do

pod 'ScoutMaps-iOS-SDK'
pod 'ScoutMaps-iOS-SDKTools'
pod 'AFNetworking', '~> 2.5'
pod 'MBProgressHUD', '~> 0.9'
pod 'SWRevealViewController', '~> 2.3'
pod 'HMSegmentedControl'

end

What could be causing this issue? Does anyone know how to fix it?
PS: I already tried a "clean" install, the output of pod outdated still the same.

A: The reason is that ScoutMaps-iOS-SDK is a dependency of ScoutMaps-iOS-SDKTools and ScoutMaps-iOS-SDKTools hasn't been updated to 2.5.
The spec for ScoutMaps-iOS-SDKTOOLS 2.4 has the below dependency, meaning any 2.4 version of ScoutMaps-iOS-SDK can be used, but not 2.5.
"dependencies": {
    "ScoutMaps-iOS-SDK": [
      "~> 2.4.0"
    ],
    ...
}


text:
Q: How is the partial derivative with respect to normal related to the gradient of a scalar field? I've been trying to understand the solution to a question based on the Gauss Divergence Theorem. The question says,
If $\phi$ is harmonic in $V$, then $\iint_{S} \frac{\partial \phi}{\partial n} dS = 0$. (We need to prove this)
The solution goes like this, and I've added my comments too-
$\iint_{S} \frac{\partial \phi}{\partial n} dS = \iint_{S} (\frac{\partial \phi}{\partial n}n).n dS$. This makes sense because $n$ is the unit normal.
$= \iint_{S} (\nabla \phi).n dS$ I have trouble here. How can we write that $\frac{\partial \phi}{\partial n}n = \nabla \phi$??
$= \iiint_{V} div(\nabla \phi)dV$, by Divergence theorem, this step is clear
$=  \iiint_{V} \nabla^{2} \phi dV = 0$, since $\phi$ is harmonic in $V$, this step is clear too..
Can anybody please explain the second step to me? Firstly, if n is the normal, what do we even, which is a vector, what do we mean by taking a partial derivative with respect to it? Even if we do, won't that result in a vector rather than a scalar? How would that result in the gradient of the vector? I tried writing that $\frac{\partial \phi}{\partial n} = \frac{\partial \phi}{\partial x}\frac{\partial x}{\partial n} + \frac{\partial \phi}{\partial y}\frac{\partial y}{\partial n} + \frac{\partial \phi}{\partial z}\frac{\partial z}{\partial n}$, but was unable to proceed. Help would be appreciated.


text:
Q: Как сделать, чтобы бот отправлял альбом из фотографий, отправленных пользователем? Как получать несколько фото в одном хендлере Aiogram? Есть некий хендлер который ловит в себя фото и к примеру пересылает куда-то там.
@dp.message_handler(content_types=types.ContentTypes.PHOTO)
async def send_to_admin(message: types.Message):
    await bot.send_photo(chat_id=ADMIN_ID, photo=message.photo[-1].file_id)

Так вот если этот юзер(который присылает боту фото) пришлет не одно а два и более, и они буду группированы вот так.

То возникает странная ситуация, хендлер реагирует на каждое отдельное фото, собственно отдельно. По факту он срабатывает дважды (по 1-му на фото), то есть наша message.photo имеет только вариации одной из фоток (размеры) но не имеет другого фото в себе.
Я написал программу, которая отправляет в чат альбом, но бот также отправляет первое фото из альбома:

Вот мой код:
media = []
async def get_state2(message: types.Message, state: FSMContext):
    global media
    if message.text == "Назад":
        await FSMAdmin.state1.set()
        await bot.send_message(message.from_user.id, 'Выберите город, в котором хотите выписать штраф',
                               reply_markup=clubs)
    else:
        photos = message.photo[-1].file_id.split()
        media.append(InputMediaPhoto(photos[-1]))
        media_files = media
        await bot.send_media_group(chat_id=config.chat_id_zel, media=media)
        await FSMAdmin.next()
        await bot.send_message(message.from_user.id, 'Напишите нарушение', reply_markup=back_button_admin)

Как мне исправить код? Помогите, уже третьи сутку бьюсь...

A: class Form(StatesGroup):
    a = State()

async def give_photo_group(msg: types.Message: state: FSMContext):
    async with state.proxy() as data:
        if 'photos' in data.keys():
            data['photos'] = data['photos'].append(msg.photo[-1].file_id)
        else:
            data['photos'] = []
    await Form.a.set()

async def echo_photo_group(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        photo_ids = data['photos']
    await state.finish()
    photo_group = types.MediaGroup()
    for file_id in photo_ids:
        photo_group.attach_photo(file_id)
    await bot.send_media_group(photo_group)


text:
Q: Return position of a node in the linked list, recursive approach So, I am trying to solve a problem where I am supposed to write a recursive method to search for a node in the linked list, and return it's index (indexing from 0). If the node doesn't exist, I need to return -1. This is how far I got implementing the logic. It works fine for all test cases I suppose, except for one, when the node is not in the linked list, it returns last index of the linked list in that case.
This is my logic.
public static int indexOfNRec(LinkedListNode<Integer> head, int n) {
    if(head==null)
        return -1;
    if(head.data==n)
        return 0;
    int count=1;
    return count+indexOfNRec(head.next,n);
}

This is the code for the LinkedListNode
class LinkedListNode<T> {
T data;
LinkedListNode<T> next;

public Node(T data)
    this.data = data;
}

I understand why my logic fails, but I am not able to solve the issue. I'm sorry to ask such a basic question, I'm poor with recursion.

A: i took a helper function to solve the problem,
public static int helper(LinkedListNode<Integer> head, int n,int pos)
{
    if(head==null)
      return -1;

    if(head.data==n)
    {
        return pos;
    }

    int ans=helper(head.next,n,pos+1);
    return ans;
}

public static int indexOfNRec(LinkedListNode<Integer> head, int n) {

  return helper(head,n,0);

}

it works in all test cases.

A: Try
int returnValue = indexOfNRec(head.next,n);
return (returnValue ==  -1) ? -1: returnValue;

(using
if (indexOfNRec(head.next,n).....
return count+indexOfNRec(head.next,n);
is inefficient because it doubles the number of times you run the recursion)

A: This is my Code. I am taking starting index as 0.
Base Case: If the head is null that means if the node is not found and it returns -1 and then while doing the calculation I check if the return is -1 then return -1 to decrease the count.
Other Cases: Increase the value by 1 as you traverse and return 0 if the node is found.
public static int indexOfNRec(LinkedListNode<Integer> head, int n) {

    if(head==null)
        return -1;

    else
    {
        if(head.data!=n)
        {
            int k = indexOfNRec(head.next, n);

            if(k!=-1)
                return k+1;

            else
                return -1;
        }
        else
            return 0;
    }

}

A: In Python v2.5 >
def searchRecursive(head, n):
    if head is None:
        return -1
    if head.data == n:
        return 0
    index = searchRecursive(head.next, n)
    return (1 + index) if index != -1 else -1

A: def findnodeRE(head,i):
if head==None :
    return -1
if head.data==i:
    return 0
head=findnodeRE(head.next,i)
if head!=-1:
    return 1+head
else:
    -1

A: In Python 3.8
def findNodeRec(head, n):
    # Your code goes here
    if head is None:
        return -1
    if head.data == n:
        return 0
    count = findNodeRec(head.next, n)
    if count!=-1:
        return 1+count
    else:
        return -1

A: This should be the function in c++ to return the position of the node in the linked list.
    int findNodeRecursive(Node *head, int n)
    {
          int smallAns;
          if(head == NULL){
             return -1;
          }
          if(head -> data == n) {
             return 0;
          }

          if(head -> data != n){
             smallAns = findNodeRecursive(head -> next, n);

              if(smallAns != -1){
                  return smallAns + 1;
              }
              else{
                  return -1;
              }
          }
    }


text:
Q: render helper and Controller instantiation I'm using the render controller extensively in my app and am having trouble understanding the  logic around Controller creation.
The code in question uses this (cut-down) template (using emblem.js):
    .span4
      render "learningNeeds" # models loaded in learningNeeds controller
    .span8
      render "notices" student.room.notices # student is defined on the top-level controller
      render "observations" # models loaded in observations controller

and the setupController for the template's Route:
App.ParentRoute = Ember.Route.extend

  setupController: (controller, model) ->
    console.log "ParentRoute setupController"

    controller.set('student', model.get('students').objectAt(0))
    @set('controller.controllers.observations.showFilters', true) # this works
    @set('controller.controllers.learning_needs.showFilters', true) # this works
    @set('controller.controllers.notices.showAdd', true) # this doesn't work
    App.currentUser = model

I'm setting the content of the learning_needs and observations controllers in observers within their respective controllers, so I'm not passing in any model to the render call in the template.
With the notices controller I'm passing in the student.room.notices as the 2nd parameter to the render call.
Now the issue is that the I'm seeing different notices controllers when I render the template to that in the Parent setupController method. That is, they have different ember ids. The controller at @set('controller.controllers.notices.showAdd', true) is different to that rendered by the template.
If I remove the student.room.notices model from the template and just use `render "notices" then the same controller is used and I can set the showAdd property and have it display in the template. The problem then is it doesn't contain any models.
The relevant docs say the render view helper will Get (or generate) the singleton instance of AuthorController but this doesn't seem the case for me.
Can anyone shed any light on this behaviour?
thanks,
Martin

A: I think you should use property bindings.
In NoticesController:
showAdd: Ember.computed.alias('parentController.noticesShowAdd'
In setupController:
controller.set('noticesShowAdd', true)
Then you don't have to worry about figuring out how to get a reference to the notices controller.
Note, if render is called inside an each, you may need to use target instead of parentController.


text:
Q: How to monitor tomcat logs with Elastic stack in ubuntu I am configuring tomcat8 logs into Elastic stack dashboard using the following reference link:
https://logz.io/blog/apache-tomcat-monitoring/
I am using a ubuntu 18.04 server installed tomcat8 and configured the logstash.conf file and filebeat file but the logs are not displayed in the kibana dashboard
Can you please update how to configure this scenario?
Here is my filebeat.yml file

filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/tomcat8/localhost_access_log.2019-09-11.txt
- /var/log/tomcat8/catalina.out.1
- /var/log/tomcat8/catalina.out

#------------- Logstash output ------------------------
               output.logstash:
               # The Logstash hosts
               hosts: ["localhost:5044"]

enter code here

This is my .conf file
input {
beats {
port => 5044

}

filter {
grok {
  match => { "message" => "%{COMBINEDAPACHELOG}" }

date {
  match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]

 geoip {
  source => "localhost"

 }

output {
 elasticsearch {
hosts => ["172.17.5.106:9200"]

}

curl -X GET "localhost:9200/_cat/indices?v"
health status index                           uuid                   pri       rep docs.count docs.deleted store.size pri.store.size
green  open   .monitoring-kibana-6-2019.09.11 gbOahp_KS56HZfeSVt0sgQ   1    0       8639            0        2mb            2mb
green  open   .monitoring-es-6-2019.09.08     NmS7exwcQA-OTgAxVWtQBA   1   0     103690           40     38.1mb         38.1mb
green  open   .monitoring-kibana-6-2019.09.08 JnOFYqNZRceaj5GA6WmL4Q   1   0       8639            0      1.9mb          1.9mb
green  open   .monitoring-es-6-2019.09.11     CXhPOf6xSDiG9bnGs58SEQ   1   0     155586           84     62.4mb         62.4mb
green  open   .monitoring-es-6-2019.09.12     RyhD98zwTVKPvl1BzDECug   1   0      64468          160     27.6mb         27.6mb
green  open   .monitoring-es-6-2019.09.09     VUIiK99ESdaGMoIOKzvstg   1   0     121067           80     47.1mb         47.1mb
green  open   .kibana_task_manager            KnCr7PerTyeFmwcwz0IamA   1   0          2            0     12.6kb         12.6kb
green  open   .kibana_1                       Lu5oH-BgSheJdAwKGXutqw   1   0        198           34      378kb          378kb
green  open   .monitoring-kibana-6-2019.09.07 te49nDoDQH2g12C3bOluvQ   1   0       8639            0      1.9mb          1.9mb
green  open   .monitoring-es-6-2019.09.10     ne6d71h1Ri2fJ2joOxV4Yw   1   0     138256           60     54.1mb         54.1mb
green  open   .monitoring-es-6-2019.09.07     I4Z0SlDjShabcVOl9oGJPQ   1   0      86414           42     31.6mb         31.6mb
green  open   .monitoring-kibana-6-2019.09.09 ruXbntBHTl6yrSkj0tormg   1   0       8640            0        2mb            2mb
green  open   .monitoring-kibana-6-2019.09.06 Go1pi-NhT8eVlKX2QgMMKA   1   0       3007            0    828.3kb        828.3kb
green  open   .monitoring-es-6-2019.09.06     oCgFiC1dRr-wjw0tdGxlRw   1   0      24058           28      9.8mb          9.8mb
green  open   .monitoring-kibana-6-2019.09.12 jr5nRZgtSAebP1jbCeQDxQ   1   0       3221            0    821.2kb        821.2kb
green  open   .monitoring-kibana-6-2019.09.10 seRLoCjXRtGU9U3ZiSl2Fw   1   0       8639            0        2mb            2mb

here is my /var/log/filebeat/filebeat file
2019-09-11T17:12:04.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:12:34.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:13:04.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:13:34.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:14:04.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:14:34.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:15:04.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
2019-09-11T17:15:34.655+0530    INFO    [monitoring]    log/log.go:144  Non-zero metrics in the last 30s        {"monitoring": {"metrics": {"beat":{"cpu":{"system":{"ticks":27$
this is my /var/log/logstash/logstash-plain.log file
[2019-09-08T00:00:13,284][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"6.8.3"}
[2019-09-08T00:00:14,084][ERROR][logstash.agent           ] Failed to execute action {:action=>LogStash::PipelineAction::Create/pipeline_id:main, :exception=>"LogStash::Config$
[2019-09-08T00:00:14,228][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2019-09-08T00:00:19,281][INFO ][logstash.runner          ] Logstash shut down.
[2019-09-08T00:00:49,251][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"6.8.3"}

A: Can you confirm your full filebeat.yml configuration? Looks like you are missing the filebeat output section.
You can check the logz.io link you posted or the official documentation on the logstash output: https://www.elastic.co/guide/en/beats/filebeat/current/logstash-output.html
output.logstash:
  hosts: ["localhost:5044"]

A: Based on the Filebeat log it's working fine.
But in your Logstash configuration, input {, date {, geoip {, and output { are missing a closing }.
And I'm not really sure about your geoip filter — that field is really called localhost? To keep it simple, I'd remove that part and get the rest working first.
Try the following config:
input {
  beats {
    port => 5044
  }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }

  date {
    match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
  }
}

output {
  elasticsearch {
    hosts => ["172.17.5.106:9200"]
  }
}

If it doesn't work, please update your answer with the new log output of Logstash.


text:
Q: Comando LaTeX para criar arquivo C Olá, gostaria de saber se existe uma maneira de gerar um arquivo a partir do PDF elaborado em LaTeX.
O que eu quero fazer:
Escrevo um código LaTeX, compilo e gero o PDF dele. Em determinado momento, quero mostrar um código que é longo demais para ficar dentro do PDF(questão de legibilidade) e então clico em um nome(Por exemplo: "TratamentoDeDados.c") e então cria-se um arquivo "TratamentoDeDados.c" na mesma pasta do PDF para a pessoa abrir, ver, compilar e testar. O clicar no nome é semelhante ao dado por referências, que abre um link externo(url) ou vai para determinada parte do PDF.
Isso evita o PDF ficar poluído com muito código(3 páginas seguidas) e enviar arquivos .rar ou .zip com o PDF e diversos códigos dentro.
Caso não seja possível criar arquivo, como faz para abri-lo com o clicar no nome, no caso de eu enviar um zip com PDF e códigos dentro?

A: Use: \usepackage[pdftex]{hyperref}
Então: \href{filename.c}{texto do link} no corpo do texto.
Pesquise sobre Hyperref do Latex para mais informações.

Neste caso, você deve distribuir o arquivo junto com o PDF. O latex não vai criá-lo, somente criar o link para a pessoa clicar.