text:
Q: Linux Raid: mystical md_d device I have a 64bit Ubuntu Jaunty server (kernel 2.6.28-17-server) installed on two SATA disks (sdc and sde) in a mirror RAID, this being my current raid configuration:
cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]

md5 : active raid1 sdd7[1] sdc7[0]
      126953536 blocks [2/2] [UU]

md2 : active raid1 sdd3[1] sdc3[0]
      979840 blocks [2/2] [UU]

md0 : active raid1 sdd1[1] sdc1[0]
      96256 blocks [2/2] [UU]

md4 : active raid1 sdd6[1] sdc6[0]
      9767424 blocks [2/2] [UU]

md3 : active raid1 sdd5[1] sdc5[0]
      979840 blocks [2/2] [UU]

md1 : active raid1 sdd2[1] sdc2[0]
      1951808 blocks [2/2] [UU]

unused devices: none

# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/md4              9.2G  922M  7.9G  11% /
tmpfs                 490M     0  490M   0% /lib/init/rw
varrun                490M  316K  490M   1% /var/run
varlock               490M     0  490M   0% /var/lock
udev                  490M  228K  490M   1% /dev
tmpfs                 490M     0  490M   0% /dev/shm
lrm                   490M  2.5M  488M   1% /lib/modules/2.6.28-17-server/volatile
/dev/md0               89M   55M   30M  65% /boot
/dev/md5              120G   96G   18G  85% /data
/dev/md2              942M   18M  877M   2% /tmp
/dev/md3              942M  186M  709M  21% /var

Users are quickly filling up the /data Samba share, so I added two additional hard disks (sda and sdb, they are the exact same type and size), as I wanted to create another mirror out of them and then mounted the new raid device inside /data.
Steps I took was creating one Linux raid autodetect partition on each of the new disks, making sure that they are the same size.
 fdisk /dev/sda -l

Disk /dev/sda: 122.9 GB, 122942324736 bytes
255 heads, 63 sectors/track, 14946 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x000e2e78

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1       14946   120053713+  fd  Linux raid autodetect

fdisk /dev/sdb -l

Disk /dev/sdb: 122.9 GB, 122942324736 bytes
255 heads, 63 sectors/track, 14946 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x000ef08e

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1       14946   120053713+  fd  Linux raid autodetect

Next I created the new mirror:
mdadm --create /dev/md6 --level=mirror --raid-devices=2 /dev/sda1 /dev/sdb1
At which point I got the following warning:
mdadm: /dev/sdb1 appears to contain an ext2fs file system
    size=120053712K  mtime=Sat Dec 19 11:10:30 2009
Continue creating array?

This is weird, as I just created the new partition, and I never had a filesystem created on it, but anyway, I continued on and waited for the sync to finish.
Everything seems fine:
cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md6 : active raid1 sdb1[1] sda1[0]
      120053632 blocks [2/2] [UU]

md5 : active raid1 sdd7[1] sdc7[0]
      126953536 blocks [2/2] [UU]

md2 : active raid1 sdd3[1] sdc3[0]
      979840 blocks [2/2] [UU]

md4 : active raid1 sdc6[0] sdd6[1]
      9767424 blocks [2/2] [UU]

md3 : active raid1 sdc5[0] sdd5[1]
      979840 blocks [2/2] [UU]

md1 : active raid1 sdc2[0] sdd2[1]
      1951808 blocks [2/2] [UU]

md0 : active raid1 sdc1[0] sdd1[1]
      96256 blocks [2/2] [UU]

unused devices: none

mdadm --detail /dev/md6
/dev/md6:
        Version : 00.90
  Creation Time : Sat Dec 19 11:33:31 2009
     Raid Level : raid1
     Array Size : 120053632 (114.49 GiB 122.93 GB)
  Used Dev Size : 120053632 (114.49 GiB 122.93 GB)
   Raid Devices : 2
  Total Devices : 2
Preferred Minor : 6
    Persistence : Superblock is persistent

    Update Time : Sat Dec 19 12:24:14 2009
          State : clean
 Active Devices : 2
Working Devices : 2
 Failed Devices : 0
  Spare Devices : 0

           UUID : b901925f:b5ca90e0:afcf3cfb:09b88def (local to host szerver.mtvsz.local)
         Events : 0.4

    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1

But once I reboot, here comes the problem:
cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
md_d6 : inactive sdb1[1](S)
      120053632 blocks

md3 : active raid1 sdc5[0] sdd5[1]
      979840 blocks [2/2] [UU]

md5 : active raid1 sdc7[0] sdd7[1]
      126953536 blocks [2/2] [UU]

md2 : active raid1 sdc3[0] sdd3[1]
      979840 blocks [2/2] [UU]

md1 : active raid1 sdd2[1] sdc2[0]
      1951808 blocks [2/2] [UU]

md0 : active raid1 sdd1[1] sdc1[0]
      96256 blocks [2/2] [UU]

md4 : active raid1 sdd6[1] sdc6[0]
      9767424 blocks [2/2] [UU]

unused devices: none

 ls /dev/md*
/dev/md0  /dev/md2  /dev/md4  /dev/md_d6    /dev/md_d6p2  /dev/md_d6p4
/dev/md1  /dev/md3  /dev/md5  /dev/md_d6p1  /dev/md_d6p3

So my question is: What the hell is this with md_d6 and its partitions?

A: Ok, it seems this is a mdadm bug or I missed a manual step. After issuing this command
mdadm --examine --scan --config=mdadm.conf >> /etc/mdadm/mdadm.conf
and rebooting it seems the raid array is now ok. Stupid bug :)


text:
Q: ColdFusion get method I am sending a value of a variable from an http url to another cfm page, but I am not sure how to get that value on the other page. In php we use $_GET['variable']; I am not sure what is the equivalent of that in ColdFusion.

A: Use #URL.variable# for GET.
Use #FORM.variable# for POST.

A: There are enough good answers, but I'll just add that one of the nice things about associative array notation for accessing struct keys is that you still have access to keys that are syntactically invalid.  So if you created a page called test.cfm like such:
<cfdump var="#url#">
<cfoutput>
#url['bad bad var name']#<br />
</cfoutput>

And called it like such:
http://localhost/test.cfm?bad bad var name=foo

You would see 'foo' output on the page.
But if you tried this:
<cfdump var="#url#">
<cfoutput>
#url.bad bad var name#
</cfoutput>

You would see:

Invalid CFML construct found on line 3
  at column 10.  ColdFusion was looking
  at the following text:
bad

Because variable names can't contain spaces.
Of course no one would intentionally name a URL parameter with a space (I hope), but this comes in handy with things like queries and external data is out of the developers immediate control.

A: You can access them using #url.variable#. For example, in PHP you might have $_GET['id'] and in CF you would have #url.id#

A: ColdFusion has the option of accessing these variables very much like you're doing in PHP:
PHP:
$foo = $_GET['variablename'];
$bar = $_POST['variablename'];

CFScript:
foo = URL['variablename'];
bar = FORM['variablename'];

CFML:
<cfset foo = URL['variablename']>
<cfset bar = FORM['variablename']>

Edit: Discussion of Form Scope Case Insensitivity, and a Workaround
ColdFusion will (helpfully?) convert all form fieldnames to uppercase in the form scope. In cases where a fieldname is repeated, the multiple values will be merged into a single comma-separated value. When you don't have control over the form itself, this can lead to frustration.
Given the form:
<form name="main" action="handler.cfm" method="post">
  <input type="text" name="conFUSion" value="abc" />
  <input type="text" name="CONfusion" value="def" />
  <input type="submit" name="Submit" />
</form>

The form scope on the receiving page would look like this:

But you can use gethttprequestdata().content to directly access the original form case-preserved fields and values as posted:

conFUSion=abc&CONfusion=def&Submit=Submit

Since ColdFusion structs are case-insensitive, we can't simply parse this string into a regular struct. Instead we can turn to java.util.HashMap, which is very much like a ColdFusion struct, but does preserve case:
arFormscope = gethttprequestdata().content.split('&');
cs_form = createobject('java','java.util.HashMap').init();
for( i=1; i<=arraylen(arFormscope); i++ ){
  arElement = arFormscope[i].split('=');
  key = arElement[1];
  value = arElement[2];
  cs_form[key] = value;
}

Dumping the cs_form hashmap, we get:

...and finally:
cs_form['CONfusion']; // def
cs_form['conFUSion']; // abc
cs_form['CONFUSION']; // Error, undefined in java.util.HashMap

A: I've done this in coldfusion 7 before.
You can use the cgi.query_string value to get the query string and then split as follows:
httpGetValues = createobject('java','java.util.HashMap').init();

nameValuePairs = cgi.query_string.split('&');
for( i=1; i lte arraylen(nameValuePairs); i = i + 1 ){
    pair= nameValuePairs[i].split('=');
    key = URLDecode(pair[1], "UTF-8");
    value = URLDecode(pair[2], "UTF-8");
    httpGetValues[key] = value;
}

Make sure that you decode the values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: When fetching list's items the link of title column is missing I wrote a spfx web part using sp-pnp-js to fetch items from a list, this is my query to the list:
public async getAgreements(): Promise<Agreement[]> {
    let select = '*';

    let Agreements: Agreement[] = [];

    const items = await sp.web.lists.getById('ID_OF_THE_LIST').items
      .select(select)
      .get();

    items.forEach(item => {
        Agreements.push({
            AgreementName: item.Title,
            CustomerAgreementNr: item.CustomerAgreementNr

        });
    });

    return new Promise<Agreement[]>(async(resolve) => {
        resolve(Agreements);
    });
  }

In the SharePoint list I changed the display name of the title column to AgreementName so when I want to render the list in the web part I use AgreementName.
To render the list I am using ListView and IViewField and it looks like this:
export default class AgreementContainer extends React.Component<IAgreementContainerProps, IAgreementContainerState> {
constructor(props: IAgreementContainerProps) {
    super(props);

    this.state = {
        agreements: []
    }
};

private viewFields: IViewField[] = [
    {
        name: "AgreementName",
        linkPropertyName: "AgreementName.ServerRelativeUrl",
        displayName: "Agreement Name",
        maxWidth: 25,
        minWidth: 25,
        sorting: true,
        isResizable: true
      },
      {
        name: "CustomerAgreementNr",
        displayName: "Customer Agreement Nr",
        maxWidth: 4,
        isResizable: true
      }
]

public componentDidMount(): void {
    this.props.provider.getAgreements().then((agreements) => {
        this.setState({
            agreements: agreements
        });
    });

}

public render(): JSX.Element {
    console.log(this.state.agreements);
    return (

        <ListView
            items = {this.state.agreements}
            viewFields={this.viewFields}
        />

      );
}
}

But the result for the AgreementName column is just an empty a-tag with a tabindex attribute:
Agreement

I have tested with the internal name instead (Title) but the result is the same.
How can I fetch the link in order to link the item name?
And a last question, there are date columns too in the list and when they gets rendered the date is in this format: 2019-03-26T13:00:00Z , is there a way to convert the date to a friendly format? something like 2019-03-26 ?
Best regards,
Americo

A: Date field will always come in ISO date format only. You can use custom JS function to get it converted in to desired style. Example JS function:
function ConvertISOdateFormatToRequiredFormat(date) {
    var formattedDate = null;
    if (date != "" && date != null) {
        var Ldate = new Date(date);
        var year = Ldate.getFullYear();
        var month = Ldate.getMonth() + 1;
        var dt = Ldate.getDate();

        if (dt < 10) {
            dt = '0' + dt;
        }
        if (month < 10) {
            month = '0' + month;
        }

        //var months = { 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec' };
        formattedDate = month + "/" + dt + "/" + year;
        return formattedDate;
    }
    else {
        return formattedDate;
    }
}

Regarding Title, Try to query that list in browser like https://siteaddress/_api/web/lists/getbytitle('List title')/items
And then check how the value is coming in TITLE FIELD. You will not get the link. If you need to frame the link, you can form the link with the help of ID column.


text:
Q: Contact form 7 NOT working on my WAMP localhost So, i knew that when using CF7 on localhost was unable to send email to your mail box. It wasn't the first time i'm using CF7, so i know that you still can test out the form and it will able to show up a successful green border message and said that your message was successful sent.
But now the problem is i'm not only cannot test my form and it keep show up the red border message said that [There was an error trying to send your message. Please try again later.] So how can i fix it?
I also did some research about this problems and it's about  [mail server was down, inaccessible or experiencing other problems / contact your host for support / contact your server admin. ] I did installed the smpt plugin before i test  the form (because i've found  a solution said that you can send your email through your localhost by installing smpt plugin, so i decided to give it a try)   and it turn out not working so i thought that it was the smpt plugin affected the CF7 not working, and i go ahead and uninstall smpt plugin but my CF7 form still not working. I've also tried uninstall and reinstall CF7 but my CF7 form still not working.
Any help will be appreciated, thanks!
This is the form

Your Name (required)

    [text* your-name]

Your Email (required)

    [email* your-email]

Subject

    [text your-subject]

Your Message

    [textarea your-message]

[submit "Send"]

This is the mail setting

A: Install hMailServer on your server. Or install smtp plugin then add smtp details of your email.


text:
Q: Test non static methods in Rspec? Is it possible to check what arguments is being passed to a non static method when testing with rspec?
If I for i.e want to test class A, inside class A i call class B, B is already tested. The only thing I want to test is the ingoing arguments to B.
class A
  def method
    number = 10
    b = B.new
    b.calling(number)
  end
end

class B
  def calling(argument)
    # This code in this class is already testet
  end
end

How do I test the ingoing arguments to b.calling?
I've tried this so far, without success.
it "should work" do
  b = mock(B)
  b.should_receive(:calling).at_least(1).times
  A.new.method
end

It always fails, beacuse b never was called.

A: the b in your spec isn't the b A is instantiating (it returns a real instance of B when you call new since you haven't stubbed it), try this:
it "should work" do
  b = mock(B)
  B.should_receive(:new).and_return(b)
  b.should_receive(:calling).at_least(1).times
  A.new.method
end


text:
Q: Find dates with 1 hour difference from the first datetime of each day on MongoDB Below an extract of my data
{ _id: ObjectId("1"), date: 2021-07-01T08:00.000+00:00, price: 10, id: 1}
{ _id: ObjectId("2"), date: 2021-07-01T08:20.000+00:00, price: 10.5, id: 1}
{ _id: ObjectId("3"), date: 2021-07-01T08:40.000+00:00, price: 9.8, id: 1}
{ _id: ObjectId("4"), date: 2021-07-01T09:00.000+00:00, price: 10.2, id: 1}
{ _id: ObjectId("5"), date: 2021-07-01T09:20.000+00:00, price: 10.9, id: 1}
{ _id: ObjectId("6"), date: 2021-07-01T09:40.000+00:00, price: 13, id: 1}
{ _id: ObjectId("7"), date: 2021-07-02T07:00.000+00:00, price: 10, id: 2}
{ _id: ObjectId("8"), date: 2021-07-02T07:20.000+00:00, price: 10.2, id: 2}
{ _id: ObjectId("9"), date: 2021-07-02T07:40.000+00:00, price: 8, id: 2}
{ _id: ObjectId("10"), date: 2021-07-02T08:00.000+00:00, price: 10.7, id: 2}
{ _id: ObjectId("11"), date: 2021-07-02T08:20.000+00:00, price: 10, id: 2}
{ _id: ObjectId("12"), date: 2021-07-02T08:40.000+00:00, price: 11, id: 2}
{ _id: ObjectId("13"), date: 2021-07-03T08:00.000+00:00, price: 11.5, id: 2}
{ _id: ObjectId("14"), date: 2021-07-03T08:20.000+00:00, price: 10.8, id: 2}

Is there a way to SELECT for each IDs the first hours within a day on each day ?
The result based on the extract would be
{ _id: ObjectId("1"), date: 2021-07-01T08:00.000+00:00, price: 10, id: 1}
{ _id: ObjectId("2"), date: 2021-07-01T08:20.000+00:00, price: 10.5, id: 1}
{ _id: ObjectId("3"), date: 2021-07-01T08:40.000+00:00, price: 9.8, id: 1}
{ _id: ObjectId("7"), date: 2021-07-02T07:00.000+00:00, price: 10, id: 2}
{ _id: ObjectId("8"), date: 2021-07-02T07:20.000+00:00, price: 10.2, id: 2}
{ _id: ObjectId("9"), date: 2021-07-02T07:40.000+00:00, price: 8, id: 2}
{ _id: ObjectId("13"), date: 2021-07-03T08:00.000+00:00, price: 11.5, id: 2}
{ _id: ObjectId("14"), date: 2021-07-03T08:20.000+00:00, price: 10.8, id: 2}

A: Query does

*

*makes string dates to date objects

*group by year and day
collect all documents in day-info
finds the minimun hour, for each day

*filter all the day-info, and keep only those that happened in the minimun hour

*restore document structure

Test code here
Query (if you have dates, and not strings, skip the first $set stage)
aggregate(
[ {
  "$set" : {
    "date" : {
      "$dateFromString" : {
        "dateString" : "$date"
      }
    }
  }
}, {
  "$group" : {
    "_id" : {
      "year" : {
        "$year" : "$date"
      },
      "day" : {
        "$dayOfYear" : "$date"
      }
    },
    "day-info" : {
      "$push" : "$$ROOT"
    },
    "min-hour" : {
      "$min" : {
        "$hour" : "$date"
      }
    }
  }
}, {
  "$project" : {
    "day-info" : {
      "$filter" : {
        "input" : "$day-info",
        "as" : "d",
        "cond" : {
          "$eq" : [ {
            "$hour" : "$$d.date"
          }, "$min-hour" ]
        }
      }
    }
  }
}, {
  "$unwind" : {
    "path" : "$day-info"
  }
}, {
  "$replaceRoot" : {
    "newRoot" : "$day-info"
  }
} ]
)

Edit (to keep the dates that their difference is < 1 hour from the minimun date of each day you can do this)
Test code here
Query
db.collection.aggregate([
  {
    "$set": {
      "date": {
        "$dateFromString": {
          "dateString": "$date"
        }
      }
    }
  },
  {
    "$group": {
      "_id": {
        "year": {
          "$year": "$date"
        },
        "day": {
          "$dayOfYear": "$date"
        }
      },
      "day-info": {
        "$push": "$$ROOT"
      },
      "min-date": {
        "$min": "$date"
      }
    }
  },
  {
    "$set": {
      "day-info": {
        "$filter": {
          "input": "$day-info",
          "as": "d",
          "cond": {
            "$lt": [
              {
                "$subtract": [
                  "$$d.date",
                  "$min-date"
                ]
              },
              {
                "$multiply": [
                  60,
                  60,
                  1000
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    "$unwind": {
      "path": "$day-info"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$day-info"
    }
  },
  {
    "$sort": {
      "date": 1
    }
  }
])


text:
Q: unable to read POST parameters in spring application I m using angular js for posting parameters to spring application.
At angular side
$http.post('dashboard/processSearch',{processRequestName:'TestName',displayName:'Test'})
    .then(function(response) {
        console.log(response.data);
    });

At controller side in spring
@RequestMapping(value = "/processSearch", method = RequestMethod.POST)
@ResponseBody
public String searchAll(@RequestParam String processRequestName, @RequestParam String displayName) {

    return processRequestName+"####"+displayName;
}

I m getting complete webpage in ajax response with error message
Error
    Application encountered an error while performing the operation.
    See error details below.
    Error Reference: 1459234251503-5
label.error.missingservletrequestparameterexception

A: Specify the params argument
Break your http call down differently.
$http({
  url: dashboard/processSearch,
  method: "POST",
  params: {processRequestName: 'TestName', displayName:'Test'}
});

This is the correct way to pass params.
But you might need to pass headers in a similar way to the params
headers: {
   'Content-Type': undefined
}

Use a factory
Also you should make http requests in a factory method that returns the result. You can then add that factory to any controller you need. This is where you do the .then part of your controller.
Your factory should look something like this
angular.module('yourService', []).factory('YourFactory', [ '$http',  function($http){
  return{
    getStuff: function(){
        return // your http request
    }
  };
}]);

You can then call your factory in your controller like this
angular.module('yourCtrlMod', ['yourService']).controller('yourCtrl', [ '$scope','yourFactory', function($scope, yourFactory){

  yourFactory.getStuff().then(function(res){
    $scope.yourScope= res.data;
  });

}]);

Note that this is for a get not a post, in your case you will have to post the data and send arguments. to the factory and fill out the params or headers.


text:
Q: How to use multiple models in MVC3 asp If I have an MVC3 ASP.net page which contains a the model "iEnumerable<mymodel.CarsForHire>" - which links directly into an entity framework model- and I also now want to include the default user management model that MVC3 generates, how can I use both models at once?
I assume I will have to pass a collection in, or create a model called "blah" which has a field "carsforHire" which marries up to iEnumerable<mymodel.CarsForHire>, but not sure where to start.
Any ideas would be greatly appreciated

A: You already mentioned the solution; create a view model class that holds all the required data. For example:
public class SomeViewModel
{
   public User CurrentUser { get; set; }
   public IEnumerable<mymodel.CarsForHire> Cars { get; set; }
}

Construct that model in the controller and pass it to your view. And don't forget to update the type declaration at the top of your view.

A: What I usually do is create a ViewModel class. For example:
public class CarsViewModel
{
    public IEnumerable<mymodel.CarsForHire> CarsForHire { get; set; }

    public UserModel User { get; set; }
}

Then create the view with CarsViewModel instead of IEnumerable<mymodel.CarsForHire>

A: You can use Navigational properties of EF if you want to.i.e
public class carForHire()
{
 int property1{get; set;}
 .
 .
 .
//Navigationla property
public virtual blah blah { get; set; }
}

at your page/view you can acces it like

@foreach(var item in Mode)
  {
 item.blah.blahProperty
  }


text:
Q: Can Windows Media Player create playlists based on folder structure? Over the years I've carefully molded my digital media collection into a series of folders that make it easy for me to find what I'm looking for. I recently discovered the awesomeness that is streaming video from Windows 7 Media Player to the PS3 so I can watch it on the big screen without all the hassle of hooking the computer up to the TV. The problem is, I totally lose my carefully crafted folder structure and all my videos become one giant mess again... not cool! As a temporary solution, I've created a few playlists for my favorites (Dexter Season 4, Dexter Season 5, Breaking Bad Season 1, etc.). This is a HUGE pain in the a$$.
So, is there a way to get Windows Media Player (on Windows 7) to maintain some sort of folder structure based on the location of the actual video files? So if I have my videos sorted into folders by show and season, Media Player will pick that up and let me browse it in the same way.
As an alternative answer, I'll accept suggestions for a program that can also stream to PS3 and has this "folder organization" feature.

A: Don't bother going for complex solutions, think logical steps ;)
Open Windows Media Player (WMP), and also open Windows Explorer.  From Windows Explorer, right-click the folder you want to add, then select 'Add to Windows Media Playerlist'.  WMP will add all songs in all subdirectories of that folder to a list.  You can then save and rename the utitled list.  It will be easy for you to later merge folder as you wish.
Why hasn't someone posted this solution before???? beats me?
(note this works for Windows 7, latest WMP version as of 13/01/2011)

A: Not to seem like a condescending jerk, but I used to listen to my music based on file-system metadata like folders and file names just like you. There is a better way. Focus on getting the correct metadata into your files. For MP3s you should get all of your ID3 tags setup correctly using something like the Picard tagger. The same principal should apply for your videos -- get the metadata right. Then you can use Windows Media Player, MediaMonkey, etc to create auto playlists for you that are exactly tailored to what you want to watch or listen to. For the cost of the initial investment in setting up your metadata correctly, you will be repaid many times over by the ability to make any playlist in seconds much more easily and flexibly than you can using your folder approach.

A: Drag Folder to playlist, click "list options" on top right side of the playlist. The go down to "Sort list by", and select "File name".
Should help.

A: MediaMonkey V4 has this feature (UPnP sharing by Location).  It's not yet released (in fact the beta program hasn't even begun), but if you want to try the development build, it's available at:
http://www.mediamonkey.com/forum/viewtopic.php?f=19&t=54156
Disclosure: I work on MediaMonkey

A: A simple solution would be setting folder and sub folders to Music type content. This will be effective when using single folder for all your music.

A: in WMP  right click on Music in the navigation panel and then "customize navigation panel". In the music section check Folder.


text:
Q: Interface between two related JPA entities This is an extension of the following question
Interface between two related JPA entities
I have exactly the same scenario, but with one more addition.
To put it into the same example stated by #OpenSource , the Fax ans Email tables already extending from "Source" through InheritanceType as "Joined" which is another base class for many other classes. Now as in your example, you have made Fax and Email to extend from Channel which is specified with InheritanceType as TABLE_PER_CLASS.
I don't think I can implement the same approach (specifying TABLE_PER_CLASS) in my case as well. Please help me out to overcome this situation.

A: this is using ManyToAny mapping instead ManyToOne or OneToOne
@Entity
public class Delivery {
    @Id
    @GeneratedValue
    private Long id;

    @Any(metaColumn = @Column(name = "type"))
    @AnyMetaDef(idType = "long", metaType = "string",
            metaValues = {
             @MetaValue(targetEntity = Fax.class, value = "fax"),
             @MetaValue(targetEntity = Email.class, value = "email"),
       })
    @JoinColumn(name="channelId")
    private Channel channel;
}


text:
Q: How to open a program using keyboard input? My project is to make a program that you can run while you are playing games or other programs in the background.
When you press a certain key, your notepad should open and also close after you press the same key again.
I have managed to open notepad with subprocess and that works fine but I have no idea to make it open only when a certain key is pressed.
Thanks for any help!
EDIT:
What I tried already:
import subprocess
import keyboard

if keyboard.is_pressed('k'):
    subprocess.Popen('C:\\Windows\\System32\\notepad.exe')

input()

here it just doesn't detect any keyboard input, the input() at the end makes the program not close instantly
import subprocess
import keyboard

keyboard.add_hotkey('ctrl+k', print,args=("hello", "test"))

input()

Here if I press "ctrl+k it" will print hello test that means the hotkey works fine. When I switch this part "print,args=("hello", "test")" to "subprocess.Popen('C:\Windows\System32\notepad.exe')"(it should open the program instead of printing hello test) the notepad opens instantly after I run the program and when I press "ctrl+k" I get a big error.

A: The problem is that you check for the key 'k' only once at the beginning. If you want the program to correctly work then you should try this:
import time
import subprocess
import keyboard
while True:
    if keyboard.is_pressed('k'):
        subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
        time.sleep(5)

-I used the time so that you can only open the program once 5 seconds(If you're curious, see what happens without it)-

A: A more complex, but still working example could be the following. With this code your program will be always listening the keyboard, not only when you are focused on the input, so may be mre practical in your case
from pynput import keyboard
import subprocess
import threading

class MyException(Exception): pass

class Listening:
    """Is allways waiting for the keyboard input"""
    def __init__(self):
        self.notepad_open = False # to know the state
        with keyboard.Listener(
                on_press=self.on_press) as listener:
            try:
                listener.join()
            except:
                pass

    def on_press(self, key):
        try:
            if key.char == "k":
                if not self.notepad_open:
                    self.subprocess = \
                        subprocess.Popen('C:\\Windows\\System32\\notepad.exe')
                    self.notepad_open = True # update state
                else:
                    self.subprocess.kill()
                    self.notepad_open = False # update state
        except: # special key was pressed
            pass

thread = threading.Thread(target=lambda: Listening())
thread.start()


text:
Q: ASP.Net website makes browser load unwanted (non-referenced) plugins I've found that some of my ASP.Net web apps prompt the browser to load plugins that I'm not explicitely using and certainly haven't deliberately referenced in the project settings.
Two that come to mind are for MS MediaPlayer and the "SVG Viewer for Netscape".
The only commonality I've determined so far is that the two sites/apps affected both use Master pages (nested in some cases).
We don't use SVG file types (just the normal mix of jpg/gif/png) and no video/audio (not yet anyway).
Can anyone provide a hint as to where the references for these might be creeping in?  e.g. Is it a server-level include? Or a .Net runtime default when using master pages?
Does anyone else even experience this, or is it just me?
No urgency, I'd just like to remove it if possible.
Thanks.
Al

A: If you look at the page source in your browser, you should see what's in the page that requires a plugin. If you load external Javascript, you will have to look at that too. Do you have ads on the site that include 3rd party code?


text:
Q: HTML application drop down - from an array of folders I've got an HTML application, where I want users to select a folder from a drop-down list.
To populate this drop-down list, I would need the application to check for all folders in a directory and list those folders in the drop-down list.
Is this possible with JavaScript or VB Script?

A: OK, found the answer myself anyway.  Here's an example for anybody else wanting to do this:
HTML:

    Select Folder:
        <select id="folder" class="inputfields" tabindex="1" name="folder" size="1" style="width:278px;"">
            <option value="0">Select a folder...</option>
        </select>

VB (within the Window_OnLoad Sub):
Dim oFSO, oFolder, oSubFolder, i, oNewOption
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("\\Server\Share")
Set oSubFolder = oFolder.SubFolders

For Each i in oSubFolder
    Set oNewOption = window.document.CreateElement("OPTION")
    oNewOption.Text = i.Name
    oNewOption.Value = i.Name
    Folder.Add(oNewOption)
Next


text:
Q: How to parameterize a path in ANT? I have the following  defined in a file called build-dependencies.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="build-dependencies">
  ...
  <path id="common-jars">
    <fileset file="artifacts/project-1/jar/some*.jar" />
    <fileset file="artifacts/project-2/jar/someother*.jar" />
  </path>
  ...
</project>

I include it at the top of my build.xml file. Now I need to make the artifacts folder a parameter so it can be changed during execution of different targets.
Having this...
<?xml version="1.0" encoding="UTF-8"?>
<project name="build-dependencies">
  ...
  <path id="common-jars">
    <fileset file="${artifacts}/project-1/jar/some*.jar" />
    <fileset file="${artifacts}/project-2/jar/someother*.jar" />
  </path>
  ...
</project>

...and defining an "artifacts" property (and changing it) in the target does not work because it seems that the property substitution happens when the path is defined in build-dependencies.xml
How can I solve this? One way I was thinking was to have a parameterized macro and call that before the path is actually used, but that seems not elegant. Something like this:
<macrodef name="create-common-jars">
  <attribute name="artifacts"/>
  <sequential>
    <path id="common-jars">
      <fileset file="@{artifacts}/project-1/jar/some*.jar" />
      <fileset file="@{artifacts}/project-2/jar/someother*.jar" />
    </path>
  </sequential>
</macrodef>

EDIT: Ivy and command line parameters are not an option.

A: You don't want a parameterized path.  You want a PatternSet.  You can define the patternset at the top-level and then just refer to it in individual targets when you need it.  For your example:
<?xml version="1.0" encoding="UTF-8"?>
<project name="build-dependencies">
  ...
  <patternset id="common-jars">
    <include name="project-1/jar/some*.jar" />
    <include name="project-2/jar/someother*.jar" />
  </patternset>
  ...
  <path id="instrumented-jars">
    <fileset dir="instrumented">
      <patternset refid="common-jars" />
    </fileset>
  </path>
  ...
  <path id="standard-jars">
    <fileset dir="not-instrumented">
      <patternset refid="common-jars" />
    </fileset>
  </path>
  ...
</project>

A: Lets call your file build.xml. So you execute it by running ant command. In the first case the artifacts names is hardcoded in the property defined on the third line below
<?xml version="1.0" encoding="UTF-8"?>
<project name="build-dependencies">
<property name="artifacts" value="first-value" />
  ...
  <path id="common-jars">
    <fileset file="artifacts/project-1/jar/some*.jar" />
    <fileset file="artifacts/project-2/jar/someother*.jar" />
  </path>
  ...
</project>

Now when you want to change it and use another value for that artifacts property, we run the script thus
ant -Dartifacts=new-value

This will override the hardcoded artifacts value in build.xml
If working in terms of ant targets you can do something similar, in the target on first line define the property, and if you want to overwrite the default value then pass the property as a parameter when that target is called.
Your comment reminded me of something else. Have your developers create a artifacts-dir-name.xml file. It will have only one line:
<?xml version="1.0" encoding="UTF-8"?>
<project name="artifacts-file">
<property name="artifacts" value="new-value" />
</project>

Now in your build.xml file, before the line where artifacts property is defined, import that file thus:
<import file="artifacts-dir-name.xml" optional="true" />

Now in Eclipse if this file exists, then the property is read from it and artifacts is set to "new-value", else the property is read from build.xml and is set to "first-value". All the developers need to do is to ensure artifacts-dir-name.xml file exists in that directory. This can run within Eclipse too.

A: I'd recommend using ivy to manage your classpath dependencies. Ivy has a neat concept called configurations that allows you to group collections of artifacts based on their usage.
Here's an adaption from one of my own build files:
<target name="retrieve" description="3rd party dependencies">
    <ivy:resolve/>

    <ivy:cachepath pathid="build.path" conf="build"/>
    <ivy:cachepath pathid="runtime.path" conf="runtime"/>
</target>

The configurations are managed in the ivy.xml file (Would replace your build-dependencies.xml file)
<ivy-module version="2.0">
    <info organisation="com.myspotontheweb" module="HelloWorld"/>

    <configurations>
        <conf name="build" description="jars needed for build" />
        <conf name="runtime" extends="build" description="jars needed at runtime" />
    </configurations>

    <dependencies>
        <dependency org="org1" name="project1" rev="1.0" conf="build->default"/>
        <dependency org="org2" name="project2" rev="1.0" conf="build->default"/>
        <dependency org="org3" name="project3" rev="1.0" conf="runtime->default"/>
        <dependency org="org4" name="project4" rev="1.0" conf="runtime->default"/>
    </dependencies>
</ivy-module>

The jar artifacts associated with each project would be downloaded and cached automatically from the on-line maven repositories or you can create your own local repository to hold collections of locally owned artifacts.

A: is using environment variables an option (if they are set when eclipse is launched they will be picked up)? If so, have each one set ARTIFACTS and this should work:
<?xml version="1.0" encoding="UTF-8"?>
<project name="build-dependencies">
  <property environment="env"/>
  <path id="common-jars">
    <fileset file="${env.ARTIFACTS}/project-1/jar/some*.jar" />
    <fileset file="${env.ARTIFACTS}/project-2/jar/someother*.jar" />
  </path>
</project>

A: OK, I think there is no other obvious way for me to do what I am trying to do, except use a macro that takes a parameter and creates the path with the appropriate artifacts folder.
To give a bit of context, why I was trying to what I wanted is to have "instrumented" and "not-instrumented" artifacts in separate folders. And in my "targets" I could just vary the artifacts mode. So what I do now is I have a macro: <initialise-build-settings artifacts-mode="instrumented" /> that sets up all the paths and other variables.
Thanks for your answers guys.

A: You can do this with different dependencies:
setpath.xml:
<project name="setpath">
  <target name="setCommonJars">
    <path id="common-jars">
      <fileset file="${param1}/some*.jar" />
      <fileset file="${param1}/someother*.jar" />
    </path>
  </target>
</project>

build.xml:
<project name="Test path" basedir=".">
  <import file="./setpath.xml" />

  <target name="buildT1" depends="setT1,setCommonJars">
    <property name="jar-str" refid="common-jars" />
    <echo message="buildT1: ${jar-str}" />
  </target>

  <target name="buildT2" depends="setT2,setCommonJars">
    <property name="jar-str" refid="common-jars" />
    <echo message="buildT2: ${jar-str}" />
  </target>

  <target name="setT1">
    <property name="param1" value="t1" />
  </target>

  <target name="setT2">
    <property name="param1" value="t2" />
  </target>

</project>

If you call target buildT1 then the t1 directory will be used, if you call buildT2 then the t2 directory will be used.


text:
Q: how to programmatically export all azure databricks notebooks out of a workspace I am implementing a lifecycle management plan of Azure Databricks notebooks for my organization.  One part of this management plan is to programmatically identify and deprecate "stale" notebooks out of a particular workspace (e.g., notebooks that haven't been ran in x days).  To identify stale notebooks manually, I do three things -- (1) export all notebooks out of Azure Databricks, (2) export all notebook runs out of Log Analytics (via the DatabricksJobs table), and (3) compare (1) and (2).  I want to automate this and feed it into an Excel file or Power BI dashboard.
I know how to automate (2).  Is it possible to automate (1)?  If so, how?


text:
Q: Confused with the python results after using some function I have some problem here. Please look at my code and I don't know what's wrong in the code. It is simple but the results are confusing me. I attached the code below.
import numpy as np
import matplotlib.pyplot as plt

def S(xc):
    N=len(xc)
    r=0.0
    s=0.0

    # calculation quartile
    for m in range(0,N-1):
        for n in range(m+1,N):
            if (xc[m] > xc[n]):
                q=xc[m]
                xc[m]=xc[n]
                xc[n]=q

    if (N % 4 < 2):
        q=(xc[N-N/4-1] + xc[N-N/4])*0.5-(xc[N/4-1]+xc[N/4])*0.5
    else:
        q=xc[N-N/4-1]-xc[N/4]

    #calculation standard deviation

    for m in range(0,N):
        r+=xc[m]
        s+=xc[m]*xc[m]
    r=np.sqrt(s/N-(r/N)*(r/N))

    #calculation
    if (q<r):
        s=q
    else:
        s=r
    hasil=0.9*(s/1.34)*pow(N,-0.2)
    return hasil

fc=0.3
fm=0.02
mu=1
Nsim=10

bb=[]
for nn in range(0,Nsim):
    bb.append((1+(mu*np.cos(2*np.pi*fm*nn)))*np.cos(2*np.pi*fc*nn))

print bb
print S(bb)
print bb

The code works while I just delete the function of "S" in the main function, however, after the "S" function, the data on variable "bb" was different even though I just print the same variable. I don't understand what happened.
I appreciate your help. Thanks a lot
Alvin

A: Calling S(bb) changes the contents of bb through statements like xc[m]=xc[n].

A: This is the (un)expected behaviour when working with mutable types in Python. In your case, passing in a mutable type bb, which is a list, to the function S.
You pass bb into S() with the variable name xc and within S, you've got the lines xc[m]=xc[n] and xc[n]=q. This changes the list xc, which is the same list bb points to.
Simpler example of what is happening:
>>> def funny(some_list):
...     for i in range(len(some_list)):  # terrible way to iterate over a list
...         some_list[i] = some_list[i] * 2  # assigning back to the list
...
>>>
>>> alist = [1, 2, 3]
>>>
>>> funny(alist)
>>> alist
[2, 4, 6]
>>>

alist got changed after calling funny() because of the assignment to the list which I passed in.
If you don't want that behaviour, either pass in a copy of the list as S(bb[:]) or create a new list inside S by creating a copy of xc.

A: bb is a list, and lists are mutable.
Even though S() refers to its argument by a different name, xc, ultimately it refers to the same object.  When S() executes statements such as xc[n]=q, the underlying list object is altered.


text:
Q: Replace Light Locker with Gnome screensaver There have been many issues reported concerning Light Locker. Sometimes the lock doesn't work, it locks by itself when not supposed to and many more. Bottom line is Light Locker's major issue is, it doesn't hold the applied or user settings after a reboot or log out.

A: Tried many workarounds to no avail. The way I solved this issue was by removing Light-Locker completely and installing gnome screensaver.
Replace Light-Locker with Gnome Screensaver:

*

*Start Synaptic Package Manager.

*Type light-locker, then uncheck light-locker and light-locker-settings and click [Apply changes].

*Then type gnome-screensaver and check the box to the left and click apply changes again.

Or, using the terminal:
sudo apt-get remove --purge light-locker
sudo apt-get install gnome-screensaver

It works perfectly, didn't mess up my configuration with lightdm, and looks good too. If you're not satisfied with the background shown every time you lock your screen, you can install gnome-tweak-tool. If you can't find it in the applications menu, you can either run it through terminal gnome-tweak-tool or or create a launcher using the same command. Once it's open go to the desktop tab, and choose the location of the background of your liking.

Now you can lock your screen and enjoy a nice screensaver/locking application that works! Good luck! :)


text:
Q: How do I output this JSON value where the key starts with a number? Take this json response:
    {
   "self":"http://macpro.local:2990/jira/rest/api/2/issue/CSS-4/votes",
   "votes":2,
   "hasVoted":true,
   "voters":[
      {
         "self":"http://macpro.local:2990/jira/rest/api/2/user?username=admin",
         "name":"admin",
         "avatarUrls":{
            "16x16":"http://macpro.local:2990/jira/secure/useravatar?size=small&avatarId=10062",
            "48x48":"http://macpro.local:2990/jira/secure/useravatar?avatarId=10062"
         },
         "displayName":"admin",
         "active":true
      },
      {
         "self":"http://macpro.local:2990/jira/rest/api/2/user?username=timn_1",
         "name":"timn_1",
         "avatarUrls":{
            "16x16":"http://macpro.local:2990/jira/secure/useravatar?size=small&avatarId=10062",
            "48x48":"http://macpro.local:2990/jira/secure/useravatar?avatarId=10062"
         },
         "displayName":"User Two",
         "active":true
      }
   ]
}

I'm at a loss for how to get the avatarUrls->16x16 from above. I've been getting everything else pretty easily with commands like:
$decoded = json_decode($result);
$decoded->votes; //returns # of votes
$decoded->voters->name; //returns the name

But how do I get the 16x16 value? I get an error if I try this:
$decoded->voters->avatarUrls->16x16;

A: Same as always.
$decoded->voters->avatarUrls->{'16x16'}

A: You can also do
$decoded = json_decode($result, true);
$decoded['voters']['avatarUrls']['16x16'];

if you like the Array style better.


text:
Q: PHP - Call to undefined function requiring a file from a different folder and using namespace EDIT: I removed namespaces and it still doesn't work. If i move the file in the same folder with blog.php, it works. For the moment, I'm connecting to the database again in the admin file, but I supose that's not a solution.
This is my first question posted. I've started to learn PHP recently and i really like it but i'm stuck now with a problem. I've searched for answers but i couldn't find anything related.
So here's my problem.
I'm trying to build a simple blog and I want to create an admin section. So i created a new folder 'admin' and a file 'index.php' inside it. When I require the 'blog.php' file which connects to the database, I get the error:
'Fatal error: Call to undefined function Blog\DB\connect() in C:\xampp\htdocs\blog\blog.php on line 5' .
In a file db.php which contains all my database related functions I use the namespace Blog\DB. What I dont't really get is that if i move the admin 'index.php' file in the same folder as blog.php it works.
Here is the code from both files.
blog.php :
 <?php
    require 'functions.php';
    require 'db.php';
    //Connect to the db
    $conn = Blog\DB\connect($config);
    if (!$conn) die('Problem connecting to the db!');
    ?>

admin/index.php
<?php
require '../blog.php';
?>

db.php uses:
namespace Blog\DB;

Thank you!

A: Try changing
$conn = Blog\DB\connect($config);

to
$conn = \Blog\DB\connect($config);

Even though not sure if that should work then as I don't think it's namespacing problem.

A: try this ....
require __DIR__ . '/../db.php';

I am also working with PHP and ran into same issue as you. I tried the above line and it worked.
Note: I am working without aliases and namespaces.

A: I had the same problem and I just added
require '../db.php';
in admin/index.php
It solves the problem, but I dont know why that problem occured.
My best guess is that when we require files that uses namespace(like your blog.php uses Blog/DB) we have to require files where we set that namespace( db.php )

A: I recently came across the same problem going through the same PHP lessons. The problem is including an include in a sub-directory causes file path problems. It has nothing to do with namespaces.
replace require 'db.php'; in blog.php with:
 require __DIR__ . '/db.php';

if you're running a PHP version lower than 5.3 use:
 require dirname(__FILE__) . '/db.php';

now when it is included in /admin/index.php the reference will be correct for both the blog and the admin sub-directory.


text:
Q: How to submit an outside variable to Gravity Forms through WP filter This type of work is new to me, so please be patient if the answer is something easy.
I'm using Wordpress and Gravity Forms on my site, and I want to pre-populate the form with data from an object (the object comes from an API, so I can't just use wordpress current_user object).
How can I use an outside variable inside a wordpress filter?
For Example:
$fname = $object->first_name;
add_filter('gform_field_value_firstname', *Populate the field with $fname*);

The below is the normal usage of the function, from Gravity Forms Docs (http://www.gravityhelp.com/documentation/page/Gform_field_value_$parameter_name)
add_filter('gform_field_value_firstname', "dothis");

Where "dothis" points to a function.
The below also works (based on this excellent article: http://www.doitwithwp.com/pre-populate-fields-using-gravity-forms/):
add_filter('gform_field_value_firstname', create_function("", 'return "John";' ));

However, I can't figure out how to get it to accept an outside variable also.  For example, I'd like to do:
$fname = $object->first_name;
add_filter('gform_field_value_firstname', create_function("", 'return $fname;' ));

But php tells me that fname is an undefined variable.
I've reviewed this thread PHP: How to make variable visible in create_function()? , but I could not get the Closure solutions to work. I have PHP Version 5.2.17.
Would you please post an example of how to do this correctly?

A: Make $fname a global variable and you can reference it in your create_function as a global.
global $fname = $object->first_name;
add_filter( 'gform_field_value_firstname', create_function( '', 'global $fname; return $fname;' ) );

However if you have multiple values to return, it's better to make $object global:
global $object;
add_filter( 'gform_field_value_firstname', create_function( '', 'global $object; return
$object->first_name;' ));
add_filter( 'gform_field_value_lastname', create_function( '', 'global $object; return $object->last_name;' ));

And so on...


text:
Q: HTML/Javascript trick needed to set  width I have the following problem:
I have to list several items each with several properties on a web page. The listing is done in two HTML tables. One table for the headers and one table for the items. This separation is needed in order to have possibility to scroll only through the list. (It would be odd to have a scrollbar in the header section). AFAIK there is only one way to do scrolling in a list in HTML is the div overflow property.
The problem is that I need to set the width of columns ( elements) in the whole listing i.e. in header and in the elements list. Here is a simplified example of how it is done now:

        1	 2	 3	 4

                123456789101112	 2	 3	 4

The problem is that since the  elements in the list may have long (I mean many characters) values the browsers expand the cells even if width attribute is used. Since the header is in a separate  its columns will have a different length then the columns of the div's .
So far I have tried to let the browser render the columns in the list and then get those computed styles and apply them to the header's columns but it seems that the header columns do not get exactly that widths. I have had the same problem in other places in the project, but since there the text widths were the constant I used pixels for the widths, different lengths in FF and in IE8, but now the problem is - I think- even more complex.
How can I make the columns have the same width in both tables?

A: Your example is invalid HTML. I wouldn't recommend using that way at all.
The only way to make all the columns have the same width (without the help of JavaScript) is in fact having them in the same table.
Check out this question. I haven't tested them, but some of the answers look like they provide the functionality you need using only one table element using thead and tbody elements.

A: I haven't tested it a lot but this appears to work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

    1	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

        123456789101112	 2	 3	 4

Update: It only seems to work in Firefox.

A: The following example uses JavaScript to set the width of header cells:

            1	 2	 3	 4

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

                123456789101112	 2938547	 34534546	 42222221134

                123	 29385	 34534546444446232	 42222221

When the page has been loaded, the ResizeHeaderTable method is called. The ResizeHandlerTable method uses the offsetWidth property to retrieve and the style.width property to set the width of cells. Finally, it set the width of the div that contains the table for the items.
If you need further details about the offsetWidth property, the following link will be useful:
offsetWidth property


text:
Q: CKEditor Remove (selected) from label on click I have created a simple plugin to move some of the formatting buttons to a dropdown button. The dropdown button has both an icon and a label. The plugin works as intended except that when clicked on the label shows both the intended text as well as adding "(selected)" to the end.
Here is the button default view (the formatting button):

And here is how it looks when clicked on:

Here is the code for the plugin:
CKEDITOR.plugins.add( 'sf_formatting', {
init: function( editor ) {
     var format = {};
        editor.addMenuGroup( 'format_group' );

        format.indent = {
            label: 'Increase Indent',
            group: 'format_group',
            command: 'indent',
            order: 6
        };

        format.outdent = {
            label: 'Decrease Indent',
            group: 'format_group',
            command: 'outdent',
            order: 7
        };

        editor.addMenuItems( format );

        editor.ui.add( 'Formatting', CKEDITOR.UI_MENUBUTTON, {
            label: 'Formatting',
            // Disable in source mode.
            modes: {
                wysiwyg: 1
            },
            icon: 'dropdown',
            onMenu: function() {
                var active = {};

                // Make all items active.
                for ( var p in format )
                    active[ p ] = CKEDITOR.TRISTATE_OFF;
                    return active;
                }
            } );
        }
});

I have a second issue
The outdent (decrease indent) only appears when the text has been indented. In the main menu it is always there but greyed out. How can I force the outdent button to always be visible in the dropdown box but not accessible.
Here is a screenshot of the dropdown when the text has been indented:

I'd be really grateful for any help.

A: I managed to create a hack to make this work as no one seems to know the answer.
In the language file, the relevant entry is "%s (Selected)". %s is replaced by the menu title in the plugin code.
I just removed the "(Selected") and now it works fine FOR MY USE.
It may break other things I am unaware of, but it works for me


text:
Q: onActivityResult is deprecated in DialogFragments but not in Activity in activity this method still work but when i call it in Dialog Fragments, it is deprecated.
in DialogFragment

in Activity

Edit:i use the Matisse library for load image , it like
library link: https://github.com/zhihu/Matisse
 Matisse.from(getActivity())
                        .choose(MimeType.ofImage())
                        .countable(true)
                        .maxSelectable(9)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .showPreview(false) // Default is `true`
                        .forResult(REQUEST_CODE_AVATAR);

how can i use ActivityResultLaucher for this library?
explain to me why and how can i fix it? please
Have a nice day,everyone!

A: First thing is that result activity is deprecated. This is the new way to obtain results from an activity. You should be able to do similarly with a dialog fragment. The reason it was deprecated is because when there is low memory inactive activities are often removed along with the result and this causes errors.
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        Intent data = result.getData();
                        doSomeOperations();
                    }
                }
            });

    public void openSomeActivityForResult() {
        Intent intent = new Intent(this, SomeActivity.class);
        someActivityResultLauncher.launch(intent);
    }


text:
Q: Scala cannot infer I have a very simple snipper of Spark code which was working on Scala 2.11 and stop compiling after 2.12.
import spark.implicits._
val ds = Seq("val").toDF("col1")

ds.foreachPartition(part => {
  part.foreach(println)
})

It fails with the error:
Error:(22, 12) value foreach is not a member of Object
  part.foreach(println)

The workaround is to help the compiler with such code:
import spark.implicits._
val ds = Seq("val").toDF("col1")
println(ds.getClass)

ds.foreachPartition((part: Iterator[Row]) => {
  part.foreach(println)
})

Does anyone have a good explanation on why the compiler cannot infer part as an Iterator[Row].
ds is a DataFrame which is defined as type DataFrame = Dataset[Row].
foreachPartition has two signtures:

*

*def foreachPartition(f: Iterator[T] => Unit): Unit

*def foreachPartition(func: ForeachPartitionFunction[T]): Unit
Thank you for your help.

A: This is to help someone facing the issue and workaround of what can be done to get around this issue.
You can convert Dataframe to rdd and then use foreachpartition and you will be able to compile and build your code.
ds.rdd.foreachPartition(part => {
  part.foreach(println)
})


text:
Q: How detect why lock table row? I working with PHP 7 (5.6.11) and postgresql 9.4 on Ubuntu 15.10 and Freebsd.
My code select single row by id from table with "for update" option.
Sometimes (one case of hundreds) this query executes very long time, about 20-90 seconds. My code working in about 30 threads.
As I understand, "select * from table for update" lock only single row in table and i can get such behavior only if another process already select this row. Is i right? But it can't happend because script executing only after getting message from message broker.
Single message for single row. So i can't imagine who and why can block this row. (select * from table for update used in one place, where I get message from queue).
I try use info from pg_locks and ps ax output. I save this info before select for update and then, if i catch long query, i send this info in logs. I see pid of process that locking table, but i don't see this pid in ps ax output. This confuses me.
Does anyone have any idea?

A: I found reason. I use own task manager that work with ActiveMQ. Sometimes for some reasons task manager set pause for some kind of tasks. Then, after some event, task unpaused and resend in queue. Resending wrapped in database and ActiveMQ transactions.
For work with ActiveMQ i use this library: https://github.com/centraldesktop/php-stomp
For sending messages i use sync mode and i found, that i forgot use this mode for transactions. So when task resends in queue, first messages got into the queue without transactions, they run scripts and... And this scripts should wait until resender finish resend tasks and commit his database transactions.

A: Different database products use drastically different locking mechanisms.  Some, when you do a select * from table for update where id=34 may lock one row, or one block.  You need to read the official documentation.
If you do a select * from table for update without any criteria, you will lock the entire table until you commit or rollback


text:
Q: The trace map in a finite field. Let $p$ be a prime number, and consider the mapping called the trace
$$ Tr \quad : \quad \mathbb{F}_{p^n} \ \longrightarrow \ \mathbb{F}_{p^n} \quad : \quad x \ \longmapsto \ x + x^p + x^{p^2} + \cdots + x^{p^{n-1}}$$
My syllabus Abstract Algebra states the following:

*

*Every element $x \in \mathbb{F}_{p^n}$, is mapped to $\mathbb{F}_p$.

*The restricted mapping $Tr' \ : \ \mathbb{F}_{p^n} \ \rightarrow \mathbb{F}_p $ is surjective.

I failed to prove both these statements, and I ask you for some help.

Research effort for the first statement
We can see $\mathbb{F}_{p^n}$ as a vector space with the scalar field $\mathbb{F}_p$. I showed that $Tr$ is a linear mapping in this setting. I convinced myself that the mapping is not an ismorfism in general by looking at the case where $p=n=2$ and $x\neq 0 \neq y$. Assume that $Tr$ is multiplicative. then
$$Tr(xy) \ = \ Tr(x)Tr(y) \quad \iff \quad xy + x^2y^2 \ = \ (x+x^2)(y+y^2) \ = \ x^2y^2 +xy^2+x^2y +xy$$
and by substracting we see
$$x^2y+x^2y=0 \quad \iff \quad xy(x+y) = 0 \quad \iff \quad x = -y$$
And this is not generally true in a field with four elements... I had no inspiration to continue some other way.
Research effort for the second statement
I knew that for all elements $x \in \mathbb{F}_p, \ Tr(x) = \sum_{j=1}^n x^{p^j}=\sum_{j=1}^n x$. If this the mapping would be injective here, we would be done since the sum $x+ \cdots +x$ is an element of $\mathbb{F}_p$. If $p$ divides $n$ though, this won't work because every element $x \in \mathbb{F}_p$ would be mapped to 0.

I hope you can provide me hints to prove the statements. Thank you for your time.

A: First: The elements of $F_{p^n}$ that are in $F_p$ are exactly the elements $x$ that satisfy $x^p=x$ (if you know Galois theory, this is the generator of the Galois group of $F_{p^n}$ over $F_p$). Can you prove that for any image of the trace map?
By the way, the trace map is not multiplicative!
Second: The trace is a polynomial of degree $p^{n-1}$ so it can have at most so many zeros. This means that there is an element that has non-zero trace.


text:
Q: Locate nearest major city I'm working on a website that allows users to find our nearest Motel location (There are 26 of them across the US). I have a list of cities where they are located at.
I want to display the nearest location when a user goes on our front page. For example if a user comes from Newark, NJ, he will be shown images from our NYC motel and if a user comes from San Jose, CA he will be shown San Francisco images.
What's the best way to do this? Does anyone know any examples out there on the web that shows what I'm trying to do? Is this even possible?
I saw Groupon and LivingSocial using this so I thought why dont I give it a shot. :)

A: You'd first need to store the latitude/longitude coordinates of your motels in a database - use google maps, it won't take too long with 26.
Then get the visitor location, using something like IP2Location - http://www.ip2location.com/developers.aspx
Then calculate the distance between the visitor and each of your motels - http://sebastian-bauer.ws/en/2010/12/12/geo-koordinaten-mysql-funktion-zur-berechnung-des-abstands.html (it is in English...)

A: If you're using apache, you can give geoip a try.
http://www.maxmind.com/app/mod_geoip

A: You could give Geolite city a try. It is free (with an attribution clause) or can alternatively be bought. That reduces the "find closest city to user's IP address" problem to "find the closest city to a known city".
The same company offers a city database, which among other things contains longitude/latitude. That should do the trick.

A: I used this code to calculate distance of a googlemaps latitude and longitude from a table of addresses.
Geocode was a function that returned an array of latitude and longitude from google maps api given an address string, in the case below a zip.  The table of your locations would have to include lat and lng columns.  In this example i used decimal(8,5) types but you could also use a point column type.
$starting_location = geocode($zip);
$distance = '(3959 * acos(cos(radians('.$starting_location['latitude'].')) * cos(radians(lat)) * cos(radians(lng) - radians('.$starting_location['longitude'].')) + sin(radians('.$starting_location['latitude'].')) * sin(radians(lat))))';
$location_row = query('SELECT location_id,addr,addr2,city,state,zip,phonenumber,'.$distance.' AS distance FROM location_info WHERE '.$distance.' is not null ORDER BY distance LIMIT 1');

Correct me if I am linking to another's answer incorrectly, but I think I got my direction from this question: Fastest Way to Find Distance Between Two Lat/Long Points

A: You can get the nearest city to an IP address using the free data on MaxMind.com (I beleive you can pay for more accurate databases).  If you can get the lat/long for the city and compare it to the lat/long for each of your motels you win :)

A: What you want is to store the lat/lng coordinates of the motels and then let the user type his location into the browser most likely a zipcode and then you want to use the harvesine formule to calc the distance between the user and the motel to display nearby motels. Or you can use a IP to geo coordinate service like IP2location to get the users location.


text:
Q: How to use scope in web worker using angular Here my code. But i am getting the error.Please help me on this issue.
In controller
if(typeof(Worker) !== "undefined") {
    if(typeof(worker) == "undefined") {
        var worker = new Worker("assets/scripts/directives/custommultifilter.js");
        worker.postMessage({ "getobject":scope.payloadRowCollection});
         worker.onmessage = function(event) {
                 console.log(event);
         }
    }
 }

In web worker (custommultifilter.js)
self.addEventListener("message", function(e) {
  $scope.arr = [1,2,3];
     postMessage($scope.arr);
}, false);

A: It is not possible to share variables between web workers and the "main" script. You would run into concurrency issues if it was.
But you can communicate via events:
// in the worker
self.postMessage('someData);

// in angular
worker.addEventListener('message', function(e) {
    console.log('Worker said: ', e.data);
}, false);

Here is a good tutorial about web workers.
http://www.html5rocks.com/en/tutorials/workers/basics/


text:
Q: Sending 32bit integer from python script to arduino via serial for use in driving RGB strip first post so go easy on me.
I have made a python script which takes a screenshot of the current display and finds the most frequently reappearing RGB colour value.
I am attempting to send this to via serial to an arduino pro micro (with some supplementary components)  to drive a 12v LED strip.
I am bit-shifting the individual red, green and blue values, and am adding them together into an unsigned 32 bit integer to be send to the arduino which will then use a bitmask to then get the original values back using PWM pins on the arduino control three MOSFETS (N-Channel) to drive the individual colours on the RGB strip. Each colour has 256 values so can be represented in 8bits seen below.
32bit unsigned int
un-used  blue     green    red
00000000 00000000 00000000 00000000
red mask
00000000 00000000 00000000 11111111
green mask
00000000 00000000 11111111 00000000
blue mask
00000000 11111111 00000000 00000000
My issue is that the serial communication between the python script and the arduino doesn't appear to be working, and I cannot figure out why. Is it something to do with the format of the unsigned 32 bit integer I'm sending? I'm not really finding any information on the acceptable formats and have little experience using serial communications.
What I do know is that the arduino circuit is definitely connected correctly as I can fully drive the RGB strip by specifying values on the arduino side.
The python script is definitely connecting to the arduino as I am connecting using hardware information found in windows device manager when the arduino is connected, and while the script is running I cannot use anything else to connect to the COM port used by the arduino.
The python script is calculating and formatting the values as I intend as I can simply print them to console instead of writing to serial to confirm.

from PIL import Image
import serial
import serial.tools.list_ports
import pyscreenshot as ImageGrab
import time
from collections import Counter

if __name__ == '__main__': ###main program###

    # open comms with arduino
    VID = "2341" #arduino pro micro HEX vendor ID given throught the arduino IDE
    PID = "8037" #arduino pro micro HEX product ID given throught the arduino IDE
    arduino_pro_micro_port = None
    ports = list(serial.tools.list_ports.comports()) #get ports information

    for port in ports:
        if PID and VID in port.hwid: #look for matching PID and VID
            arduino_pro_micro_port = port.device #serial port of arduino nano pro

    if arduino_pro_micro_port == None:
        print("Couldn't find an ardiuno pro micro to communicate with")
    else:
        COMPort = serial.Serial(arduino_pro_micro_port, 115200, writeTimeout = 0) #open connection for RGB values to be written

        while True: #loop forever
            image = ImageGrab.grab() #grab screenshot
            image = image.resize((512, 288)) #20% size for faster processing
            image = image.load() #load image so pixel information can be interrogated

            RGBlist = []

            #seperate pixel tuple into lists for red, green  and blue
            for horizontal in range(0, 512, 1): #for all horizontal pixels
                for vertical in range(0, 288, 1): #for all vertical pixels

                    red = image[horizontal, vertical][0]
                    blue = image[horizontal, vertical][1] << 8
                    green = image[horizontal, vertical][2] << 16
                    RGBlist.append(red + green + blue)

            sendLong = Counter(RGBlist).most_common(1)
            print("send " + str(sendLong[0][0]))
            COMPort.write(sendLong[0][0]) #write RGB to serial port
            print("reci "+ str(COMPort.readline())) #read and print line from arduino
            time.sleep(0.1) #wait 0.1 seconds
```end of python code

```arduino code

//set pin integers for RGB
int LEDRPin = 5;
int LEDGPin = 6;
int LEDBPin = 9;

//setup variable store for RGB values
unsigned long incomingLong = 0; //store the incomoing byte for processing#

unsigned long redMask = 255; //bitmask for red value
unsigned long greenMask = 65280; //bitmask for green value
unsigned long blueMask = 16711680; //bitmask for blue value

unsigned long Rv = 0; //red value will be stored here
unsigned long Gv = 0; //green value will be stored here
unsigned long Bv = 0; //blue value will be stored here

unsigned long SAVE_Rv = 0; //red value will be saved here
unsigned long SAVE_Gv = 0; //green value will be saved here
unsigned long SAVE_Bv = 0; //blue value will be saved here

void setup() {
  //initialise RBG pins as outputs
  pinMode(LEDRPin, OUTPUT);
  pinMode(LEDGPin, OUTPUT);
  pinMode(LEDBPin, OUTPUT);

  //start serial comms
  Serial.begin(115200);
  if(Serial.available())// only send data back if data has been sent
  {
    incomingLong = Serial.read(); //read RGB values from serial port
    Serial.write("Ready");
  }
}

void loop() {
  delay(300);
  if(Serial.available() >= 0) // only send data back if data has been sent
  {
    incomingLong = Serial.read(); //read RGB values from serial port
    Serial.write(incomingLong);

    Rv = redMask & incomingLong; //get red value
    Gv = greenMask & incomingLong; //get green value
    Bv = blueMask & incomingLong; //get blue value

    Rv = Rv >> 0; //shift to LSB
    Gv = Gv >> 8; //shift to LSB
    Bv = Bv >> 16; //shift to LSB

    Rv = (int) Rv; //Cast to int
    Gv = (int) Gv; //Cast to int
    Bv = (int) Bv; //Cast to int

    analogWrite(LEDRPin, Rv); //write red value to output pin
    analogWrite(LEDGPin, Gv); //write green value to output pin
    analogWrite(LEDBPin, Bv); //write blue value to output pin

    SAVE_Rv = Rv;
    SAVE_Gv = Gv;
    SAVE_Bv = Bv;
  }
}

```end of arduino code

A: I've written and tested my watered down communication solution for your case on python27 and arduino Uno but should give you more or less the same results. Test it and let me know if you need clarification or get stuck at some point.
# python27

import serial
import serial.tools.list_ports
import struct
import sys

arduino_pro_micro_port = 'COM3'
COMPort = serial.Serial(arduino_pro_micro_port, 115200, writeTimeout = 0)

while True:
    r = 12
    g = 145
    b = 87
    if COMPort.in_waiting:
        #COMPort.write(struct.pack("l", 123)) # sending one long directly
        COMPort.write(struct.pack("BBB", r, g, b)) # B means unsigned byte
        print COMPort.readline()

// Arduino

void setup() {
  // put your setup code here, to run once:
  //start serial comms
  Serial.begin(115200);
  Serial.println("Ready");
}

void loop() {
  // I'm taking the delay off as that might cause synchronization issues on the receiver side

  while (Serial.available() <= 3); // only send data back if data has been sent
  int r = Serial.read(); //read RGB values from serial port
  int g = Serial.read(); //read RGB values from serial port
  int b = Serial.read(); //read RGB values from serial port
  Serial.println("RGB: ");
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  delay(3000);
}


text:
Q: New domain is both registered with and hosted at AWS Route 53 but resolution fails I have registered the domain duhastdiewahl.org at Amazon AWS Route 53.
I do it step for step like this:
http://share.pho.to/AAUSM

*

*Create Hosted Zone (NS/SOA-Record default)

*Add A-Record to my elastic ip adress for my EC2-Instance

Unfortunately if i ping the adress the name can't be resolved and tools like http://mxtoolbox.com says that the nameservers couldn't be found.
Can anybody tell me what is wrong?
Thank you for your support :)

A: Your nameservers are configured incorrectly in Route 53 "Registered Domains" -- they don't match the servers assigned to you in "Hosted Zones."
Route 53 is two different services -- domain registration and DNS hosting -- and the settings between the two of them need to match.  One possible cause of a mismatch is deleting and recreating your hosted zone.  That wouldn't fix anything, but a lot of people seem to try it anyway.  When you do that, it assigns four new name servers do your domain for hosting -- but the registrar service doesn't learn about this, because there's not necessarily a connection between the two services.  You could register a domain on one AWS account, and host the DNS on another, if you wanted -- the two "sides" of Route 53 are essentially independent.
To fix:
In the Route 53 console, click Hosted Zones, click your domain, and make a note of the assigned 4 name servers.  Don't change anything here.
Click "Registered Domains."
Select your domain.
Choose "add/edit name servers."
Enter the correct values for the assigned Route 53 name servers, which you obtained from the Hosted Zones screen.


text:
Q: wget on failure returns last command executed code unknown Here is a small bash code which initially creates a temporary file tmpfile using mktemp followed by a wget operation on success or failure removes the temporary file created.
#!/bin/bash -ex
tmpfile="$(mktemp)"
wget -q $1 -O /tmp/temp.txt
if [ $? -eq 0 ] ; then
    echo "wget success"
    rm "${tmpfile}"
else
    echo "wget fail"
    rm "${tmpfile}"
fi

When a right url is passed to the script, wget on success checks the return value of last command using $? and deletes the temporary file as expected.
root@box:/# ./temp.sh www.google.com
++ mktemp
+ tmpkeyfile=/tmp/tmp.83uGY1NH5B
+ wget -q www.google.com -O /tmp/temp.txt
+ '[' 0 -eq 0 ']'
+ echo 'wget success'
wget success
+ rm /tmp/tmp.83uGY1NH5B

However if a url which result wget a unsuccessful such as 404-not found etc., I assume last executed wget should fail against if check and delete temporary file in else block. This isn't happening as wget just returns without any last return value as shown below. This indeed doesn't delete the temporary file when ever call to wget fails.
root@box:/# ./temp.sh www.googlegoogle.com
++ mktemp
+ tmpkeyfile=/tmp/tmp.pSL7hKyAlz
+ wget -q www.googlegoogle.com -O /tmp/temp.txt
root@box:/#

May I know how to capture every return failure code of wget by any means.

A: Question:

May I know how to capture every return failure code of wget by any
  means.

It should response every return http status code:
wget --server-response http://googlegoogle/nx.file 2>&1 | awk '/^  HTTP/{print $2}'

EDIT:
I have tried your code, and it works fine
bash -x ./abc.sh www.googlegoogle.com
++ mktemp
+ tmpfile=/tmp/tmp.pwa08vGnjo
+ wget -q www.googlegoogle.com -O /tmp/temp.txt
+ '[' 4 -eq 0 ']'
+ echo 'wget fail'
wget fail
+ rm /tmp/tmp.pwa08vGnjo

This is the list of exit codes for wget:
0       No problems occurred
1       Generic error code
2       Parse error — for instance, when parsing command-line options, the .wgetrc or .netrc…
3       File I/O error
4       Network failure
5       SSL verification failure
6       Username/password authentication failure
7       Protocol errors
8       Server issued an error response

Check this: Link


text:
Q: Explaining the optial behaviour of DVD reader lens Here is the lens removed from a DVD reader/writer's head

I do not have the dimension of the lens, neither could I find it online. Correct me if I am wrong, but I guess it is a plano-convex lens.
I placed this lens on top of a cellphone screen(with the flat side coinciding with the screen) and here is what I saw - a highly magnified image of the RGB pixels of the screen.
Here is a collage of screenshots from a video -

Optically, the object is placed very close to the lens. Then using the lens formula
$$
{1 \over v} - {1 \over u} = {1 \over f}
$$
we get $v = u$ for $u =0$. And by the magnification equation,
$$
M = -{v \over u}
$$
we get magnification as $1$ for $\lim {u \to 0}$. But we see a very large magnification. How to explain this optical behaviour?

A: First, a few links will help. Here is a quick overview of what lens design is. Here is an explanation of how lenses work. The second link has several useful links. Start with magnification. You can see that a large magnification requires light rays to be deflected by a large angle.
You are getting a large magnification because is this is a strong lens (short focal length). You can tell because the lens is strongly curved. The spherical side has a small radius. Large diameter lenses cannot be this strong.
There are various ways to calculate the focal length of a lens. The simplest is the thin lens approximation. It is for cases where the thickness of the lens is small compared to other lengths (weaker lenses). You cannot use it for this lens.
For a thick lens, you need to take the location of each surface into account when calculating focal length. The thick lens formula is a better approximation.
For a thick lens, you can still use $1/v - 1/u = 1/f$. But you need to measure from the right locations, as shown here.
So u is not 0. You would have to know the lens parameters to calculate it.


text:
Q: select latest answer and also nos of attempt? I'm working on quiz app. One of my table attempts is:
id   qid   answer
--   ---   ------
 1    42   hello
 2     7   magic
 3    42   ni hao
 4    42   ciao
 5     1   foo
 6    42   ohayo

I need latest answer on the question no 42 (qid=42), and also the number of time attempts on this question. I've try:
SELECT answer, count(*) FROM attempts WHERE qid=42 ORDER BY id DESC;

Then I just realize that ORDER BY execute after count(*), so my query here gives answer of first attempt, not latest.
My workaround is to split this into 2 query:
SELECT answer   FROM attempts WHERE qid=42 ORDER BY id DESC LIMIT 1;
SELECT count(*) FROM attempts WHERE qid=42;

I wonder if this can be combine into 1 query?

A: This should get you 1 result per qid w/ the number of attempts as well as the answer associated w/ the first attempt.
SELECT A.qid, answer as FirstAnswer, B.Attempts
FROM attempts A
INNER JOIN (SELECT DISTINCT
    qid,
    COUNT(*) over(Partition by qid) as NumberAttempts,
    MIN(id) over(partition by qid) as First_AnswerID
    from attempts) B ON A.id = B.First_AnswerID

OR....
SELECT A.qid, A.answer as FirstAnswer, B.NumAtmps, C.FirstID FROM attempts A
INNER JOIN (SELECT qid, count(*) as NumAtmps FROM attempts group by qid) B ON A.qid = B.qid
INNER JOIN (SELECT qid, min(id) as FirstID FROM attempts group by qid) C ON A.qid = C.qid AND A.id = C.FirstID


text:
Q: IOT Hub AMQP protocol error I am running the Getting started with IOT Hub example, for Node.js:
I followed all steps, but when I run the readDeviceToCloudMessage application, I receive this error in my console:

name: 'AmqpProtocolError',
  message: 'undefined:Attempted to perform an unauthorized operation.

Does somebody know what might be causing the error?
Kind regards
URL:
var protocol = 'amqps';
var eventHubHost = 'myHost';
var sasName = 'iothubowner';
var sasKey = "myKey"

var uri = protocol + '://' + encodeURIComponent(sasName) + ':' + encodeURIComponent(sasKey) + '@' + eventHubHost;

A: One thing comes to mind is, the eventHubHost should contain the value of the Event Hub namespace, not the eventhub name. Can you confirm its the namespace?
Hope this helps!
Mert


text:
Q: Unbound breakpoints while debugging TypeScript VS Code I am using VS Code on my Ubuntu machine to debug a Nest.js TypeScript project. Some of my breakpoints are unbound and does not get hit at all. I have played a lot with launch.json. Indeed, I have tried several launch.json and tsconfig.json files. Also used auto attach feature. However, some of my breakpoints are not bound.
It seems that my not bound breakpoints is related to something other than launch.json. Anyone can help me please?
Note 1: Nest.js is a framework based on TypeScript and Node.js.
Note 2: I have a similar project on my machine which can be debugged very fine. So my machine is able to do the debug in general. Consider that settings on both projects are same.

A: In vsCode:
go to preferences => settings =>
search 'breakpoints' =>
check 'Allow Breakpoints Everywhere'


text:
Q: How can I name Button object as what my String variable brings public void createButton(int x, int y, String s) {
    try {
        JButton btn1 = new JButton();
        jPanel1.add(btn1);
        btn1.setLocation(x, y);
        btn1.setSize(50, 50);
        btn1.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
    }
}

That is the method which I use to create random buttons. But I can't give the button a name manually every time. I want name button object with what my String variable contains.

A: From your comment on another answer:

I don t want change button name.i want button variable name (in this case it is btn1) change to what string s brings.

Java is not designed that way, if you want to keep a reference for each JButton you can create an array:
JButton buttonsArray[] = new JButton[5]; //Or any amount of buttons

Then use them like this:
for (int i = 0; i < buttonsArray.length; i++) {
    buttonsArray[i] = createButton(text[i]);
}

Where text[i] is a String array where you have all the text for your JButtons
Or probably with an ArrayList of JButton:
ArrayList <JButton> buttonsList = new ArrayList <JButton>();

And then use it like:
for (int i = 0; i < text.length; i++) {
    JButton button = createButton(text[i]);
    buttonList.add(button);
}

Then you can select each button with:
buttonArray[i].setText("Hello"); //Or whatever method you want to call
buttonList.get(i).setText("Hello");
jPanel1.add(buttonsArray[i]);
jPanel1.add(buttonsList.get(i));

Now your createButton() method should look like this:
public JButton createButton(String s) {
    JButton btn1 = new JButton(s);
    //Add more code here
    return btn1;
}

In this question you can see an similar example using an array of JRadioButton

IMPORTANT NOTE
Finally I need to add this to my answer, don't set location /bounds of each JComponent manually instead use a proper Layout Manager that does the job for you and Empty Borders to create space between them if needed.
I bet you're using a null layout and while that might seem like the best and easiest way to create a GUI, the more GUIs you create, you're gonna get more errors due to this and more troubles trying to maintain it.
See: Null layout is evil and Why is it frowned upon to use a null layout in swing?.
I hope that helps

A: public void createButton(int x, int y, String s) {
    try {
        JButton btn1 = new JButton(s);
        jPanel1.add(btn1);
        btn1.setLocation(x, y);
        btn1.setSize(50, 50);
        btn1.setVisible(true);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e);
    }
}

The constructor JButton(text) internally calls setText(text). So btn1.setText(text) later on would be the same. From the code:
/**
 * Creates a button with initial text and an icon.
 *
 * @param text  the text of the button
 * @param icon  the Icon image to display on the button
 */
public JButton(String text, Icon icon) {
    // Create the model
    setModel(new DefaultButtonModel());

    // initialize
    init(text, icon);
}

Keep in mind: setText() and setName() are not the same thing!