text:
Q: How do I handle outlooks VSTO objects as if they are mailitems I have written some VSTO (2003) code that sucessfully applies some mandatory subject line changes according to attachements of mail items. The code is written to operate on microsoft.office.interop.outlook.mailitem However, I need the same code to operate on other types such as microsoft.office.interop.outlook.appointmentitem for instance(infact it needs to work for anything the user can send that would have a subject).
Assuming the outlook item types have a subject property, an attachments property and a save method, how can I approach writing code that works for all relevant interop.outlook types.
I tried addressing this via reflection but GetProperty is returing null so I can't use GetValue on it

? mi.GetType().GetProperty("Subject")
null

?(mi as Microsoft.Office.Interop.Outlook.MailItem).Subject
"Test Subject"

there doesn't seem to be a generic outlookitem class I can cast to, to do this. What's the correct approach ?
EDIT:
To clarif my code starts like this...

    void Application_ItemSend(object Item, ref bool Cancel)
    {
            if (Item is Microsoft.Office.Interop.Outlook.MailItem)
            {
                Microsoft.Office.Interop.Outlook.MailItem currentItem =
                    Item as Microsoft.Office.Interop.Outlook.MailItem;

then does stuff to currentItem (including passing to to various functions currently typed with Microosft.Office.Interop.Outlook.MailItem properties. I want them to handle "Microsoft.Interop.Outlook.somethingsendable"

A: That's not going to work out of the box - AppointmentItem and MailItem are completely different interfaces, so polymorphism is not an option.
The best I can suggest is that you create a SendableItem class of your own to wrap the PIA interfaces you need to support, and encapsulate the switching code there behind a common wrapper for the 'common' operations you want to use.  You would create a SendableItem using either a MailItem or an AppointmentItem but once created, they look the same from the outside of the SendableItem wrapper.


text:
Q: Integrate Payment API with wordpress How difficult is integrate Payment API with wordpress site?
Im trying to figure out how to integrate Montonio payment api with wordpress.
maybe possible add with hook?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with Screen after installing ubuntu 17.04 I recently installed Ubuntu 17.04, replacing Windows. This was my first Ubuntu installation everything went smoothly except that my screen is not properly aligned at the edges:

How can I fix this?


text:
Q: How to decrypt a password in lua? I have an encrypted password "$H$9f1gABgoDXyr1P0AT7Wz8qAB3.QNGF" and I want to decrypt it but I really can't understand which encryption they used for this password. I took this password from my website forum mysql database. Can anyone tell me how to decrypt this and also tell me the name of this encryption? I've been searching for this since 1 hour and found nothing useful.

A: You can't, by design.
The "encrypted password" you've posted is one-way encrypted using a trapdoor function: the only way to get the original password is to enter the original password and see it produce the same output.
If you could "decrypt" this password, there'd be nothing stopping an attacker, after breaking into your password database, from doing the same.


text:
Q: How to translate this SQL query into Hibernate's HQL? Having used Hibernate before but never to this extent, I have struggled while trying to translate the following query into a valid Hibernate SQL query.
SELECT * FROM
(SELECT * FROM scripts WHERE (script.type LIKE 'DATA'))
AS A JOIN
(SELECT * FROM req_executions
WHERE (req_executions.fk_database NOT IN
(SELECT executions.fk_database FROM executions
WHERE executions.fk_script = req_executions.fk_script))
OR ((req_executions.fk_database = 12 AND req_executions.fk_database != 8)
AND req_execution.fk_database NOT IN (SELECT executions.fk_database FROM execution
WHERE executions.fk_script = req_executions.fk_script)))
AS B
ON (A.id = B.fk_script)

The result of this query is a filtered table of scripts that are pending for execution.
I have tried things like:
"SELECT req FROM (SELECT s FROM Script s
WHERE( s.filename LIKE :filename AND s.type = :scriptType AND s.ticketNumber LIKE :ticketNumber )
JOIN (SELECT re FROM RequiredExecution re
WHERE (re.key.databaseId NOT IN (SELECT e.database FROM Execution e WHERE e.script.id = re.key.scriptId))
OR ((re.key.databaseId = :forAllId AND :dbId != :syncId)
AND re.key.databaseId NOT IN
(SELECT e.database FROM Execution e WHERE e.script.id = re.key.scriptId)))) WHERE (s.id = re.key.scriptId)"

and using "AS"
but I am still far from a solution. Any tips?

A: I thought you had to select FROM an entity and not from another SELECT ... I don't know if it is possible, seems tough anyway.
You might consider sticking with native SQL query calling session.createSQLQuery("the native SQL").
and .addEntity(YourEntityClass.class) to auto map results
and .setParameter(, 0 based numbered, while the query uses ? placeholders instead of :named_parameter.

A: In the end I was forced to use a nativeQuery instead, because "...HQL subqueries can occur only in the select or where clauses." as stated in 14.13. Subqueries.


text:
Q: Plotting hourly time series with unspecified time I am currently working on a dataframe with 25 columns and 120 rows. As in the dataframe, date and time are stored separately. An extract of my dataframe is like this:
          date 1 2 3 4 5 6   7    8    9   10   11   12
1   2013-08-01 0 0 0 0 0 0 369 2416 1934 1125  768  653
2   2013-08-02 0 0 0 0 0 0 401 2328 1962 1080  849  588
5   2013-08-05 0 0 0 0 0 0 551 2855 2317 1099  876  805
6   2013-08-06 0 0 0 0 0 0 420 2382 1937 1065  844  710
7   2013-08-07 0 0 0 0 0 0 405 2397 1930 1081  768  773
8   2013-08-08 0 0 0 0 0 0 391 2273 1942 1098  831  633
11  2013-08-12 0 0 0 0 0 0 555 2938 2163 1071  898  700
12  2013-08-13 0 0 0 0 0 0 323 2375 1819 1087  905  734

where only 12 hours out of 24 hours are shown.
I want to have an hourly time series plot with minimal changes to the above dataframe. Thanks in advance.

A: You have to melt the data.frame to make the hour a single variable, as you want to look at it as a single variable.
library(data.table)
hour_cols <- as.character(1:24)
plot_df <-
  melt(your_data_frame, id.vars = "date", measure.vars = hour_cols)
require(ggplot2)
ggplot(plot_df, aes(x = variable, y = value, colour = date)) +
  geom_point()

See ?data.table::melt for further details on this method.
EDIT: This method will of course will only look good with not too many different dates.  I here considered that there will only be the 12 dates you supplied in the question.

A: You need to convert you date from wide to long format. For this you can use gather from tidyr (?tidyr::gather) and combine date and time:
library(tidyr)
long_data <- data %>%
  gather(time, val, `1`:`12`) %>%
  mutate(datetime = paste0(date, " ", time, ":00"))

And then plot the data:
library(ggplot2)
ggplot(long_data, aes(x = variable, y = value) +
  geom_point()


text:
Q: How to add a VLookUp Code to a Command Button on Click I have a userform that inputs data to Excel based on user input. Once the "Ok" command button is click the data is input and the form clears and moves to the next empty row. Before the data is input on the command click, I want to verify the text input with a pop up confirmation - "Employee ID #### is Bob Smith" - if this is correct users can select Ok and the data input code will continue, if not it will return to the userform to correct. I tried using a vlookup code but get a run time or stack overflow error.
Here is my code:
Private Sub OkButton1_Click()

Dim myLookupValue As String
Dim myFirstColumn As Long
Dim myLastColumn As Long
Dim myColumnIndex As Long
Dim myFirstRow As Long
Dim myLastRow As Long
Dim myVLookupResult As Long

Dim myTableArray As Range

myLookupValue = IDTextBox
myFirstColumn = 1
myLastColumn = 2
myColumnIndex = 2
myFirstRow = 2
myLastRow = 500

    With Worksheets("Sheet2")
        Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn))
    End With

    myVLookupResult = WorksheetFunction.VLookup(myLookupValue, myTableArray, myColumnIndex, False)

    MsgBox "Employee Id" & myLookupValue & " is " & myVLookupResult
        Cancel = True

If Ok Then

Dim emptyRow As Long

'Make Sheet1 active
Sheet1.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer information
Dim x As Integer

    x = 0

    For Each cCont In Me.Controls
        If TypeName(cCont) = "CheckBox" Then
            If cCont.Value = True Then
                x = x + 1
            End If
        End If
    Next

    If x = 0 Then
        MsgBox "Please Select a Lunch Option"
        Else
        Cells(emptyRow, 1).Value = IDTextBox.Value
        End If

If MealCheckBox1.Value = True Then Cells(emptyRow, 2).Value = 5

If ExtraCheckBox2.Value = True Then Cells(emptyRow, 3).Value = 1

If DessertCheckBox3.Value = True Then Cells(emptyRow, 4).Value = 1

If DrinkCheckBox4.Value = True Then Cells(emptyRow, 5).Value = 1

Call Lunch_Initialize

IDTextBox.SetFocus

End If

End Sub

Using the code as is I get Run-Time error '1004' Unable to get the VLookup property of the WorksheetFunction class.


text:
Q: ASP.Net MVC5 set secure and HTTPOnly flags I need to set the httponly and the secure flag to all the cookies of my site to pass the security scans of my customer.
The web.config is configured correctly I think
<system.web>
   <httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" />

And it is working for all the cookies I create inside my application, but not for google analitycs ones (I know I can not do anything about it) and what I suppose are the session cookies of asp.net (ai_user and ai_session).

Searching for this two cookies lead to nothing.
How can I force the httponly and secure flags?
I do not know if it is related, but I have also this rewrite rule
<rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
    </rule>
  </rules>
</rewrite>

I tried to disable it, but nothing changed

A: I stumbled upon "ai_session" and "ai_user" cookies now with my project and I think they are from application insights. If you investigate further, please report back to community.

A: The right way to require SSL is via a global filter
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     filters.Add(new HandleErrorAttribute());
     filters.Add(new System.Web.Mvc.AuthorizeAttribute());
     filters.Add(new System.Web.Mvc.RequireHttpsAttribute());
}


text:
Q: I've got an issue doing validations by JavaScript If I validate any textbox by using ID or type (in jQuery) etc. like:
var element=document.getElementById('tbxSearchField').value
if(element=="")
{alert("please enter text");}

And the HTML is:
<input class="input" id="tbxSearchField" name="tbxSearchField" placeholder="Search" type="text" value="">

If anyone changes the ID of the element in browser using inspect element option then the validation doesn't work.
How to give security for this kind of situation? Is there any way to stop this from client side?

A:
Is there any way to stop this from client side

No, there is no. Client side validation is only for users convenience. Validation logic can be changed anytime by simple editing code in browser dev tools.

How to give security for this kind of situations?

You have always to revalidate data from client on server.

A: Well the best way to securily validate inputs is to use Server Side validation, but with jQuery you can avoid using id or class to validate inputs:
var elements=$( "input:text" );
for(element in elements){
  if(element.val()=="")
  {
   alert("please enter text");
  }
}

Or you can use Javascript querySelector() Method:
var elements=document.querySelector('input[type="text"]');
for(element in elements){
  if(element.value=="")
  {
   alert("please enter text");
  }
}

A: The JavaScript validations are client-side validations. The end user could easily break this with the browser's JavaScript settings.
It is best to use Ajax validation for security purposes.
The blog post Form Validation Using Ajax will help more to use Ajax validations.


text:
Q: xsl wrap a choose result in a div tag How do you wrap the "when" and "otherwise" results in a  tag?
In my example below I tried adding a the div but it ends up wrapping each result.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
   <xsl:output method="xml" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" encoding="UTF-8" />
   <xsl:include href="vcardbook.xsl" />
   <xsl:template name="entriesLoopBook">

         <xsl:for-each select="entries/entry ">

               <xsl:choose>
                  <xsl:when test="$fid != 887">

                        <xsl:call-template name="vcardbook" />

                  </xsl:when>
                  <xsl:otherwise>

                        <xsl:call-template name="vcardbook" />

                  </xsl:otherwise>
               </xsl:choose>

         </xsl:for-each>

   </xsl:template>
</xsl:stylesheet>

Result from code above:

How I would like it to look:

Thank you for your help.

A: As I rule I wouldn't recommend using for-each, but to make as few changes to your code as possible, try this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0">
   <xsl:output method="xml" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" encoding="UTF-8" />
   <xsl:include href="vcardbook.xsl" />
   <xsl:template name="entriesLoopBook">

              <xsl:for-each select="entries/entry[<wherever you get $fid from> != 887">
                <xsl:call-template name="vcardbook"/>
              </xsl:for-each>

              <xsl:for-each select="entries/entry[<wherever you get $fid from> = 887">
                <xsl:call-template name="vcardbook"/>
              </xsl:for-each>

         </dv>

   </xsl:template>
</xsl:stylesheet>


text:
Q: Rspec with Rails - url_helpers outside before/it blocks? In my app, I have an identical form on two separate pages. I've written a series of tests for the one page, and would like to simply loop over the test suite for my second page, passing in the page for which the test suite should run against. The problem is, I can't seem to access the url_helpers in a clean way.
This is what I have so far that works:
require 'rails_helper'

describe "my tests" do
  subject { page }

  paths = ["/signin", "/signup"]
  paths.each do |path|
    describe "user signs in via #{path}" do
      before { visit path }

      describe "user enters invalid information" do
        before do
          fill_in "Email", with: user.email, match: :first
          fill_in "Password", with: user.password.reverse, match: :first
          click_button "Sign in"
        end

        it { should have_title("Sign in") }
        it { should have_content "Invalid email/password combination!" }
        its(:current_path) { should eq "/signin" }
      end
  end
end

If I replace "/signin" with signin_path, I get
undefined local variable or method `signin_path' for RSpec::ExampleGroups::Authentication:Class (NameError)

But I'm using url_helpers successfully throughout the rest of my test script, albeit inside before and it blocks. If I fully qualify the url_helper with Rails.application.routes.url_helpers.signin_path it works, but I'd rather have this work automatically. If I do an include at the top of the script, I get
ActionView::Template::Error:
   arguments passed to url_for can't be handled. Please require routes or provide your own implementation

Again, not ideal. I'd rather have this just work. Any thoughts?
Thanks in advance.

A: Are there no errors if you just did one path? If so, then why not use a RSpec shared_example
require 'rails_helper'

shared_examples 'get_user_in' do |path|
    describe "user signs in via #{path}" do
      before { visit path }

      describe "user enters invalid information" do
        before do
          fill_in "Email", with: user.email, match: :first
          fill_in "Password", with: user.password.reverse, match: :first
          click_button "Sign in"
        end

        it { should have_title("Sign in") }
        it { should have_content "Invalid email/password combination!" }
        its(:current_path) { should eq "/signin" }
      end
  end
end

describe "/signin" do
  subject { page }
  include_examples "get_user_in", 'signin'
end

describe "/signup" do
  subject { page }
  include_examples "get_user_in", 'signup'
end

Didn't test this out, so there might be some error here.


text:
Q: Logic doesn't work after .then I have a Login end point that respond me a json.
I'm using vue-router to do a POST and then Store a token in localStorage, but after the POST, the json shows on the screen:
{"success":false,"message":"Login ou senha inválidos!"}

It should return on the page login, with the message
This is the code:
var vmLogin = new Vue({
el: '#login',
data: {
email: '',
msg: '',
password: ''
},
beforeCreate: function () {
 if(localStorage.getItem("timeTaskToken") !== null) {
  window.location.href = '/'
}
},
methods: {
getLogin: function (e) {

  this.$http.post('/login', {email: this.email, password: this.password}).then((response) => {
    alert('teste!');
    if(response.body.success === true) {

      localStorage.setItem("timeTaskToken", response.body.token);
      window.location.href = '/'
    } else {
        this.msg = response.body.message
    }

  }, (response) => {
    // error callback
  });
  e.preventDefault();
}
}
});

login page
<form id="login" class="form-horizontal" method="post">

{{ msg }}

 Email

  <input type="email" v-model="email" class="form-control" name="email" placeholder="Email">

Password

  <input type="password" v-model="password" class="form-control" name="password"  placeholder="Password">

      <input type="checkbox"> Remember me

  <button type="submit" class="btn btn-default" @click="getLogin">Sign
  in</button>

  </form>

It's like nothing after .then works...
The returned JSON just appear in the screen.

A: I expect the problem is that the Sign In button is a submit button and you just want it to be a button button.
Change
<button type="submit" class="btn btn-default" @click="getLogin">Sign in</button>

To
<button type="button" class="btn btn-default" @click="getLogin">Sign in</button>

Note the type="button".
If you leave it as type submit then the form is is actually posted and code execution will stop. This also explains why you see a page that has just the JSON result; that is just the response from posting that form.
Alternatively, move e.preventDefault() to the top of the method.
You could also use @click.prevent="getLogin".

A: Just add a console.error in you error callback
}, (response) => {
    console.error(response);
  });

This is the first step because maybe you just enter here ..


text:
Q: Problems with wowza, dash, ssl, and cors I'm trying to stream mpeg video using dash.js and wowza. I configured VHost.xml to stream ssl over port 443 and gave it my keystorepath and keystorepassword.  I used this link https://maximilian-boehm.com/hp2121/Create-a-Java-Keystore-JKS-from-Let-s-Encrypt-Certificates.htm to create my jks from letsencrypt certificates.  I created the jks from my fullchain.pem and privKey.pem.  I also enabled CORS in crossdomain.xml.  I can see that SSL streaming and CORS are enabled in the enginemanager ui as well.  Here is how I create the stream using the wowza rest api on port 8087.
HTTP POST called : http://ip-address:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/App/streamfiles/96728ede-bda0-4fe7-86e1-724f5ea6237b
Post Response: {"success":true,"message":"","data":null}
HTTP PUT called : http://ip-address:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/streamfiles/96728ede-bda0-4fe7-86e1-724f5ea6237b/actions/connect?connectAppName=App&appInstance=_definst_&mediaCasterType=rtp&vhostName=_defaultVHost_&streamfileName=96728ede-bda0-4fe7-86e1-724f5ea6237b
PUT Response: {"success":true,"message":"Publish stream successfully started [App/_definst_]: mp4:96728ede-bda0-4fe7-86e1-724f5ea6237b.stream","data":null}

I've tried these POST and PUT requests with hostname:8087 rather than ip-address:8087 and get the same error.
Then from my js I see this error in the console in chrome.
GET https://hostname/App/96728ede-bda0-4fe7-86e1-724f5ea6237b.stream/manifest.mpd 404 (Not Found)
c @ dash.all.min.js:6
(anonymous) @ dash.all.min.js:6
index#/security:1 XMLHttpRequest cannot load https://hostname/App/96728ede-bda0-4fe7-86e1-724f5ea6237b.stream/manifest.mpd. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8090' is therefore not allowed access. The response had HTTP status code 404.

Can anyone see what I'm doing wrong or has faced this issue before?


text:
Q: Chance/Probability in GAMS I would appreciate it if anyone could help me with this problem of mine, I have a random variable N which is following Poisson distribution and another Variable named M which is calculated based on other things and I know it is being calculated correctly cause i solved the example by hand. The problem is the part where GAMS wants to calculate the probability of N

*Number of emergency patients arriving at time period t on day d
Table N(t,d)
    1   2
1   1   1
2   1   1
3   1   1;

file emp / '%emp.info%' /;put emp '* problem %gams.i%'/;
$onput
randvar N(1,1) poisson Ltotal
randvar N(2,1) poisson Ltotal
randvar N(3,1) poisson Ltotal
randvar N(1,2) poisson Ltotal
randvar N(2,2) poisson Ltotal
randvar N(3,2) poisson Ltotal
$offput

put "randvar N(1,1) poisson Ltotal", N('1','1')/;
put "randvar N(2,1) poisson Ltotal", N('2','1')/;
put "randvar N(3,1) poisson Ltotal", N('3','1')/;
put "randvar N(1,2) poisson Ltotal", N('1','2')/;
put "randvar N(2,2) poisson Ltotal", N('2','2')/;
put "randvar N(3,2) poisson Ltotal", N('3','2')/;

file emp1 / '%emp.info%' /;put emp '* problem %gams.i%'/;
$onput
chance (N(t,d)<=M(t,d)) Re(t,d)
$offput


text:
Q: Make dynamically loaded images ease in and out using actionscript I have 4 buttons and 4 images when I click a button a different image appears.  I want the images to ease in and out after each button click.  I have tried the code below but can't seem to figure it out.
home_btn.addEventListener(MouseEvent.CLICK, homeClick);
function homeClick(e:MouseEvent):void{
    backgroundimg.source = "images/bluebg.jpg";
    var bluebgTween:Tween = new Tween(backgroundimg, "alpha", Strong.easeIn, 1, 0, 3, true);

}

A: If fading in then fading out, set the initial alpha of backgroundimg to 0.
backgroundimg.alpha = 0;

You can then fade in on the CLICK event.  Note that I've swapped the begin and finish values for the Tween.
Once the tween has finished, the yoyo() method can then be used to fade out again.
home_btn.addEventListener(MouseEvent.CLICK, homeClick);
function homeClick(e:MouseEvent):void{
    backgroundimg.source = "images/bluebg.jpg";
    var bluebgTween:Tween = new Tween(backgroundimg, "alpha", Strong.easeIn, 0, 1, 3, true);

    bluebgTween.addEventListener(TweenEvent.MOTION_FINISH, onFinish);

    function onFinish(te:TweenEvent):void {
        bluebgTween.yoyo();
        bluebgTween.removeEventListener(TweenEvent.MOTION_FINISH, onFinish);
    }
}

I used these sites as a reference for this:

*

*http://www.republicofcode.com/tutorials/flash/as3tweenclass/

*http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/fl/transitions/Tween.html


text:
Q: c# keyboard hook works for only 10 times then it stops (or is supressed)? It is the classic low level keyboard hook that I have used several times before quite successfully but lately it does not work right. It reads the keyboard inputs for exactly 10 times (10 times from any of the keys defined in HookCallback function) and then it stops. It is like some security feature of the OS or some other program like maybe an anivirus is getting in the way and  suppressing the keyboard hook after 10 times.
Has anyone else encountered this 10 times limit? What could be the problem, in your opinion? I am using Windows 7 64 Bit and avast free antivirus. The program is written in c# 2008.
Here is the relevant code from program.cs:
 static class Program
{

    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        _hookID = SetHook(_proc);
        Application.Run(new Form1());
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);

            if ((Keys)vkCode == Keys.Delete)
            {
                Form1.staticmethod1();
            }
            else if ((Keys)vkCode == Keys.F8)
            {
                Form1.staticmethod2();
            }
            else if ((Keys)vkCode == Keys.F9)
            {
                Form1.staticmethod3();
            }

        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

Thanks in advance.


text:
Q: Table-driven test for file creation I got an example from @volker about table driven test like following
But currently I miss what I should put in the real test, this test is using byte, currently im not sure what to put in the args and the expected []byte,
e.g. I want to check that in the file there is 2 new line and then application entry, how can I do it without the need to create the real file and parse it?
type Models struct {
    name        string
    vtype       string
    contentType string
}

func setFile(file io.Writer, appStr Models) {
    fmt.Fprint(file, "1.0")

    fmt.Fprint(file, "Created-By: application generation process")
    for _, mod := range appStr.Modules {
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, "\n")
        fmt.Fprint(file,  appStr.vtype) //"userApp"
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, appStr.name) //"applicationValue"
        fmt.Fprint(file, "\n")
        fmt.Fprint(file, appStr.contentType)//"ContentType"
    }
}

func Test_setFile(t *testing.T) {
    type args struct {
        appStr models.App
    }
    var tests []struct {
        name string
        args args
        expected []byte
   }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            b := &bytes.Buffer{}
            setFile(b, tt.args.AppStr)
            if !bytes.Equal(b.Bytes(), tt.expected) {
                t.Error("somewhat bad happen")
            }
        })
    }
}

I read and understand the following example but not for byte and file
https://medium.com/@virup/how-to-write-concise-tests-table-driven-tests-ed672c502ae4

A: If you are only checking for the static content at the beginning, then you really only need one test. It would look something like this:
func Test_setFile(t *testing.T) {
    type args struct {
        appStr models.App
    }
    var tests []struct {
        name string
        args args
        expected []byte
    }{
        name: 'Test Static Content',
        args: args{appStr: 'Some String'},
        expected: []byte(fmt.Sprintf("%s%s%s", NEW_LINE, NEW_LINE, "Application")),
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            b := &bytes.Buffer{}
            setFile(b, tt.args.AppStr)
            if !bytes.Equal(b.Bytes(), tt.expected) {
                t.Error("somewhat bad happen")
            }
        })
    }
}

Although, since you only have one case for this test, there really isn't a need to use table driven tests here. You could clean it up to look something like this:
func Test_setFile(t *testing.T) {
    b := &bytes.Buffer{}
    setFile(b, 'Some String')
    want := []byte(fmt.Sprintf("%s%s%s", NEW_LINE, NEW_LINE, "Application"))
    got := b.Bytes()
    if !bytes.Equal(want, got) {
        t.Errorf("want: %s got: %s", want, got)
    }
}


text:
Q: Create a new JSON array that contain specific properties from another JSON I have this JSON array of objects
  "questions": [
  {
    "id": "id",
    "answer":"answer",
    "question_type": "q_type",
    "question": {
      "header":"Text",
      "question_image": "link",
      "answers_list": ["array"],
    }
  },
  {
    "id": "id",
    "answer":"answer",
    "question_type": "q_type",
    "question": {
      "header": "Text",
      "question_image": "link",
      "choices_type": "text",
      "choices": ["array"]
    }
  }
 ]

and i want to extract from this json another json that contain id and answer only like this
"answers": [{"question": question_id, "answer": "text"}]

A: You can use the JavaScript map function (assuming the variable q contains your questions object):
var out = q.questions.map(function(element) {
              return {"question": element.id, "answer": element.answer};
          });

A: Assuming both the question id and the answer are in the questions objects, then you could do it as follows:
var answers = [];

for(var i = 0; i < questions.length; i++)
{
    answers.push({
        question: questions[i].id,
        answer: questions[i].answer
    });
}

This also assumes you declare the questions array as var questions = ...

A: Here your json
var json = {"questions": [
  {
    "id": "id",
    "answe":"answer",
    "question_type": "q_type",
    "question": {
      "header":"Text",
      "question_image": "link",
      "answers_list": ["array"]
    }
  },
  {
    "id": "id",
    "answer":"answer",
    "question_type": "q_type",
    "question": {
      "header": "Text",
      "question_image": "link",
      "choices_type": "text",
      "choices": ["array"]
    }
  }
 ]}

Now iterate it and create a new Json object
var answers = []
var question = {}

json.questions.forEach(function(value, index){
    question.id = value.id;
    question.answer = value.answer;
    answers.push(question);

});

var resultJson = {};

resultJson.answers = answers;

A: var answers = questions.reduce(function (result, question){
    return result.concat(item.question.answers_list.map(function (answer) {
        return {
            question: {
                id: question.id
            },
            answer: answer
        }
    }));
}, []);

You'll need to 'map' question's data, because you'll need to be careful of circular references if you want to parse it to JSON.
But you specify all you want is the question.id. So that's no problem.

A: This will map your original JSON to the specified JSON. Uses a reviver function.

var json = '{"questions":[{"id":"id","answer":"answer","question_type":"q_type","question":{"header":"Text","question_image":"link","answers_list":["array"]}},{"id":"id","answer":"answer","question_type":"q_type","question":{"header":"Text","question_image":"link","choices_type":"text","choices":["array"]}}]}';

var keep = ['', 'questions', 'id', 'answer'];
var newJson = JSON.stringify(JSON.parse(json, function(k, v) {
  var idx = k && k == +k;
  if (idx || keep.indexOf(k) > -1) {
    if (idx && typeof v === 'object') {
      var id = v.id;
      delete v.id;
      v.question = id;
    }
    return v;
  }
}));
document.body.textContent = newJson;
console.log(newJson);


text:
Q: How To Create A High Performance Selectors [no jquery please] I m a JavaScript pure developer i design my own framework when i tested my selectors module i found a very big issue which is performance
in the selectors module i don't do a very complex selector like jquery i do a simple one
my big cause here when i run my selectors in some cases i have to get all elements on the body of the page and have to loop over them to get a specific kind of elements like TD elements for instance , note >>>> dont tell me use getElementsByTagName('TD') cause in my selectors i can make the developer select more than 1 tagName like
getElementsByTagNames('td,tr')

so in that case i have to get all and then loop over and pic only the needed items
i found that way is very performance eater in the other hand jquery have a hilarious speed to select items doesn't jquery do loops also or what so my main question here
how to do a high performed selectors using JavaScript
:)
thanks

A:
doesn't jquery do loops also or what

jQuery is smart enough to use an existing selector library (sizzle.js).
Sizzle is smart enough to let the browser do the work. document.querySelectorAll does the trick.
edit: actually, sizzle.js used to be inherent part of jquery, but is a separate project now

A: You can still use getElementsByTagName if you do something like this:
function getElementsByTagNames(elements) {
    elements = elements.split(",");
    var foundElements = [];
    for(var i = 0, len = elements.length; i<len; i++) {
        foundElements.push(document.getElementsByTagName(elements[i]));
    }
    return foundElements;
}

Now if you call getElementsByTagNames("tr,div"), an array containing all tr and div elements will be returned.


text:
Q: What happens to an IDisposable object after I return it? I have a C# function that flips the orientation of a DataSet:
static DataSet FlipDataSet(DataSet my_DataSet)
    {
        using (DataSet ds = new DataSet())
        {
            foreach (DataTable dt in my_DataSet.Tables)
            {
                DataTable table = new DataTable();
                for (int i = 0; i <= dt.Rows.Count; i++)
                {
                    table.Columns.Add(Convert.ToString(i));
                }
                DataRow r = null;
                for (int k = 0; k < dt.Columns.Count; k++)
                {
                    r = table.NewRow();
                    r[0] = dt.Columns[k].ToString();
                    for (int j = 1; j <= dt.Rows.Count; j++)
                        r[j] = dt.Rows[j - 1][k];
                    table.Rows.Add(r);
                }
                ds.Tables.Add(table);
                table.Dispose();
            }
            return ds;
        }
    }

I modified this code from a snippet I found on the interwebs to wrap the created DataSet in a using statement and explicitly dispose of the IDisposable objects it creates. My question is, what happens to the DataSet ("ds" in the above code) when it is returned, in terms of disposal? I cannot explicitly call .Dispose() on ds after I return it, obviously, so does .NET return the value and then dispose of it properly, or am I missing something entirely?

A: The ds DataSet will be disposed as soon as you leave the using block, so you'll be returning a disposed DataSet to the caller.
Why do you say that you can't call Dispose on the DataSet after you've returned it? I suspect that's exactly what you'll need to do.
Remove the using block from your FlipDataSet method and then dispose of the returned DataSet in the calling code, preferably by wrapping it in a using block.

A: As mentioned in another answer already, you will return a disposed dataset.  This is "A Bad Thing"TM.
I believe very strongly that every IDisposable should always be wrapped in a using block.  However, sometimes the trick is exactly where that using block goes.  For functions that return an IDisposable, you just create the object as normal.  The using block wraps the line the calls the function.

A: You already have some really good answer, but I want to present another persepective.
This is really a question of ownership. Whoever owns that DataSet is responsible for disposing it. But, who really owns it? In this case FlipDataSet creates the new instance but is transfering ownership because it returns that instance to the caller and does not continue to hold the reference itself. That means the lifetime management of the instance is now the caller's responsiblity.
It is beneficial to think in terms of ownership when generalizing this situation to other scenarios. Just because a property or method happens to return a IDisposable instance does not mean that it is transferring ownership. Ideally you would defer to that API's documentation for hints. However, in most of the cases I have seen there is an implication that if the instance is extracted from a property then that instance is still owned by the containing class and in that case it is not the callers responsiblity to manage lifetime. Likewise, if the instance is extracted from a method then it is usually the case that the method created that instance and makes no effort to continue holding a class reference to it and in that case it is the callers responsiblity to manage lifetime.

A: You probably don't want to do this. The DataSet is disposed when the using block exits regardless of how the block exits (normal exit, return, or thrown exception), meaning that the value you return will have been disposed and be mostly unusable to the caller.
The right thing to do is to not have a using block in this function. The using block should be in the caller.

A: As LukeH says, there is probably a bug in your current code. If you remove that using statement for the DataSet and return it, then it's up to the caller of your method to Dispose of it properly which is how it has to be since your code can't tell when it should be disposed off.

A: Even if your caller is disposing of the returned dataset by wrapping the function call inside a using statement, i think you should still have a try/catch block inside your function to ensure your dataset is disposed in the catch block and re-throw the exception if it happens.
The new DataTable() code however should be wrapped in a using statement


text:
Q: Как в Reacte js добавить полю input дополнительно список возможных адресов Мне нужно сделать поле инпут в которое можно в водить адрес, после чего у меня отправляется запрос на яндекс апи карт и возвращается список адресов, при клики на который данные будут переданы в input и зафиксированы.
В официальной документации https://ru.react.js.org/docs/forms.html есть вариант как сделать просто список, но в поле я не могу  в вести адрес, поскольку список стал фиксированный.

A: В вашем случае логика довольно проста:

*

*Создайте ваш input.

*Храните его value в каком либо состоянии, к примеру используя хук useState().

*Создайте функцию-обработчик, которая будет реагировать на событие onChange вашего input, изменяя состояние, созданное с помощью useState() на value, что будет получено этой функцией.

*Передайте её в атрибут onChange вашего input.

Готово. Вы создали свой управляемый компонент. Теперь вы можете использовать значение, хранимое в состоянии для ваших нужд (к примеру запросов на сервер, etc.).
Для создания сложных форм рекомендую использовать вспомогательные библиотеки, к примеру Formik.


text:
Q: Where in your pipeline does a company that does X+ of deployments per day deal with running E2E/UA Tests The ideal goal for my system is the ability to perform an arbitrary number of deployments per day to production while making sure each 'push' goes through the full test suite to make sure it holds up to our specifications/user stories.
This is a manageable challenge with Integration / Unit tests which usually are rock solid but fails to be reasonable when I try to test E2E tests which are notoriously flakey (and sometimes fail due to unknown circumstances).
I often use E2E testing to test full User stories using NightwatchJS. A typical test may start from a login and consisting of a sequence of complicated steps which are executed in order. I try my best to make sure all E2E tests are as small as possible (so when they fail other user stories are not skipped) but I am still subject to often random test failures which make running them as part of the deployment pipeline a no-go.
I therefore have a few questions about how other organizations who acheive multiple deployments per day run manage testing in their deployment pipeline:

*

*What rate of failure do you find for your E2E testing suite? How do you work as a team to improve it

*At what stage of the deployment do you run E2E tests: Automatically before merges to master? Manually? Does a small backend change result in a E2E suite run? How long does it extend your deployment pipeline by?

*Does an E2E test failure equal a deployment failure?

*In what environment do you run E2E tests, on local development machines? in QA servers? on shared development environments? on Staging?

I'm really interested in finding out at what point your E2E test suites run and what levels of flakiness you experience. Any input would be great!
Cheers
Deepak


text:
Q: Retrieving RSSI values from all devices connected to network I'm building an application that lists the hostnames of devices connected to the network and their corresponding RSSI values. Is there any way I can collect this information for each network device?
I was able to use the WLAN API (I'm on Windows) in Python to get the RSSI values for nearby wireless LAN networks, but I want to get that information for each device connected to the network. I also tried using the scapy module in Python, but I was only able to get the hostnames, not the RSSI values.
I've done a lot of digging and haven't found a definitive answer to this. Just looking for some direction. Is this possible?

A: Here is an idea based on one approach you seem to have pursued.
Code will collect the signal strength using one station as a monitoring station.
To run correctly on a Macbook you need to disconnect the interface from the network before running.
Here is sample output (x added to obscure mac addresses):
x4:x9:x2:ed:03:39 -78
x4:xd:x1:55:e8:de -86
x0:xa:x6:13:e6:ac -78
x8:x3:xd:63:b6:85 -87
x0:x8:xa:04:24:a2 -78
x0:x1:x6:d2:2a:65 -88

from scapy.all import *

conf.use_pcap=True

maxrssi = {}

def callBack(pkt):
    # print(pkt.show())
    if pkt.haslayer(Dot11):
        key = None
        if not pkt.FCfield.to_DS and pkt.FCfield.from_DS:
            if pkt.addr3 is not None:
                key = pkt.addr3
        else:
            if pkt.addr2 is not None:
                key = pkt.addr2
        if key is not None:
            if key in maxrssi.keys():
                if maxrssi[key] < pkt.dBm_AntSignal:
                    maxrssi[key] = pkt.dBm_AntSignal
                    #print("NEW MAX for ", key, maxrssi[key]);
            else:
                maxrssi[key] = pkt.dBm_AntSignal
                #print("NEW MAX for ", key, maxrssi[key]);

sniff(iface='en0', monitor='True', prn=callBack, count=200)
for sta in maxrssi:
    print(sta, maxrssi[sta])

Suggesting, because another user recently asked how to get RSSI using python


text:
Q: Verificar se o valor está contido no Range Jquery/Javascript Como verificar se o valor 15 está dentro do range ?
var range = [10, 50];

var valor = 15

A: A variável range não é um range, é um array com dois valores.
Assim sendo, só é necessário fazer uma operação de comparação comum.
Para incluir os extremos use >= e <=, caso contrário use < e >.

var range = [10, 50];
var valor = 15;

if(valor >= range[0] && valor <= range[1]) {
  console.log('está dentro do range');
}

A: Uma outra forma é com a expressão:
(valor-range[0])*(valor-range[1]) <= 0
          ↓                ↓
       1º valor         2º valor
       da array         da array

Seria:
(15-10) * (15-50) <= 0
5 * -35 <= 0
-175 <= 0 // verdadeiro, está no range

Se o resultado da expressão for igual ou menor a zero, está no
  range.

Testes:

var range  = [10, 50];
var valor  = 15;

var valor2 = 9;
var valor3 = 51

if( (valor-range[0])*(valor-range[1]) <= 0 ){
  console.log(valor+' está dentro do range');
}else{
  console.log(valor+' não está dentro do range');
}

if( (valor2-range[0])*(valor2-range[1]) <= 0 ){
  console.log(valor2+' está dentro do range');
}else{
  console.log(valor2+' não está dentro do range');
}

if( (valor3-range[0])*(valor3-range[1]) <= 0 ){
  console.log(valor3+' está dentro do range');
}else{
  console.log(valor3+' não está dentro do range');
}

A:

//Range
var range = [10, 50];

//Range invertido - para teste
//var range = [1000, 50];

//Valores para teste
var valor1 = 15;
var valor2 = 150;

//Limites
var menor = range[0];
var maior = range[1];

//Teste de range invertido!
//Caso os números estejam invertidos - não formando range
if(menor>maior){
  menor = range[1];
  maior = range[0];
}

//Testes

//Teste 1
document.getElementById('resposta1').innerHTML = //Insere a resposta no DIV1
  valor1 + ": "
  + (valor1>=menor && valor1<=maior?'Sim!':'Não!'); //Teste com if ternário - comparação dos limites com o valor 1

//Teste 2
document.getElementById('resposta2').innerHTML = //Insere a resposta no DIV2
  valor2 + ": "
  + (valor2>=menor && valor2<=maior?'Sim!':'Não!'); //Teste com if ternário - comparação dos limites com o valor 2

-

-


text:
Q: New windows covered by top panel After update from 11.04 to 11.10 I experience a disturbing bug:
New windows are always positioned at the top of the screen behind the top panel instead of being aligned to the bottom of the panel.
It could seem to be a minor bug, but it is really disturbing to hunt the window panel anytime I want move the window. Is there any quick fix/settings available?
Thanks
PS: I wanted to attach screenshots, but the system don't let me.

A: Answer approved by OP in comments.

Have you tried CompizConfigSettingsManager-> Windows Management-> Place
  Windows ? I have this happening in 11.04 with a third Writer document
  window opening above the first Writer document window and hence, under
  the top panel. This did not happen (to me) in 11.10 which I have been
  using since beta 2 so I never tried finding a permenant fix.


text:
Q: Need help understanding "An Image Signature for any Kind of Image" I'm trying to implement the paper titled An Image Signature for any Kind of Image, but I'm having trouble understanding what they mean in this paragraph:

For each column of
  the image, we compute the sum of absolute values of differences between adjacent pixels in that column. We compute
  the total of all columns, and crop the image at the 5% and
  95% columns, that is, the columns such that 5% of the total
  sum of differences lies on either side of the cropped image.
  We crop the rows of the image the same way (using the sums
  of original uncropped rows).

First, what do they mean by "sum of absolute values of differences between adjacent pixels in that column"? If start at the top-left pixel and work downwards (down the column), we can compute the difference between (0,0) and (0,1), but what about the next pixel? Am I supposed to compute the difference with just the pixel below, or the pixels on either side, or perhaps even the 4 or 8 neighbours?
And then, as I understand it, we sum these differences for each column such that each column is reduced to a single number?
Then we use this information to crop the left and right edges of the photo, right?

A: I didn't read your link, but from your question...
"Sum of absolute values of differences between adjacent pixels in that column":
sum = abs(pix1 - pix2) + abs(pix2 - pix3) + ...

You perform this computation for pixels 1 and 2 in the column, then 2 and 3, and so on. Do this for every column. Then sum all of the column sums together.
Start a new sum, adding column sums from the left. Once that new sum gets over 0.05 * sum_of_all_columns, you've passed the 5% threshold and know which column to crop at on the left side. Do the same thing on the right side going the other direction.
Basically they're looking to automatically crop out edges of the image that have no interesting features.


text:
Q: Examples of solving a problem by introducing new parameters First let's see some examples:

*

*I've seen a lot of examples of calculating the definite integrals by introducing a suitable parameter, but still cannot understand why this method so effective, while calculating the integral directly could be incredibly difficult.

*I remember that in linear algebra we can prove the following fact by introducing a new parameter $x$:

Fact: For any $A,B\in M_n(\mathbb R),$ we have $\chi_{A\cdot B}(t)=\chi_{B\cdot A} (t).$

Here for any $A\in M(\mathbb R),$ $\chi_A(t):=\det(tE-A)$ is the characteristic polynomial of matrix $A,$ and $E$ is the identity matrix in $M_n(\mathbb R).$

Proof: If at least ome of $A,B$ is non-degenerate, for example, assume that $A$ is non-degenerate, then we have $$\chi_{AB}(t)=\det(tE-AB)=\det(A\cdot(tE-BA)\cdot A^{-1})=\det(tE-BA)=\chi_{BA}(t).$$
Now if both  $A$ and $B$ are degenerate,  then we can find that since polynimal $f(x)=\det(A+xE)$ only have finite roots, and $f(0)=\det A=0,$ then there exists a deleted neighbourhood $U(0)$ of $0,$  such that $f(x)\neq 0,\ \forall\ x\in U(0).$
Denote the real coefficient polynomial ring as $\mathbb R[t],$ then notice that map $\varphi:\mathbb R\to \mathbb R[t],\ x\mapsto \chi_{(A+xE)B}(t)-\chi_{B(A+xE)}(t)$
is continuous, and $\varphi(x)=0,\ \forall\ x\in U(0),$ so we have $\varphi(0)=0,$ or $\chi_{A\cdot B}(t)=\chi_{B\cdot A} (t).$
End of proof

*Another interesting example: https://math.stackexchange.com/q/1395378
I'm really interested in the motivation of introducing the new parameter  and would like to see more examples of solving problems through introducing a new parameter.
Question:  Give (as many as possible) examples of solving or simplifying a problem by introducing new parameters. Also, explanation of why it works is also welcomed.

A: (I will adopt the convention of giving different responses in different answers, labeled community wiki.)
Here's an example I quite like. The problem is to prove that the following definitions of $e$ are equivalent:

*

*The unique positive real $e$ such that $\displaystyle \ln e = \int_1^e \frac{dt}{t} = 1$.

*$\displaystyle \sum_{n=0}^{\infty} \frac{1}{n!}$

*$\displaystyle \lim_{n \to \infty} \left( 1 + \frac{1}{n} \right)^n$.

The easiest way to approach this is to generalize it to proving that the following definitions of $e^x$ (introducing the new parameter $x$) are equivalent:

*

*The unique positive real $e^x$ such that $\displaystyle \ln e^x = \int_1^{e^x} \frac{dt}{t} = x$.

*$\displaystyle \sum_{n=0}^{\infty} \frac{x^n}{n!}$.

*$\displaystyle \lim_{n \to \infty} \left( 1 + \frac{x}{n} \right)^n$.

The reason is that we now have the freedom to differentiate with respect to $x$, and introduce a fourth equivalent definition:

*The unique function $e^x$ such that $\displaystyle \frac{d}{dx} e^x = e^x$ and $e^0 = 1$.

Once you've established that there is indeed a unique function with these properties, which is not hard, showing that the other three definitions give the same function amounts to showing that they all satisfy these properties, which just involves differentiating all of the definitions above with respect to $x$.
To my mind, this also explains what the point of $e$ is: it's really $e^x$ that is consistently the star player in mathematics, and $e$ just happens to be its value at $x = 1$.
Another nice exercise from here is to use definition 4 to prove the exponential property $e^{x + y} = e^x e^y$. This can be done from any of the other three definitions but it's tedious to do it directly from either definitions 2 or 3, although not bad with definition 1.

A: A fact from the theory of continued fractions:

Let $$\frac{p_n}{q_n} = a_0 + \frac{1}{a_1 + \frac{1}{\ddots \frac{1}{a_n}}} $$
  in lowest terms, where $a_0, a_1, \ldots$ are positive integers.  Then for each $n$, $$p_n q_{n+1} - p_{n+1} q_n = (-1)^{n+1}.$$
  It follows that $$\frac{p_{n+1}}{q_{n+1}} - \frac{p_n}{q_n} = \frac{(-1)^n}{q_n q_{n+1}}.$$

My favorite proof of this involves introducing an extra variable $x$ and defining
$$ f_n(x) = a_0 + \frac{1}{a_1 + \frac{1}{ \ddots \frac{1}{a_n + x}}}. $$
Then, if you work a few examples, you are naturally led to the conjecture that $f_n(x) = \frac{p_n + p_{n-1} x}{q_n + q_{n-1} x}$.  The point of introducing the extra variable of $x$ is that it allows you to substitute on the very inside:
$$ f_{n+1}(x) = f_n\left(\frac{1}{a_{n+1} + x}\right). $$
This allows you to express $p_{n+1}$ and $q_{n+1}$ in terms of $a_{n+1}$, $p_n$, $p_{n-1}$, $q_n$, $q_{n-1}$, and then from there it becomes straightforward to show the desired result by induction.  Whereas with the original continued fraction, but without this trick, it would appear to be necessary to start over the calculations for $\frac{p_n}{q_n}$ for each new value of $n$, which would make it very difficult to try to find relations between the various $p_n$ and $q_n$.
(Actually, once you've done the work above, you're still left with a gap: you don't know whether $\frac{p_n}{q_n}$ is actually a fraction in lowest terms.  The equation $p_n q_{n+1} - p_{n+1} q_n = (-1)^{n+1}$ would imply that $p_n$ and $q_n$ are relatively prime; however, at this point, we have what appears to be a circular argument.  To correct the circular dependencies, the final proof technically goes: define sequences $p_n$ and $q_n$ by the recursion relations you found using the argument above.  Then by induction, $f_n(x) = \frac{p_n + p_{n-1} x}{q_n + q_{n-1} x}$ and $p_n q_{n+1} - p_{n+1} q_n = (-1)^{n+1}$.  Now the latter equation implies that $p_n$ and $q_n$ are relatively prime, and therefore we conclude that $\frac{p_n}{q_n} = f_n(0)$ is indeed the lowest terms representation of the $n$th partial term of the continued fraction.)

A: Shortest path algorithms. The aim is to find the shortest path from $s$ (for source) to some $v$, where $s$ and $v$ are vertices in a weighted directed graph. All the algorithms below solve this problem by way of solving a more general problem.
Examples:
Bellman-Ford: Find the shortest path between vertex $s$ to every other vertex $v$ which has at most $k$ edges. The algorithm uses the fact that once the answer is known for $k$ then it's easy to find it for $k+1$.
Dijkstra's algorithm: Find the $k$ closest vertices to vertex $s$. Again, if the answer is known for $k$ then it's easier to find it for $k+1$.

All pairs shortest path. The aim is to output a matrix that gives the shortest path between every pair of vertices.
Examples:
Floyd-Warshall: Find the shortest path between every pair of vertices, subject to the constraint that all the intermediate vertices in the paths are limited to $\{1,\dotsc,k\}$. Keep increasing $k$. See also Kleene's algorithm for turning a finite automaton into a regular expression.

A: In Littlewood's highly entertaining
"A Mathematician's Miscellany",
on page 21,
he writes about a theorem
due to M. Riesz
for which
an elegant proof
(G. Thorin ("Convexity Theorems",
 Communications
du seminaire mathematique de l'Universite de Lund, 9))
involves
nested upper bounds
and the innermost upper bound
is taken
with respect to a variable that is not there.
In the proof,
an upper bound
with respect to a real $\sigma$
has
$\sigma$
replaced by
$s+it$
and a new upper bound is
inserted that is
taken with respect to $t$.

A:
I've seen a lot of examples of calculating the definite integrals by introducing a suitable parameter, but still cannot understand why this method so effective, while calculating the integral directly could be incredibly difficult.

I want to point out that even when you calculate a definite integral "directly" you are often still doing it by implicitly introducing a parameter. Every time you compute a definite integral by computing an indefinite integral by computing an antiderivative you are introducing a new parameter, namely the bounds of the indefinite integral. The reason you do this is so you can differentiate with respect to your new parameter, and then apply the fundamental theorem of calculus.
So let me take a moment to philosophize about why this works so well. The point is that understanding a mathematical statement or object in isolation is often hard, but understanding it in the context of a family of objects is often much easier, because you can leverage relationships between the objects to use your understanding of some of them to understand the others. This is a very general principle and extends far beyond integrals. It may seem like you are getting away with something or doing too little work but the work goes into choosing a suitable family.
A simple example of this is using induction to prove a whole sequence $P(n)$ of statements even if you originally only wanted to prove, say, $P(10)$; the reason you introduce the parameter $n$ is so you can leverage your understanding of $P(0)$ to understand $P(1)$, etc.
Similarly when you introduce a parameter into an integral you are converting what used to be an isolated integral $I$ into a parametric family of integrals $I(t)$, and now you can try to understand how this family behaves as a function of $t$, e.g. see if it satisfies any differential equations. If it does, you can do a kind of "continuous induction" in the parameter $t$, as in the definition of $e^x$ as the unique function satisfying $\frac{d}{dx} e^x = e^x$ and $e^0 = 1$, and leverage your understanding of, say,  $I(0)$ to understand $I(t)$ for any $t$, and hence to understand $I(1)$ or whatever your original integral was.


text:
Q: Python: How to round numbers smaller than 1 adaptively with specified precision? I usually use
x = round(x, 3)

to round a number to the precision of 3 digits. Now I have this array:
[-1.10882605e-04 -2.01874994e-05  3.24209095e-05 -1.56917988e-05
 -4.61406358e-05  1.99080610e-05  7.04079594e-05  2.64600122e-05
 -3.53022316e-05  1.50542793e-05]

And using the same code just flattens everything down to 0. What I would like to have though is a function that gives me the most significant 3 digits rounded like it usually works for numbers larger than 1. Like this:
special_round(0.00034567, 3)
=
0.000346

Any idea how this could be done? Thanks!

A: Here is a solution that figures out the order of magnitude and does an elment wise rounding.
Note that this will only work correctly for values < 1 and > -1, which I guess is a valid assumption regarding your example data.
import numpy as np
a = np.array([-1.10882605e-04, -2.01874994e-05,  3.24209095e-05, -1.56917988e-05,
 -4.61406358e-05,  1.99080610e-05,  7.04079594e-05 , 2.64600122e-05,
 -3.53022316e-05 , 1.50542793e-05])

def special_round(vec):
  exponents = np.floor(np.log10(np.abs(vec))).astype(int)
  return np.stack([np.round(v, decimals=-e+3) for v, e in zip(vec, exponents)])

b = special_round(a)
>>> array([-1.109e-04, -2.019e-05,  3.242e-05, -1.569e-05, -4.614e-05,
        1.991e-05,  7.041e-05,  2.646e-05, -3.530e-05,  1.505e-05])

A: Problem is, numbers you provided are starting to be so small that you are approaching limit of floating point precision, thus some artifacts show up seemingly for no reason.
def special_round(number, precision):
    negative = number < 0
    number = abs(number)
    i = 0
    while number <= 1 or number >= 10:
        if number <= 1:
            i += 1
            number *= 10
        else:
            i += -1
            number /= 10
    rounded = round(number, precision)
    if negative:
        rounded = -rounded
    return rounded * (10 ** -i)

Output:
[-0.0001109, -2.019e-05, 3.2420000000000005e-05, -1.569e-05, -4.614e-05, 1.9910000000000004e-05, 7.041000000000001e-05, 2.646e-05, -3.5300000000000004e-05, 1.505e-05]

A: You can do so by creating a specific function using the math package:
from math import log10 , floor
import numpy as np

def round_it(x, sig):
    return round(x, sig-int(floor(log10(abs(x))))-1)

a = np.array([-1.10882605e-04, -2.01874994e-05,  3.24209095e-05, -1.56917988e-05,
              -4.61406358e-05,  1.99080610e-05,  7.04079594e-05,  2.64600122e-05,
              -3.53022316e-05,  1.50542793e-05])
round_it_np = np.vectorize(round_it)  # vectorize the function to apply on numpy array
round_it_np(a, 3)  # 3 is rounding with 3 significant digits

This will result in
array([-1.11e-04, -2.02e-05,  3.24e-05, -1.57e-05, -4.61e-05,  1.99e-05,
    7.04e-05,  2.65e-05, -3.53e-05,  1.51e-05])

A: Here is a solution:
from math import log10, ceil

def special_round(x, n) :
    lx = log10(abs(x))
    if lx >= 0 : return round(x, n)
    return round(x, n-ceil(lx))

for x in [10.23456, 1.23456, 0.23456, 0.023456, 0.0023456] :
    print (x, special_round(x, 3))
    print (-x, special_round(-x, 3))

Output:
10.23456 10.235
-10.23456 -10.235
1.23456 1.235
-1.23456 -1.235
0.23456 0.235
-0.23456 -0.235
0.023456 0.0235
-0.023456 -0.0235
0.0023456 0.00235
-0.0023456 -0.00235

A: You can use the common logarithm (provided by the built-in math module) to calculate the position of the first significant digit in your number (with 2 representing the hundreds, 1 representing the tens, 0 representing the ones, -1 representing the 0.x, -2 representing the 0.0x and so on...). Knowing the position of the first significant digit, you can use it to properly round the number.
import math

def special_round(n, significant_digits=0):
    first_significant_digit = math.ceil((math.log10(abs(n))))
    round_digits = significant_digits - first_significant_digit
    return round(n, round_digits)

>>> special_round(0.00034567, 3)
>>> 0.000346


text:
Q: Apache Camel JMS: "Not allowed to create destination" when trying to connect to a queue I am trying to setup a route in Camel that reads messages from a JMS queue.
The application uses Tibco and I am not allowed to post here any of the data, but the path for the factory and the queue follows the format /path/to/queueName:type, where type can be qcf (Queue Connection Factory) and queue.
I am using the Spring-DSL, the XML is:
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">...</prop>
            <prop key="java.naming.provider.url">...LDAP Server URL...</prop>
            <prop key="java.naming.referral">follow</prop>
            <prop key="java.naming.security.credentials">...</prop>
            <prop key="java.naming.security.principal">uid=...,ou=...,dc=...,dc=...</prop>
        </props>
    </property>
</bean>

<bean id="jmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate"/>
    <property name="jndiName" value="/path/to/queueConnectionFactory:qcf"/>
</bean>

<bean id="authenticatedConnectionFactory" class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
    <property name="targetConnectionFactory" ref="jmsQueueConnectionFactory"/>
    <property name="username" value="..."/>
    <property name="password" value="..."/>
</bean>

<bean id="testjms" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory" ref="authenticatedConnectionFactory"/>
</bean>

<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
    <route id="jmsRouteTest">
        <from uri="testjms:queue:/path/to/queue:queue" />
        <to uri="file:c:\inbox?fileName=jmsMessage.txt" />
    </route>
</camelContext>

While the application is running it keeps throwing the following lines in the log:
12:41:19:385 - WARN - DefaultMessageListenerContainer - Setup of JMS message listener invoker failed for destination 'path/to/queue:queue' - trying to recover. Cause: Not allowed to create destination
12:41:20:494 - INFO - DefaultMessageListenerContainer - Successfully refreshed JMS Connection

One thing to notice is that the first slash "/" for the destination disappears, but if I remove the "queue:" from the URI the same error occurs, but the destination becomes '/path/to/queue:queue'.
I have searched for this error and find a question here on stackoverflow:
Does anyone know exactly what javax.jms.InvalidDestinationException: Not allowed to create destination means?
Just to be sure that the configuration is correct, I have created the following class (copying the exact same settings from Spring XML to the class):
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import java.io.*;

public class Test {

public static void main(String[] args) throws Exception {
    Properties properties = new Properties();

    properties.put("java.naming.provider.url", "...LDAP Server URL...");
    properties.put("java.naming.factory.initial", "...");
    properties.put("java.naming.referral", "follow");
    properties.put("java.naming.security.principal", "uid=...,ou=...,dc=...,dc=...");
    properties.put("java.naming.security.credentials", "...");
    properties.put("JmsConnectionFactory", "/path/to/queueConnectionFactory:qcf");
    properties.put("JmsDestinationName", "/path/to/queue:queue");
    properties.put("JmsUserName", "...");
    properties.put("JmsPassword", "...");

    Context context = null;
    QueueConnection connection = null;
    QueueSession session = null;
    QueueReceiver receiver = null;

    context = new InitialContext(properties);

    Queue queue = (Queue) context.lookup((String) properties.get("JmsDestinationName"));
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup((String) properties.get("JmsConnectionFactory"));

    connection = queueConnectionFactory.createQueueConnection((String) properties.getProperty("JmsUserName"),
                                                              properties.getProperty("JmsPassword"));

    session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

    connection.start();

    receiver = session.createReceiver(queue);

    while (true) {
        TextMessage message = (TextMessage) receiver.receive();

        System.out.println("Received: " + message.getText());

        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        if ("b".equals(s)) {
            break;
        }
    }

    connection.close();
}

}

With this class I am able to read the messages that are in the queue.
Have anyone experienced this problem before?
Please let me know if you guys need more information.
Thank you.

A: Sounds like you need to have some Tibco Admin guy to create that queue on the Tibco message broker first.

A: Thank you for the help, but the solution was really simple.
I have downloaded the source codes to debug and ended up in a Spring class named DefaultMessageListenerContainer, the exception was thrown when the createConsumer method was called in the session.
This led me to a topic in Spring forum http://forum.spring.io/forum/spring-projects/integration/jms/129634-dbus-jms-message-listener-javax-jms-jmssecurityexception-not-permitted
Basically it says that in order to prevent this error JNDI should be used to get the destination instead of session.createQueue().
Then I searched for a way to use a JNDI name in the endpoint URI and found http://camel.465427.n5.nabble.com/JMS-queue-JNDI-instead-of-physical-name-td494620.html
Which basically tells that a destination resolver is needed. Adding it resolved the error.
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop...</prop>
        </props>
    </property>
</bean>

<bean id="jmsQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jndiTemplate"/>
    <property name="jndiName" value="..."/>
</bean>

<bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.JndiDestinationResolver">
    <property name="jndiTemplate" ref="jndiTemplate" />
    <property name="cache" value="true" />
</bean>

<bean id="testjms" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
    <property name="destinationResolver" ref="jmsDestinationResolver" />
</bean>

<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">
    <route id="testRoute">
        <from uri="testjms:jmsJNDIName?connectionFactory=jmsQueueConnectionFactory&username=...&password=..." />
        <to uri="file:C:\inbox" />
    </route>
</camelContext>

tl;dr - Use JNDI to get the queue and specify a destination resolver.

A: The name of the createQueue method is misleading. It's not intended to actually create the queue itself, but merely a Queue object referencing an already existing queue (look at the Javadoc).
JMS doesn't provide any API to create (non-temporary) queues. This is why you have to create the queue by other means (generally some administration tool) and then look it up in JNDI.
But some JMS providers "misuse" this method to auto-create the queue when needed, making it non-portable to a different JMS provider. This was merely documented to be allowed in JMS 2.0


text:
Q: How to generate PublicKey for PrivateKey in X25519? I'm working with X25519-keys based encryption at the moment.
My question is, basically, how to derive PublicKey from existing X25519 PrivateKey?
I've tried the following:
    protected PublicKey generatePublicKeyFromPrivate(PrivateKey privateKey) throws GeneralSecurityException {
        PublicKey basePublicKey = generatePublicKey(BigInteger.valueOf(9));
        KeyAgreement keyAgreement = KeyAgreement.getInstance(X25519);
        keyAgreement.init(privateKey, new ECGenParameterSpec(X25519));
        keyAgreement.doPhase(basePublicKey, true);
        byte[] bytes = keyAgreement.generateSecret();
        return generatePublicKey(new BigInteger(bytes));
    }

PublicKey is successfully generated. And I even compared this approach with the third-party library approach (Google Tink): generated PubliKeys match.
However, when I try to use Java's KeyPairGenerator to get both PrivateKey and PubliKey at once and then try to generate a PublicKey for that PrivateKey myself, they differ.
    public KeyPair generateX25519KeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(X25519);
        return keyPairGenerator.generateKeyPair();
    }

I decided to look up the source code of the KeyPairGenerator (XDHKeyPairGenerator implementation) and found the part when they do multiplication:
    /**
     *
     * Multiply an encoded scalar with a point as a BigInteger and return an
     * encoded point. The array k holding the scalar will be pruned by
     * modifying it in place.
     *
     * @param k an encoded scalar
     * @param u the u-coordinate of a point as a BigInteger
     * @return the encoded product
     */
    public byte[] encodedPointMultiply(byte[] k, BigInteger u) {
        pruneK(k);
        ImmutableIntegerModuloP elemU = field.getElement(u);
        return pointMultiply(k, elemU).asByteArray(params.getBytes());
    }

However, the method that is used to separately generate PubliKey uses another multiplication:
    /**
     * Compute a public key from an encoded private key. This method will
     * modify the supplied array in order to prune it.
     */
    public BigInteger computePublic(byte[] k) {
        pruneK(k);
        return pointMultiply(k, this.basePoint).asBigInteger();
    }

As you can see, the difference is that in the first case they apply the asByteArray() method to the result:
     * Returns the little-endian encoding of this' % 2^(8 * len), where this'
     * is the canonical integer value equivalent to this.
     *
     * @param len the length of the desired array
     * @return a byte array of length len containing the result
     */
    default byte[] asByteArray(int len) {
        byte[] result = new byte[len];
        asByteArray(result);
        return result;
    }

So my question really is: why do they do so? Why this "little-endian encoding" is applied to the PublicKey when the KeyPairGenerator is being used, but it's not applied when the PublicKey is derived from the PrivateKey separately.

A: The public key is computed by multiplying the base point by the "clamped" secret scalar and returning the encoded X coordinate.
Clamping means masking the 3 least significant bits, masking the top bit, and setting the second top bit.
See RFC7748 for details.
But looks like this is more of a programming question, and the actual issue may not have anything to do with X25519. For a given secret, compare the output you get from that code with the same operation implemented with a different library. If the public keys match, the issue is somewhere else.


text:
Q: Python variable confusion I new to Python and I am reading about Quickselect algorithm and found some helpful code.
I do not understand how pivotIndex is declared twice and not over written.
I would like some clarification on how Python is not over writing pivotIndex.
I removed the second declaration of pivotIndex and I receive random output.
def qselect(k, array):
    n = k-1

    def partition(left, right, pivotIndex):
        pivotValue = array[pivotIndex]

        array[pivotIndex], array[right] = array[right], array[pivotIndex]
        storeIndex = left
        for i in range(left, right):
            if array[i] < pivotValue:
                array[storeIndex], array[i] = array[i], array[storeIndex]
                storeIndex += 1

        array[right], array[storeIndex] = array[storeIndex], array[right]
        return storeIndex

    def select(left, right):
        if left == right:
            return array[left]
        pivotIndex = random.randint(left, right)
        pivotIndex = partition(left, right, pivotIndex)

        if n == pivotIndex:
            return array[n]
        elif n < pivotIndex:
            return select(left, pivotIndex-1)
        else:
            return select(pivotIndex+1, right)

    return select(0, len(array)-1)

A: It is overwritten.
pivotIndex = random.randint(left, right)
pivotIndex = partition(left, right, pivotIndex)

Here what happens is that we find a random value for pivotIndex within the range of the values of left and right.
we use that value as a parameter to the function partition and assign the returned value to pivotIndex.


text:
Q: How to map multipolygons from a json file that has multiple attributes in Python Hey I want to map all districts of Berlin and found a json file that contains all GPS Data as Multipolygons. Now I am struggling with plotting these datas on a map.

I managed to read them and created a table with the json data. But I cannot work with this format.
charlottenburg = BerlinMap[(BerlinMap['id'] == 404538)]
charlottenburg

    print(charlottenburg.geometry['coordinates'].contains((52.51141, 13.30211)))
But I only get this Error:

--------------------------------------------------------------------------- KeyError                                  Traceback (most recent call
    last)  in
    ----> 1 print(charlottenburg.geometry['coordinates'].contains((52.51141,
    13.30211)))

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/series.py
  in getitem(self, key)    1069         key =
  com.apply_if_callable(key, self)    1070         try:
  -> 1071             result = self.index.get_value(self, key)    1072     1073             if not is_scalar(result):
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pandas/core/indexes/base.py
  in get_value(self, series, key)    4728         k =
  self._convert_scalar_indexer(k, kind="getitem")    4729         try:
  -> 4730             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))    4731         except KeyError
  as e1:    4732             if len(self) > 0 and (self.holds_integer()
  or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index_class_helper.pxi in
  pandas._libs.index.Int64Engine._check_type()
KeyError: 'coordinates'

What I want is to create something like this:
https://gist.github.com/chaudum/e8097ab9873ec71666b2


text:
Q: How to change a word's color in td (jquery) How to change Weekend's color to blue?
I'm using razor and I have a flag-enum which can directly convert to string like this:
var a = 1|2|6|7;
var weekdayStr=a.ToString();//weekdayStr=="Monday, Tuesday, Weekend"

And the html:

Monday, Tuesday, Weekend

How do I only change one word's color, not all text in td?

A: You'll have to either manually add an html tag, or find the td and modify it with jQuery.
$('td').html($('td').html().replace('Weekend', 'Weekend'));
$('td span').css('color', 'blue');

Something like this fiddle
UPDATE:
new jsFiddle

A: $(document).ready(function(){
  var build = '';
  var data = $('#yourtd_id').html().split(',');
  $.each(data,function(v){
         if(v == 'Weekend'){
          build+=''+v+',';
         }else{
          build+=''+v+',';
         }

  });
$('#yourtd_id').html(build)

});

A:  $.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
  var node = this.firstChild,
    val,
    new_val,
    remove = [];
  if ( node ) {
    do {
      if ( node.nodeType === 3 ) {
        val = node.nodeValue;
        new_val = val.replace( search, replace );
        if ( new_val !== val ) {
          if ( !text_only && /</.test( new_val ) ) {
            $(node).before( new_val );
            remove.push( node );
          } else {
            node.nodeValue = new_val;
          }
        }
      }
    } while ( node = node.nextSibling );
  }
  remove.length && $(remove).remove();
});
};

$("td").replaceText( /Weekend/g, "Weekend" );
$('td span').css('color', 'blue');

reference from


text:
Q: Sony Camera Api on Android Wear I created a Android Wear application that can control a supported Sony Camera using the Sony Camera Api. I got it all working(recoring, liveview etc.), so i wanted to focus on the "connecting" thing.
As said in the following question i connect to the Sony Camera using a hardcoded ip-address because UDB Multicast is not supported on Android Wear:
Using Sony Camera API on AndroidWear
I know this is not best practice, so i wanted to know if there is something else then SSDP to get the ip-address from the Sony Camera.
Is there a list of ip-addresses per device, or is there a another protocol to find out, or will it be soon supported in Android Wear? Questions i can not answer.

A: Not a direct answer to your question, but the alternative to using SSDP on the watch is to use it on the phone.
You would of course, use the paired smartphone to discover the camera using SSDP. And, the smartphone would share the camera's URL with the watch.


text:
Q: Why does the cat command only read from the first file descriptor? From the console, I've created 2 empty files, and I tried to read them simultaneously.
$ echo -n '' | tee f1 > f2
$ cat f1 f2
$ cat <(tail -f f1) <(tail -f ./f2)

On the other console I've run my tests.
$ echo 'tee test' | tee -a f1 >> f2
$ echo 'f1 test' >> f1
$ echo 'f2 test' >> f2
$ cat f1 f2
tee test
f1 test
tee test
f2 test

However, cat on the first console only read outputs from the first fd.
$ cat <(tail -F ./f1) <(tail -F ./f2)
tee test
f1 test

Why? How do I then read simultaneously from two or more file descriptors?

A: cat processes its arguments sequentially; tail -f f1 continues running, so cat keeps waiting for input on <(tail -f f1), and doesn't move on to processing <(tail -f f2).
You'll see the output from tail -f f2 if you kill the first tail.
A better tool to track multiple files simultaneously is tail itself (at least, GNU tail):
tail -f f1 f2

If you don't want to see file headers, use -q:
tail -qf f1 f2

A: cat a b doesn't read simultaneously from a and b; it opens a,
reads it from start to finish, closes a, and then goes on to do the
same with the next file it was given as an argument.
In the case where the arguments are pseudo-files that do tail -f and
thus do not have an "end", cat would only ever read from the first file.
If for some reason all you need is to open many files at once, paste
could be a way:
$ echo f1 >f1; echo f2 >f2
$ cat <(tail -F f1) <(tail -F f2)
f1
^C

$ paste <(tail -F f1) <(tail -F f2)
f1      f2
^C


text:
Q: How to access broadcastreceiver of another application I have two applications A1 and B1.A1 have a broadcastreceiver and i want to register this broadcastreceiver from B1.So I tried
Intent intent = new Intent();
intent.setClassName("pkgname","pkgname.BroadCastReceiverName");
intent.setAction("xxx.x...xxx");
getApplicationContext().sendBroadcast(intent);

But it does not fire/register any receiver.
How to access the broadcastreceiver of one application in another application?
Thanks in Advance

A: Hope this will work for you,
In App1: calling a Broadcast Receiver(Name of my broadcast receiver "MyBroadCastReceiver") of App2.
you can place this method in any Button onClick() or as per your requirement.
 private void getAnotherAppMethod(){
    Intent intent = new Intent("Updated");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    // for Example, here packageName of app2 is "com.app2.example" and its class name with packageName can be like "com.app2.example.yourBroadCastRecevier"
    intent.setComponent(new ComponentName("package name of app2","package.yourbroadcastreciverName in app2"));
    getContext().sendBroadcast(intent);
}

In App2: Called broadcast receiver which is Located in App2
public class MyBroadCastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent != null)
        {
            String sIntentAction = intent.getAction();
            if (sIntentAction != null && sIntentAction.equals("youActionName"))
            {
                Toast.makeText(context, "Hello From App2", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();
            }
        }

    }
}

In App2: AndroidManifest.xml file
add this below code inside your application tag
<receiver
       android:name=".MyBroadCastReceiver"
       android:enabled="true"
       android:exported="true">
       <intent-filter>
            <action android:name="youActionName" />
       </intent-filter>
</receiver>

A: The broadcastReceiver in your application-B1 should be registered in the AndroidManifest.xml file with the appropriate intent-filter that you are broadcasting from application-A1.

A: First of all always put some error checking when using reflection like this, because required package and receiver might not be available on users phone.
The above method should work but you have to set some prerequisites before it can:
Set android:exported="true" to your broadcast receiver in another application
Run the other application at least once after install because global receivers like this get registered only if the application is ran at list once by the user. I think this is the case from android 4.x onwards but could be the same on older versions (if someone knows exact version when this was changed please add)

A: You can create a method(for example register()) in an Activity of App A1(for example Activity1) and add some code to that to registers it's brodcastreceiver.In onCreate() of Activity1 check extras of it's Intent if it has a key for example reg invoke register() in onCreate() of Activity1. Now, when you want to register your broadcastreciever,it is enough to start Activity1 from App B1 with an intent that has an extra with that specific key,for example reg.


text:
Q: How do you use RSL with swc This is the setup:
1) I have an SWF in which I have defined a component in the library with a custom class as the linkage. The component has been set up for "export for run time sharing"
2) I have an fla where I copied over the component and linked to the first SWF via "import for run time sharing". This fla will be published as a SWC. The content of this fla resides in a movieclip to which I give a linkage so I can instantiate it in the app that has the SWC in its lib path.
3) I have a flex application that has the SWC added to its library path.
When I run my flex application, my RSL component does not work at all.

A: If you're creating a swc, that's not RSL.  RSL means you're using a compiled SWF to include a symbol in your application.  A swc is just a collection of compiled classes (library) that does not hold any specific runtime symbol information.  Plus, I don't think Flash does RSL in the traditional flex sense.
I believe what you want to do is add the same options you have in you FLA, but instead create a swf from it.  From there, you can embed the symbol you want in flex by doing this:
[Embed(source="path/to/yourSwf.swf", symbol="theSymbolId")]
public var yourSymbol:Class;


text:
Q: Getting IP Address of user browsing the website I am trying to get the IP address of the user who is browsing the website, might be through mobile phones or PC. I have tried using a set of code, but what I get back is ::1, may I know if this is wrong or it's meant to be like that?
private string GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    ipAddress = VisitorsIPAddr;
    return ipAddress;
}

Thank you for the help in advance.

A: ::1 and 127.0.0.1 and localhost are same, they means THIS computer. You are connected to your application on same machine, where you have an application. Try to deploy application to some server.
Remember to make sure if you are getting a public or private IP address.


text:
Q: Deleting duplicates from a MySQL database with a single duplicate colum So I have read through a lot of Stack Overflow questions on this... and I really couldn't get my answer :(. I've only been working with MySQL for about 4 months, so I am not exactly a pro.
Anyways, I have data in my table that looks something similar to this...
id | user | amount

1 | dillyg10 | 16
2 | dillyg10 | 18

As you can see, the user field is dupped. This happens a lot in my data set, although my table is very small, only about 1000 rows.
So if you guys could give me some advice... I would really appreciate it, also go through what you do in the query, I'm trying to learn and hopefully I won't have to ask a question like this again :).

A: You can use below query to delete duplicate record.
DELETE FROM test_table
      WHERE ID IN (SELECT   MAX (ID)
                       FROM test_table
                   GROUP BY user);

A: If you want to delete all but a row with a maximum id out of duplicate rows per user then you can do it like this
DELETE t
  FROM table1 t JOIN
(
  SELECT user, MAX(id) id
    FROM table1
   GROUP BY user
  HAVING COUNT(*) > 1
) q
   ON t.user = q.user
  AND t.id <> q.id

Here is SQLFiddle demo
If on the other hand you want to leave rows with maximum amount out of duplicate rows
DELETE t
  FROM table1 t JOIN
(
  SELECT i.id, i.user, i.amount
    FROM
  (
    SELECT user, MAX(amount) amount
      FROM table1
     GROUP BY user
    HAVING COUNT(*) > 1
  ) p JOIN table1 i
      ON p.user = i.user
     AND p.amount = i.amount
) q
   ON t.user = q.user
  AND t.amount <> q.amount
   OR (t.amount = q.amount
       AND t.id < q.id)

Here is SQLFiddle demo


text:
Q: All about frontier (boundary) in topological space In Engelking (theorem 1.3.2 p.24) and Choquet (prop 6.6 p.17 and exercice 17 p.112), there are several facts about frontier (or boundary) in topological spaces, but I can't find counter-examples simple but not too trivial to some counter-intuitive results.
I guess it is because reasonning in the plane is too specific (metric space and separation...).
Let $X$ denoted a topological space. For instance, one surprising property is: $\bar{A}\backslash A \subset fr(A)$ without equality in general. A counter-example in $X=\mathbb{R}$ is $A=\mathbb{Q}$ ($\bar{\mathbb{Q}}\backslash \mathbb{Q}= \mathbb{R}\backslash \mathbb{Q}\varsubsetneq fr(\mathbb{Q})=\mathbb{R}$).
Other surprising fact is : $fr(\bar{A})\subset fr(A)$ without equality in general. (Same counter-example.)
In general, examples one can easily find involve dense subsets. For instance, a ball (open, closed, or neither the first nor the second) in the plane satisfies the equality of the inclusion above. I just can see it by calculating the sets, but what I want is to understand why it works in some case and not in others...
Can you help me, please ?
Is there explicit or exhaustive literature about that ?

A:
In a topological space, $fr(A)=\bar{A}\backslash A$ if and only if $A$ is open.

Proof :
We define $fr(A)$ to be $\bar{A}\backslash int(A)$ where $int(A)$ is the interior of $A$ (the biggest open set contained in $A$). Hence we have $fr(A)=\bar{A}\backslash A$ if and only if $\bar{A}\backslash A=\bar{A}\backslash int(A)$.
By set-theoretic argument (using the fact that both $A$ and $int(A)$ are contained in $\bar{A}$) this happens if and only if $A=int(A)$. This happens if and only if $A$ is open (if $A$ is open then $A$ is the biggest open set contained in $A$, and if $A=int(A)$ then in particular $A$ is open).
Now $fr(\bar{A})=\bar{\bar{A}}\backslash int(\bar{A})=\bar{A}\backslash int(\bar{A})$ and $fr(A)=\bar{A}\backslash int(A)$. So both are equal if and only if $int(\bar{A})=int(A)$. I don't think there is a better caracterization of those last sets.

A: Here is a simple counter-example in the real line. Hope it will help some people...
Let's take $X=\mathbb{R}$ and $A=\{0\}\cup ]1,2[\cup ]2,3[$. Then $\bar A = \{0\}\cup [1,3]$, $\stackrel{\circ}{A} = ]1,2[\cup ]2,3[$, and hence
$$fr(\bar A) = \{0,1,3\} \varsubsetneq fr(A) = \{0,1,2,3\} \varsupsetneq  fr(\stackrel{\circ}{A}) = \{1,2,3\}.$$


text:
Q: Convert an existing Keystore to an android debug keystore for eclipse Sometimes it might be handy to use an existing keystore in eclipse (Android -> Build -> CustomKeystore) to build from within eclipse.
The Eclipse plugin does not allow to change the keystore password, key-alias and key password though.
Is there a way to convert an existing keystore to match the default requirements?

A: The following keytool commands should do the trick. There definitly is a simpler way, but it already took enough time figuring this one out :)
keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000
keytool -delete -alias androiddebugkey -keystore debug.keystore
keytool -importkeystore -srckeystore src.keystore -destkeystore debug.keystore
keytool -changealias -alias srcalias -destalias androiddebugkey -keystore debug.keystore
keytool -keypasswd -alias androiddebugkey -keystore debug.keystore

*

*This creates a new keystore and imports an existing key from a source keystore

*keystore. src.keystore -> your source keystore that will be used

*srcalias -> your source alias you're currently using

*passwords are entered on cmdline

use 'keytool -list -keystore debug.keystore' to check the result.

A: Very useful information, should be voted up. I wrote a small batch file basing on Icyerasor's answer:
keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -keyalg RSA -keysize 2048 -validity 10000 -storepass android -keypass android -dname "CN=kristjan sander, OU=Unknown, O=bitspinners, L=tallinn, ST=Unknown, C=ee"
keytool -delete -alias androiddebugkey -keystore debug.keystore -storepass android
keytool -importkeystore -srckeystore keystore.jsk -srcstorepass qwerty -destkeystore debug.keystore -storepass android
keytool -changealias -alias bitspinners.eu -destalias androiddebugkey -keystore debug.keystore -storepass android -keypass qwerty
keytool -keypasswd -alias androiddebugkey -keystore debug.keystore -storepass android -keypass qwerty -new android
keytool -list -keystore debug.keystore -storepass android