text:
Q: How to fix "Value cannot be null. Parameter name: value" I am trying to create multiple threads based on Data tables rows, if there are 10 rows in a table, it creates 10 threads. I keep getting this error "Value cannot be null.Parameter name: value". What am I missing in this?
I am getting error inside Savedata method at first catch statement that is "inner excep" comment.
try
{
    DataProvider DPrvdr = new DataProvider();
    DPrvdr.ConnectionString = strConMAS500; // read only

    //getting all the sales order
    DataTable dt = DPrvdr.GetDataSetSProc("uspMAS500SOSER_GetSO").Tables[0];
    List<DataTable> lstDt = SplitTable(dt, MaxSOinThread); // Split the Data table as per MaxSO in Threads - Currently it is 1

    if (lstDt != null)
    {
        Parallel.ForEach(lstDt, (currentdt) =>
        {
            hashSOTbl = Savedata(currentdt);
        });
    }
}
catch (Exception ex)
{
    LogMessage("Error " + ex.Message);
}

    protected Hashtable Savedata(DataTable dt)
    {
        SOEntityBOLWS_Client c = new SOEntityBOLWS_Client();
        Hashtable hashSODetails = new Hashtable();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            try
            {
                //initializing the SO object
                SOEntityForClient.SalesOrder s = c.GetNewSO(dt.Rows[i]["CreatedBy"].ToString(), dt.Rows[i]["SessionID"].ToString());
                string SONO = string.Empty;
                s.CustID = dt.Rows[i]["CustID"].ToString().Trim();
                s.CompanyID = dt.Rows[i]["CompanyID"].ToString().Trim();
                s.CustPONo = dt.Rows[i]["CustPONo"].ToString();

                s.CustClassID = (dt.Rows[i]["CustClassID"].ToString());
                s.SalesSourceID = (dt.Rows[i]["SalesSourceID"].ToString());
                s.CreateUserID = (dt.Rows[i]["CreatedBy"].ToString());
                int rowkey = Convert.ToInt32(dt.Rows[i]["RowKey"].ToString());

                DataProvider DPrvdrheaderComment = new DataProvider();
                DPrvdrheaderComment.ConnectionString = strConMAS500; // read only
                SqlParameter[] sqlHeaderComment = new SqlParameter[2];
                sqlHeaderComment[0] = new SqlParameter("@DocOwnerKey", rowkey);
                sqlHeaderComment[1] = new SqlParameter("@ParentDocType", 801);//801 for header comment

                //getting Comment
                DataTable dtHeaderComment = DPrvdrheaderComment.GetDataSetParams("uspMAS500SOSER_GetSOComments", sqlHeaderComment).Tables[0];
                if (dtHeaderComment.Rows.Count > 0)
                {
                    s.Comments = new List<SOEntityForClient.Comment>();
                    for (int m = 0; m < dtHeaderComment.Rows.Count; m++)
                    {

                        SOEntityForClient.Comment cm = new SOEntityForClient.Comment();
                        cm.CommentText = dtHeaderComment.Rows[m]["CommentText"].ToString();
                        cm.ExtCmntID = dtHeaderComment.Rows[m]["ExtCommentID"].ToString();
                        cm.ParentDocType = 801;
                        cm.SeqNo = m + 1;
                        s.Comments.Add(cm);
                    }
                }

                DataProvider DPrvdrLine = new DataProvider();
                DPrvdrLine.ConnectionString = strConMAS500; // read only
                SqlParameter[] sqlline = new SqlParameter[1];
                sqlline[0] = new SqlParameter("@RowKey", rowkey);

                DataTable dtLine = DPrvdrLine.GetDataSetParams("uspMAS500SOSER_GetSOLine", sqlline).Tables[0];

                for (int k = 0; k < dtLine.Rows.Count; k++)
                {
                    SOEntityForClient.SOLine l = new SOEntityForClient.SOLine();
                    l.ItemID = dtLine.Rows[k]["ItemID"].ToString();
                    //l.Description = dtLine.Rows[k]["Description"].ToString();
                    l.QtyOrd = Convert.ToDecimal(dtLine.Rows[k]["QtyOrd"].ToString());
                    l.UnitMeasID = dtLine.Rows[k]["UnitMeasID"].ToString();
                    l.UnitPrice = Convert.ToDecimal(dtLine.Rows[k]["UnitPrice"].ToString());
                    l.TradeDiscPct = Convert.ToDecimal(dtLine.Rows[k]["TradeDiscPct"].ToString());
                    l.WhseID = dtLine.Rows[k]["WarehouseID"].ToString();
                    l.PromiseDate = DateTime.Parse(dt.Rows[i]["DfltPromDate"].ToString());
                    l.RequestDate = DateTime.Parse(dt.Rows[i]["DfltRequestDate"].ToString());
                    l.ShipDate = DateTime.Parse(dt.Rows[i]["DfltShipDate"].ToString());

                    DPrvdrLineComment = new DataProvider();
                    DPrvdrLineComment.ConnectionString = strConMAS500; // read only
                    SqlParameter[] sqlComment = new SqlParameter[2];
                    sqlComment[0] = new SqlParameter("@DocOwnerKey", (dtLine.Rows[k]["SOLineKey"].ToString()));
                    sqlComment[1] = new SqlParameter("@ParentDocType", 802);//802 for line comment

                    //getting Comment
                    DataTable dtLineComment = DPrvdrLineComment.GetDataSetParams("uspMAS500SOSER_GetSOComments", sqlComment).Tables[0];
                    if (dtLineComment.Rows.Count > 0)
                    {
                        l.SOLineComments = new List<SOEntityForClient.Comment>();
                        for (int m = 0; m < dtLineComment.Rows.Count; m++)
                        {
                            SOEntityForClient.Comment cm = new SOEntityForClient.Comment();
                            cm.CommentText = dtLineComment.Rows[m]["CommentText"].ToString();
                            cm.ExtCmntID = dtLineComment.Rows[m]["ExtCommentID"].ToString();
                            cm.ParentDocType = 802;//802 for line comment
                            cm.SeqNo = m + 1;
                            l.SOLineComments.Add(cm);
                        }
                    }
                    //Save SO line.
                    s.LineItems.Add(l);
                }

                try
                {
                    //checking line count
                    if (s.LineItems.Count != 0)
                    {
                        int UpdateProcessStatus = 0;
                        try
                        {
                            string warning = c.SaveSO((dt.Rows[i]["CreatedBy"].ToString()), (dt.Rows[i]["CompanyID"].ToString().Trim()), dt.Rows[i]["TranNo"].ToString(), "801", s, dt.Rows[i]["SessionID"].ToString(), "OverrideDate:true");

                            if (warning.Contains("Saved"))
                            {
                                hashSODetails.Add(dt.Rows[i]["TranNo"].ToString(), dt.Rows[i]["CompanyID"].ToString());
                                UpdateProcessStatus = 1;
                            }
                            else
                            {
                                UpdateProcessStatus = 0;
                            }

                            DPrvdr = new DataProvider();
                            DPrvdr.ConnectionString = strConMAS500;
                            SqlParameter[] sqlParam = new SqlParameter[4];

                            sqlParam[0] = new SqlParameter("@Tranno", dt.Rows[i]["TranNo"].ToString());
                            sqlParam[1] = new SqlParameter("@Message", warning);
                            sqlParam[2] = new SqlParameter("@UpdateProcessStatus", UpdateProcessStatus);
                            sqlParam[3] = new SqlParameter("@CompanyID", (dt.Rows[i]["CompanyID"].ToString()));

                            DPrvdr.InsertDeleteUpdateDataStrProc("uspMAS500SOSER_SaveSOStatus", sqlParam);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogMessage("Error while calling web service for Row Key : " + (dt.Rows[i]["RowKey"].ToString()) + " inner excep : " + ex.Message);
                }
            }

            catch (Exception ex)
            {
                LogMessage("Error while calling web service for Row Key : " + (dt.Rows[i]["RowKey"].ToString()) + " outter excep : " + ex.Message);
            }
        }
        return hashSODetails;
    }

A: DataTable dt = new DPrvdr.GetDataSetSProc("uspMAS500SOSER_GetSO").Tables[0];


text:
Q: Modify specific cell value using Axlsx gem given the column number and row numer I am trying to use asxlx gem to write an excel sheet but I have failed miserably trying to access individual cell values..
For example for do I get the value of the cell  2 in column 2
How do I change the value of cell 10 in column 19 ??

A: You should be able to access the value of any given cell via standard index references.
A trivial example:
p = Axlsx::Package.new
ws = p.workbook.add_worksheet
ws.add_row [1, 2, 3, 4]

ws.rows[0].cells[1].value = 5

would set the value of the second cell in the first row to 5
Please note, however that axlsx is a sparse generator. You cannot arbitrarily set the value for a cell that has not been added to the sheet via add_row.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clojure - partitioning by set value I have a query which returns a count of objects grouped by these objects in a table although what I want to do afterwards is to firstly sort the values from highest to lowest and the partition them into 10 groups.
What I have so far allows me to either sort the counted values from max to min or, if i comment the sort out, or partition the values by a set number. I would like to know where Im going wrong here because I cant see it. I am pulling the count of objects from the query initially, sorting and then trying to partition them into arrays which I will index at a later stage:
tosort(map(keyword :objectscounted)data)
sorted(sort > tosort)
part(into [] (partition-all 10 sorted))

Where I am also stuck is when using the partition - I need 10 groups of values, not 10 values in each group, any help here is appreciated! Thanks in advance

A: If I understood correctly your problem, all you need is to partition dynamically according to your sorted list element count:
user> (def v (range 50))
#'user/v
user> (clojure.pprint/pprint (partition-all (/ (count v) 10) v))
((0 1 2 3 4)
 (5 6 7 8 9)
 (10 11 12 13 14)
 (15 16 17 18 19)
 (20 21 22 23 24)
 (25 26 27 28 29)
 (30 31 32 33 34)
 (35 36 37 38 39)
 (40 41 42 43 44)
 (45 46 47 48 49))

Of course if total elements is not divisible by 10, your result will have have more than 10 groups, unless you have a different strategy to distribute elements among groups.


text:
Q: Recreate the Siri-like curley quotes in iOS I'm not sure if they use an image or if it's some kind of text transformation, but how does apple achieve the curly quote style found in Siri responses? When I attempt to recreate it with regular quotes I get just that, regular quotes.

A: It looks like they are using the UNICODE "Left Double Quotation" and "Right Double Quotation" marks -- code point U+201C (") and U+201D (").  You can embed them directly into your source (see wikipedia for how to type them).
bash$ cat foo.m
#include <Foundation/Foundation.h>
int
main() {
    NSLog(@""%@"\n", @"Hello");
    return 0;
}
bash$ gcc foo.m -framework Foundation
bash$ ./a.out
"Hello"

You can embed them as UTF-8 sequences using hex escapes as well:
    NSLog(@"\xE2\x80\x9C%@\xE2\x80\x9D\n", @"Hello");

A: They are called "smart quotes" or "book quotes", which is a different Unicode code point than regular quotes. The unicode code point for smart quotes are U+201C for the "Left double quotation mark" and U+201D for the "Right double quotation mark". Compare that to U+0022 which is "Quotation mark".


text:
Q: 2016 15-inch MacBook Pro speaker makes buzzing sound I have a MacBook Pro (15-inch, Late 2016). I have noticed that when I play any sound through the speaker, the speaker starts buzzing. The buzz stops after ~1 minute without playing any sound. When I put the sound on mute, the speaker won't play the audio out loud but the buzzing still happens. The volume of the buzzing sound stays the same when I adjust the volume of the laptop, even on mute. I'm pretty sure it is the speaker because I can also hear the sound when the fan is on max.
I have tried restarting the computer several time, resetting SMC and PRAM, plugging in power adapter and removing it. But those didn't made any progress on fixing it. Any more ideas before I take the machine to the Apple Store?
P.S. Many people reports that it is an outdated Bootcamp driver issue, but I never installed Windows on my MacBook. I am running the latest version of macOS.
EDIT:
When I plug in headphone, the buzz stops. It starts buzzing again when I unplugged the headphone.


text:
Q: Change all RO files starting with a period to RW I need to search a directory structure for all files beginning with a period (don't ask...) and change them from read-only to rw.  I can identify those files with the first command, but how can I translate that into the 2nd command?
dir .*.* /s /a-D /ar

Now I want to take that output and run attrib +r.  This is what I've gotten, but it isn't working.
for /f %f in ('dir .*.* /s /a-D /ar') DO "ATTRIB +R" "%G"

I think I am close, but DOS batch commands have never worked as I expect them to (my problem, not DOS's)

A: The reason it's not working is because attrib +r makes the processed tokens read-only again and also because you use capital %G where you should use small letters.
In Windows read-only files are different from Linux in ways that you either mark a file as read-only or not.
If it is not read-only it will use the properties found in the ACL for the folder/file.
Typically it will generate the file RW instead of Read-Only.
You can read more about it here:
http://msdn.microsoft.com/en-us/magazine/cc982153.aspx
So for your question:
for /f %f in ('dir .*.* /s /a-D /ar') DO "ATTRIB -R" "%g"

(As I dont have any files or folders prefixed with . I cannot test and see if the above works, you may want to use %f instead of %g, depending on which token you want to use.)
The above will do attrib -r which removes the read-only attribute.
You may want to use double %% for batch-scripts that are to be executed as .bat, .cmd etc.
As stated in the for /? help screen:

"To use the FOR command in a batch program, specify %%variable instead
  of %variable."

Further more:

"Variable names are case sensitive, so %i is different from %I."


text:
Q: Light coming from distant stars As we know, light travels with a constant speed and the Universe is ever-expanding and endless. Considering this fact, is it possible that the sky we see should change everyday? Let's say today we see 100 stars in the sky because the light from those 100 have only reached Earth. There could be distant stars whose light has yet to reach Earth, so we might see another 100 stars the very next day.

A: You're right that there are numerous stars that are so far away and were created so "recently" that their light has still not arrived at Earth. However, most processes in the Universe happen on extremely long timescales (for human standards). In the Milky Way, on average approximately one star is born every year (see e.g. here). But the timescales from the initial collapse of a molecular cloud and until ignition of the star are of the order $10^5$--$10^6$ years (see e.g. here). This means that new stars don't simply "pop up" on the sky, but instead slowly evolve.
The theoretical limit to what we can see is given by the distance that light has traveled since the Big Bang. The Universe is 13.8 billion years old, but due to the expansion, we can actually see 46.5 billion lightyears away. As we also look back in time the farther we look away, we see the Universe at this distance before it had formed any galaxies at all, though. So, a hundred new stars cannot be seen every day. Instead, every molecular cloud, protostar, main sequence star, old star, and many other objects are seen every day as a tiny bit more evolved than the previous day, where "a tiny bit" means "not at all" for most practical purposes.
Note, however, that some processes do take place on very short timescales. For instance, when a massive dies, it suddenly explodes in a supernova. Here you see a clear evolution from day to day. The even more energetic gamma-ray burst evolve on timescales of seconds to minutes, and neutron stars spin at rates of several hundred times per second.
Thus, if for instance you instead of stars ask about supernovae, then the answer would be "Yes, the light from distant supernovae has yet to reach us, and approximately once per day a new supernova pops up one the sky."


text:
Q: Mean.IO +Grunt - Configure as unix service I have an Mean.io app (node.js, expresss, grunt);
All fine on my own machine, I run with grunt command at the app root.
I need to install it on a server (CentOS) someone can give a clue?

A: I recommend to you using Supervisor.
I'm using following configuration:
[program:daemon]
command = /usr/local/bin/node server.js
user = server
directory = /home/server/mnt/
autostart = true

Eventually declare NODE_MODULES environment variable if you are using global modules.
PS. Some people are using node-forever but I'm fully satisfied with Supervisor.


text:
Q: Importing/Using p5.Sound into React I'm trying to get p5.sound into my React app, after having successfully gotten p5.js canvas functionality working.
I have a p5Wrapper for my p5 sketch.  And as I said the canvas functionality works great(ish).  But, I'm unable to get the sound functionality into either the parent component, the wrapper, or the sketch itself.
Any help is greatly appreciated!
I have p5.js, p5.sound, and p5.dom all local in my repo.  And here are the component, wrapper, and sketch I'm working with....
THE COMPONENT
    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    import Style from "../oogles/oogles.scss";
    import P5Wrapper from "../../../wrappers/P5Wrapper";
    import Oogle from "../oogles/sketch.js";

    class Oogles extends Component {
        constructor(props) {
            super(props);
            this.state = {
                sketch : Oogle
            };
        }

        componentDidMount() {
            console.log("oogles");

        }
        render() {
            return (

Oogles

                    <P5Wrapper sketch={this.state.sketch} />

            )
        }
    }

    export default Oogles;

THE WRAPPER:
    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    import Style from "../wrappers/wrapper.scss";
    import p5 from 'p5';
    import "../../p5/addons/p5.sound.js";

    class P5Wrapper extends Component {
        constructor(props){
            super(props);
            this.state = {
                parentW: window.innerWidth,
                parentH: '',
            };
            this.updateCanvasDimensions = this.updateCanvasDimensions.bind(this);
        }

        componentDidMount(){
            this.canvas = new p5(this.props.sketch, this.el);
            // window.addEventListener("resize", this.updateCanvasDimensions);
        }

        componentWillReceiveProps() {

        }

        updateCanvasDimensions(){
            this.setState({ parentW: window.innerWidth })
        }

        render() {
            return
{this.el = el}}>
;
        }

    }

    export default P5Wrapper;

THE SKETCH
export default function Oogle(p){
    let parentW = document.querySelector(".oogle").clientWidth;
    let parentH = document.querySelector(".oogle").clientHeight;
    let cnv = null;

    p.setup = function(){
        cnv = p.createCanvas(parentW, parentH);
        // mic = new p5.AudioIn();
        // mic.start();
        // fft = p.FFT();
        // fft.setInput(mic);
    }

    p.draw = function(){
        let backgroundColor = p.color('rgb(111, 77, 111)');
        // window.addEventListener("resize", updateCanvasDimensions);
        parentW = document.querySelector(".oogle").clientWidth;
        parentH = document.querySelector(".oogle").clientHeight;
        p.background(backgroundColor);

        // var spectrum = fft.analyze();
        // p.print(spectrum);
        // p.ellipse(spectrum[20] += 20, spectrum[20] += 20, spectrum[0] += 200, spectrum[15]);

        // p.beginShape();
        // for (i = 0; i < spectrum.length; i++) {
        //     p.vertex(i, map(spectrum[i] += 20, 0, 255, height, 0));
        // }
        // p.endShape();
    }
    }

A: This seems to be a problem faced by many...
I'm using react-p5-wrapper and have similar problems too.
https://github.com/and-who/react-p5-wrapper/issues/61
I have a workaround that only works on function calls.
I added window.p5 = p5 after calling import * as p5 from "p5"
import * as ml5 from "ml5"
window.p5 = p5
import "p5/lib/addons/p5.sound"

Then I'll be able to use the p5.loadSound() function. However if I try to use new p5.Envelope() constructor it'll still throw me an error.
export default function sketch(p5) {
    p5.setup = () => {
        p5.createCanvas(400, 400)
        song = p5.loadSound(url("./assets/hurry.mp3")) // Will work
        env = new p5.Envelope() // Will error
...

So if it's just simple load and play a sound then this "hack" will work but if you need to use the constructor then it'll fail.
Update: you just need to change p5.Envelope() to p5.constructor.Envelope() !!!


text:
Q: What's the best way of implementing a messaging queue table in mysql It's probably the tenth time I'm implementing something like this, and I've never been 100% happy about solutions I came up with.
The reason using mysql table instead of a "proper" messaging system is attractive is primarily because most application already use some relational database for other stuff (which tends to be mysql for most of the stuff I've been doing), while very few applications use a messaging system. Also - relational databases have very strong ACID properties, while messaging systems often don't.
The first idea is to use:

create table jobs(
  id auto_increment not null primary key,
  message text not null,
  process_id varbinary(255) null default null,
  key jobs_key(process_id)
);

And then enqueue looks like this:

insert into jobs(message) values('blah blah');

And dequeue looks like this:

begin;
select * from jobs where process_id is null order by id asc limit 1;
update jobs set process_id = ? where id = ?; -- whatever i just got
commit;
-- return (id, message) to application, cleanup after done

Table and enqueue look nice, but dequeue kinda bothers me. How likely is it to rollback? Or to get blocked? What keys I should use to make it O(1)-ish?
Or is there any better solution that what I'm doing?

A: I've built a few message queuing systems and I'm not certain what type of message you're referring to, but in the case of the dequeuing (is that a word?) I've done the same thing you've done.  Your method looks simple, clean and solid.  Not that my work is the best, but it's proven very effective for large-monitoring for many sites.  (error logging, mass email marketing campaigns, social networking notices)
My vote: no worries!

A: Brian Aker talked about a queue engine a while ago. There's been talk about a SELECT table FROM DELETE syntax, too.
If you're not worried about throughput, you can always use SELECT GET_LOCK() as a mutex. For example:
SELECT GET_LOCK('READQUEUE');
SELECT * FROM jobs;
DELETE FROM JOBS WHERE ID = ?;
SELECT RELEASE_LOCK('READQUEUE');

And if you want to get really fancy, wrap it in a stored procedure.

A: In MySQL 8 you can use the new NOWAIT and SKIP LOCKED keywords to avoid complexity with special locking mechanisms:
START TRANSACTION;
SELECT id, message FROM jobs
 WHERE process_id IS NULL
 ORDER BY id ASC LIMIT 1
 FOR UPDATE SKIP LOCKED;
UPDATE jobs
 SET process_id = ?
 WHERE id = ?;
COMMIT;

Traditionally this was hard to achieve without hacks and unusual special tables or columns, unreliable solutions or losing concurrency.
SKIP LOCKED may cause performance issues with extremely large numbers of consumers.
This still does not however handle automatically marking the job complete on transaction rollback. For this you may need save points. That however might not solve all cases. You would really want to set an action to execute on transaction failure but as part of the transaction!
In future it's possible there may be more features to help optimise with cases such as an update that can also return the matched rows. It's important to keep apprised of new features and capabilities in the change log.

A: Your dequeue could be more concise.  Rather than relying on the transaction rollback, you could do it in one atomic statement without an explicit transaction:
UPDATE jobs SET process_id = ? WHERE process_id IS NULL ORDER BY ID ASC LIMIT 1;

Then you can pull jobs with (brackets [] mean optional, depending on your particulars):
SELECT * FROM jobs WHERE process_id = ? [ORDER BY ID LIMIT 1];

A: Here is a solution I used, working without the process_id of the current thread, or locking the table.
SELECT * from jobs ORDER BY ID ASC LIMIT 0,1;

Get the result in a $row array, and execute:
DELETE from jobs WHERE ID=$row['ID'];

Then get the affected rows(mysql_affected_rows). If there are affected rows, process the job in the $row array. If there are 0 affected rows, it means some other process is already processing the selected job. Repeat the above steps until there are no rows.
I've tested this with a 'jobs' table having 100k rows, and spawning 20 concurrent processes that do the above. No race conditions happened. You can modify the above queries to update a row with a processing flag, and delete the row after you actually processed it:
while(time()-$startTime<$timeout)
{
SELECT * from jobs WHERE processing is NULL ORDER BY ID ASC LIMIT 0,1;
if (count($row)==0) break;
UPDATE jobs set processing=1 WHERE ID=$row['ID'];
if (mysql_affected_rows==0) continue;
//process your job here
DELETE from jobs WHERE ID=$row['ID'];
}

Needless to say, you should use a proper message queue (ActiveMQ, RabbitMQ, etc) for this kind of work. We had to resort to this solution though, as our host regularly breaks things when updating software, so the less stuff to break the better.

A: I would suggest using Quartz.NET
It has providers for SQL Server, Oracle, MySql, SQLite and Firebird.

A: This thread has design information that should be mappable.
To quote:
Here's what I've used successfully in the past:
MsgQueue table schema
MsgId identity -- NOT NULL
MsgTypeCode varchar(20) -- NOT NULL
SourceCode varchar(20)  -- process inserting the message -- NULLable
State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL
CreateTime datetime -- default GETDATE() -- NOT NULL
Msg varchar(255) -- NULLable
Your message types are what you'd expect - messages that conform to a contract between the process(es) inserting and the process(es) reading, structured with XML or your other choice of representation (JSON would be handy in some cases, for instance).
Then 0-to-n processes can be inserting, and 0-to-n processes can be reading and processing the messages, Each reading process typically handles a single message type. Multiple instances of a process type can be running for load-balancing.
The reader pulls one message and changes the state to "A"ctive while it works on it. When it's done it changes the state to "C"omplete. It can delete the message or not depending on whether you want to keep the audit trail. Messages of State = 'N' are pulled in MsgType/Timestamp order, so there's an index on MsgType + State + CreateTime.
Variations:
State for "E"rror.
Column for Reader process code.
Timestamps for state transitions.
This has provided a nice, scalable, visible, simple mechanism for doing a number of things like you are describing. If you have a basic understanding of databases, it's pretty foolproof and extensible. There's never been an issue with locks roll-backs etc. because of the atomic state transition transactions.

A: You can have an intermediate table to maintain the offset for the queue.
create table scan(
  scan_id int primary key,
  offset_id int
);

You might have multiple scans going on as well, hence one offset per scan. Initialise the offset_id = 0 at the start of the scan.
begin;
select * from jobs where order by id where id > (select offset_id from scan where scan_id = 0)  asc limit 1;
update scan set offset_id = ? where scan_id = ?; -- whatever i just got
commit;

All you need to do is just to maintain the last offset. This would also save you significant space (process_id per record). Hope this sounds logical.


text:
Q: ¿Cómo escribir REGEX que excluya una URL que contenga una palabra específica en la API de Google Analytics Reporting? Estoy escribiendo un código con la nueva API de Google Analytics Reporting. Quiero encontrar las páginas más visitadas en esta semana, excluyendo ciertas URLs, para el filtro uso REGEX y todo funciona bien, excepto con una expresión que no sé como ponerla.
Estes es el código donde creo el filtro:
$dimensionFilterExclude = new Google_Service_AnalyticsReporting_DimensionFilter();
$dimensionFilterExclude->setDimensionName('ga:pagePath');
$dimensionFilterExclude->setOperator('REGEXP');
$dimensionFilterExclude->setExpressions('^(evangelios|/biblia/comentarios/evangelios/|feature/comentarios-biblicos/|^/$|biblias.html|/liturgia-semana-+)');
$dimensionFilterExclude->setNot(true);
$dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause;
$dimensionFilterClause->setFilters([$dimensionFilterExclude]);
$dimensionFilterClause->setOperator( 'and' );

Y la expresión que no está funcionando es la última, en setExpressions, o sea esta: |/liturgia-semana-+. Lo que quiero es que ignore URLs que tengan el término /liturgia-semana-, como esta por ejemplo:
/e92ac84894ac/liturgia-semana-xxxiv-del-tiempo-ordinario-ciclo-a

He intentado de varias maneras, usando también asterisco y otras cosas, pero nada funciona. Este valor es  aleatorio e92ac84894ac, y esto también cambia: xxxiv-del-tiempo-ordinario-ciclo-a, por lo que quiero ignorar todo lo que tenga /liturgia-semana-.
¿Cómo podría hacerlo?

A: Es necesario separar la búsqueda en dos grupos:

*

*Los que deben aparecer al inicio de la cadena (o línea)

*Los que pueden tener contenido anterior

Haciendo una prueba rápida:
$regExp = '/^(evangelios|\/biblia\/comentarios\/evangelios\/|feature\/comentarios-biblicos\/)|((.+)biblias.html|(.+)\/liturgia-semana-+)/m';
$urls = <<<URLS
evangelios/evangelio1.html
/biblia/comentarios/evangelios/otra-cosa
feature/comentarios-biblicos/mas-cadenas
/abassdadass/biblias.html
/e92ac84894ac/liturgia-semana-xxxiv-del-tiempo-ordinario-ciclo-a
/url-excluida/biblia/comentarios/evangelios/
/evangelios/excluida-por-diagonal-inicial/
/liturgia-semana-excluida/por-falta-elemento-inicial/
URLS;

preg_match_all($regExp, $urls, $matches);
var_dump($matches);

Resultado:
array (size=5)
  0 =>
    array (size=5)
      0 => string 'evangelios' (length=10)
      1 => string '/biblia/comentarios/evangelios/' (length=31)
      2 => string 'feature/comentarios-biblicos/' (length=29)
      3 => string '/abassdadass/biblias.html' (length=25)
      4 => string '/e92ac84894ac/liturgia-semana-' (length=30)
  1 =>
    array (size=5)
      0 => string 'evangelios' (length=10)
      1 => string '/biblia/comentarios/evangelios/' (length=31)
      2 => string 'feature/comentarios-biblicos/' (length=29)
      3 => string '' (length=0)
      4 => string '' (length=0)
  2 =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '/abassdadass/biblias.html' (length=25)
      4 => string '/e92ac84894ac/liturgia-semana-' (length=30)
  3 =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '/abassdadass/' (length=13)
      4 => string '' (length=0)
  4 =>
    array (size=5)
      0 => string '' (length=0)
      1 => string '' (length=0)
      2 => string '' (length=0)
      3 => string '' (length=0)
      4 => string '/e92ac84894ac' (length=13)

Explicación:
/^(evangelios|\/biblia\/comentarios\/evangelios\/|feature\/comentarios-biblicos\/)|((.+)biblias.html|(.+)\/liturgia-semana-+)/m

*

*^ Buscará al inicio de la cadena o línea cualquier coincidencia del primer grupo, esto ya lo tenías claro y funcionando:
(evangelios|\/biblia\/comentarios\/evangelios\/|feature\/comentarios-biblicos\/)

*| Disyuntiva para buscar en el segundo grupo si no hubo coincidencias en el primero:
((.+)biblias.html|(.+)\/liturgia-semana-+)

*(.+) Indica que puede haber cualquier caracter ., uno o más + antes de la cadena buscada, en este caso, biblias.html o liturgia-semana-

*+ No sé porqué lo incluiste después de liturgia-semana-, no es necesario

*m El modificador multilínea es solo para probar

Nota: Estoy muy lejos de ser experto en expresiones regulares, pero tú ya tienes las bases y no podría haber sugerido algo sin RegExr.com.


text:
Q: Resize only a part of texture, OpenGL I'm working on GUI in OpenGL. I'm using this image to texture my button:

You can't see it very well, but it has a light border (2 pixels width) around it.
What I want to achieve is to have nicely resizable button which keeps it's borders untouched. According to hints given me here, on StackOverflow I decided to use 9-cell-pattern, so I divided my quad into 9 parts like this:

I really like an effect I achieved if it goes about borders, but the problem is with a quad that is in the center (9th):

I would like to repeat or wrap a texture like I do but with ignoring borders.
So my question is - is there any way to do this with only one texture which I'm using now? Or should I create second texture, which would be decreased by a border width and to render this quad in the middle with this texture?
Also I don't know if it's necessary, but I'm putting here a fragment of my code:
This is a code I'm using for tiling/wrapping a texture:
switch(m_bTiling)
{
case true:
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
                     GL_REPEAT );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
                     GL_REPEAT );
    break;
case false:
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
                     GL_CLAMP );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
                     GL_CLAMP );
    break;
}

And here is a code to draw quads:
// Top left quad [1]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(0.0f, 1.0-maxTexCoordBorderY);
    glVertex2i(pos.x, pos.y + m_borderWidth);

    // Top left
    glTexCoord2f(0.0f, 1.0);
    glVertex2i(pos.x, pos.y);

    // Top right
    glTexCoord2f(maxTexCoordBorderX, 1.0);
    glVertex2i(pos.x + m_borderWidth, pos.y);

    // Bottom right
    glTexCoord2f(maxTexCoordBorderX, 1.0-maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + m_borderWidth);
glEnd();

// Top middle quad [2]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(maxTexCoordBorderX, 1.0 - maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + m_borderWidth);

    // Top left
    glTexCoord2f(maxTexCoordBorderX, 1.0);
    glVertex2i(pos.x + m_borderWidth, pos.y);

    // Top right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, 1.0);
    glVertex2i(pos.x + width - m_borderWidth, pos.y);

    // Bottom right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, 1.0 - maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + m_borderWidth);
glEnd();

// Top right quad [3]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(1.0 - maxTexCoordBorderX, 1.0 - maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + m_borderWidth);

    // Top left
    glTexCoord2f(1.0 - maxTexCoordBorderX, 1.0);
    glVertex2i(pos.x + width - m_borderWidth, pos.y);

    // Top right
    glTexCoord2f(1.0, 1.0);
    glVertex2i(pos.x + width, pos.y);

    // Bottom right
    glTexCoord2f(1.0, 1.0 - maxTexCoordBorderY);
    glVertex2i(pos.x + width, pos.y + m_borderWidth);
glEnd();

// Middle left quad [4]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(0.0, maxTexCoordBorderY);
    glVertex2i(pos.x, pos.y + height - m_borderWidth);

    // Top left
    glTexCoord2f(0.0, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x, pos.y + m_borderWidth);

    // Top right
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + m_borderWidth);

    // Bottom right
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + height - m_borderWidth);
glEnd();

// Middle right quad [5]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(1.0 - maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height - m_borderWidth);

    // Top left
    glTexCoord2f(1.0 - maxTexCoordBorderX, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + m_borderWidth);

    // Top right
    glTexCoord2f(1.0, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x + width, pos.y + m_borderWidth);

    // Bottom right
    glTexCoord2f(1.0, maxTexCoordBorderY);
    glVertex2i(pos.x + width, pos.y + height - m_borderWidth);
glEnd();

// Bottom left quad [6]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(0.0, 0.0);
    glVertex2i(pos.x, pos.y + height);

    // Top left
    glTexCoord2f(0.0, maxTexCoordBorderY);
    glVertex2i(pos.x, pos.y + height - m_borderWidth);

    // Top right
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + height - m_borderWidth);

    // Bottom right
    glTexCoord2f(maxTexCoordBorderX, 0.0);
    glVertex2i(pos.x + m_borderWidth, pos.y + height);
glEnd();

// Bottom middle quad [7]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(maxTexCoordBorderX, 0.0);
    glVertex2i(pos.x + m_borderWidth, pos.y + height);

    // Top left
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + height - m_borderWidth);

    // Top right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height - m_borderWidth);

    // Bottom right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, 0.0);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height);
glEnd();

// Bottom right quad [8]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(1.0 - maxTexCoordBorderX, 0.0);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height);

    // Top left
    glTexCoord2f(1.0 - maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height - m_borderWidth);

    // Top right
    glTexCoord2f(1.0, maxTexCoordBorderY);
    glVertex2i(pos.x + width, pos.y + height - m_borderWidth);

    // Bottom right
    glTexCoord2f(1.0, 0.0);
    glVertex2i(pos.x + width, pos.y + height);
glEnd();

// Middle middle quad [9]
glBegin(GL_QUADS);
    // Bottom left
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + height - m_borderWidth);

    // Top left
    glTexCoord2f(maxTexCoordBorderX, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x + m_borderWidth, pos.y + m_borderWidth);

    // Top right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, maxTexCoordHeight - maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + m_borderWidth);

    // Bottom right
    glTexCoord2f(maxTexCoordWidth - maxTexCoordBorderX, maxTexCoordBorderY);
    glVertex2i(pos.x + width - m_borderWidth, pos.y + height - m_borderWidth);
glEnd();

A: Well - I see your problem. You're using a constant value of maxTexCoordBorderX (and Y) for your "middle middle" quad. You need to recompute the UV coords of the center quads as the size changes (ex: width / (currWidth - 2 * borderWidth)), then you can set that texture to repeat always, but since you modify the texture coords as the  ui element resizes, the center part won't ever repeat.
Of course - if you're going to use a VBO or something more performant at some point of time in the future, you can simply define two fragment shaders (each with their own sampler2D objects; one repeats, the other stretches) for each of the tiling modes and render all corner quads and middle-middle quads using the "repeat" shader and all edge quads using the stretch shader. This will not require a recompute and ought to be very fast.
Note: You're drawing multiple quads here, this is not a good idea. I would recommend using an indexed mesh with shared vertices. This will minimize the possibility of "tears" at the borders of your quads.

A: If you were stretching the edges/center, you'd be fine, but since you're tiling, you're going to have to create a second texture with just the center part.
Note that this can be done programmatically if you have the size of the border. You'd copy the contents of the center into a new 2d array then upload that to another texture.
Another solution (as I stated in a comment) would be to set the texture coordinates of the middle middle quad to the same ones as the inner vertices of the corner. That way the texture of the center quad is stretched out. Note that this will create some weird stretching on the shine in the top right corner unless the entire thing is contained in the top right corner quad. You'd still have issues with this if you wanted to use your repeat solution.
If you still want to repeat the center part and don't mind moving your entire rendering pipeline to non-deprecated OpenGL, then ananthonline's answer is better. If you don't want to/can't move your rendering code to more modern OpenGL, then the texture copy is pretty much the only solution.


text:
Q: Bulk Gathering of Numerous Discovered Items (This is for Zabbix 2.2.2.)
I have a discovery rule that can return 100+ items that I'd like to monitor.
Each item's data can be gathered by a UserParameter invoking a separate executable.
Implementing these as passive checks eats the zabbix agent alive, spawning an external process for each item.
The data for all the items could easily be collected all at once and sent to the Zabbix server in bulk (via zabbix_sender). I don't know how to implement this properly. The documentation doesn't answer the (potentially stupid) questions I have.
How can I have the Zabbix agent make a single external invocation of my custom data-gathering script and send back all the data in bulk for the 100+ discovered items as well as not invoking a client-side action for every item?
What I want to avoid is having the Zabbix agent attempt to collect each item individually.
The discovery rule has to create the items. As I understand it, each item will result in the zabbix agent attempting to do something to collect its data. Is there a way I can prevent this or associate a group of items with a single client-side active check?
Part of what I don't understand is how active checks are supposed to be implemented. If one active check can send back a batch of items' data, how would the item be defined for that host (so that the agent didn't attempt to gather the item's data individually) and what item would be defined to invoke the active check (or whatever item type should be used) that would do the actual data gathering (but not save any data itself)? This is the real question that the documentation doesn't answer for me. How does Zabbix intend for me to implement active checks or use zabbix_sender to send bulk updates for items (that the agent will attempt to gather on its own).

A: Basic Zabbix concept - one item (check) = one value. Zabbix server doesn't provide parser functionality to parse multiple values, so it has to be always only one value.
If you want to return more value, than you have to use some workarounds, see
zabbix UserParameter return 2 or more values
Zabbix sender example:
allow command execution in the zabbix-agent and create item (active or passive) to run your script:
system.run["myscript.sh > output_for_zabbix_sender.txt; zabbix_sender -s <host_name> -z <zabbix_server> -i output_for_zabbix_sender",nowait]

It will execute command in nowait mode. myscript.sh produces output in format:
hostname key1 value1
hostname key2 value2
...

And this output is processed (sent) to the zabbix server by zabbix_sender. Item type must be Zabbix trapper in this case (zabbix_sender). Eventually you don't need system.run item, you can execute script with zabbix_sender as cron job.
If you need perfect monitoring solution don't forget to handle errors, minimize IOPs, ...
You can use zabbix_sender also for discovering - just follow documentation about required format, e.g.:
hostname discovery_key {"data":[{"{#ID}": "/"},{"{#ID}":"/usr"},{"{#ID}":"/var"}]}


text:
Q: Is Cheney the same character as Wraith? I just started reading Armageddon's Children, and there is a dog named Cheney. From the description it sounds like Wraith, or at least a descendant. Is there anything anywhere that confirms this?

A: No.
Wraith was absorbed by Nest and became one with her during the events of "A Knight Of The Word". Wraith was a creature of magic

 made by Nest's father who was a demon.

Cheney was found as a stray dog and adopted by Hawk. He was just a big strong dog with no special abilities (nothing beyond the abilities of a very good and loyal dog).


text:
Q: Connecting to MySql database on windows 2008 server via PHP I am trying to connect to a MySql db on a windows 2008 server via my php code, however I am getting the following error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server at 'reading initial communication packet', system error: 110 in /home/---/---/--/collector.php on line 19
Lost connection to MySQL server at 'reading initial communication packet', system error: 110

this is my code:
mysql_connect("the.server.net", "mysqluser", "password") or die(mysql_error());

I have looked for solutions on the internet and I saw a lot of suggestions about enabling external connections, but this is not the problem as I am able to connect via MySql Workbench from a different computer.
I was hoping anyone has any suggestions/tips/ideas etc


text:
Q: XAML GUI to Powershell with variables A fellow member on Superuser got me onto this guide on creating a GUI to a powershell script however I am new to this area so I need a little guidance on the coding.
This is the XAML code generated by Visual Studio 2015;
<Window x:Name="Title" x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="New Mailbox" Height="400" Width="420">
<Grid>
    <Image x:Name="image" HorizontalAlignment="Left" Height="100" Margin="14,10,0,0" VerticalAlignment="Top" Width="386" Source="C:\Users\Daniel Neocleous\Documents\Visual Studio 2015\Projects\WpfApplication1\WpfApplication1\Images\SibelcoLogo.png"/>
    <RadioButton x:Name="radioButton" Content="Step 1" HorizontalAlignment="Left" Margin="150,125,0,0" VerticalAlignment="Top"/>
    <RadioButton x:Name="radioButton_Copy" Content="Step 2" HorizontalAlignment="Left" Margin="217,125,0,0" VerticalAlignment="Top"/>
    <Button x:Name="button" Content="Create Mailbox" HorizontalAlignment="Left" Margin="150,152,0,0" VerticalAlignment="Top" Width="119" Height="35"/>
    <GroupBox x:Name="groupBox" Header="Output" HorizontalAlignment="Left" Height="169" Margin="10,192,0,0" VerticalAlignment="Top" Width="394">
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="147" Margin="0,0,-1.143,-0.714" TextWrapping="Wrap" VerticalAlignment="Top" Width="384"/>
    </GroupBox>

</Grid>

Now from what I have understood I have to modify this code by removing the x's and the x:Class="WpfApplication1.MainWindow" string and add the following to the end;
#Read XAML
    $reader=(New-Object System.Xml.XmlNodeReader $xaml)
    try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
    catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."; exit}
    #===========================================================================
    # Store Form Objects In PowerShell
    #===========================================================================
    $xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}
    #===========================================================================
    # Shows the form
    #===========================================================================
    $Form.ShowDialog() | out-null

I am a little stuck from here though assuming what I have out above is correct. How do I tie all this to the Gui?
GUI
There are two Radio buttons and depending which one is selected I want a different script to run and the Powershell output to be displayed in the text box at the bottom but how can I accomplish this?
The Powershell I want to run on Step 1
$credentials = get-credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri URL -Credential $credentials –AllowRedirection
Import-PSSession $Session
set-ADServerSettings -ViewEntireForest $true
Enable-RemoteMailbox -Identity test@test.com -RemoteRoutingAddress test@test.com.onmicrosoft.com
Enable-RemoteMailbox -Identity test@test.com -Archive

Step 2
$msolcred = get-credential
connect-msolservice -credential $msolcred
Set-MsolUser -UserPrincipalName test@test.com -UsageLocation GB
$LicOpt = New-MsolLicenseOptions -AccountSkuId company:STANDARDPACK -DisabledPlans MCOSTANDARD
Set-MsolUserLicense -UserPrincipalName test@test.com -AddLicenses company:STANDARDPACK -LicenseOptions $LicOpt
Remove-PSSession $Session

Thanks for the advice guys.

A: Your $Form should be a Window object and thus support all its methods, so to react to certain events you have to read the state of the controls.
As this is script based, i would just name all the relevant parts and search for them using FindName (your script apparently already creates powershell variables for all named controls). You then can access the properties like IsChecked to differentiate which RadioButton is selected. To listen to a button click you probably need Register-ObjectEvent. As you use ShowDialog you have a blocking call that returns when the DialogResult is set, so you should set that in your event listener.
Edit: I just played around with this and here's a small sample that shows the basic process.
ScriptWindow.xaml
<Window x:Name="Title"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <ListBox x:Name="selection" SelectionMode="Single">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <RadioButton IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                                 Content="{Binding}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <sys:String>Step 1</sys:String>
            <sys:String>Step 2</sys:String>
        </ListBox>
        <Button x:Name="run">Run</Button>
        <GroupBox Header="Output">
            <TextBox x:Name="output" IsReadOnly="True"/>
        </GroupBox>
    </StackPanel>
</Window>

ScriptWindow.ps1
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase

$xaml="ScriptWindow.xaml"
$xmlReader=(New-Object System.Xml.XmlTextReader $xaml)
$app=(New-Object System.Windows.Application)
$form=[Windows.Markup.XamlReader]::Load( $xmlReader )
$doc=(New-Object System.Xml.XmlDocument)
$doc.Load($xaml)
$run = $form.FindName("run")
$selection = $form.FindName("selection")
$output = $form.FindName("output")
$run.Add_Click({ $output.Text = $selection.SelectedItem })
$app.Run($form)

Apparently you can also add event listeners via Add_*, Register-ObjectEvent did not work for me. In the callback i just assign the selected option to the TextBox, you will want to do a case distinction on the selected value and execute your respective actions.


text:
Q: show a detaildisclosure button to the uitableview without custom cell How to show a detail disclosure button to the uitableview without using the custom cell. I know its by using the accessoryType: method, but don't know how to implement that..pls help..

A: cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

A: // Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];
    return cell;
}

[cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];


text:
Q: Grails - No class def found error when calling web service Updated to reflect new error message after changes
Howdy, I am trying to call a web service from Grails, but keep running in to errors.
Here's what my class looks like:
import groovyx.net.ws.WSClient

...
    def serviceUrl = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL"
    def proxy = new WSClient(serviceUrl.toString(), this.class.classLoader)
    serviceResult = proxy.FahrenheitToCelsius("80")
    println serviceResult

...
I am encountering a grails runtime exception:
Error 500: Executing action [index] of controller [myPackage.myController] caused exception: java.lang.NoClassDefFoundError: org/apache/cxf/endpoint/Client
Have been trying to troubleshoot, but have been unable to find any helpful resources.  Any help or suggestions on how to remedy would be much appreciated.
Thanks.

A: You missed the new operator it looks like:
def proxy = new WSClient(serviceUrl.toString(), this.class.classLoader)


text:
Q: Symfony2 image optimiztion I have a site developed with symfony2. It's full of images. But now problem  is, its taking too much time to load images. Is there any easy way to compress all images with single command?
I have read this doc link
but it seems need to place the {% image %} tag for every images on the twig template. I dont want to do that as i have imgage tag in more than 100 files. So please suggest me an easy and good way to do that. Thanks in advance.


text:
Q: Not able to decode mp4 file using latest ffmpeg library : av_decode_video2 I am writing a wrapper code around latest ffmpeg library. I am supplying MP4 files from local system. My problem is that I am unable to get any decoded frames when I use av_decode_video2(). The return value comes out to be negative. I have used av_read_frame() which returns 0. I googled about the problem I am facing but no where could I find the correct explanation. Please give me insight here. Pasting the pseudo code here.
    av_init_packet(avpkt);
    picture=av_frame_alloc();
    pFrameRGB=av_frame_alloc();
    codec = avcodec_find_decoder(CODEC_ID_H264);
    c= avcodec_alloc_context3(codec)
    avcodec_open2(decoderLibraryData->c, decoderLibraryData->codec, NULL)
    FormatContext = avformat_alloc_context();
    char *pUrl ="./1.MP4";

    iRet = avformat_open_input(atContext, pUrl, pFmt, NULL);

    if(FormatContext == NULL)
    {
        printf("could not assign any memory !!!!!!!!! \n");
    }

    avformat_find_stream_info(FormatContext, NULL);

    while(av_read_frame(FormatContext,avpkt) >= 0)
    {

      len = avcodec_decode_video2(c, picture, &got_picture,avpkt);

      printf("CODEC MANAGER len %d Frame decompressed %d \n",len,got_picture);

      if (len <= 0)
      {
        return ERROR;
      }
    }
}

        if(lastHeight != 0 && lastWidth != 0)
        {
            if(lastWidth != c->width || lastHeight != c->height )
            {
                av_free(buffer);
                buffer = NULL;
                lastWidth = c->width;
                lastHeight = c->height;

            }
        }
        else
        {
            lastWidth = c->width;
            lastHeight = c->height;
        }
        decodeFlag = 1;
        if(!buffer)
        {
            int numBytes;
            v_mutex_lock(globalCodecLock);
            switch(inPixFormat)
            {
            case RGB:

                // Determine required buffer size and allocate buffer
                numBytes=avpicture_get_size(PIX_FMT_RGB24, c->width, c->height);

                buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
                avpicture_fill((AVPicture *)pFrameRGB,buffer,PIX_FMT_RGB24,c->width, c->height);

                if(cntxt)
                    sws_freeContext(cntxt);

                cntxt = sws_getContext(c->width, c->height, c->pix_fmt,
                        c->width, c->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);

                break;

            }
            v_mutex_unlock(globalCodecLock);
            if(cntxt == NULL)
            {
                printf("sws_getContext error\n");
                return ERROR;
            }
            }

        {
            sws_scale(cntxt, picture->data, picture->linesize, 0, c->height, pFrameRGB->data, pFrameRGB->linesize);
            if(rgbBuff)
            {

                if(c->width <= *width && c->height <= *height)
                {
                    saveFrame(pFrameRGB, c->width, c->height, rgbBuff,inPixFormat);

                    *width = c->width;
                    *height = c->height;
                    rs = SUCCESS;
                    break;
                }
                else
                {
                    rs = VA_LOWBUFFERSIZE;
                }
            }
            else
            {
                rs = VA_LOWBUFFERSIZE;
            }
        }
        if(width)
        {
            *width = c->width;
        }
        if(height)
        {
            *height = c->height;
        }
        if(rs == VA_LOWBUFFERSIZE)
        {
            break;
        }

I am getting the return value of av_read_frame as 0 but av_decode_video2 returns value in negative. I am not able to get any clue here.

A: Make sure you have called
av_register_all();

or
avcodec_register_all();

at the beginning of your app.
Also it seems the problem is from calling avformat_find_stream_info. Test with the following code:
    AVPacket avpkt;
    av_init_packet(&avpkt);
    AVFrame* picture = av_frame_alloc();
    AVFrame* pFrameRGB = av_frame_alloc();

    AVFormatContext* c2 = avformat_alloc_context();

    char *pUrl = "C:/Sample Videos/20-06-34.MP4";
    int video_stream_index = 0;

    AVInputFormat* pFmt;
    int iRet = avformat_open_input(&c2, pUrl, pFmt, NULL);

    AVStream* stream = c2->streams[video_stream_index];

    AVCodec* codec = avcodec_find_decoder(stream->codec->codec_id);
    avcodec_open2(stream->codec, codec, NULL);

    if (c2 == NULL)
    {
        printf("could not assign any memory !!!!!!!!! \n");
    }

    while (av_read_frame(c2, &avpkt) >= 0)
    {

        int got_picture;
        int len = avcodec_decode_video2(stream->codec, picture, &got_picture, &avpkt);

        printf("CODEC MANAGER len %d Frame decompressed %d \n", len, got_picture);

        if (len <= 0)
        {
            return ERROR;
        }
    }


text:
Q: objective c post get request with body I have the server and encrypt:93mrLIMApU1lNM619WzZje4S9EeI4L2L.
I want to connect and get json from it. I tried:
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://mydomain.co.il/clubs"]];
[request setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"requestReply: %@", requestReply);
}] resume];

But I get: html source with "Invalid Encryption key".
Somebody said me that without body I'll not get the result. What should I do? And what about encrypt:93mrLIMApU1lNM619WzZje4S9EeI4L2L ?

A: Your encoding of the data might be wrong, try changing it to utf-8 encoding like this:
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


text:
Q: Не работает форма на wordpress, что делать?  Вот код
` <?php
if (isset($_POST['name'])) {$name = $_POST['name']; if ($name == '') {unset($name);}}
if (isset($_POST['email'])) {$email = $_POST['email']; if ($email == '') {unset($email);}}
if (isset($_POST['subject'])) {$subject = $_POST['subject']; if ($subject == '') {unset($subject);}}
if (isset($_POST['body'])) {$body = $_POST['body']; if ($body == '') {unset($body);}}
if (isset($name) && isset($email) && isset($subject) && isset($body)){
$address = "pups22297@gmail.com";
$message = "Имя: $name \nE-mail: $email \nТема: $subject \nТекст: $body";
$send = mail ($address,$subject,$message,"Content-type:text/plain; charset = UTF-8\r\nFrom:$email");
if ($send == 'true')
{echo "Спасибо, ваше сообщение успешно отправлено!";}
else {echo "Ошибка, сообщение не отправлено!";}
}
else
{
echo "Вы заполнили не все поля, необходимо вернуться назад!";
}
?>

Не хочу использовать плагины. Поэтому сделал свою форму отправки, но она не отправляет письмо, в чём дело?`

Есть вопросы?

Если у вас есть вопросы, вы хотите получить консультацию или есть какие-то предложения, то напишите нам сообщение, в котором можете всё подробно изложить и объяснить. Мы с вами свяжемся по телефону или напишем на почту, которую вы укажете в сообщени.

       <form action="/wp-content/themes/pro-rbt.ru/myForm.php" method="POST">

            <input type="text" class="form-control d-block w-100" id="Name" name="name" placeholder=" Имя" required="">

            <input type="text" class="form-control d-block w-100" id="phone" name="phone" placeholder="8 (__) __-_-__" required="">

            <input type="text" class="form-control d-block w-100" id="email" name="email" placeholder="Электронная почта" required>

            <textarea class="form-control d-block w-100 htextearea" id="Textarea" name="message" placeholder="Ваше сообщение" required></textarea>

         <button type="submit" class="btn form_btn">Отправить сообщение</button>
      </form>


text:
Q: Deadlock on async GCD using XMPPFramework As our app has been getting bigger and bigger, we started to notice deadlocks inside the XMPPFramework CoreDataStorage's scheduleBlock: method, shown below:
- (void)scheduleBlock:(dispatch_block_t)block
{
    // By design this method should not be invoked from the storageQueue.
    //
    // If you remove the assert statement below, you are destroying the sole purpose for this class,
    // which is to optimize the disk IO by buffering save operations.
    //
    NSAssert(!dispatch_get_specific(storageQueueTag), @"Invoked on incorrect queue");
    //
    // For a full discussion of this method, please see XMPPCoreDataStorageProtocol.h
    //
    // dispatch_Async
    //          ^

    OSAtomicIncrement32(&pendingRequests);
    dispatch_async(storageQueue, ^{ @autoreleasepool {

        block();
        [self maybeSave:OSAtomicDecrement32(&pendingRequests)];
    }});
}

Although it happens inside a framework, I do believe this issue is pertinent to the whole GCD discussion, since it happens only in very specific situations (in our case, it was first reported only through a stress test) and the code mentioned above works perfectly for the great majority of cases.
What we have noticed is that if this method is called many times in a short period of time, suddenly it will generate a deadlock. As our logs pointed out, one of the calls with enter the dispatch_async, but never "leave it". The following ones will only increment the "pendingRequests" variable, "hitting" a blocked storageQueue and never being executed.
This issue does not seem to be easy to reproduce. In our tests, we launch between 2 and 5 calls to the method every second. The deadlock happens randomly somewhere between 5 and 50 seconds. Depending on the number of calls per second and other adjustments, you can postpone this to somewhere around 150 seconds, but it does not solve the issue (the deadlock will still happen, just later). It might also be important to mention that the calls to this methods come from different threads, including the mainThread.
Since the issue is very hard to reproduce through "common means", at least in our app, it should not be critic. However, we are now afraid that this might happen "randomly" for our users. We do not feel "safe" with the method anymore, specially in terms of scaling.
So, we would like to start and join a further discussion around this, which is a pretty conventional use for GCD. If anyone finds a possible point of failure in the method, or if anyone would like to suggest a different approach or point out to some different practices, it would all be very welcome.
EDIT 1 - This is a log showing a deadlock. I've numbered the lines to make it easier to discuss. You will notice that everything went smoothly until line 30. There, a block is schedule in XMPPMessageArchivingCoreDataStorage, coming from the main thread. Right after, another block is scheduled, now coming from thread 11. Neither of these will get to be executed. On lines 33 and 35, you will notice that the queue starts to build, but the storage thread is never "released", so none of the queued operations will ever be executed.
1 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Event #30 started
2 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
3 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
4 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
5 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
6 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
7 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Schedule Block Thread: <NSThread: 0x15e972c30>{number = 18, name = (null)}
8 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Will Schedule Block -> 1 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d6bf4a0>{number = 7, name = (null)}
9 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
10 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 1 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
11 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]>
12 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Will Schedule Block -> 1 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
13 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
14 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 1 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
15 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
16 - Oct 19 16:45:18 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
17 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
18 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
19 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
20 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d6bf4a0>{number = 7, name = (null)}
21 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Event #31 started
22 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Will Schedule Block -> 1 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
23 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
24 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Schedule Block Thread: <NSThread: 0x15e972c30>{number = 18, name = (null)}
25 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]>
26 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
27 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 1 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
28 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Schedule Block Thread: <NSThread: 0x15e9caaf0>{number = 16, name = (null)}
29 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Did Finish Schedule Block -> 0 pending requests - Storage Queue :<OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]>
30 - Oct 19 16:45:19 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
31 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Will Schedule Block -> 1 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15eaf8a50>{number = 11, name = (null)}
32 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Event #32 started
33 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Will Schedule Block -> 2 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
34 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Will Schedule Block -> 0 pending requests - Storage Queue: <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Caller Thread: <NSThread: 0x15d51a0a0>{number = 1, name = main}
35 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Will Schedule Block -> 3 pending requests - Storage Queue: <OS_dispatch_queue: XMPPMessageArchivingCoreDataStorage[0x15d5c8c90]> / Caller Thread: <NSThread: 0x15eaf8a50>{number = 11, name = (null)}
36 - Oct 19 16:45:20 Ronaldo-Juniors-iPhone: Dispatched Scheduled Block at storage queue <OS_dispatch_queue: XMPPRosterCoreDataStorage[0x15d5c7ec0]> / Schedule Block Thread: <NSThread: 0x15eaf8a50>{number = 11, name = (null)}


text:
Q: Angularjs Controller test giving TypeError: undefined is not a function

.controller('ClientsCtrl', ['$scope', '$location', '$filter', '$modal', 'ngTableParams',
      function($scope, $location, $filter, $modal, ngTableParams) {

        var trowser = PY.getBooks($scope, $location, $modal);

      };

controllertestspec.js

'use strict';

describe('suite', function() {

  var scope, ctrl;
  beforeEach(module('clients'));
  beforeEach(inject(function($controller) {
    scope = {};
    var modalInstance = jasmine.createSpy('fakeModal');
    ctrl = $controller('ClientsCtrl', {
      $scope: scope,
      $modal: modalInstance
    });
  }));

  it('should change greeting value if name value is changed', function() {

  });

});

I have added the js file having module PY and if i try to print console.log(typeof PY.Books) it shows as function.
When i tried to run the spec file am getting error
Chrome 39.0.2171 (Mac OS X 10.9.5) clients module should change greeting value if name value is changed FAILED
    TypeError: undefined is not a function
        at Object.PY.getBooks


text:
Q: Using an autowired singleton bean in a non spring managed java class Alright, this might seem pretty stupid to all the veterans out there, but bear with me here, as I'm only finding my way around Spring & Spring Boot.
I've got a Controller class here,
@RestController
public class Controller {

    private static final Logger logger = LogManager.getLogger(Controller.class);

    private static Controller controller = null;

    @Autowired
    private ApplicationParameters applicationParameters;

    public static Controller getInstance() {
        if (controller == null) {
            synchronized (Controller.class) {
                if (controller == null) {
                    controller = new Controller();
                }
            }
        }
        return controller;
    }

    public Controller() {}

    public ApplicationParameters getApplicationParameters() {
        return applicationParameters;
    }

    @RequestMapping("/")
    public void init() {
        try {
            for (Entry<String, String> prop : applicationParameters.getProperties().entrySet())
                logger.info("Loaded System Property: " + prop.getKey() + " -> " + prop.getValue());

                Utils.concatenate("key1", "key2");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

which autowires the ApplicationParameters bean with properties from a Property file.
Utils Class
public class Utils {

protected static final Logger logger = LogManager.getLogger(Utils.class);

    //Need to get the value of the property keys propKey1 & propKey2 and concat them.
    public static String concatenate(String propKey1, String propKey2) throws Exception {
        if(StringUtils.isNoneEmpty(propKey2) && StringUtils.isNoneEmpty(propKey1)) {
            return Controller.getInstance().getApplicationParameters().getProperties().get(propKey1) + Controller.getInstance().getApplicationParameters().getProperties().get(propKey2)
        } else {
            logger.error("System Property is undefined." );
            return null;
        }
    }

So, I'd like use this autowired ApplicationParameters bean as a singleton instance throughout the lifecycle of my project.
For instance, I'd like to use it in the Utils class. Clearly Utils class is not spring managed, its just a regular old java class.
So I'd like to know how to use fully initialized applicationParameters in my Utils class.
This is what I've tried so far:

*

*Autowiring the ApplicationParameters again in the Utils class, like this,
public class Utils {

@Autowired
private ApplicationParameters applicationParameters;

protected static final Logger logger = LogManager.getLogger(Utils.class);

But applicationParameters will be null here as, I'm presuming, this is because, Utils is not a spring managed bean.

*Make Controller class singleton. (Not sure how to go about doing this as init() needs to get invoked when web server starts, then where to call getInstance()?)

Hence, would someone be so kind as to assist a novice here.
P.S. The Utils class is shown only as a sample to bring home the fact that, a spring managed autowired bean has to be used in a regular java class.

A: You could make the spring context accessible from outside with a helper class like this one:
public class SpringContextUtil implements ApplicationContextAware {
   static ApplicationContext applicationContext;

   public void setApplicationContext(ApplicationContext context) throws BeansException {
     applicationContext = context;
   }

   public static ApplicationContext getApplicationContext() {
     return applicationContext;
   }
}

Then, you could do something like this: SpringContextUtil.getApplicationContext.getBean("applicationParameters")

A: As a first rule, don't. A second don't either. Only if you really must, as there is no garantuee that this will work reliable as there is no way that everything has been properly initialized when this method is called. Instead try re-working your util to be a spring managed class as well.
If you really want, ditch most of your code as you are trying to be too smart in your code. Use this hack (yes it is a hack imho and should be avoided if necessary!).
public class SpringUtil {

  private static final ApplicationContext ctx;

  SpringUtil(ApplicationContext ctx) {
    SpringUtil.ctx=ctx;
  }

  public static Controller getController() {
    return this.ctx.getBean(Controller.class);
  }

  public static ApplicationParameters getApplicationParameters() {
    return ctx.getBean(ApplicationParameters.class);
  }
}

Then cleanup your controller
@RestController
public class Controller {

    private static final Logger logger = LogManager.getLogger(Controller.class);

    @Autowired
    private ApplicationParameters applicationParameters;

    @GetMapping("/")
    public void init() {
        try {
            for (Entry<String, String> prop : applicationParameters.getProperties().entrySet())
                logger.info("Loaded System Property: " + prop.getKey() + " -> " + prop.getValue());

                Utils.concatenate("key1", "key2");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

THen use the SpringUtil to obtain the ApplicationParameters instead of the controller
public class Utils {

protected static final Logger logger = LogManager.getLogger(Utils.class);

    //Need to get the value of the property keys propKey1 & propKey2 and concat them.
    public static String concatenate(String propKey1, String propKey2) throws Exception {
        if(StringUtils.isNoneEmpty(propKey2) && StringUtils.isNoneEmpty(propKey1)) {
            return SpringUtils.getApplicationParameters().getProperties().get(propKey1) + SpringUtils.getApplicationParameters().getProperties().get(propKey2)
        } else {
            logger.error("System Property is undefined." );
            return null;
        }
    }

However this is quite a hack and might work in 90% of the cases. Also there is quite a design flaw/smell as you are doing a lot of getter chaining in your class. So all in all you are probably better of refactoring the Utils to make use of regular method calls and proper design techniques.


text:
Q: Check if string contains any substring in an array in Ruby I am using the Tmail library, and for each attachment in an email, when I do attachment.content_type, sometimes I get not just the content type but also the name. Examples:
image/jpeg; name=example3.jpg

image/jpeg; name=example.jpg

image/jpeg; name=photo.JPG

image/png

I have an array of valid content types like this:
VALID_CONTENT_TYPES = ['image/jpeg']

I would like to be able to check if the content type is included in any of the valid content types array elements.
What would be the best way of doing so in Ruby?

A: If image/jpeg; name=example3.jpg is a String:
("image/jpeg; name=example3.jpg".split("; ") & VALID_CONTENT_TYPES).length > 0

i.e. intersection (elements common to the two arrays) of VALID_CONTENT_TYPES array and attachment.content_type array (including type) should be greater than 0.
That's at least one of many ways.

A: So if we just want existence of a match:
VALID_CONTENT_TYPES.inject(false) do |sofar, type|
    sofar or attachment.content_type.start_with? type
end

If we want the matches this will give the list of matching strings in the array:
VALID_CONTENT_TYPES.select { |type| attachment.content_type.start_with? type }

A: # will be true if the content type is included
VALID_CONTENT_TYPES.include? attachment.content_type.gsub!(/^(image\/[a-z]+).+$/, "\1")

A: There are multiple ways to accomplish that.  You could check each string until a match is found using Enumerable#any?:
str = "alo eh tu"
['alo','hola','test'].any? { |word| str.include?(word) }

Though it might be faster to convert the array of strings into a Regexp:
words = ['alo','hola','test']
r = /#{words.join("|")}/ # assuming there are no special chars
r === "alo eh tu"

A: I think we can divide this question in two:

*

*How to clean undesired data

*How to check if cleaned data is valid

The first is well answered above. For the second, I would do the following:
(cleaned_content_types - VALID_CONTENT_TYPES) == 0

The nice thing about this solution is that you can easily create a variable to store the undesired types to list them later like this example:
VALID_CONTENT_TYPES = ['image/jpeg']
cleaned_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/jpeg']

undesired_types = cleaned_content_types - VALID_CONTENT_TYPES
if undesired_types.size > 0
  error_message = "The types #{undesired_types.join(', ')} are not allowed"
else
  # The happy path here
end


text:
Q: Generating HTML with inclosed HTML stored in DB I'm generating HTML pages with dynamic content. Users can personalize their pages, by adding a footer. My user control panel stores the footer in a UFT-8 table (MySQL). The footer itself can have HTML.
When I generate my page I'm inserting the footer inside a DIV. My doctype is
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'+
               '<html xmlns="http://www.w3.org/1999/xhtml">'+#10+
               '<head>'+#10+
               '<meta http-equiv="content-type" content="text/html;charset=utf-8" />'+#10+

This works, but accentuation and characters like "•", don't display correctly. I've tried using HTMLEscape, but it's breaking the footer HTML.
My question is: what is the most simple way to correct this, without iterating all the special chars and escaping them one by one.

A: Things I would check:

*

*does the compiler issue warnings about string conversion problems?

*can you save the HTML to a file, and open it with an editor like Notepad++ to verify it is UTF-8 encoding?

*does the web server set the Content-Type header to text/html; charset=utf-8?


text:
Q: Grafana, range starting from specific hour I have a prometheus metric, that is a global counter like following
sum(increase(http_404_counter_total{namespace="XXX"}[50y]))
I also need another counter that ranges from {today 00:00} and now(), which I will be using as "Todays counts"
Do you have any idea how I can achieve this?
Edit: Grafana V7.1.5

A: To select "today so far" use the following time range:
From: now/d
To:   now


text:
Q: Simple Facebook "Share Link" I am working on a site where posts are made and I'd like to give visitors the ability to "share" a particular post that they link on their timeline. I have never done any social media integration, but I followed the instructions via the FB API and am still having problems. It's easier to show you than try to explain it. Go to http://www.badcustomerbureau.com/ and click on any of the Share links at the top of any post. Instead of sharing the post you clicked on, it tries to share a generic post with the same photo every time (photo of a dog). I used the code generator on the FB help site and it still has this issue. Please help!
I did receive one suggestion from a member of this site, but I am still seeing the same behavior.

A: I think its already working. I've tried it before in my own website http://socialviralworld.com/. You just have to login first and see the changes.
See image:


text:
Q: how to add deep-linking in android app? please tell me Intent filter in Manifest file for deep linking.

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data
                android:host="packagename"
                android:scheme="android-app" />
        </intent-filter>

A: I would probably go for a library like DeepLinkDispatch, which simplifies the setup and maintenance of the deep links configuration.
From the README.md
@DeepLink("foo://example.com/deepLink/{id}")
public class MainActivity extends Activity {

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getIntent().getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
       Bundle parameters = getIntent().getExtras();
       String idString = parameters.getString("id");
       // Do something with the ID...
    }
  }
}

And does not contaminate your manifest as only one Activity is declare
<activity
    android:name="com.airbnb.deeplinkdispatch.DeepLinkActivity"
    android:theme="@android:style/Theme.NoDisplay">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="airbnb" />
    </intent-filter>
 </activity>


text:
Q: rails-api:render json multiple values I have a model
class Banner < ActiveRecord::Base
  validates :title, presence: true, length: { maximum: 50 }
  validates :description, length: { maximum: 200 }

  belongs_to :document

  def img_url
    document.medium_url
  end
end

and serializer
class BannerSerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :img_url, :document_id
end

When I'm using render json: Banner.all, it response correctly (has "img_url" in the responding
{
"banners": [
    {
      "id": 1,
      "title": "This is title of banner",
      "description": "This is long description...",
      "img_url": "http://localhost:3000//system/documents/attachments/000/000/023/medium/one-piece.jpg?1459601536",
      "document_id": 23
    }
  ]
}

But when I want to return with other object by using.
example:
render json: {
      banners: Banner.all,
      blogs: Blog.all,
      partners: Partner.all
    }

The responding don't exist "img_url" (it don't use Serializer).
Please help.

A: Serializer has new method. That you can call it from controllers too.
render json: BlogSerializer.new(Blog.all)

For array, use ArraySerializer.
Example:
blogs = ActiveModel::ArraySerializer.new(blogs, each_serializer: ArticleSerializer)