text:
Q: Trouble using the Haversine formula I'm trying to use the Haversine formula to locate all bus stops within 1 mile of my current location. I have a MySQL DB table that contains the latitude/longitude locations of 5500 bus stops, and am using the following SQL query:
"SELECT id,
( 3959 * acos( cos( radians(37.865971) ) * cos( radians( stopLat ) ) * cos( radians( stopLon ) - radians(-122.283775) ) + sin( radians(37) ) * sin( radians( stopLat ) ) ) )
AS distance FROM stops HAVING distance < 1 ORDER BY distance";`"

stops is the name of the DB table.
stopLat is the name of the column in which the latitudes are listed.
stopLon is the name of the column in which the longitudes are listed.
The lat/long of the location I'm using is 37.865971, -122.283775.
I'm doing this from a Java program. The program runs successfully, but my ResultSet comes
back empty even though I am sure there are 50+ bus stops within a mile of the location being inputted.
Where am I going wrong?
EDIT: I've noticed that when I change 1 to anything over 500, it returns the entire result set. Further, it tells me that they are all between 497-480 miles away, which indicates the the problem is (as I suspected) in the math, i.e. in the statement itself.
EDIT - SOLVED  (see my own answer below)

A: This expression:
sin( radians(37) )

isn't precise enough. Changing it to:
sin( radians(37.865971) )

gives the expected result.


text:
Q: Is % percentage a valid url character I am trying to put a url, something like the following urn:test.project:123, as part of the url.
Does it make sense to encode urn:test.project:123 into urn%3atest.project%3a123 and decode it back to urn:test.project:123 at the receiver end?
http://{domain}/abc/urn%3atest.project%3a123/Manifest

A: Yes, it's a valid character.  It's the escape character for URLs in a similar way to how the ampersand & is the escape character for xml/html, and the backslash \ is the escape character for string literals in c-like languages.  It's the (very important) character that allows you to specify (through an escape sequence) all the other characters that wouldn't be valid in a URL.
(And yes, it makes sense to encode such a string so it's a legal URL, and as @PaulPRO mentions, most frameworks will automatically decode it for you on the server-side.)

A: Yes, the %3a means that 3a is the HEX encoded value for ':'
If you put it in the url as %3a your server will most likely automatically decode it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to delete sections in collection views How can I delete individual sections from a controller view? I have a button in the header and everything is connected. Just not sure how can I write the code for 3 different sections.
My data model
var fire = [UIImages]
var water = [UIImages]
var air = [UIImages]

var fireLabel = [String]
var waterLabel = [String]
var airLabel = [String]

My cell configuration code
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    if indexPath.section == 0 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.fire.image = fireImages[indexPath.row]
        cell.fireLabel.text = fireNames[indexPath.row]

    return cell

    } else if indexPath.section == 1 {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.water.image = waterImages[indexPath.row]
        cell.waterLabel.text = waterNames[indexPath.row]

        return cell

    } else {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        cell.air.image = airImages[indexPath.row]
        cell.airLabel.text = airNames[indexPath.row]

        return cell

    }

}

And here is my button code, its in every header. What I want to do is that when you click on this button, it deletes that entire section. Again for each. But I can't seem to make it work.
//Delete Section Button
@IBAction func deleteSectionButton(sender: UIButton) {

    //Section tag
    let section = sender.tag

    //Update data model
    fireImages.removeAtIndex(section)
    fireNames.removeAtIndex(section)

    self.collectionView?.deleteSections(NSIndexSet(index: section))

}

I'm getting this error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections.  The number of sections contained in the collection view after the update (3) must be equal to the number of sections contained in the collection view before the update (3), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).'
But I don't know what it means.

A: you can just reload the collection view after updating your data. It will populate back your data proportionally to the collection view
self.collectionView.reloadData();


text:
Q: Enhance existing web app with Sencha ExtJS? I have an existing web application which uses a standard jQuery powered datagrid, but could really do with something more fancy.
All the ExtJS examples on the Sencha website use their layout creator and how a desktop app can be replicated in the browser. I would like to know - is it possible (and feasible) to use the ExtJS components/widgets in 'normal' HTML pages, as per a standard webapp?

A: Yes, absolutely.  You can include the ExtJS library on your page, just like jQuery, and do all kinds of things -- manipulate the DOM, add/remove HTML elements on your page, insert ExtJS components anywhere within your markup, etc.
For example, if you have an element with an id of "my-ext-widget", then you can create an ext component (like a panel) and insert it in that element, like this:
Ext.onReady(function() {
    myPanel = new Ext.Panel({
        title:'Sample Panel',
        height:300,
        width:200,
        html:'This is a sample panel'
    });

    myPanel.render("my-ext-widget");
});

What exactly are you trying to do?

A: What you are asking for is possible and without being too invasive on your current code base. i.e. you can load you existing DOM and then do the Sencha magic after your page loads (in onReady as explained by Jonathan) for whatever you can think of (within the ExtJS boundaries offcourse).
Also, not all examples use their layout creator.
This is a perfect example of the concept you are trying to get at-
How to create a grid from an existing, unformatted HTML table


text:
Q: Erro ao executar o UPDATE Ao executar o UPDATE ocorreu os seguintes erros:
Notice: Undefined variable: mysqli in C:\xampp\htdocs\guaraparivirtual\count\count.php on line 17

Fatal error: Uncaught Error: Call to a member function query() on null in C:\xampp\htdocs\guaraparivirtual\count\count.php:17 Stack trace: #0 {main} thrown in C:\xampp\htdocs\guaraparivirtual\count\count.php on line 17

Código:
 <?php include ("../incluir/conexao.php"); ?>

<?php
$id = $_GET["id"];

                $propaganda_count=mysqli_query($con,"select click,link FROM bannersclick where id='$id'");
                while($count_click=mysqli_fetch_array($propaganda_count)){

                    $clickget = $count_click['click'];
                    $linkget = $count_click['link'];
                }

$clickget = $clickget + 1;

    $sqli = "UPDATE bannersclick SET click = '$clickget' where id = '$id'";
    $mysqli->query($sqli);

header( "Location: $linkget" , TRUE , 302 );
?>

A linha 17 dos erros é: $mysqli->query($sqli);
Busquei solucionar, mas não compreendi o motivo do erro.

A: Pelo erro, parece que nenhuma conexão foi iniciada na variável $mysqli. E observando o restante do código adicionado, a variável $mysqli não existe até você utilizá-la na linha 17, na query anterior, você utiliza a variável $conn para fazer a pesquisa.
Sem alterar demais o código, ao invés de usar uma variável que não existe, utilize a variável de conexão que você utilizou na query anterior:
<?php include ("../incluir/conexao.php"); ?>

<?php
    $id = $_GET["id"];

    $propaganda_count=mysqli_query($con,"select click,link FROM bannersclick where id='$id'");

    while($count_click=mysqli_fetch_array($propaganda_count)){
        $clickget = $count_click['click'];
        $linkget = $count_click['link'];
    }

    $clickget = $clickget + 1;

    $sqli = "UPDATE bannersclick SET click = '$clickget' where id = '$id'";
    $conn->query($sqli);

    header( "Location: $linkget" , TRUE , 302 );
?>

Atente-se ao que diz a documentação:

It is possible to switch between styles at any time. Mixing both styles is not recommended for code clarity and coding style reasons.

Ou seja, não é recomendável utilizar os dois modos ao mesmo tempo, por razões de organização e clareza de código.
Fonte: Documetação PHP


text:
Q: mat-datepicker makes the app crash without logged error I've got this page component template at the url /demo
<mat-form-field>
  <input matInput placeholder="Choose a date">
</mat-form-field>

Which renders fine, but as soon as I rewrite this as
<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

the app redirects to the url / and does not displays anything but blank space. Nothing is logged in the console.
The code is supposed to work because it's copied from Angular Material basic datepicker example. I've imported MatFormFieldModule, MatInputModule and MatDatepickerModule.
What is happening?

A: A solution is to additionally import the optional Material module MatNativeDateModule. No dependency is explicitly stated in Material's doc on mat-datepicker, but it seems to be required in some cases.
Thanks to @pengyy 's answer on this question that helped me get to this solution.

A: In case somebody still encounters this problem, even after the solution of Nino Filiu, try to add the MatDatePickerModule dependency in the app.module.ts.
I had a lazy loaded module, containing mat-dialogs where the mat-datepicker was used.
I initially had my mat dependencies within the lazy loaded module. Only after moving MatDatePickerModule to the app.module.ts, the view (dialog) stopped crashing.


text:
Q: CSS how to make table's column width less than the content? I want to make one width of column in table to be less, than content with. Here's my code:
html:

            col1
            col2
            col3
            col4

            aaaaaa
            aaaaaa
            aaaaaa
            aaaaaa

scss:
.table {
    margin: 0;
    padding: 0;
    border-collapse: collapse;
    table-layout: fixed;
}

td, th {
    border: 1px solid black;
    padding: 5px 8px;
}

td:first-child, th:first-child {
    width: 10px;
    overflow: hidden;
    white-space: nowrap;
}

As I understand setting table-layout: fixed should helped, but nothing is really changed. The first column's with still is not 10px.
How can I set width to a column then?

A: You may give it a try with max-width instead.
disclaimer: unsure if all browsers will take it

.table {
    margin: 0;
    padding: 0;
    border-collapse: collapse;
    table-layout: fixed;
}

td, th {
    border: 1px solid black;
    padding: 5px 8px;
}

td:first-child, th:first-child {
    max-width: 10px;
    overflow: hidden;
    white-space: nowrap;
}

            col1
            col2
            col3
            col4

            aaaaaa
            aaaaaa
            aaaaaa
            aaaaaa

A: Also when I added width: 100% to the table, code started to work


text:
Q: Text Boxes Not Populating from Database Framework: ASP.NET 4.5 | Database: MSMMS
My demo application is supposed to populate textboxes with dynamic data when a selection is made from a dropdown list. I've added a button, that when pressed fires, an OnClick event that is supposed to assign values from the DB to the appropriate textboxes. Right now my code looks like:
protected void btnChoose_Click(object sender, EventArgs e)
    {
        API_DatabaseEntities1 db = new API_DatabaseEntities1();
        var customer = (from c in db.Customers
                        where c.CustomerID == 4
                        select c).FirstOrDefault();

        if (customer == null)
        {
            return;

        }

        if (ddlCustomer.SelectedValue == "Marisol") {

            tbDescription.Text = customer.ToString();
            tbFName.Text = customer.Fname;
            tbSocial.Text = customer.SSN;
            tbDOB.Text = customer.DOB.ToString();
            tbFName1.Text = customer.Fname;
            tbMName.Text = customer.Mname;
            tbLName.Text = customer.Lname;
            tbPrimaryPhone.Text = customer.PrimaryPhone;
            tbSecondaryPhone.Text = customer.SecondaryPhone;
            tbAdd1.Text = customer.Address;
            tbCity.Text = customer.City;
            tbZip.Text = customer.Zip;
            tbEmail.Text = customer.Email;
            tbMonLease.Text = customer.MortLeaseAmt;
            tbEmployer.Text = customer.Employer;
            tbPosition.Text = customer.Position;
            tbHireDate.Text = customer.HireDate.ToString();
            tbWorkPhone.Text = customer.WorkPhone;
            tbGross.Text = customer.GrossIncome;

        }

        Debug.WriteLine(tbPosition.Text);

    }

When the button is clicked, the page sends a request to the DB, but the textboxes remain blank. I am returning a value from the database, but it's not populating. Here is some code from my front page:
<form id="form1" runat="server">

    <asp:DropDownList ID="ddlCustomer" runat="server" DataSourceID="SqlDataSource1" DataTextField="Fname" DataValueField="CustomerID"></asp:DropDownList>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:APIConnectionString %>" SelectCommand="SELECT [CustomerID], [Fname], [Lname] FROM [Customer] ORDER BY [Fname]"></asp:SqlDataSource>

    <asp:Button ID="btnChoose" runat="server" Text="Choose Test Case" OnClick="btnChoose_Click" />

 Description of Goods and/or Services:<asp:TextBox ID="tbDescription" runat="server"></asp:TextBox>

 Membership #:<asp:TextBox ID="tbMembership" runat="server"></asp:TextBox> Ext.: <asp:TextBox ID="tbExt1" runat="server"></asp:TextBox>
 First Name:<asp:TextBox ID="tbFName" runat="server"></asp:TextBox>

  Soc Sec No.: <asp:TextBox ID="tbSocial" runat="server"></asp:TextBox> Date of Birth:<asp:TextBox ID="tbDOB" runat="server" ></asp:TextBox>

I'm not sure if the problem is from the code behind or from the front page design. Any help would be appreciate. Thank you.

A: It looks like your code is checking for a selection in the drop-down list of the name "Marisol" - however, the "Value" field of the drop-down list is configured to use the CustomerID column.  So this code populating the fields will never execute.
Maybe you should instead be using ddlCustomer.SelectedValue in the WHERE clause of your query.


text:
Q: Option strict on disallows late binding error I am already using following code. (Following code is okey)
Public Class Form1

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim FSO As Object = CreateObject("scripting.filesystemobject")
    FSO.deletefolder("C:\ATTACHMENTSSS")
End Sub

End Class

I did option strict is on.
Now I have this error: http://prnt.sc/afi2ws
How to solve that error?

A: Use the methods from the System.IO classes like DirectoryInfo
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim di = new DirectoryInfo("C:\ATTACHMENTSSS")
    If di.Exists Then
       di.Delete(True)
    End If
End Sub


text:
Q: symfony2 assets:install output directory I am trying to change the default "web" directory of symfony to something else for example public_html.
I got most of it working by following the manual here -> http://symfony.com/doc/master/cookbook/configuration/override_dir_structure.html
Very last part of that document explains how to change assetic so that assetic:dump will output to the correct directory, so that works, and the website also works.
However the document doesn't seem to explain how to change the output directory of the assets:install command.
When i run this command it still outputs to the web directory.
Does anybody know how to change this ?

A: assets:install requires a parameter telling where to install the assets:
app/console assets:install path

Just provide your path instead of web.

A: You can set a path parameter to assets:install
But I think in some case better not overriding the directory structure, preferably making a symlink to the web dir.


text:
Q: Stream and parse a large collection (not array) of json objects from a file I need to stream and parse a json of the following format from a large json file?  I have tried the usual method of which only parses an array, but it fails for the following format.
{
    "ABCD": {
        "name": "John",
        "cars": [],
        "nums": [],
        "id": "52000"
    },
    "WXYZ": {
        "name": "Jone",
        "cars": [],
        "nums": [],
        "id": "32000"
    },
    ...
}

A: Declare a type representing the values:
type Value struct {
    Name string
    Cars []string
    Nums []int
    ID   string
}

Use the json.Decoder in stream mode mode to read the top-level object. See commentary for details.
func decodeStream(r io.Reader) error {
    dec := json.NewDecoder(r)

    // Expect start of object as the first token.
    t, err := dec.Token()
    if err != nil {
        return err
    }
    if t != json.Delim('{') {
        return fmt.Errorf("expected {, got %v", t)
    }

    // While there are more tokens in the JSON stream...
    for dec.More() {

        // Read the key.
        t, err := dec.Token()
        if err != nil {
            return err
        }
        key := t.(string) // type assert token to string.

        // Decode the value.
        var value Value
        if err := dec.Decode(&value); err != nil {
            return err
        }

        // Add your code to process the key and value here.
        fmt.Printf("key %q, value %#v\n", key, value)
    }
    return nil
}

Use it like this:
err := decodeStream(f) // f is the *os.File
if err != nil {
    // handle error
}

Run it on the Go Playground.


text:
Q: Why static files are served on Heroku without activating WhiteNoise? I followed a tutorial on deploying Django app on Heroku server and I stumble across this:

*

*I have installed WhiteNoise package for serving statics

*Added inside settings.py:

MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

But omitted to activate it inside wsgi.py file:
from whitenoise import WhiteNoise
from my_project import MyWSGIApp
    application = MyWSGIApp()
    application = WhiteNoise(application, root='/path/to/static/files')
    application.add_files('/path/to/more/static/files', prefix='more-files/')

Why the static files are served on the production site ? Should not the above code be responsible for this ?

A: The wsgi.py integration hasn't been required since v3.0 and was removed in v4.0.


text:
Q: angular how to control all your addrows? guys I'm trying to create a Form Array once I clicked the modal, the mat-table will appear. and I will select a row, once I clicked the row it will pass to the other component
but, when I add a row again it will get the value of the first row. The first row Data should be static, then I can click a row again without affecting the first row that has been selected.

DIALOG HTML

<mat-table [dataSource]="DataSource">

  <ng-container matColumnDef="Name">
    <mat-header-cell *matHeaderCellDef>ITEM CODE</mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.ItemCategory.Item}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
                <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selectedRow(row)"></mat-row>
              </mat-table>

DIALOG TS

constructor(private micro:ItemSVCPropertyService, private dialogRef: MatDialogRef<ItemDialogComponent>,)

     selectedRow(row){
        this.micro.ItemServices= (row)
        this.dialogRef.close();
      }

COMPONTENT THAT NEED TO GET THE OBJECT ONCE I CLICK THE SELECTED ROW

.HTML

<form [formGroup]="Form">
<ng-container  formArrayName="ItemRec">

ITEM

<button mat-raised-button color="accent" (click)="openDialog()">
<mat-icon>search</mat-icon>
</button>

<input type="" style="width:200px" class="form-control"
formControlName="Item">

</ng-container>
</form>

.TS

openDialog(){
this.dialog.open(ItemDialogComponent)
.afterClosed().subscribe(response => {
if(response === 'save'){
 }
});
}

addRow(): void {
      this.ItemRec.push(this.CreateItemRec());
    }

CreateItemRec(): FormGroup {
        return this.fb.group({
          id:[0],
          Item:['',Validators.required],
        })

    }

 this.Form = this.fb.group({
    Id:['0'],
    ItemRec: this.fb.array([this.CreateItemRec()])
  })
 }

get ItemRec(): FormArray {
      return <FormArray>this.Form.get('ItemRec') as FormArray
    }

THIS CODE TO GET THE OBJECT OF THE OTHER COMPONENT USING SERVICES

get getList() {
      return this.micro.getList?.Item;
   }

.SERVICES

@Injectable({
  providedIn: 'root'
})
export class ItemServices {
  getList:myDTO;
}

similar problem
Getting the specified value from the FormArray in Angular 9


text:
Q: How to use `stringr` in `dplyr` pipe I am having trouble with this code which attempts to edit some strings in a dplyr pipe. Here is some data that throws the following error. Any ideas?
data_frame(id = 1:5,
           name = c('this and it pretty long is a',
                    'name is a',
                    'so and so and so and so  and so',
                    'this is a',
                    'this is a variabel name'))
%>%

str_trunc(.,
   string = .$name,
   width = 10,
   side='right',
   ellipsis = '')

Gives me this error: Error in str_trunc(., string = .$name, width = 10, side = "right", ellipsis = ". . . ") : unused argument (.).
Thanks.

A: You need to mutate or mutate_at/if/all to change the contents of the column.
data_frame(id = 1:5,
       name = c('this and it pretty long is a',
                'name is a',
                'so and so and so and so  and so',
                'this is a',
                'this is a variabel name')) %>%
mutate_at("name", str_trunc, width = 10, side='right', ellipsis = '')

# A tibble: 5 x 2
     id name
  <int> <chr>
1     1 this and i
2     2 name is a
3     3 "so and so "
4     4 this is a
5     5 "this is a "

I use mutate_at here out of personal preference. Note that the mutating column is automatically passed as the first argument. If you want to put it somewhere else in the function call, refer to it as ..

A: There is no data parameter in str_trunc, so you need to feed it the string.  You can use
data_frame(id = 1:5,
           name = c('this and it pretty long is a',
                    'name is a',
                    'so and so and so and so  and so',
                    'this is a',
                    'this is a variabel name'))$name %>%
  str_trunc(width = 10,
            side='right',
            ellipsis = '')

A: if you want to add/update column from existing one, please use mutate function.
you can't use the stringr function directly in the pipe.
data_frame(id = 1:5,
           name = c('this and it pretty long is a',
                    'name is a',
                    'so and so and so and so  and so',
                    'this is a',
                    'this is a variabel name'))  %>%
           mutate(name=str_trunc(name,width=10,side='right',ellipsis=''))
## # A tibble: 5 x 2
##      id name
##   <int> <chr>
## 1     1 this and i
## 2     2 name is a
## 3     3 "so and so "
## 4     4 this is a
## 5     5 "this is a "

the mutate(blah blah) is equivalent to followings
> df<-data_frame(id = 1:5,
        name = c('this and it pretty long is a',
                 'name is a',
                 'so and so and so and so  and so',
                 'this is a',
                 'this is a variabel name'))

> df
## # A tibble: 5 x 2
##      id name
##   <int> <chr>
## 1     1 this and it pretty long is a
## 2     2 name is a
## 3     3 so and so and so and so  and so
## 4     4 this is a
## 5     5 this is a variabel name
> df$name<-str_trunc(df$name,width=10,side='right',ellipsis='')
> df
## # A tibble: 5 x 2
##      id name
##   <int> <chr>
## 1     1 this and i
## 2     2 name is a
## 3     3 "so and so "
## 4     4 this is a
## 5     5 "this is a


text:
Q: Changing reportviewer values in code I have an integer value stored in my database representing a document status.
I want to write a report that shows the status in one of the columns.
However, I don't want to show the raw integer value in the column. I want to show a string that transforms the status to a human-readable format.
eg:
1 -> New
2 -> Pending
3 -> Sent

This feels like it requires more than an expression - ie: C# code. Is this possible?

A: You could also solve the problem by using a CASE in the query you use to select.
SELECT
CASE
  WHEN Status = 1 THEN 'New'
  WHEN Status = 2 THEN 'Pending'
  WHEN Status = 3 THEN 'Sent'
END as "StatusStr"
FROM
...
;

A: If you are passing integer parameter to the report viewer and you want to transform it to some "string" you can assign expression for the column like
=IIF(Fields!Status.Value = 1, "New", IIF(Fields!Status.Value = 2, "Pending", "Sent"))


text:
Q: r - subsetting one row of data frame drops zero decimal from number Data
Given a data frame
df <- data.frame("id"=c(1,2,3), "a"=c(10.0, 11.2, 12.3),"b"=c(10.1, 11.9, 12.9))

> df
  id    a    b
1  1 10.0 10.1
2  2 11.2 11.9
3  3 12.3 12.9

> str(df)
'data.frame':   3 obs. of  3 variables:
 $ id: num  1 2 3
 $ a : num  10 11.2 12.3
 $ b : num  10.1 11.9 12.9

Question
When subsetting the first row, the .0 decimal part from the 10.0 in column a gets dropped
> df[1,]
  id  a    b
1  1 10 10.1

> str(df[1,])
'data.frame':   1 obs. of  3 variables:
 $ id: num 1
 $ a : num 10
 $ b : num 10.1

I 'assume' this is intentional, but how do I subset the first row so that it keeps the .0 part?
Notes
Subsetting two rows keeps the .0
> df[1:2,]
  id    a    b
1  1 10.0 10.1
2  2 11.2 11.9

A: I assume you understand this is a matter of how the number is printed, and not about how the value is stored by R. Anyway, you can use format to ensure the digits will be printed:
> format(df[1,], nsmall = 1)
   id    a    b
1 1.0 10.0 10.1
> format(df[1,], nsmall = 2)
    id     a     b
1 1.00 10.00 10.10

The reason for this behavior is not about the number of rows being printed. R will try to display the minimum number of decimals possible. But all numbers in a column will have the same number of digits to improve the display:
> df2 <- data.frame(a=c(1.00001, 1), b=1:2)
> df2
        a b
1 1.00001 1
2 1.00000 2

Now if I print only the row with the non-integer number:
> df2[1,]
        a b
1 1.00001 1


text:
Q: How to crop an image in Edge & IE 11 to zoom out (negative sx/sy or swidth/sheight too large) My problem is with ctx.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); in that when sx or sy are negative, both IE and Edge browsers simply don't seem to display any image at all. If swidth or sheight are greater than img's dimensions, neither IE nor Edge will display the image either.
I have some code a lot like what's found here: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_canvas_drawimage3
This is a copy of the code from that site:
<!DOCTYPE html>

Image to use:

Canvas:

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

Note: The canvas tag is not supported in Internet
Explorer 8 and earlier versions.
 //That's fine, I'm just here about IE 11 today.

I'm trying to crop arbitrary images that may be very tall and skinny or wide and short such that they fit into a square.
Like this:
How can I crop an image in IE and Edge that will fit into a square such that I'm adding whitespace around it? It seems like Microsoft only ever expects me to be zooming in on an image, not zooming out. Note: This works great in Chrome and Firefox.

A: I get the exact same results in IE, Chrome, FX and Edge. Check the values that you are using in each browser (50,0,150,200,10,10,150,160)... also check each browsers zoom settings are the same and the display DPI settings... to zoom an image in canvas you can use the transform method.


text:
Q: python - Pattern matching assign regex groups to class members I am trying to parse a data stream into a class by defining a regex with named groups that correspond to the member variables.

import re
##-------------------------------------------------------------------------------------------------
pattern = """^(?P<A>\w{4})(?P<B>\w{4})(?P<C>\w{4})"""
##-------------------------------------------------------------------------------------------------
class Data:
    def __init__(self):
       self.A       = 0     ##4 bytes
       self.B       = 0     ##4 bytes
       self.C       = 0     ##4 bytes

    def show(self):
       print( "Data:" )
       print( "------------------------------------" )
       members = [attr for attr in dir(self) if not callable(getattr(self,attr)) and not attr.startswith("__")]
       for member in members:
           print("%s:%s" % (member, getattr(self, member)) )
##-------------------------------------------------------------------------------------------------
hex_stream = "00001111BEEF"
##-------------------------------------------------------------------------------------------------
SearchObj = re.search(pattern, hex_stream, re.I)
if SearchObj:
    D = Data()
    members = [attr for attr in dir(D) if not callable(getattr(D, attr)) and not attr.startswith("__")]
    for member in members:
        grp_name = "\'"  +member + "\'"
        print( grp_name )
        setattr( D, member, int( SearchObj.group( grp_name ), 16 ) )
        val = getattr( D, member )
        print("%s:%s" % ( val, member ) )

The above complains about there being "no such group" on the setattr() line when 'A' is printed for the grp_name.  Where syntactically am I going wrong?

A: I'd change the init method to take the member values, like so:
class Data:
    def __init__(self, A, B, C):
       self.A       = A
       self.B       = B
       self.C       = C

Then, you can use the match.groupdict method like so:
match = re.search(pattern, hex_stream, re.I)
if match:
    # pmatch is a dict (grp_name -> grp_value)
    pmatch = match.groupdict()
    # we create a new dict by converting the grp_value to an int:
    params={name: int(value,16) for (name,value) in pmatch.items()}
    # then we just create D from those values.
    D = Data(**params)

So why should you do it that way?
The implementation you posted inspects the object D in order to determine the attributes that need to be set.  What happens if you add a non-callable member to your class later on?  It will get very messy.  It's also difficult to understand.  Since your regex match tells you which attributes it knows, you should only set those.

A: You loop over the groups using for member in members:, which means that in every iteration, member contains the group name.
You then make grp_name from member by embedding it in ''s, which is the problem. Instead of  grp_name being the group name A, it's 'A', which is not an existing group name. Not adding the 's will fix the problem.


text:
Q: MarkLogic Node.js npm module cannot process >400 error status I'm using Marklogic npm module v2.1.1 with my express(v4.16.4) Node app. In my controller function I'm using the db.eval method to return the data along with necessary status code using function xdmp.setResponseCode(). Please find the below code snippet
// controller function
function getNewsArticleById(db: any, fileName: string, req: any, res: any, next: any) {
  return db.eval(
     `xdmp.setResponseCode(403, 'Forbidden');
     {data: 'abc'};`,
     {},
     })
    .result(
      data => {
        res.json(data[0].value);
      },
      err => {
        console.log(err);
        next(err);
      });
}

The above function is attached to a route t return the desired response which could be either a success (200 response codes) or failures (400 response codes). The success case works fine but when ever the code sets to 400 or greater response code I get a 500 error saying

eval JavaScript on server: cannot process response with 403 status.

To me, it seems to be a limitation of the db.eval() MarkLogic function
Can you please suggest me how to fix this? If not, what should be best alternative to handle it?

A: The typical approach for evaluated code would be to return an error value instead of setting an HTTP status code.
If you want to provide an HTTP interface to your scripting code on the MarkLogic enode, you might consider writing and installing an endpoint.  An endpoint has complete control over the HTTP response.
You might also write and install a resource service extension, which is invoked by the REST API but can specify an error HTTP status when throwing an error as described here:
http://docs.marklogic.com/guide/rest-dev/extensions#id_20992
Likely stating the familiar, installing an endpoint or resource service extension is also more secure than sending code for evaluation from a client with a privileged role.
Hoping that helps,


text:
Q: Mixed conditionals - Future / Future It is the first time that I ask a question, thanks in advance to whoever is going to reply.
I am studying conditional sentences and I cannot find anywhere a structure for a hypotethical future situation with a future result. I am giving you an example to understand if it is possible to express what I want to say, please correct me if I am wrong.
"If I were going to the concert tonight, I would be fulfilling the dream of my life"

A: To cast the hypothetical distinctly into the future, employ the future periphrastic subjunctive mood, for example:
"If I were to go to the concert tonight, I would be fulfilling a lifetime dream."
-or-
"If I were going to go to the concert tonight, I would be fulfilling a lifetime dream."

A: Your existing sentence is fine. You can change it if you wish, but there is no reason to do so.

If I were going to the concert tonight, I would be fulfilling the dream of my life.

This is something you might say the morning of the concert, before it takes place that night.


text:
Q: Find values from a Word table in an Excel table I want to iterate through the values of a column in a table in a word file, and check if those values are in a column in a table in an Excel file. I have the following code:
Private Sub CompararColumnas_Click()

   Dim wrdTbl As Table
    'Set your table
    With ActiveDocument
        If ActiveDocument.Tables.Count >= 1 Then
            Set wrdTbl = .Tables(InputBox("Table # to copy? There are " & .Tables.Count & " tables to choose from."))
        End If
    End With

    Dim AD_UsersPath As String
    AD_UsersPath = "C:\Users\" & Environ("Username") & "\Desktop\Comparar Columnas VBA\Animales.xlsx"
    Dim AD_USERS As Object
    Set AD_USERS = CreateObject("Excel.Application")
    AD_USERS.Visible = False
    AD_USERS.Application.Workbooks.Open AD_UsersPath

    LastRow = ThisDocument.Tables(1).Columns(1).Cells.Count
    Dim I As Integer
    For I = 1 To LastRow
        wVal = ThisDocument.Tables(1).Cell(I, 1)
        User = AD_USERS.Cells(AD_USERS.Range("A:A").Find(What:=wVal).Row, 1).Text
        wrdTbl.Cell(I, 2).Range.Text = User
    Next I

End Sub

This code iterates in wVal the values from the first column in a table from Word and after that it goes to Excel to find those values in the first column of the Excel table. If it finds them, it copies the values in the second column of the word table. However, it gives me an error 91. If instead of Find(What:=wVal) I put something like Find(What:="Word") it does not give me an error and puts the word "Word" in every cell of the second column of the word table. How can I solve this?

A: Cell values in Word have a two-character "end of cell" marker (Chr(13) + Chr(7)) which you need to remove:
Private Sub CompararColumnas_Click()

   Dim wrdTbl As Table
    'Set your table
    With ActiveDocument
        If ActiveDocument.Tables.Count > 1 Then
            Set wrdTbl = .Tables(InputBox("Table # to copy? There are " & _
                                  .Tables.Count & " tables to choose from."))
        Else
            Set wrdTbl = .Tables(1) 'default to the only table
        End If
    End With

    Dim AD_UsersPath As String, wb As Object, ws As Object
    AD_UsersPath = "C:\Users\" & Environ("Username") & _
                   "\Desktop\Comparar Columnas VBA\Animales.xlsx"
    Dim AD_USERS As Object
    Set AD_USERS = CreateObject("Excel.Application")
    AD_USERS.Visible = False
    Set wb = AD_USERS.Workbooks.Open(AD_UsersPath)
    Set ws = wb.Worksheets(1)

    Dim LastRow As Long, I As Long, User
    LastRow = wrdTbl.Columns(1).Cells.Count

    For I = 1 To LastRow
        wVal = TwrdTbl.Cell(I, 1)
        Left(wVal, Len(wVal)-2) 'strip off "end of cell" marker
        User = ws.Cells(ws.Range("A:A").Find(What:=wVal).Row, 1).Text
        wrdTbl.Cell(I, 2).Range.Text = User
    Next I

    wb.Close False
    AD_USERS.Quit

End Sub


text:
Q: Moving or designating thread stack space in windows I'm doing parallel programming in a NUMA computer (I do not have the computer yet, it's scheduled to arrive soon™).
I have a pool of worker threads on each NUMA node (with processor affinity set) and a balancer that spreads work evenly among the pools/nodes. This is to ensure all memory allocations are on the local memories. This is all fine and dandy.
During start up the pool worker threads are created from the main thread and they have to do some inital setup before they can set their own affinities (3rd party library requirement, nothing I can do about it).
I'm worried that there will be a hidden performance penalty as the stack frames of the worker threads get allocated on the wrong nodes, causing foreign memory accesses.
Is this a real issue? Somehow I believe it has been solved already...
Anyway what I'm looking for is a way to make sure that the stack of each thread gets allocated on the correct NUMA node.
My dedicated google boy came up with this: Allocating a Thread's Stack on a specific NUMA memory which is kind of what I want to do, but it's pthreads and I need a windows solution.

A: There is a remarkable lack of information on this on MSDN, but given what I've heard Mark Russinovich describe when talking about windows memory internals I wouldn't worry about it unless I started to see a noticeable slowdown.
In the scheme of things even cross node memory accesses are still faster than say... swapping to disk. More importantly because the physical mapping of memory to active pages has no relationship with the memory space on windows (a purely virtual memory space), the kernel will likely remap the stack pages for each thread based on affinity.
I don't really think this is going to affect you, if it would there would already be an exposed solution because the SQL Server team would have run into it a long time ago.


text:
Q: How to fix Jade syntax error: Expected space? I've inherited a project where the previous developer decided to use jade for markup.
Unfortunately I've been tasked with the simple task of adding what I thought was going to be a simple change and is turning out to be a pain in the ass.
I am attempting to add a class to a table row based on an input value, however when ever I try to do this I get the following error:
While building the application:
client\views\home\home.jade: Jade syntax error: Expected space
{{{var derp = "derp";}}}
^
packages/compileJade/plugin/handler.js:54:1: Cannot read property 'head' of undefined (compiling client/views/home/home.jade) (at fileModeHandler)

For the life of me I can't figure out what white space is needed and its making me incredibly frustrated.
I've used the jade demo editor and I know that what I'm trying to do will work, but no matter what I do it doesn't work when I apply it to my own project. What on earth am I doing wrong?
I'm including both markup and template:
home.jade
template(name='home')
  .issues-info.z-depth-2
    h1.title TOTAL ALERTS
    h1.large-number #{issuesLength}

    .last-update
      h2 #{lastUpdateDate}
      h2 #{lastUpdateHour}

    +spinner

  .issues-table
    table.striped
      thead
        tr
          th#customername.sort Customer
          th#devicename.sort Device Name
          th#deviceclass.sort Device Class
          th#servicename.sort Service
          th#date Transition Time
          th#psaticketdetails.sort Ticket #

      tbody
        +each issues
        - var derp = styleClass(servicename)
          tr(class=derp)
            td #{customername}
            td #{devicename}
            td #{deviceclass}
            td #{servicename}
            td #{transitiontime}
            td #{psaticketdetails}

home.js
Session.set('sortField', 'date')
Session.set('descending', true)

Template.home.events({
  'click #date': function () {
    Session.set('descending', !Session.get('descending'))
    Session.set('sortField', 'date')
  },

  'click .sort': function (event) {
    Session.set('descending', !Session.get('descending'))
    Session.set('sortField', event.target.id)
  }
})

Template.home.helpers({
    styleClass: function(input){
      if(input == "moo"){
        return "herp";
      } else {
        return "derp";
      }
    },

  lastUpdateDate: function () {
    return Session.get('lastUpdateDate')
  },

  lastUpdateHour: function () {
    return Session.get('lastUpdateHour')
  },

  issuesLength: function () {
    var issues = Issues.find().fetch(), customers = {}, services = {}

    _.each( Customers.find().fetch(), function (customer) {
        customers[customer.name] = true
      })

    _.each(Services.find().fetch(), function (service) {
        services[service.name] = true
      })

    issues = _.filter(Issues.find().fetch(), function (issue) {
        return customers[issue.customername]
      })

    issues = _.filter(issues, function (issue) {
        return services[issue.servicename]
      })
    return issues.length
  },

  issues: function () {
    var issues = Issues.find().fetch(), customers = {}, services = {}

    _.each(Customers.find().fetch(), function (customer) {
        customers[customer.name] = true
      })

    _.each(Services.find().fetch(), function (service) {
        services[service.name] = true
      })

    issues = _.filter(Issues.find().fetch(), function (issue) {
        return customers[issue.customername]
      })

    issues = _.filter(issues, function (issue) {
        return services[issue.servicename]
      })

    var sortField = Session.get('sortField')
    var descending = Session.get('descending')

    if (sortField === 'date') {
      issues.sort(function (a, b) {
        return a.date - b.date
      })
    } else {
      issues.sort(function (a, b) {
        var fieldA = a[sortField].toLowerCase()
        var fieldB = b[sortField].toLowerCase()

       if (fieldA < fieldB) return -1
       else if (fieldA > fieldB) return 1
       else return 0
      })
    }

    if (descending) issues.reverse()

    return issues
  }
});


text:
Q: Why holes are better in storing both valley and pseudospin information? Recently I attended a class about transition-metal dichalcogenides (TMDC) and, during the lecture, the professor said that holes are better than electrons in storing both pseudospin and valley information. I know that it's somehow related to transitions due to phonons and the fact that they are efficient in transferring momentum but not spin, but I don't know much more. Could you help me? Thanks and have a good day!

A: In this paper by Kumar et al. from 2021 it is shown that the lifetime of holes is orders of magnitude longer than that of electrons. The paper explains that this is due to the differing energy landscapes seen by both species, meaning that it is much easier for electrons to be scattered. Excited electrons "live" in the conduction band which is only spin-orbit split slightly, while holes "live" in the conduction band which is spin-orbit split much more.
It could be in this sense that "holes are better carriers of valley information": because they live longer.


text:
Q: HTML5 Audio Tag can't be played on android I want to write an HTML page, that can play some audio files. I use this code:
<audio width="100%" controls >
<source src="sprachMemo.mp3" type="audio/mpeg" />
<source src="sprachMemo.m4a" type="audio/x-aac" />
<source src="sprachMemo.ogg" type="audio/ogg" />
<source src="sprachMemo.wav" type="audio/wav" />
Problem!
</audio>

When I open the page with Chrome and a PC it work. But on the mobile, it shows the audio file, but you can not play it. So it just shows, that there is a file used.
I have also been looking for other solutions , but want to have a simple variant. And as I could see, the system worked on other sites.
How can I make it work on Android, too?


text:
Q: How to query field names from custom object by data type? I have custom object ExchangeRate__c. How to get all fields, which have data type "currency" and put their field names in a string?

A: You wouldn't use a query for this, but rather the DescribeSObjectResult and DescribeFieldResult classes.
Schema.SObjectType.<Sobject API Name>.fields gives you a Map<String, Schema.SObjectField> containing the field tokens for all of the fields on the object
You can then iterate over those Schema.SObjectField instances, and get the DescribeFieldResult from them using the getDescribe() method.
The DescribeFieldResult class gives you access to the metadata of the field, including what type of field it is (the getType() method).

A: You can use below method and pass the object name ExchangeRate__c as parameter:
public static String getCurrencyFields(String obj) {
    List<String> fields = new List<String>();
    SObjectType objType = Schema.getGlobalDescribe().get(obj);
    Map<String,Schema.SObjectField> mfieldsMap = objType.getDescribe().fields.getMap();

    for(Schema.SObjectField fld : mfieldsMap.values()) {
        if(fld.getDescribe().getType()==Schema.DisplayType.CURRENCY){
            fields.add(fld.getDescribe().getName());
        }
    }
    return String.join(fields,',');
}


text:
Q: Posting New html from TINYMCE Seems like a simple problem, I have a form and when someone needs to edit data, the textarea that is controlled by TINYMCE loads the values, but when I change it and submit the form, the new changes are not being posted.
What am I doing wrong?
UPDATE
How do I do it via this, or do it say on click in the editor.  I am using jquery validate, this is the submit handler.
$(form).ajaxSubmit({
                target:'#result',
                success:function(){

                    $('html, body').animate({scrollTop:'90px'}, 500);},
                clearForm: false});

                }});

A: You have to call tinyMCE's save method when the user clicks the submit button:
$(form).ajaxSubmit({
    beforeSerialize: function() {
        tinyMCE.get('content').save();  // 'content' is the id of your textarea
    },

    ...
});

Reference: http://wiki.moxiecode.com/index.php/TinyMCE:API/tinymce.Editor/save


text:
Q: Removing all empty columns and rows in data.frame when rows don't go away I have two data.frames, dA (HERE) and dB (HERE). They are exactly the same EXCEPT that dB has one completely empty column and multiple empty rows.
dA <- read.csv("https://raw.githubusercontent.com/izeh/m/master/irr3.csv", h = T)
dB <- read.csv("https://raw.githubusercontent.com/izeh/m/master/irr4.csv", h = T)

I want remove all empty columns and all empty rows in dB so that dB becomes exactly like dA.
Currently, I try the following to achieve my goal but it looks like empty rows don't get removed:
# remove columns with all NA
B1 <- dB[, colSums(is.na(dB)) != nrow(dB)]

# remove rows with all NA
B2 <- B1[rowSums(is.na(B1)) != ncol(B1), ]   # NOW, check by:  `nrow(B2)` the `NA` haven't
                                             # been removed !!

A: You have NA and also empty rows. You can do
B1[rowSums(is.na(B1) | B1 == "") != ncol(B1), ]

#   study.name  group.name outcome ESL prof scope type
#1  Shin.Ellis    ME.short       1   1    2     1    1
#2  Shin.Ellis     ME.long       1   1    2     1    1
#3  Shin.Ellis   DCF.short       1   1    2     1    2
#4  Shin.Ellis    DCF.long       1   1    2     1    2
#5  Shin.Ellis  Cont.short       1   1    2    NA   NA
#6  Shin.Ellis   Cont.long       1   1    2    NA   NA
#8    Trus.Hsu       Exper       1   2    2     2    1
#.....

We can also use filter_all from dplyr
library(dplyr)
B1 %>% filter_all(any_vars(!is.na(.) & . != ""))

A: Here is an option with Filter from base R
Filter(function(x) !all(is.na(x)), dB)
#  study.name  group.name outcome ESL prof scope type
#1  Shin.Ellis    ME.short       1   1    2     1    1
#2  Shin.Ellis     ME.long       1   1    2     1    1
#3  Shin.Ellis   DCF.short       1   1    2     1    2
#4  Shin.Ellis    DCF.long       1   1    2     1    2
#5  Shin.Ellis  Cont.short       1   1    2    NA   NA
#6  Shin.Ellis   Cont.long       1   1    2    NA   NA
#7                              NA  NA   NA    NA   NA
#8    Trus.Hsu       Exper       1   2    2     2    1
#...

Or with any
Filter(function(x) any(!is.na(x)), dB)

To remove the rows
B1[!!rowSums(!is.na(B1) & B1 != ""),]

Or using Reduce
B1[Reduce(`|`, lapply(B1, function(x) !is.na(x) & x != "" )),]

A: You can use replace to convert "" to NA and use then is.na. To remove complete rows and colls you can use apply with the function all.
x  <- is.na(replace(dB, dB=="", NA))
dB[!apply(x, 1, all), !apply(x, 2, all)]

or using rowSums and colSums, like in the question:
x <- is.na(dB) | dB == ""
dB[rowSums(x) != ncol(x), colSums(x) != nrow(x)]


text:
Q: How can I set the coordinates of a picture in XML, Java Hello I am trying to make an app with java and XML and I want to have a picture in a specific location on the page. How would I do this?
I tried:
ImageView sprite = (ImageView)findViewById(R.id.sprite);
sprite.setX(0);
sprite.setY(500);

and I got an error at sprite.setX(0); and sprite.setY(500);
setX or setY does not exist...

A:
First of all, I do not see any relationship with XML, you should post all your code so we can analyze it and find what that error produces
  It's strange that there are no setX and setY methods in your ImageView control, maybe you're trying to call setX and setY in the wrong place

But assuming no, you can try the following:
AbsoluteLayout.LayoutParams param = new AbsoluteLayout.LayoutParams(int width, int height, int x, int y)

sprite.setLayoutParams(param);

where
int X = 0;
int Y = 500;
YourLayout.LayoutParams param = new YourLayout.LayoutParams(sprite.getMeasuredWidth(), sprite.getMeasuredHeight(), X, Y);
sprite.setLayoutParams(param);

Also
Suppose you want a ImageView of size 80x90 on your screen at postion 90x60
RelativeLayout relativeLayout = new RelativeLayout(this);

ImageView sprite = (ImageView)findViewById(R.id.sprite);

//Where 80 is the width and 90 the height
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(80, 90);

// Setting position of our ImageView
//you can use the margins of the layout
layoutParams.leftMargin = 80;
layoutParams.topMargin = 90;
//layoutParams.rightMargin = 80; //Example
//layoutParams.bottomMargin = 90; //Example

relativeLayout.addView(imageView, layoutParams);

In any case, I recommend you post your complete code so we can help you


text:
Q: (Gensim)Python : FileNotFoundError: [Errno 2] No such file or directory: 'mycorpus.txt' I am currently going through Gensim tutorial on Corpora and Vector Spaces in that I am right now trying to understand  Corpus Streaming – One Document at a Time.
After I compiled these lines of codes referring the above link in python3:
class MyCorpus(object):
    def __iter__(self):
        for line in open('mycorpus.txt'):
            # assume there's one document per line, tokens separated by whitespace
            yield dictionary.doc2bow(line.lower().split())

corpus_memory_friendly = MyCorpus()  # doesn't load the corpus into memory!

print(corpus_memory_friendly)

for vector in corpus_memory_friendly:  # load one vector into memory at a time
    print(vector)

I am getting this error:
<__main__.MyCorpus object at 0x7f2e37e17d68>

Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    for vector in corpus_memory_friendly:  # load one vector into memory at a time
  File "<pyshell#41>", line 3, in __iter__
    for line in open('mycorpus.txt'):
FileNotFoundError: [Errno 2] No such file or directory: 'mycorpus.txt'

I have already downloaded mycorpus.txt still I am getting this error. Where should I store mycorpus.txt file.
Thanks for your help.


text:
Q: Hibernate have 2 Threads and one getting error when Hibernate create the schema in DB I have this output:
21:22:25,518 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,518 INFO  [stdout] (ServerService Thread Pool -- 13)     alter table Contacto
21:22:25,518 INFO  [stdout] (ServerService Thread Pool -- 13)         drop
21:22:25,518 INFO  [stdout] (ServerService Thread Pool -- 13)         foreign key FK_5jh2jf636mhuh77q4hwl1i2w0
21:22:25,519 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,519 INFO  [stdout] (ServerService Thread Pool -- 50)     alter table Contacto
21:22:25,519 INFO  [stdout] (ServerService Thread Pool -- 50)         drop
21:22:25,519 INFO  [stdout] (ServerService Thread Pool -- 50)         foreign key FK_5jh2jf636mhuh77q4hwl1i2w0
21:22:25,587 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,587 INFO  [stdout] (ServerService Thread Pool -- 13)     drop table if exists Contacto
21:22:25,596 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: alter table Contacto drop foreign key FK_5jh2jf636mhuh77q4hwl1i2w0
21:22:25,596 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) Can't DROP 'FK_5jh2jf636mhuh77q4hwl1i2w0'; check that column/key exists
21:22:25,597 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,597 INFO  [stdout] (ServerService Thread Pool -- 50)     drop table if exists Contacto
21:22:25,600 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,600 INFO  [stdout] (ServerService Thread Pool -- 13)     drop table if exists Usuario
21:22:25,600 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,601 INFO  [stdout] (ServerService Thread Pool -- 50)     drop table if exists Usuario
21:22:25,604 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,604 INFO  [stdout] (ServerService Thread Pool -- 13)     create table Contacto (
21:22:25,604 INFO  [stdout] (ServerService Thread Pool -- 13)         id integer not null,
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)         email varchar(255),
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)         nombre varchar(255),
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)         telefono varchar(255),
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)         usuario_cuenta varchar(255),
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)         primary key (id)
21:22:25,605 INFO  [stdout] (ServerService Thread Pool -- 13)     )
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50)     create table Contacto (
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50)         id integer not null,
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50)         email varchar(255),
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50)         nombre varchar(255),
21:22:25,606 INFO  [stdout] (ServerService Thread Pool -- 50)         telefono varchar(255),
21:22:25,607 INFO  [stdout] (ServerService Thread Pool -- 50)         usuario_cuenta varchar(255),
21:22:25,607 INFO  [stdout] (ServerService Thread Pool -- 50)         primary key (id)
21:22:25,607 INFO  [stdout] (ServerService Thread Pool -- 50)     )
21:22:25,625 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: create table Contacto (id integer not null, email varchar(255), nombre varchar(255), telefono varchar(255), usuario_cuenta varchar(255), primary key (id))
21:22:25,625 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,625 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) Table 'contacto' already exists
21:22:25,626 INFO  [stdout] (ServerService Thread Pool -- 13)     create table Usuario (
21:22:25,626 INFO  [stdout] (ServerService Thread Pool -- 13)         cuenta varchar(255) not null,
21:22:25,626 INFO  [stdout] (ServerService Thread Pool -- 13)         apellidos varchar(255),
21:22:25,627 INFO  [stdout] (ServerService Thread Pool -- 13)         email varchar(255),
21:22:25,627 INFO  [stdout] (ServerService Thread Pool -- 13)         nombre varchar(255),
21:22:25,627 INFO  [stdout] (ServerService Thread Pool -- 13)         password varchar(255),
21:22:25,628 INFO  [stdout] (ServerService Thread Pool -- 13)         primary key (cuenta)
21:22:25,628 INFO  [stdout] (ServerService Thread Pool -- 13)     )
21:22:25,628 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,629 INFO  [stdout] (ServerService Thread Pool -- 50)     create table Usuario (
21:22:25,629 INFO  [stdout] (ServerService Thread Pool -- 50)         cuenta varchar(255) not null,
21:22:25,629 INFO  [stdout] (ServerService Thread Pool -- 50)         apellidos varchar(255),
21:22:25,629 INFO  [stdout] (ServerService Thread Pool -- 50)         email varchar(255),
21:22:25,630 INFO  [stdout] (ServerService Thread Pool -- 50)         nombre varchar(255),
21:22:25,630 INFO  [stdout] (ServerService Thread Pool -- 50)         password varchar(255),
21:22:25,630 INFO  [stdout] (ServerService Thread Pool -- 50)         primary key (cuenta)
21:22:25,630 INFO  [stdout] (ServerService Thread Pool -- 50)     )
21:22:25,639 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: create table Usuario (cuenta varchar(255) not null, apellidos varchar(255), email varchar(255), nombre varchar(255), password varchar(255), primary key (cuenta))
21:22:25,639 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) Table 'usuario' already exists
21:22:25,640 INFO  [stdout] (ServerService Thread Pool -- 50) Hibernate:
21:22:25,640 INFO  [stdout] (ServerService Thread Pool -- 50)     alter table Contacto
21:22:25,640 INFO  [stdout] (ServerService Thread Pool -- 50)         add constraint FK_5jh2jf636mhuh77q4hwl1i2w0
21:22:25,641 INFO  [stdout] (ServerService Thread Pool -- 50)         foreign key (usuario_cuenta)
21:22:25,641 INFO  [stdout] (ServerService Thread Pool -- 50)         references Usuario (cuenta)
21:22:25,641 INFO  [stdout] (ServerService Thread Pool -- 13) Hibernate:
21:22:25,641 INFO  [stdout] (ServerService Thread Pool -- 13)     alter table Contacto
21:22:25,642 INFO  [stdout] (ServerService Thread Pool -- 13)         add constraint FK_5jh2jf636mhuh77q4hwl1i2w0
21:22:25,642 INFO  [stdout] (ServerService Thread Pool -- 13)         foreign key (usuario_cuenta)
21:22:25,642 INFO  [stdout] (ServerService Thread Pool -- 13)         references Usuario (cuenta)
21:22:25,657 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000230: Schema export complete
21:22:25,664 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 13) HHH000389: Unsuccessful: alter table Contacto add constraint FK_5jh2jf636mhuh77q4hwl1i2w0 foreign key (usuario_cuenta) references Usuario (cuenta)
21:22:25,665 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 13) Can't write; duplicate key in table '#sql-2f4_20'

It looks like the application have 2 Threads of hibernate, and these Threads are making the same SQL sentences (such as creating the same tables, etc...)
What's going on?
Thanks in advance

A: Your problem isn't in hibernate. Your code isn't in sync with the compiled code.
Try having it always in sync or create a new workspace and download your code from your repo overthere.


text:
Q: OutputCache doesn't work I want to cache return data from an action. I use the OutPutCacheAttribute for this purpose. Here is my client code:
$(document).ready(function() {
    $.get('@Url.Action("GetMenu", "Home")', null,
        function(data) {
            parseMenu(data);
    });
}

And here is my server code:
[HttpGet]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.Server)]
public ContentResult GetMenu()
{
    string jsonText = GetData(); //some code
    return new ContentResult
    {
        Content = jsonText,
        ContentType = "text/json"
    };
}

As you can see I use OutputCacheAttribute for caching server response. But it does not work. Every time I load the page the action Home/GetMenu is called. And it is called even if I type in browser's address bar directly 'localhost/Home/GetMenu'. Where am I was mistaken?
UPD I created the second action to test this attribute without debugging. Here is its code:
[HttpGet]
[OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "none")]
public JsonResult GetJson()
{
    return Json(new
    {
        random = new Random().Next(100)
    },
    JsonRequestBehavior.AllowGet);
}

I supposed if OutputCache attribute works properly (and I use it properly) then action is called once and I get the same response every time. But if not then I get the different responses every time because every time random number is genereted.
And when I called this action some times I have always received different respnses, such as {"random":36}, {"random":84} and so on

A: In its default implementation, output cache is process-bound and stored in-memory. As a result, if you do something like stop and start debugging, you've destroyed anything you previously cached. Actually, more accurately, you've killed the process and started a new process, and since the cache is process-bound it went away with the old process.

A: Please try this
  [OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient,VaryByParam = "none")]

If not working Please try :
        [HttpGet]
    [OutputCache(Duration = 86400, Location = OutputCacheLocation.ServerAndClient, VaryByParam = "none")]
    public JsonResult GetJson()
    {
        return Json(new{message = "Record created successfully!!!"},JsonRequestBehavior.AllowGet);
    }

N.B. : more information about Outputcache

A: Have you checked web.config that it isn't disabled?
https://msdn.microsoft.com/en-us/library/ms228124(v=vs.100).aspx
<caching>
    <outputCache enableOutputCache="false">
    </outputCache>
</caching>


text:
Q: What changes with difficulty? So far I've just been playing through on normal, but it has me wondering what exactly is different if I play on Hard or the last one (Lunatic?).
Do the enemies get stronger? Is the math for combat changed somehow? Are my units weaker? Are there more enemy units?
What exactly changes with each step up in difficulty?

A: I found a post here:

Enemies have higher stats
  Enemies have more skills
  There are more enemies
  Reeking Boxes cost 4800 G as opposed to 500 G on Normal
  Reinforcements attack on the turn they spawn (always with warning they're coming)
  Enemies are aggro'd more easily (i.e. enemies attack in larger groups)
  Enemies have stronger weapons from earlier in the game and cap out at stronger weapons (typically +4mt +10 hit forges of the strongest basic weapons, as opposed to having just the strongest basic weapons)
  The cumulative level cap is higher
  Staff users (and dancers?) gain less EXP

*

*I can confirm that Reeking Boxes are extremely expensive, and usually not worth the cost of purchase.

*Reinforcements also do attack on the turn they appear, which has been a major cause of restarts for me.  I'm not sure what is meant by warning, as I rarely get any.  I don't know if that's a thing in Normal, though.

*They do use blue (customized) weapons, but I don't know how that compares to Normal.

*I would not be surprised to have reduced XP for support characters.  First thing I did was turn Olivia into a Myrmidon, and that solved her leveling issues.


text:
Q: Jqplot pie/donut chart seriesColors array not reused/repeated I am using jqplot to draw pie-chart and donut-charts.
And I am using the 'seriesColors' to give customised colors to the slices http://www.jqplot.com/docs/files/jqplot-core-js.html#jqPlot.seriesColors
seriesColors : [ "0571B0", "#5E3C99", "#008837"]
If the data(array-values to be passed) has only three values, then it does display the colors properly.
But if there are more than 3 values, it just displays that slice in black color.
It doesn't repeat/reuse the colors from the beginning (as said in the documentation).
Here it is:
var s2 = [['a', 8], ['b', 12], ['c', 6]];
var plot1 = $.jqplot('div_1', [s2], {
                title: 'Chart 1',

                seriesDefaults:{
                  renderer:$.jqplot.DonutRenderer ,
                  rendererOptions:{
                        startAngle: -90,
                        innerDiameter: 100,
                        showDataLabels: true,
                        dataLabels:'percent'
                     }
                    },
                    seriesColors: ["#0571B0", "#5E3C99", "#008837"],
                    highlighter: {
                        show: true
                    },
                    legend: { show:true, rendererOptions: {numberRows: 1}, location: 's', placement: 'outsideGrid'}
                });

But if I add a 4th value in the array, the colors are not reused.
i.e if I modify the above array to
var s2 = [['a', 8], ['b', 12], ['c', 6], ['d', 9]];

Then the 4th slice ('d') is displayed in black color.
How do I fix this?

A: Found a fix to this.
Hope this helps out others who are facing a similar issue.
Here's the code.
var dataValues = [['a', 8], ['b', 12], ['c', 6], ['d', 9], ['e', 14]];

//Define the seriesColors array..
var seriesColors = ["#0571B0", "#5E3C99", "#008837"];

var seriesColorsLength = seriesColors.length;
var donutChartSeriesColors = new Array();

//Prepare a new array which would be passe to the chart..
//This will handle even if there are more value than the seriesColors array..
for(var i = 0; i < dataValues.length; i++) {
donutChartSeriesColors[i] = seriesColors[(seriesColorsLength-1) % i];
}

var plot1 = $.jqplot('div_1', [dataValues ], {
            title: 'Chart 1',

            seriesDefaults:{
              renderer:$.jqplot.DonutRenderer ,
              rendererOptions:{
                    startAngle: -90,
                    innerDiameter: 100,
                    showDataLabels: true,
                    dataLabels:'percent'
                 }
                },
                seriesColors: donutChartSeries,
                highlighter: {
                    show: true
                }
});


text:
Q: How to append innerHTML of a button on Ember.view I have created a view for button.
App.NumberButtonView = Ember.View.extend({
tagName: 'button',
classNames: ['ButtonClass']
});

My button model is
App.NumberBtns = DS.Model.extend({
value: DS.attr('string'),
width: DS.attr('string'),
height: DS.attr('string'),
className: DS.attr('string'),
type:DS.attr('string')

})
App.NumberBtns.FIXTURES = [  {
id: '108',
value: '8',
style: {
    width: '50px',
    height: '50px'
},
className: 'NumberBtnClass',
type: 'number',
}, {
id: '109',
value: '9',
style: {
    width: '50px',
    height: '50px'
},
className: 'NumberBtnClass',
type: 'number',
}, {
id: '110',
value: '0',
style: {
    width: '50px',
    height: '50px'
},
className: 'NumberBtnClass',
type: 'number',

}
]
How can i pass the value of the button to the view from the controller.
We can do it by adding tags  and appending the innerHTML. But how to append the innerHTML in the buttonView from model through controller

A: We can set the controller using
setupController: function (controller, model) {
    controller.set('model', model);

to display the name use itemBinding
{{#each btn in model.operatorBtn}}
{{#view App.NumberButtonView itemBinding="btn"}}
<i> {{view.item.value}} </i>
{{/view}}
 {{/view}}
 {{/each}

Now the value will get displayed in the view.


text:
Q: load a json file containing list of strings I have a json file containing a list of strings like this:
['Hello\nHow are you?', 'What is your name?\nMy name is john']

I have to read this file and store it as a list of strings but I am so confused that how should I read json file like this. Also, I should use utf-8 encoding format.

A: The file you have shown is not in json format. Anyways, to read a json file you have to do following
import json
jsonObj = json.loads('path/to/file.json')

This will return a dictionary object and store it in jsonObj.

A: Let's assume you have one or multiple lines as described in the json file. Here is my suggestion (Remember to replace the file name test.json to yours):
import ast

with open("test.json", "r") as input_file:
    line_list = input_file.readlines()

all_texts = [item for sublist in line_list for item in ast.literal_eval(sublist)]
print(all_texts)


text:
Q: How do you write one function that works on (arrays|series) and scalars? Say I have a function that parses a couple of columns (in the case of a DataFrame) or a couple of scalars into a datetime64.
How can I write one piece of code that works on both scalars and arrays/series?
I seem to remember there's a standard way of doing this but can't find it.
As a further part of this, how would I write this one callable if the operations I needed to perform were different between arrays and scalars?


text:
Q: Selected cell L&F default colors from UIManager in custom renderer I have a custom JList renderer that has an image and some labels. I know how to set the background and foreground of this list using the isSelected variable and the UIManager default L&F.
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        panel.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
        panel.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());

This works fine but I am unsure about the JLabel's colors though, since there is "selected" color key. As such when the item is selected it doesn't change color and has little contrast.
I found a list of keys I can use to get data from UIManager but I'm not sure which ones are used for "selected JList item label".
For example on OSX the default is white background with black text. However on selection the cell background is blue and the text becomes white. I want to know how to lookup what color the label turns to (in this case, white). Foreground/background/disabled are the only ones I can find.


text:
Q: Mocking generic interfaces with Kotlin and Mockito I am trying to mock a generic interface in Kotlin using Mockito. But so far I have found no natural solution. Given:
interface X<T> {
    fun x(): T
}

fun f(x: X<Int>) = x.x()

I could mock X with any of the following:

*

*val x = f(Mockito.mock(X::class.java) as  X<Int>)
But that would generate an "unchecked cast" warning.

*@Mock lateinit var x: X<Int>
But I do not want to use the @Mock annotation because I like to have my fields final.

*Introduce a helper function, as the mockito-kotlin library does:
inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)!!
Then call it like this:
val x: X<Int> = mock()
But I do not want to use helper functions.
Is there an elegant pure Kotlin way to mock a generic interface with Mockito?
(I would prefer a version of 1. without the warning.)

A: Just use mockito-kotlin project. This project contains all must have helpers for mockito. And supports mockito 2.1 as well.
Upd. To deal with "uncheked cast" use Reified type parameters.
You say that "But I do not want to use helper functions.", but why? This is inline function, so in compile time function will be inlined at all call sites will.

A: The mockito-kotlin library prevents indeed the need to suppress warnings if used correclty.
Here is an example. In the Maven pom.xml you import the library:
<dependency>
    <groupId>com.nhaarman.mockitokotlin2</groupId>
    <artifactId>mockito-kotlin</artifactId>
    <version>2.2.0</version>
</dependency>

Then in your tests, you import the mock method:
import com.nhaarman.mockitokotlin2.moc

Then you can comfortably mock whatever you need to mock:
@Before
fun setUp() {
    val sessionFactory: FactoryBean<SessionFactory> = mock()
    val eventDateReminderService: EventDateReminderService = mock()
    val eventDateService: EventDateService = mock()
    val templateService: TemplateService = mock()
    reminderService = ReminderService(sessionFactory, eventDateReminderService, eventDateService, templateService)
}

No need for casting or suppressing warnings. If you use the Mockito library directly, you will need to cast and suppress warnings.

A: Alternatively you can use Mockk library.
It supports annotations, so to create a mock it's enough to write:
@ExtendWith(MockKExtension::class)
class BookSpec {

  @MockK
  lateinit var author: Author
}

and then to record some behaviour:
every { author.name() } returns "Milosz Brzezinski"

or
every { author.rank() } throws OutOfScaleException()


text:
Q: Schema.org breadcrumbs with entry linking to a non-existing page (which redirects to the homepage)? I am trying to organize my SERP and I want my site to display like this on SERP:

www.example.com > services > repair

But the problem is the "services" URL doesnt exist but 301 redirected to homepage.
<script type="application/ld+json">
{
    "@context": "http:\/\/schema.org",
    "@type": "BreadcrumbList",
    "itemListElement": [{
        "@type": "ListItem",
        "position": 1,
        "item": {
            "@id": "\/services\/",
            "name": "Services"
        }
    },
    {
        "@type": "ListItem",
        "position": 2,
        "item": {
            "@id": "\/repair\/",
            "name": "Repair"
        }
    }]
}

Will the above code work?


text:
Q: Is an antipattern returning differente objects in a single rest method? I have seen around the Internet several rest web services with the following behaviour. In case there are any errors, they return a Error object, otherwise they return, say, MyClass.
See the following example...

/*
 * Data transfer objects
 */
@Data
public class Error {
  private Integer id;
  private String description;
}

@Data
public class MyClass{
  // Whatsoever attribute...
}

/*
 * Web service (code omitted and abbreviated for the sake of simplicity)
 */
@PostMapping("myclass")
public ResponseEntity<MyClass> createMyClass(
    @RequestBody MyClass pMyClass
) {
    Optional<MyClass> optMyClass = facade.createMyClass(pMyClass);
    if(optTrip.isEmpty())
        Error err = Error.Builder().id(400).description("Any reason...").build();
        return ResponseEntity.ok(err); //may return the same HTTP 400 error instead of 200 Ok
    else
        return ResponseEntity.ok(optMyClass.get());
}

I feel that this is an antipattern for two major reasons. The first one is that the web method is not returning one kind of class objects, usually writing T or ? as returning class. The second one is that they are taking responsability of returning any error it may occur, instead of taking advantage of using HTTP headers and answers themselves.
Do you agree with me?

A: You might think of it as an anti-pattern, yes. Consider this definition for example:

According to the authors of Design Patterns, there must be at least two key elements present to formally distinguish an actual anti-pattern from a simple bad habit, bad practice, or bad idea:

*

*A commonly used process, structure, or pattern of action that despite initially appearing to be an appropriate and effective response to a problem, has more bad consequences than good ones.

*Another solution exists that is documented, repeatable, and proven to be effective.

Your example respects both of these points.
First of all, when you call a REST method, you might get an exception or error. You need to return a response to the client, and because you can't build the actual response object ('cause the method failed in some way), you have to return an error object. This is the right thing to do, but the problem is that the method that builds the normal response object also takes care of building the error object. This breaks the principle of Separation of Concerns. The method is concerned with error handling and error response generation too. This seems to be the appropriate and effective response to the problem but in time causes problems because all of your code is littered with all sorts of pieces that build error objects instead of actual response objects.
An now, point 2 of the above definition comes into play. There is another solution that exists that is documented, repeatable, and proven to be effective. It's been a while since I've written Spring REST services, but I do remember that you had good options for exception handling (HandlerExceptionResolver, @ExceptionHandler, etc) that you could use to cleanly handle exceptions and errors in a global and reusable manner. All that code for handling and building error objects moved outside of the methods themselves and the concerns were separated. Much cleaner, much more maintainable.
So with these two points, you might think at the example you are showing as an anti-pattern. There isn't an authority anywhere to actually confirm or infirm this naming, but more experienced developers can definitely tell you it's a bad idea and practice to handle errors like that in REST services.
If you are learning to build Spring REST services and see Internet examples with that behavior in them, consider also if they are not simple examples focusing on teaching you concepts piece by piece. At some point you might discover more advanced examples that may say "Remember when we called the method and we built error objects to return? That was not a really good way of doing it. Let's explore a better alternative. Keep reading...", etc.


text:
Q: Can I use calculated Homography for transforming 2D coordinates from one camera to the other stereo camera? Sorry if it sounds stupid but I really need to ask this.
Once homography is calculated, can I use this to project 2D coordinate of an object's center detected in one camera to the other stereo camera as 2D coordinate?

A: Once you have the homography that maps the transformation between the two cameras, the conversion is really straightforward.
All you have to do is to call
cv::perspectiveTransform(leftCamPts, rightCamPts, H );

It will fill the rightCamPts with the correct points.
But you must make sure you have the correct homography (the one that describes the transform between left and right camera, and not one of the many transforms that are calculated in a stereo engine). Also, check the correct order for left-to-right calls. you may need to invert your matrix before applying it.


text:
Q: Call vared and complete files from a different directory I have the following zsh function which lets me edit symbolic links using the vared ZLE builtin.
function lned {
  emulate zsh
  setopt err_return extended_glob local_options local_traps
  local -a data
  link_path=${1%%/##}
  zstat -A data -L +link $link_path
  target=$data[1]
  if [[ -z $target ]]; then
    print -rl 1>&2 "$link_path: not a symbolic link"
    return 2
  fi
  vared -p "${(q)1} -> " target
  if [[ -n $target && "$target" != "$data[1]" ]]; then
    # We can't use 'ln -sf' if $link_path is a symlink to a directory, so remove
    # it manually first.
    # Check that this is still a symlink, in case the file was changed while we
    # were editing (this leaves only a very small time interval where we might
    # remove a non-symlink).
    rm -- $link_path(@)
    ln -s -- $target $link_path
  fi
}

This is nice, but when I'm editing a relative symbolic link in a directory other than the current one, the file name completions are relative to the wrong directory. I want to fix that.
I could run pushd -- $link_path:h/ before calling vared and popd afterwards. However, this would not restore the current directory if the user interrupted the shell by pressing Ctrl+C at the wrong moment. This can be solved by setting traps exactly right, and maybe using cd rather than pushd, which is probably useful also to avoid having to detect whether the link is in the current directory (in which case pushd wouldn't push anything).
I'd like to minimize the disruption caused by the directory change, which means also locally turning off chpwd, restoring OLDPWD, and perhaps more which I'm not thinking of. Also, if I have no permission to cd back into the current directory, I'd be in a lurch — this is a very rare case but I'd prefer to support it.
It would be simpler if I could just set things up so that files are completed relative to a different directory during the vared call. How can I do that? If this is impossible, what's the best way to minimize the impact of a temporary directory change?

A: In your function lned, add the following before calling vared:
local curcontext=lned:::

Put the following in a file called _lned in your $fpath:
#autoload
_files -W $link_path:h/

Then add this to your ~/.zshrc:
zstyle ':completion:lned:*' completer _lned

Now it works as expected.


text:
Q: How do I limit the resources available to a program? I'm delving into multi-threaded programming with Java, but I'm finding it hard to test my program for bugs. My computer simply has too many resources and cores, making it hard to see how my program acts under stress.
Is there any way to limit the resources available to my program? It seems ridiculous that my only option right now is to open another application and render HD video in order to starve out the application I'm debugging.

A: An easy way to limit resources is setting up a virtual machine with limited resources.

A: Type java -X to get a whole bunch of command line options that affect available resources on the virtual machine itself.  On Linux, you can also use ulimit to limit the resources for any process, which is mostly used to protect other users on multi-user systems.  I don't know if there's something equivalent for windows.  Try playing around with the task manager.

A: You could invest in a Raspberry Pi.  The Model A costs $25 and the Model B $35.
Model A has 256MB RAM, one USB port and no Ethernet (network connection). Model B  has 512MB RAM, 2 USB ports and an Ethernet port.  They contain a ARM1176JZFS, with floating point, running at 700Mhz, and a Videocore 4 GPU.
Your resources most certainly will be limited with this, except for graphics power.


text:
Q: How to separate logging logic from business logic in a C program? And in a C++ one? I am currently coding in C and I have lots of printfs so that I can track, at some times, the flow of my application. The problem is that some times I want more detail than others, so I usually spend my time commenting/uncommenting my C code, so I can get the appropriate output.
When using Java or C#, I can generally separate both my implementation code from the logging logic by using Aspects.
Is there any similar technique you use in C to get around this problem?
I know I could put a flag called DEBUG that could be either on or off, so I wouldn't have to go all around and comment/uncomment my whole code every time I want to either show or hide the printfs. The question is I'd like to also get rid of the logging logic in my code.
If instead of C I was coding in C++, would it be any better?
Edit
It seems there is an AspectC++, so for C++ there seems to be a solution. What about C?
Thanks

A: IME you cannot really separate logging from the algorithms that you want to log about. Placing logging statements strategically takes time and experience. Usually, the code keeps assembling logging statements over its entire lifetime (though it's asymptotic). Usually, the logging evolves with the code. If the algorithm changes often, so will usually the logging code.
What you can do is make logging as unobtrusive as possible. That is, make sure logging statements always are one-liners that do not disrupt reading the algorithm, make it so others can insert additional logging statements into an existing algorithm without having to fully understand your logging lib, etc.
In short, treat logging like you treat string handling: Wrap it in a nice little lib that will be included and used just about everywhere, make that lib fast, and make it easy to use.

A: Not really.
If you have variadic macros available, you can easily play games like this:
#ifdef NDEBUG
    #define log(...) (void)0
#else
    #define log(...) do {printf("%s:%d: ", __FILE__, __LINE__); printf(__VA_ARGS__);} while(0)
#endif

You can also have logging that's turn-off-and-onable at a finer granularity:
#define LOG_FLAGS <something>;

#define maybe_log(FLAG, ...) do { if (FLAG&LOG_FLAGS) printf(__VA_ARGS__);} while(0)

int some_function(int x, int y) {
    maybe_log(FUNCTION_ENTRY, "x=%d;y=%d\n", x, y);
    ... do something ...
    maybe_log(FUNCTION_EXIT, "result=%d\n", result);
    return result;
}

Obviously this can be a bit tedious with only allowing a single return from each function, since you can't directly get at the function return.
Any of those macros and calls to printf could be replaced with something (other macros, or variadic function calls) that allows the actual logging format and target to be separated from the business logic, but the fact of some kind of logging being done can't be, really.
aspectc.org does claim to offer a C and C++ compiler with language extensions supporting AOP. I have no idea what state it's in, and if you use it then of course you're not really writing C (or C++) any more.
Remember that C++ has multiple inheritance, which is sometimes helpful with cross-cutting concerns. With enough templates you can do remarkable things, perhaps even implementing your own method dispatch system that allows some sort of join points, but it's a big thing to take on.

A: On GCC you could use variadic macros: http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html . It makes possible to define dprintf() with any number of parameters.
Using additional hidden verbose_level parameter you can filter the messages.
In this case the logging loggic will only contain
dprintf_cond(flags_or_verbose_level, msg, param1, param2);

and there will be no need in separating it from the rest of code.

A: A flag and proper logic is probably the safer way to do it, but you could do the same at compile type. Ie. Use #define and #ifdef to include/exclude the printfs.

A: Hmm, this sounds similar to a problem I encountered when working on a C++ project last summer. It was a distributed app which had to be absolutely bulletproof and this resulted in a load of annoying exception handling bloat. A 10 line function would double in size by the time you added an exception or two, because each one involved building a stringstream from a looong exception string plus any relevant parameters, and then actually throwing the exception maybe five lines later.
So I ended up building a mini exception handling framework which meant I could centralise all my exception messages inside one class. I would initialise that class with my (possibly parameterised) messages on startup, and this allowed me to write things like throw CommunicationException(28, param1, param2) (variadic arguments). I think I'll catch a bit of flak for that, but it made the code infinitely more readable. The only danger, for example, was that you could inadvertently throw that exception with message #27 rather than #28.

A: #ifndef DEBUG_OUT

# define DBG_MGS(level, format, ...)
# define DBG_SET_LEVEL(x) do{}while(0)

#else

extern int dbg_level;
# define DBG_MSG(level, format, ...)              \
   do {                                           \
      if ((level) >= dbg_level) {                 \
          fprintf(stderr, (format), ## __VA_ARGS__); \
      }                                           \
   } while (0)
# define DBG_SET_LEVEL(X) do { dbg_level = (X); } while (0)

#endif

The ## before  __VA_ARGS__ is a GCC specific thing that makes , __VA_ARGS__ actually turn into the right code when there are no actual extra arguments.
The do { ... } while (0) stuff is just to make you put ; after the statements when you use them, like you do when you call regular functions.
If you don't want to get as fancy you can do away with the debug level part.  That just makes it so that if you want you can alter the level of debugging/tracing date you want.
You could turn the entire print statement into a separate function (either inline or a regular one) that would be called regardless of the debug level, and would make the decision as to printing or not internally.
#include <stdarg.h>
#include <stdio.h>

int dbg_level = 0;

void DBG_MGS(int level, const char *format, ...) {
    va_list ap;
    va_start(ap, format);
    if (level >= dbg_level) {
        vfprintf(stderr, format, ap);
    }
    va_end(ap);
}

If you are using a *nix system then you should have a look at syslog.
You might also want to search for some tracing libraries.  There are a few that do similar things to what I have outlined.


text:
Q: One line for loop with object modification I have an array of objects where each object has a search_order attribute.
I was to go over the array and increase that attribute by 1 for all objects
This is the easy way:
res = []
for r in array:
    r.search_order+=1
    res.append(r)
return iter(res)

Is there a one line for loop that can accomplish this?
return (r.search_order+=1 for r in array)

Doest seem to work unfortunately.

A: This may not be one line but this does the job correctly
def incr_search_order(x):
    x.search_order += 1
    return x

retrun map(incr_search_order, array)
<or>
return [incr_search_order(x) for x in array]

A: You can not use an assignment within generator expression or list comprehension (it will raise SyntaxError).
Instead add the attribute with 1 and reassign the result :
old_array=(r.search_order+1 for r in array)


text:
Q: Using findAll within a certain tag in BeautifulSoup I'm trying to get all text in a certain column in a certain part of an XML file. To this end, I'm using BeautifulSoup.
When I use BeautifulSoup's FindAll function, it returns the columns from the certain part like it should, plus all the matching columns after that part, so after the closing tag.
To illustrate, an example:
My file:
<?xml version="1.0" encoding="UTF-8"?>
<doc>
    <row>
        <entry colname="col2" align="left">
stuff
</entry>
    </row>

        <row>
            <entry colname="col1" align="right">
<id="1"/>1
</entry>
            <entry colname="col2" align="left">
I want this part
</entry>
        </row>
        <row>
            <entry colname="col1" align="right">
<id="2"/>2
</entry>
            <entry colname="col2" align="left">
I want this part2
</entry>
        </row>
        <row>
            <othertag>moreStuff</othertag>
        </row>

    <row>
        <entry colname="col2" align="left">
I don't want this part
</entry>
    </row>
</doc>

My script:
from bs4 import BeautifulSoup as bs
soup = bs(open('test.xml', encoding='utf-8').read(), 'xml')
soup.body.findAll('entry', {'colname': 'col2'})

Edited script with identical output:
soup = bs(open('test.xml', encoding='utf-8').read(), 'xml')
part = soup.find('body')
part.findAll('entry', {'colname': 'col2'})

The output:
[<entry align="left" colname="col2">
I want this part
</entry>,
 <entry align="left" colname="col2">
I want this part2
</entry>,
 <entry align="left" colname="col2">
I don't want this part
</entry>]

Where the last entry shouldn't be there. How to fix this?
(Due to varying number of correct and incorrect entries throughout my files just ditching the last element of the array isn't an option)

A: Searching for body, then using findAll on it should give you what you want.
But you said that it don't ... So I tested out and cannot reproduce your problem.
from bs4 import BeautifulSoup as bs
xml = '''
<?xml version="1.0" encoding="UTF-8"?>
<doc>
    <row>
        <entry colname="col2" align="left">
stuff
</entry>
    </row>

        <row>
            <entry colname="col1" align="right">
<id="1"/>1
</entry>
            <entry colname="col2" align="left">
I want this part
</entry>
        </row>
        <row>
            <entry colname="col1" align="right">
<id="2"/>2
</entry>
            <entry colname="col2" align="left">
I want this part2
</entry>
        </row>
        <row>
            <othertag>moreStuff</othertag>
        </row>

    <row>
        <entry colname="col2" align="left">
I don't want this part
</entry>
    </row>
</doc>
'''

soup = bs(xml, 'html.parser')

print(soup.findAll('entry', {'colname': 'col2'}))

part = soup.find('body')
print(part.findAll('entry', {'colname': 'col2'}))

Which gives me the expected output:
$ python /tmp/zbefberg.py
[<entry align="left" colname="col2">
stuff
</entry>, <entry align="left" colname="col2">
I want this part
</entry>, <entry align="left" colname="col2">
I want this part2
</entry>, <entry align="left" colname="col2">
I don't want this part
</entry>]
[<entry align="left" colname="col2">
I want this part
</entry>, <entry align="left" colname="col2">
I want this part2
</entry>]

From there, try out my small example, if the problem persist try reinstalling BF4, then reinstall lxml, if it persist try using the 'html.parser' parser.

A: Using "xml" option to create the soup somehow results in all <row> after opening tag of body goes inside the  element. Print soup.prettify() to see how BS parses your XML. That said, using "html.parser" instead of "xml", as also mentioned in the other answer, fixed the problem
>>> print soup.prettify()
<?xml version="1.0" encoding="utf-8"?>
<doc>
 <row>
  <entry align="left" colname="col2">

    stuff

  </entry>
 </row>

  <row>

   <entry align="right" colname="col1">

     <id>
      ="1"/>1
     </id>

    <entry align="left" colname="col2">

      I want this part

    </entry>
   </entry>
   <row>

    <entry align="right" colname="col1">

      <id>
       ="2"/>2
      </id>

     <entry align="left" colname="col2">

       I want this part2

     </entry>
    </entry>
    <row>
     <othertag>
      moreStuff
     </othertag>
    </row>
   </row>
   <row>
    <entry align="left" colname="col2">

      I

       don't

      want this part

    </entry>
   </row>
  </row>

</doc>


text:
Q: jQuery loading empty image first in slideshow Okay, everyone, I am a total noob at jQuery, but I'm learning, and I've tried to research and implement a very simple slideshow. Looks thus:

And I have this in the body down yonder:

It runs alright for its purposes, but it's kind of irksome that it starts out with a big empty blank square image box for several seconds before proceeding with the slide show. Is there a simple way to fix this?

A: Your src in the image tag is blank when the page loads, so you need to fill it with an image like so:
    $('#imageSlide').prop('src','../Images/Slideshow/01.jpg');

A: Call Slider(); immediately before setInterval();

A:

Now put the source of first image as the last one in array as follows


text:
Q: Get the nth-child param value with a class selector that is equal to "active" in jQuery How do I get the nth-child param value with a class selector that is equal to "active" in jQuery?
I'm not sure if this is logical but I want to determine which of the list of dd elements that I have is currently selected through the nth-param value.
The code is actually a loop of vertical tabs from Foundation's Vertical Tabs.

<?php foreach($tabs as $key):?>

<a href="javascript:void(0)" onclick="ajaxFunc('<?php echo ($key['group_name']) ?>')" id="ver_tab_a"><?php echo ucwords($key['group_name']);?>

<?php endforeach ?>

+ New Group

I have a list of tabs with data acquired dynamically. I also have a static tab at the bottom which would add a new group. A click on a tab from the dynamically generated tab would add a class with value "active" What I want is when I click the static tab, a modal is open and when I cancel the modal(modal is from Foundation's Reveal also), the selected tab should revert to the active tab before I click the static tab.
On my jQuery I have:
$("#ver_tab:nth-child("+x+")").attr("class","active");

To revert to the previously selected tab where the x is the nth-child of the selected tab.
Thanks so much!

A: It sounds like you are trying to get the .index() of the .active element:
$('dd.active').index('dd')

A: I finally figured it out after a long search.
Although this answer is on different approach, nevertheless it solve my problem on how to identify the index number of my currently selected tab.
Here's what I did.
On my:

<a href="javascript:void(0)" onclick="ajaxFunc('<?php echo ($key['group_name']) ?>')" id="ver_tab_a"><?php echo ucwords($key['group_name']);?>

I added another paramater on the:
onclick="('<?php echo ($key['group_name']) ?>')"

So it looks like:
onclick="('$(this)','<?php echo ($key['group_name']) ?>')"

Then on my ajaxFunc:
function ajaxFunc(x, group_name){
    var pos = x.closest("dd").index;
}

The pos variable should now contain the index value of currently selected tab.
Thanks to this post Jquery index can't find element (-1) wrong input (with live function)! Save me so much time!