text:
Q: create a type I can enumerate on Is it possible to enumerate on a type.
For example if I declare:
type myType = 'value1' | 'value2';

Then  I would like to initialize myTypeArray with all the values of myType.
let myTypeArray: myType[] = // enumerate on the values authorized by `myType`.

Is there a structure with typescript that allows that ?

A: You can not do that with type alias because they are not compiled into the javascript output and therefore are not available at runtime.
You can do something similar with string enums:
enum MyType {
    Value1 = "value1",
    Value2 = "value2"
};

let myTypeKeys: string[] = Object.keys(MyType);
console.log(myTypeKeys); // ["Value1", "Value2"]

let myTypeValues: string[] = Object.keys(MyType).map(key => MyType[key]);
console.log(myTypeValues); // ["value1", "value2"]

(code in playground)


text:
Q: Why the method is returning padEnd as undefined? Using the following method, when I am entering 7.0 I get the following error:
Unhandled Rejection (TypeError): Cannot read property 'padEnd' of undefined
formatInput = (value) => {
  const numsAfterDot = 6;
  const isNegative = value < 0;
  const hasDecimals = value.includes(".");
  let absolute = Math.abs(value).toString();
  if (isNaN(absolute)) return;
  else {
    const split = absolute.split(".");
    let start = hasDecimals ? split[0] : absolute.slice(0, 2);
    let rest = hasDecimals ? split[1] : absolute.slice(2, numsAfterDot)
    start = start.padStart(2, "0");
    rest = rest.padEnd(numsAfterDot, "0");
    const result = `${start}.${rest}`;
    return isNegative ? `-${result}` : result;
  }
};

Can someone please help me solve this?

Expected output:
"7.0" should converts to "07.000000"
"12" should converts to "12.000000"
".12" should converts to "00.120000"
"-123" should converts to "-12.300000"
"123456" should converts to "12.345600"

A: You get the error because you test to see if the string you send in has a decimal point.
const hasDecimals = value.includes(".");

You then convert it to absolute.
let absolute = Math.abs(value).toString();

When you do that it no longer has a decimal point, so the split is going to be ['7']
so there is no split[1], hence why it is undefined.
Your code is a bit complicated. I would just split, if it is not a length of 2, I would split the string up into two parts and then pad it.

function custPad (str) {
  // convert to number
  const num = +str;
  // check if negative
  const neg = num < 0 ? '-' : '';
  // get rid of negative, split it at decimal
  const parts = Math.abs(num).toString().split('.');

  // if no decimal, than break it up
  if (parts.length === 1) {
    const nums = parts[0];
    // grab first two numbers
    parts[0] = nums.substr(0,2);
    // grab remaining
    parts[1] = nums.substr(2, 6);
  }

  // build the new string with the padding
  return neg + parts[0].padStart(2, '0') + "." + parts[1].padEnd(6, '0').substr(0,6);

}

console.log("7.0", custPad("7.0"))
console.log("7", custPad("7"))
console.log("0.12", custPad("0.12"));
console.log("123", custPad("123"));
console.log("-12", custPad("-12"));
console.log("123456", custPad("123456"));
console.log("12345678911111111", custPad("12345678911111111"));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Combining two const char* together I've tried many ways to do that, I got a void which is static and is on Console class i made, Void it self works fine:
Console::WriteLine(const char* msg)

On the other side, I got another const char* non static void which calls the Console::WriteLine void from It, I've been working on C# for around a year and on C# I can easily do something like this:
string a = "Start ";
string b = a + "End";

When i call this on C++, it gives me bunch of errors:
Player::Kill(const char* Message)
{
    Console::WriteLine("> " + Message + " <");
}

I've also tried the strcat thing and put, But it tells me to use strcat_s which doesn't really work, And also I've tried to do string instead of const char*, And tried char*, But all of them give errors for the thing I'm trying to do.

A: "const" means "cannot be changed(*1)". So you cannot simply "add" one const char string to another (*2). What you can do is copy them into a non-const character buffer.
const char* a = ...;
const char* b = ...;

char buffer[256]; // <- danger, only storage for 256 characters.
strncpy(buffer, a, sizeof(buffer));
strncat(buffer, b, sizeof(buffer));

// now buffer has the two strings joined together.

Your attempt to use std::string failed for a similar reason. You said:
std::string a = "Start";
std::string b = a + " End";

This translates to
b = (std::string)a + (const char*)" End";

Which should be ok except that it creates an extra string, what you probably wanted is
std::string a = "Start";
a += " End";

If you are getting compile errors doing this, please post them (Make sure you #include ).
Or you could do something like:
std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

All of the following work: (see live demo http://ideone.com/Ytohgs)
#include <iostream>
#include <string>

std::string addTwoStrings(const std::string& a, const std::string& b)
{
    return a + b; // works because they are both strings.
}

void foo(const char* a, const char* b)
{
    std::string str = a;
    std::cout << "1st str = [" << str << "]" << std::endl;
    str += " ";
    std::cout << "2nd str = [" << str << "]" << std::endl;
    str += b;
    std::cout << "3rd str = [" << str << "]" << std::endl;
    str = addTwoStrings(a, " ");
    std::cout << "4th str = [" << str << "]" << std::endl;
    str = addTwoStrings(str, b);
    std::cout << "5th str = [" << str << "]" << std::endl;
}

int main()
{
    foo("hello", "world");
}

*1 Or more accurately, "cannot be changed in-situ" - you can use it in expressions, etc, so for example, e.g.
const size_t len = strlen("hello");
size_t newLen = len + strlen("world");
// but this would not be legal:
len += 2; // error: len is const.

2 "const char a + const char* b" is actually trying to add two pointers not two strings, the result would be the address of string a plus the address of string b, the sum of which would be some random memory location

A: char * is a pointer (so are "> " and " <"), you cannot add pointers together.
However you can concatenate C++ strings using the + operator:
Player::Kill(const std::string& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

A: Instead of concatenating the strings and creating an extra temporary object, why not just output the 3 strings separately?
Player::Kill(const char* Message)
{
  Console::Write("> ");
  Console::Write(Message);
  Console::WriteLine(" <");
}

A: Since you say it's C++ code, just just this:
void Player::Kill(std::string const& Message)
{
    Console::WriteLine(("> " + Message + " <").c_str());
}

Ideally, your Console::WriteLine() is declared to also take a std::string const& in which case you don't need to do the .c_str()-dance.

A: #include <iostream>
using namespace std;

string string1 = "John";
string string2 = "Smith";

float string1Len = string1.length();
float combinedLen = string1.length() + string2.length();
char combine[string2.length() + string1.length()];

for(int i = 0; i < string1Len; ++i){
    combine[i] = string1[i];
}
for(int i = string1Len; i < combinedLen; ++i){
    combine[i] = string2[i - string1Len];
}

const char * combined = combine;

A: well, it is possible to make changes with const char* ,even thought it is const we cannot change its value but can change its address ,check below class for reference
    class String
{
private:
    const char* m_Name;
    int m_Size;
public:
    String() :m_Name(" "), m_Size(0) { m_Size = 0; }
    String(const char* name , int size) :m_Name(name),m_Size(size) {}
    String(const char* name) :m_Name(name) {}

    void Display()
    {
        LOG(m_Name);
    }
    int GetSize()
    {
        while (m_Name[m_Size] != '\0')
        {
            m_Size++;
        }
        return m_Size;
    }
    void Append(const char* nameToAppend)
    {
        //Create an empty char array pointer "*tempPtr" of size = existing const
        //char name pointer "m_Name"  + const char pointer appending name
        //"*nameExtention"

        //this array can store both the names
        int totalSize = 0;
        int nameToAppendSize = 0, existingNameSize = 0;
        while (nameToAppend[nameToAppendSize] != '\0')
        {nameToAppendSize++;}
        existingNameSize = this->GetSize();
        totalSize = nameToAppendSize + existingNameSize;
        char* tempPtr = new char[totalSize+1];

        //Add  existing const char name pointer "*m_Name"  +  const char pointer
        //appending name "*nameExtention" to tempPtr,  using a loop

        int currentSize = 0;
        for (int i = 0; i < existingNameSize; i++)
        {
            tempPtr[currentSize] = m_Name[i];
            currentSize++;
        }
        for (int i = 0; i <= nameToAppendSize; i++)
        {
            if (i == nameToAppendSize)
            {
                tempPtr[currentSize] = '\0'; // this line tells compiler to stop
                                             //  writting inside tempPtr
            }
            else
            {
                tempPtr[currentSize] = nameToAppend[i];
                currentSize++;
            }
        }
        //--------------------------------
        //Now change the address of your const char* with tempPtr
        //This will change the contents of the const char*
        //--------------------------------
        m_Name = (char*)tempPtr;
    }
};


text:
Q: ASP.net LoginStatus - change status to logout when log in successful How should I go about this? I mean how does the control know whether someone is logged in or not? Session ID? Cookies?
Recommendation of which one I should implement? A guide or tutorial would be appreciated.

A: It's shown in the documentation here: http://msdn.microsoft.com/en-us/library/ms228140.aspx

Remarks
  The LoginStatus control has
  two states:
Logged on to the Web site.
Logged off from the Web site.
The state is determined by the
  IsAuthenticated property of the
  Request property.
For more information about using the
  LoginStatus control and other login
  controls, see ASP.NET Login Controls
  Overview

<asp:LoginStatus id="LoginStatus1" loginText="Log In"
             logoutAction="Refresh"  logoutText="Log Out"
             runat="server" />

A: That depends on your scenario whether you are allowed to use cookies or not.
If there are no special requirements the standard Membership provider would be a good start. Out-of-the-box it uses cookies to store the authentication token.
This link gives you an idea: http://msdn.microsoft.com/en-us/library/91f66yxt.aspx

A: If you just want to check if a user is logged in or not you can use:
if (User.Identity.IsAuthenticated) {
   ...
}

A: The LoginStatus control just reads the User.Identity.IsAuthenticated property to decide what to display.  Here's a quick one-pager on how to use it.
You should probably read up on Forms Authentication in ASP.Net, and how it handles session and user cookies to deal with authentication.


text:
Q: How to set user data for a QWidget? I would like to set an integer number to be stored in a QWidget, and I think the setUserData member function would do the trick but I can't find any documentation. Any hints?

A: You might be looking for QObject::setProperty() (which is of course inherited by QWidget).

A: I am not an expert in  QT but why not just create a class that inherits from QWidget and has an integer?  Like so:
class MyDerivedWidget : public QWidget
{
    public:
  MyDerivedWidget();

    private:
  Data *myUserData;
};

Or if you insist on using the setUserData checkout the last post here.


text:
Q: Octave coding - How many vectors rotated by an angle is within the distance of another vector I don't know if this is the right forum but
I am trying to code a rotating vector v by an angle theta anticlockwise n times around a circle. Afterwards, set a variable r to be the number of these n+1 vectors that are within (strictly less than) distance d of vector w.
So far what I've done is times (n+1) by the rotational vector [cos(theta),-sin(theta);sin(theta),cos(theta)] with vector v.
So
a=(n+1)*[cos(theta),-sin(theta);sin(theta),cos(theta)]*v;
I know I have to somehow incorporate norm(a-w) <= w or something as that gives the distance between the two vectors but I'm kind of stuck on how to do so.
Alternatively, I am also thinking that instead of times'ing by (n+1), I'm thinking that maybe it's wrong and that I have to make a loop like for n=1,2,...,k, if this vector is within norm(a - w) < d then sum, else disregard or something.
This would be easy if it was manual as it would only require multiplying the rotational vector by v and find the distance between the new rotated vector and vector w, and repeat it again for however many n's but I  am having trouble coding this.
Any help would be appreciated

A: You want to do a for loop, as you suggest. Something similar to the following:
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];

r = 0;
for k=1:n
    v = A*v;
    if norm(v-w) < d
        r = r + 1;
    end
end


text:
Q: Wrong ownership when SFTP files I have successfully setup jailed SFTP access using ChrootDirectory.
Match Group sftponly
     ChrootDirectory %h
     X11Forwarding no
     AllowTCPForwarding no
     ForceCommand internal-sftp

I also used: Subsystem sftp internal-sftp -u 0002 to ensure proper permissions are applied.
My issue now is when new files or folders are SFTPed to the server, or created using the SFTP client, they are assigned to the user and the group is the user instead of apache.
How can I make it so that my files will automatically be assigned to the apache group?

A: Change the primary group of your user accordingly: usermod -g apache your_SFTP_Username


text:
Q: Adding more than 1 id using rails check_box_tag I'm new to RoR. Well, new to programming in general.
I want to pass multiple ids from first view to second view but, only the ids that I select using the check_box_tag.
---------- First view -------------------

Name:

<%= form_tag(method: "post") do %>

<%= check_box_tag("camp", params[:id]) %>

<%= submit_tag("Add to comparison cart") %>

------------- Controller ---------------
def compare
@camps = Camp.find(params[:id])

end
---------- Second view ----------------

<%= @camps.name %>

Problem:
When I'm routed to the second view it only saves the latest "camp" I checked.
Question:
How can I save multiple camps to the second view?

A: What is happening here is Camp.find() only returns a single object, whereas you obviously need to return multiple objects.
There may be an equivalent to .find() that can find and return multiple objects, but I have not used it so I do not know what it would be called. If it exists it would be an ideal solution.
An alternative would be to create an array and then use repeated Camp.find() calls to fill that array. Something like (apologies for pseudocode, do not have time to test it out):
@camps = []
for each check box
  @camps.add(camps.find(params[:id])) if checkbox is checked
end

(I am assuming you can add a to arrays in Ruby, am still new myself...)


text:
Q: Javscript Performance of Objects vs Maps for Contest Problems I used memoization to try and improve performance for a recursive algorithm. I would expect about the same performance for Objects and Maps in Javascript (O(1) for reads and writes).
Looking at other StackOverflow posts, they say performance may differ 2x or 3x performance depending on the implementation/browser, however, I am seeing a ~40x performance difference between the Objects vs Maps implementation algorithm.
The performance for the object implementation is ~8000ms on LeetCode (faster than only 5% of js solutions and slower than not using memoization).
While the map implementation performace is ~184ms on LeetCode (faster than 70% of js solutions).
Below is my code. Exact same solution, object solution is uncommented while map solution is commented out.
Does my code have a big mistake for the object memoization implementation that is making it much slower? Or is this a LeetCode Map vs Object implementation difference?

/**
 * @param {number[]} nums
 * @param {number} S
 * @return {number}
 */

var findTargetSumWays = function(nums, S) {
    //let memo=new Map();
    let memo={};
    return helper(0,S);

    function helper(numsPointer,S){
        let numWays=0;
        if(numsPointer==nums.length&&S===0){return 1;} //base case. All nums in array used and Sum matches
        if(numsPointer==nums.length){return 0;} //all nums in array used
        //if(memo.has(numsPointer+":"+S)){return memo.get(numsPointer+":"+S);}
        if(memo[numsPointer+":"+S]){return memo[numsPointer+":"+S];}

        let curr=nums[numsPointer];

        numWays+=helper(numsPointer+1,S+curr);
        numWays+=helper(numsPointer+1,S-curr);
        //memo.set(numsPointer+":"+S,numWays); //store results
        memo[numsPointer+":"+S]=numWays;
        return numWays;
    }//helper

};

Problem from LeetCode is:

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
  Find out how many ways to assign symbols to make sum of integers equal to target S.

Correct solution when using both Maps and Objects for memoization, but huge performance difference. Using Objects for memoization is actually causing performance losses.
Thank you!


text:
Q: Select multiple ranges of dataframe rows in a shiny app I have a simple shiny app
#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
               uiOutput("book1"),
               uiOutput("book4"),
               uiOutput("book5")

              ),
             mainPanel(
               DT::dataTableOutput("hot3"),
               br(),
               rHandsontableOutput("hot5")
             )
           )))
#server.r
library(shiny)
library(DT)
library(rhandsontable)
server <- function(input, output,session) {

  output$book1<-renderUI({
    numericInput("bk1",
                 "Items in test",
                 value = 1)
  })
  output$book4<-renderUI({
    numericInput("bk4", "From",
                 value = 1,
                 min=1,max=input$bk5)

  })
  output$book5<-renderUI({
    numericInput("bk5", "To",
                 value = 1,
                 min=1,max=input$bk1)

  })

  rt2<-reactive({
    DF=data.frame(
      Sel= rep(TRUE, as.numeric(input$bk5-input$bk4+1)),
      Id= (input$bk4:input$bk5),
      Label=paste("Item",input$bk4:input$bk5),
      Pf=as.integer(rep.int(0,as.numeric(input$bk5-input$bk4+1))),
      stringsAsFactors = FALSE
    )
  })
  output$hot5 <-renderRHandsontable({

    rhandsontable(rt2(),width=300,height = 300)

  })

}

As you can see I have 3 selectInput(). From the first I decide the number of total rows of my dataframe and I use the other 2 for the range of rows that I display. My final goal is to achieve displaying at the same time multiple ranges together. For example display rows from 1 to 5 and and then select rows from 7 to 8 and so on. Of course this could be achieved with other selectInputs but this is not practical. I was thinking if that would be possible with a textinput() or something that could take multiple values. I do not know if this can be done so Im open to creative ideas.


text:
Q: Javascript Regex to replace URLs with links, but not in embed (or img) tags I'm currently using the following code, to search the a div on a page for URLs and replace them with a tags.
However when we have a embed tags within the div it messes up the links within these tags.
function replaceURLWithHTMLLinks(text) {
    return text.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'$&').replace(/([^\/])(www[^ <]+(\b|$))/gim,'$1$2');
}

$(document).ready(function(){
    var htmlStr = $("div.content-a").html();
    var htmlStrAfter = replaceURLWithHTMLLinks(htmlStr);
    $("div.content-a").html(htmlStrAfter);
});

Can anyone tell be how to perhaps exclude any http://... that are preceded by a " or ' ?
Or similar?

A: Probably, you should use DOM as recommended. But in order to make your regexp work as desired, you should prepend it with (?:^|[^"']). That means match start of line or match any character excepting ' and ". So first of your regexps will look as follows:
/(?:^|[^"'])(ftp|http|https|file):\/\/[\S]+(\b|$)/gim

And your chaining of replace method is ugly. Code will be much more readable if you will split method invocations to different lines.
Update: And in order to skip first excess character you can use $1 instead of $& and your regexp must be changed to this:
/(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gim

A: +1 to what Johannes says...
    $(document).ready(function(){
       $('div.content').contents().filter(function() {
         return this.nodeType == 3;
       }).each(function(){
             this.nodeValue.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'$&').replace(/([^\/])(www[^ <]+(\b|$))/gim,'$1$2');
       });
    });

Note the code above is untested but it should look something like that i believe.


text:
Q: Plotting von Karman-Nikuradse formula I'm trying to plot the friction factor for Darcy-Weisbach formula based on the von Karman-Nikuradse formula for subsonic compressible flow:
$$ \frac{1}{\sqrt{f}}=2 \log \left(\operatorname{Re} \, \sqrt{f} \right)-0.8 \tag{1}$$
So I defined a function using NSolve:
fKN[R_] := NSolve[(1/Sqrt[f] == (2*Log[R*Sqrt[f]] - 0.8)), f]

And tried to plot it using
Plot[fKN[R], {R, 10^5, 10^6}]

But I get a bunch of errors:

NSolve::ifun
General::stop

I would apreciate if you could help me know what is the problem and how I can solve it?

A: The exact solution can be obtained using Solve
sol = f /. Assuming[R > 0,
    Solve[(1/Sqrt[f] == (2*Log[R*Sqrt[f]] - 4/5)), f] //
     Simplify] // Quiet

(* {1/(4*ProductLog[-(R/(2*E^(2/5)))]^2),
   1/(4*ProductLog[R/(2*E^(2/5))]^2)} *)

Using FunctionDomain to determine which solution applies to the region of interest
FunctionDomain[#, R] & /@ sol

(* {R < 0 || 0 < R <= 2/E^(3/5), -(2/E^(3/5)) <= R < 0 || R > 0} *)

Consequently, the second solution is desired
Clear[fKN]

fKN[R_] = sol[[2]];

LogLinearPlot[fKN[R], {R, 10^5, 10^6}]

A: Use
fKN[R_] := NSolve[(1/Sqrt[f] == (2*Log[R*Sqrt[f]] - 0.8)), f][[1, 1, 2]] // Quiet

With this,
LogLinearPlot[fKN[R], {R, 10^5, 10^6}]

Note: in this case, FindRoot is actually faster than NSolve. I leave it to you to implement it, in case speed is important to your needs.


text:
Q: How to grab youtube video title if we have link to the video I am using this code in my website. Can I grab youtube title with following code,
function setYouTubeTitle(id) {
        $.ajax({
            url: window.location.protocol + '//query.yahooapis.com/v1/public/yql',
            data: {
                q: "select * from json where url ='http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=" + id + "&format=json'",
                format: "json"
            },
            dataType: "jsonp",
            success: function (data) {
                if (data && data.query && data.query.results && data.query.results.json) {
                    YouTubeDialog.dialog({
                       title: data.query.results.json.title
                    });
                }
            }
        });
    }

Author of the code suggest to put this code in onNavigate event. I use link in my site like below. I don't know how to do it.
<a href="https://youtu.be/youtube_id" data-toggle="lightbox"><\a>

A: You have to getting familiar with coding for complete this task. I hope that with this answer you can take a look and check that it is not too difficult.

First, you have to use YouTube Data API v3.
Read the documentation of YouTube Data API v3 for get API_KEY (which will allow you to use the API).
Once you have your API_KEY, you can use the following API request:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=D3Me6YNe9tg&fields=items%2Fsnippet%2Ftitle&key={YOUR_API_KEY}

Where {YOUR_API_KEY} is the value of the API_KEY and id is the videoId you want get the title.
In the previous URL, we set the value of the videoId property to hjGZLnja1o8.
If you test this API request here, you'll get the following results:
{
 "items": [
  {
   "snippet": {
    "title": "Nightcore - Rockefeller Street"
   }
  }
 ]
}

If you insists in use another way for complete this task, you can also browse here in Stack Overflow or in Google and search: get title of url javascript, but, I wouldn't spend much time on it since YouTube has some restrictions for requests (without using its API). So, long story short: use the YouTube Data API v3.


text:
Q: What components are inside a port expander, how does it work? (Are they tiny MOSFETs?) Do port expanders use MOSFETS internally to switch the pins high/low?
My project is using a Raspberry Pi and a MCP 23017 port expander to sink some current (to GND through the port expander) from a variable resistor (200-400 ohm) at (3,3 volts from the Pi).
I have noticed that the port expander is not a perfect short circuit to GND and have measured a voltage drop between the pin of the port expander and GND.  This voltage drop increases when a higher current is sunk through it to GND. Stupidly, I was expecting the only voltage drop to be across the variable resistor (or most of it.)
Sourcing and sinking current through the GPIO of the Pi works as I thought, with a 3,3V drop across the resistor.
In the MCP 23017 datasheet, (under param No. D080) it says when MCP is operating at "Output-Low-Voltage" the voltage drop across the MCP23017 pin to GND will be 0,6V when the Iol (sunk current) is 8mA and the Vdd (supply voltage of MCP) is 4,5V. This would explain my problem.
I'm looking for literature / links explaining the basics of (I/O) port expanders which I can reference in my bachelor thesis which explains this.
So far the only thing Ihave come across is this link.
From my understanding a MOSFET has a set (Rds on) resistance when on, but the port expander resistance changes based on the current sunk or sourced.  Why? Do they internally use MOSFETs?

A:
, do they use MOSFETS internally to switch the Pins high/low?

probably? Most digital circuitry these days is CMOS.

I have noticed that the Port Expander is not a perfect short circuit to GND and have measured a voltage drop between the pin of the Port expander and GND, this voltage drop increasing when a higher current sunk through it to GND

Well, that will be specified in your port expander's datasheet. Reading that gives you more information than speculating what kind of transistors are used on the die of that IC.

In the MCP 23017 datasheet, (under param No. D080) it says when MCP is operating at "Output-Low-Voltage" the voltage drop across the MCP23017 pin to GND will be 0,6V when the Iol (sunk current) is 8mA and the Vdd (supply voltage of MCP) is 4,5V. This would explain my Problem.

Exactly!

Im looking for literature / links explaining the basics of (I/O) Port Expanders which i can reference in my bachelor thesis which explain this.

There's nothing you need to explain in your bachelor thesis: the low-pulling output transistor, whatever kind of transistor that is, has a non-zero forward voltage under current. Like anything in this universe that isn't a superconductor (I'm sure your advisor is familiar with Ohm's law...).

But from my understanding a MOSFET has a set (Rds on) resistance when on, but the Port expander Resistance changes based on the current sunk or sourced, why? So do they internally use Mosfets?

Again, whether or not they internally use MOSFETs or not doesn't matter to your application: every transistor has an effective resistance that is not zero. The question of how close you get the resistance to zero is a question of size, speed and cost. The result of the design is what is specified in the datasheet - nothing more to add to that.

A: IO port expanders are not any different than digital IO ports on any other devices. Or to put it another way, they have just as much differences than IO pins between any other devices. So you don't need to explicitly study IO stages of IO expanders, it would be false to say these are somehow special and different from IO stages of other ICs with GPIO pins.
Any device with IO has some drive strength, and some devices have weaker drive strength than others. So it will not be a perfect short circuit to GND in any case.
So digital output stengths of two devices can be compared and they will be different. Thus for the same load you will get different current.
The pin is guaranteed to be 0.6V or below, when 8mA is pulled out, and supply voltage is 4.5V. More current can be drawn, but at the same time the voltage is not guaranteed, it can be over 0.6V. And since you are using the chip at 3.3V supply, the current driving ability will be less.


text:
Q: NUnit error: the test case source could not be found This is quite simple but annoying behavior I am running into with NUnit:
I have one test like this:
   static string[] EvenStr = new string[] { "1", "2", "3", "4" };

   [Test, TestCaseSource("EvenStr")]
   public void TestMethod(string num)
   {
      Assert.IsTrue( 1 == 1 );
   }

When I run it I see this:
    One or more child tests had errors Exception doesn't have a stacktrace

    test case source could not be found

I use NUnit 3.10.1 and .net 4.5
Does anyone have any idea what is going on and why?


text:
Q: Flex 3 toaster notifications I've searched a LOT, but dint get the solution to this: Is there a way to display flex notifications in Windows taskbar, ie, the notification should still be visible even if the application s not exactly frontmost in the monitor..There are ways to do this on AIR, or even flex4..but not Flex3??

A: Flex is my runtime, not FlashPlayer..so I don think I could use flash.display.ToastWindow? As for Flex 4, a library s available for this purpose called ToasterLib..dunno if it displays even when the flex application is not the topmost in the monitor, though..


text:
Q: What is _proto_ and why is it always present faded away in any JS Object? Whenever I open an object details in console.log, after the attached properties or functions I always see "_ proto _". What is this and why is it always present even though I never declared anything like this in my object? I know it is related to some prototype feature but not exactly sure. Also, whereever it exists, whether plain js, jquery, or Angular.js it has the exact same 13 functions below it, viz. defineGetter, defineSetter, ...., set_proto.
Can someone explain it?

A: So whenever you make any object in JavaScript it inherited from Object. so a object in java script have this structure

private members
proto-Reference of the prototype of current object parent.
prototype- Reference of the current objects prototype

So if you make any object let say named as object1
var object1=new Object();
it will be inherited from Object. and have proto set to Object(you can think Object as root class).


text:
Q: Do all major occupations ending -man have a gender-neutral option? Traditionally, many professions have been known by terms ending in -man, presumably because they have often been overwhelmingly performed by men in the past. There are probably others but ones I can think of off the top of my head include:

*

*Fisherman

*Postman

*Fireman

*Policeman

*Ombudsman

*Barman

*Cameraman

*Chairman

*Linesman

Which of these have become acceptable to use for both men and women? Which have different, gender-neutral terms which are now widely used? I know that policemen are now more commonly known as police officers but I'm not aware of any gender-neutral options for the others.
I'm primarily asking in a UK context but usage from other countries would be welcome too.

A: In a comment, John Lawler wrote

In American English, if the -man is stressed and pronounced /mæn/, like mailman, then it's masculine. If, on the other hand, the -man is unstressed and pronounced /mən/, like chairman, then it can be used for either sex. Many people follow this, but individuals often vary, since many English speakers haven't learned that pronunciation is different from spelling, and they may form variant rules, seeking "correctness" from what they learn, or don't learn, in school.

A:
Well, for some of those, -person is in use, e.g. chairperson, but "fisherperson" sounds quite strange to me, though would obviously be understood (and possibly mocked). In other cases a different form is used: police officer, bartender, mail carrier. But, yeah, about half of those don't, to my knowledge, have a commonly used degendered version. – Cary C
For fisherman, see the question I linked above (fishers, fishermen and -women, or anglers, with some caveats). For the others, in AmE: postman = postal worker, fireman = firefighter, policeman = police officer, ombudsman = public advocate, barman = bartender, chairman = chair (in certain contexts) or chairperson, linesmen = repairmen (this is the official title in the telecommunications sense. I'm not familiar with the role in sports, not a sports guy). – Dan Bron
"presumably because...." Probably not. The -man element was originally gender neutral. The masculine term was wer(e), as in werewolf (the feminine form is wifwolf: wifman evolved into woman). That many (though not all) modern English speakers associate -man with men didn't change the origin of the terms. – guifa

Of potential interest:
http://english.stackexchange.com/q/247400/55623
http://english.stackexchange.com/questions/76147/gender-neutral-forms


text:
Q: AWS - Cognito Federated identities I have created a federated identities which contains:

*

*Identity pool ID us-west-2:XXXX-XXXXXXX-XXXX-XXXX-XXXX

*User Pool ID us-west-2_XXXXXXXXX

*App client ID XXXXXX

When I try with Identity pool ID to connect to:
https://cognito-idp.us-west-2.amazonaws.com/us-west-2:XXXX-XXXXXXX-XXXX-XXXX-XXXX/.well-known/jwks.json
I get:
{"message":"1 validation error detected: Value 'us-west-2:XXXX-XXXXXXX-XXXX-XXXX-XXXX' at 'userPoolId' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\w-]+_[0-9a-zA-Z]+"}

If I try with User Pool ID us-west-2_XXXXXXXXX
https://cognito-idp.us-west-2.amazonaws.com/us-west-2_xxxxxxxxxxxxxxx/.well-known/jwks.json
{"message":"User pool us-west-2_ does not exist."}

How can I fix this?

A: The identity pool id does not feature in the path, it is the user pool only https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json, as shown here.

https://cognito-idp.us-west-2.amazonaws.com/us-west-2_XXXXXXXXX/.well-known/jwks.json

A: If you are trying to know the JWKs of the identity pool then you need to invoke this path
/.well-known/jwks_uri. the path /.well-known/jwks.json is only for the user pool.
Please note that this consumes time (my experience 0.9~1.0 sec). So I recommend saving these downloaded keys in the server/lambda in an object (kid: jwk) and verify if the key (corresponds to the token to be validated) exists before calling this URL (by checking the kid of the key for example).


text:
Q: ASP.NET App Code folder If an ASP.NET application contains classes then there are two options: 1) put the classes in the appcode folder or 2) Create a separate class library.
I have found many web pages that discuss the benefits of option 2 and I was already aware of these benefits e.g.
1) The Business Logic layer is separated from the presentation layer
2) Code can be shared between multiple client applications e.g. an ASP.NET website and a VB.NET application client.
I cannot find any web pages that discuss the benefits of option 1.
My question is: are there any benefits to option 1? Am I over thinking this?

A:
Are there any benefits to using App_Code?

It's a bit subjective, but in general, Web Application Projects scale much better than Web Site Projects.
As far as I know, the only benefit of Web Site Projects is that you can change App_Code files with out having to recompile them. But many (myself included) don't like that because it makes it possible to change code on a live web server, which is almost always a bad idea.

App_Code or separate class library?

It depends. If you need to use these classes in multiple projects, create a separate class library. If you only need it in this particular web site, App_Code is perfectly acceptable.
See Web Site or Web Application? and Web Application Projects versus Web Site Projects in Visual Studio for more information.


text:
Q: Which browsers does Stack Overflow support/recommend? I know Stack Overflow can be used with almost every browser today, but I have a few more specific questions:

*

*Which browser do the developers suggest to use for Stack Overflow?

*What percent of users use a particular browser (Chrome/Firefox/IE/Safari)?

*Does the SO team have a graph representing the above statistics?

A: I use Firefox for one reason: GreaseMonkey.  There are tons of great grease monkey scripts out there for M?S[FOU].

A: alt text http://img341.imageshack.us/img341/195/browser.jpg

A: I dumped IE for Chrome because SO is SLOW on IE. It's all that fancy-pants client side stuff, especially when hiding/highlighting tags.

A: Correct answer: any browser.


text:
Q: $L^{2}$ spaces, bounding the measure of a set Let $f \in L^{2} ([0,1], \mathcal{A},\mu)$ where $\mu$ is the usual Lebesgue measure, such that $||f||_{2}=1$ and
$$
\int_{0}^{1} f d \mu \geq \alpha > 0
$$
Let $E_{\beta}= \{ x \in [0,1] | f(x) > \beta \}$.
Then, for every $\beta \in (0,\alpha)$
$$
\mu ( E_{\beta} ) \geq (\alpha-\beta)^{2}
$$
I had problems with this exercise. To be sincere, I don't know even where to start from. The only relevant inequality that I know is Chevyshev inequality but it bounds the measure of $E_{\beta}$ from above, not from below. I've tried to do some trick with integrals and charasteristic function to bound the $L^{2}$ norm of $\alpha-\beta$ from above with the $L^{2}$ norm of $\chi_{E_{\beta}}$, but I haven't succeded. My biggest concern is the lack of absolute values marks on the definition of $E_{\beta}$ which doesn't allow me to make the conclusion $x > y \Rightarrow x^{2} > y^{2}$.
Any hints?

A: You said that you didn't know where to start.
Let's start with what we know, namely $\alpha \leq \int_0^1 f \, d \mu$. We now want to connect this to the quantity $\mu(E_\beta)$ that we want to show something about. The most natural approach is to write
$$
\alpha \leq \int_0^1 f \, d\mu = \int_0^1 f \, 1_{E_\beta} \, d \mu + \int_0^1 f \, 1_{E_\beta^c} \, d\mu.
$$
Now, note that $f \leq \beta$ on $E_\beta^c$, which implies that $\int_0^1 f \, 1_{E_\beta^c} \, d \mu \leq \int_0^1 \beta \, 1_{E_\beta^c} \, d \mu \leq \beta$, since $\beta \geq 0$.
We have thus shown
$$
\alpha \leq \int_0^1 f \, 1_{E_\beta} \, d \mu + \beta.
$$
First try to figure out yourself how to proceed from here. If you don't see it after staring at the equation for ~10 minutes, look at the hint below.

 Hint: Cauchy-Schwarz inequality.

And here the full solution:

 Note that until now we did not use the fact that $\|f\|_2 = 1$. To make use of this estimate, we use the Cauchy-Schwarz inequality, which shows
 \begin{align*}\alpha \leq \beta + \int_0^1 f \, 1_{E_\beta} \, d \mu \leq \beta + \int_0^1 |f| \, 1_{E_\beta} \, d \mu \leq \beta + \sqrt{\int_0^1 |f|^2 \, d \mu} \sqrt{\int_0^1 1_{E_\beta} \, d \mu} = \beta + \sqrt{\mu(E_\beta)}. \end{align*} Rearranging this inequality will give you the desired estimate.


text:
Q: Trouble with undefined variable in laravel I have my APIrest in Laravel 5.
I'm trying to upload files.
This is my controller :
 public function makeFile(Request $request)
 {
     if(isset($request->files) && is_array($request->files)) {
         $fileArray=array();
         foreach($request->files as $key=>$fileEntity) {
             $file= new File();
             $file->file=$fileEntity['file'];
             $file->shipment_id=$fileEntity['shipment_id'];
             $file->user_id=$fileEntity['user_id'];
             $file->date=date('Y,m,d,G,i,s');
             $file->fileName=$fileEntity['fileName'];
             $file->fileType=$fileEntity['fileType'];
             $file->status=$fileEntity['status'];
             $file->save();

             array_push($fileArray, $file);
         }
         // return response()->json($fileArray);
     }
 (line 132 the one of the error)     return response()->json($fileArray);
 }

In the frontend (angularjs) when i upload a file it throws this error

ErrorException in ShipmentController.php line 132: Undefined variable:
  fileArray

Why this is happening?

A: You have to declare the $fileArray=array(); outside the first if. If the first if doesn't evaluate true, the variable isn't set.

A: You declared $fileArray variable inside if statement it works like local variable for this statement.
Solution:
public function makeFile(Request $request)
{
    $fileArray = [];
    if (isset($request->files) && is_array($request->files)) {
        foreach ($request->files as $key => $fileEntity) {
            $file= new File();
            $file->file=$fileEntity['file'];
            $file->shipment_id=$fileEntity['shipment_id'];
            $file->user_id=$fileEntity['user_id'];
            $file->date=date('Y,m,d,G,i,s');
            $file->fileName=$fileEntity['fileName'];
            $file->fileType=$fileEntity['fileType'];
            $file->status=$fileEntity['status'];
            $file->save();

            $fileArray[] = $file;
        }
    }
    return response()->json($fileArray);
}


text:
Q: Whats difference between these two calls: (_){} and (_)=>{} what I mean... when I write code in Flutter (Dart) every time I have to call some callbacks sometimes they are: (_){} while other times they are: (_) => {} .
With or without parameters _ present.
To my knowledge, they should both be called lamda functions; and lambda functions should be other kind of write funtions

A: *

*(_){} has signature Null Function

*(_) => {} has signature Map Function() and it is short form (lambda) for

() {
  return {};
}

This variant returns Map.
Full example (dartpad):
typedef SimpleFun = Null Function();
typedef LambdaFun = Map Function();
void main() {
  final SimpleFun simpleFun = (){};
  final LambdaFun lambdaFun = ()=>{};
  print(simpleFun()); // null
  print(lambdaFun()); // {}
}

A: I hope this helps:
(_) => _ is a lamba expression.
A lambda function is a small function containing a single expression. It is used to perform a specific task and it can contain only that one expression
While
(_) {} is a function that can take as many expressions as you want to give it.
Hope this answers your question.


text:
Q: Java Swing JMenu Keeps Disappearing Ok so trust me when I tell you that I have done my due diligence on this one.
I've been trying to debug this for the longest time now and I've looked over the code again and again. I've checked Stack Overflow and nobody has had this problem.
So I am trying to create a menu in Java Swing. This menu is to be on a JPanel. I know that by convention it is supposed to be on a JFrame but it would be best for my circumstances on a JPanel. The problem is that when I click on the "Functions" menu, and try to hover my mouse over to one of the Menu items in it, the menu automatically disappears. I tried to implement the same code on a JFrame but the same thing happened.
So without further ado, Here is the code:
public static String[] getRGBInputsFromDialogBox(String title) {
    JTextField rField = new JTextField(5);
    JTextField gField = new JTextField(5);
    JTextField bField=new JTextField(5);

    JPanel myPanel = new JPanel(new FlowLayout());
    myPanel.add(new JLabel("R(x,y): "));
    myPanel.add(rField);
    myPanel.add(Box.createHorizontalStrut(15)); // a spacer
    myPanel.add(new JLabel("G(x,y): "));
    myPanel.add(gField);
    myPanel.add(Box.createHorizontalStrut(15));//spacer
    myPanel.add(new JLabel("B(x,y): "));
    myPanel.add(bField);

    String[] myClasses=ClassInfo.getClasses();
    //  { { { { } , { } } , { { } , { } } } , { { { } , { } } , { { } , { } } } }

    //Creating Menu Bar
    JMenuBar menuBar=new JMenuBar();
        JMenu functionsMenu=new JMenu("Functions");
            JMenuItem[] classes=new JMenuItem[myClasses.length];
            for(int i=0;i<ClassInfo.classes.length;i++) {
                String[][] classMethods=ClassInfo.showMethodsForClass(ClassInfo.classes[i]);//  { {static} , {instance} }
                final String className=ClassInfo.classes[i].getSimpleName();
                JMenuItem[] staticMethodsItem=new JMenuItem[classMethods[0].length];
                JMenuItem[] instanceMethodsItem=new JMenuItem[classMethods[1].length];
                JMenuItem staticMenuItem=new JMenuItem("Static methods");
                JMenuItem instanceMenuItem=new JMenuItem("Instance methods");
                JMenu staticMenu=new JMenu();
                staticMenuItem.add(staticMenu);
                JMenu instanceMenu=new JMenu();
                instanceMenuItem.add(instanceMenu);

                for(int a=0;a<classMethods[0].length;a++)   {
                    final String methodName=classMethods[0][a];
                    staticMethodsItem[a]=new JMenuItem(methodName);
                    staticMethodsItem[a].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e)  {
                            ClassInfo.copyToClipBoard(ClassInfo.staticWriteableString(methodName,className));
                        }
                    });
                    staticMenu.add(staticMethodsItem[a]);
                }

                for(int a=0;a<classMethods[1].length;a++)   {
                    final String methodName=classMethods[1][a];
                    instanceMethodsItem[a]=new JMenuItem(methodName);
                    instanceMethodsItem[a].addActionListener(new ActionListener()   {
                        public void actionPerformed(ActionEvent e)  {
                            ClassInfo.copyToClipBoard(ClassInfo.instanceWriteableString(methodName));
                        }
                    });
                    instanceMenu.add(instanceMethodsItem[a]);
                }

                classes[i]=new JMenuItem(className);
                JMenu methodTypeMenu=new JMenu();
                methodTypeMenu.add(staticMenuItem); //add static method submenu to the new class submenu
                methodTypeMenu.add(instanceMenuItem);//add instance method submenu to the new class submenu
                classes[i].add(methodTypeMenu); //Make the new class a submenu
                functionsMenu.add(classes[i]); //Add a new class in the functions menu
            }
    menuBar.add(functionsMenu);
    myPanel.add(menuBar);

    int result = JOptionPane.showConfirmDialog(null, myPanel, title, JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        String[] arr= {rField.getText(),gField.getText(),bField.getText()};
        return arr;
    }
    return null;
}

Its quite a bit I know. Any kind of help at all would be greatly appreciated. Thanks a lot!
EDIT: As per request, here is my courseInfo class:
public class ClassInfo {

    public static Class<?>[] classes={Outputer.class,Vector3.class};
/*
    public static void main(String[] args)  {
        System.out.println(classes[0].getMethods()[4].toGenericString());
        //public static int Outputer.fib(int) for static methods
        //public double Outputer.getOutputB(int,int) for instance methods
    }
*/
    public static String[] getClasses() {
        final JFrame classesFrame=new JFrame("Select a Class You want to Use");
        String[] classNames=new String[classes.length];
        for(int i=0;i<classes.length;i++)   {
            classNames[i]=classes[i].getName();
        }
        return classNames;
/*
        SpinnerListModel listModel=new SpinnerListModel(classNames);
        JPanel spinnerPanel= new JPanel();
        JPanel buttonPanel=new JPanel();
        JLabel spinnerLabel=new JLabel("Choose a Class Whose Methods You Want to Inspect");
        final JSpinner classSpinner = new JSpinner(listModel);
        spinnerPanel.add(spinnerLabel);
        spinnerPanel.add(classSpinner);

        JButton inspectButton=new JButton("Inspect Methods");
        buttonPanel.add(inspectButton);

        inspectButton.addActionListener(new ActionListener()    {
            public void actionPerformed(ActionEvent e)  {
                for(int i=0;i<classes.length;i++)   {
                    if(classes[i].getName().equals(classSpinner.getValue()))    {
                        showMethodsForClass(classes[i]);
                        classesFrame.dispose();
                        break;
                    }
                }
            }
        });

        classesFrame.add(spinnerPanel);
        classesFrame.add(buttonPanel);
        classesFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        classesFrame.pack();
        classesFrame.setVisible(true);
*/
    }//End Of Method----------------------------------------------------------------------------------------------------------------

    public static String[][] showMethodsForClass(Class<?> myClass)  {
        final String className=myClass.getSimpleName();
        Method[] methods=myClass.getMethods();
        String[] staticMethodStrings1=new String[methods.length];
        String[] instanceMethodStrings1=new String[methods.length];
        int statCount=0,instCount=0;
        for(int i=0;i<methods.length;i++)   {
            String method=methods[i].toGenericString();
            System.out.println(method); //For Debugging
            if(!method.contains("private") && !method.contains("java."))    {
                if(methodIsStatic(method))  {
                    staticMethodStrings1[statCount]=method;
                    statCount++;
                } else  {
                    instanceMethodStrings1[instCount]=method;
                    instCount++;
                }
            }
        } //End of for loop

        String[] staticMethods=new String[statCount];
        String[] instanceMethods=new String[instCount];

        for(;statCount>0;statCount--)   {
            staticMethods[statCount-1]=staticMethodStrings1[statCount-1];
        }

        for(;instCount>0;instCount--)   {
            instanceMethods[instCount-1]=instanceMethodStrings1[instCount-1];
        }
        String[][] arr= {staticMethods,instanceMethods};
        return arr;
/*      JFrame frame=new JFrame("Select a Method to Copy");
        frame.setLayout(new GridLayout());

        JPanel staticPanel=new JPanel();
        JPanel instancePanel=new JPanel();
        final JComboBox staticMethodsBox=new JComboBox(staticMethods);
        final JComboBox instanceMethodsBox=new JComboBox(instanceMethods);
        JButton copyStaticButton=new JButton("Copy this Static Method");
        JButton copyInstanceButton=new JButton("Copy this Instance Method");

        copyStaticButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)  {
                copyToClipBoard(staticWriteableString((String)staticMethodsBox.getSelectedItem(),className));
            }
        });

        copyInstanceButton.addActionListener(new ActionListener()   {
            public void actionPerformed(ActionEvent e)  {
                copyToClipBoard(instanceWriteableString((String)staticMethodsBox.getSelectedItem()));
            }
        });

        staticPanel.add(staticMethodsBox);
        staticPanel.add(copyStaticButton);

        instancePanel.add(instanceMethodsBox);
        instancePanel.add(copyInstanceButton);

        frame.add(staticPanel);
        frame.add(instancePanel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
*/

    }//End Of Method----------------------------------------------------------------------------------------------------------------

    private static boolean methodIsStatic(String methodString)  {
        return methodString.contains("static ");
    }//End Of Method----------------------------------------------------------------------------------------------------------------

    //public static int Outputer.fib(int) for static methods
    //public double Outputer.getOutputB(int,int) for instance methods

    public static String staticWriteableString(String methodStr,String className)   {
        return methodStr.substring(methodStr.indexOf('.')-className.length());
    }

    public static String instanceWriteableString(String methodStr)  {
        return methodStr.substring(methodStr.indexOf('.'));
    }

    public static void copyToClipBoard(String myString) {
        StringSelection stringSelection = new StringSelection (myString);
        Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
        clpbrd.setContents (stringSelection, null);
    }

}//End of Class---------------------------------------------------------------------------------------------------------------------

A: I think I understood the problem. You are getting mixed with JMenu and JMenuItem. This is the structure:
JMenuBar has a JMenu/JMenuItem has a JMenu/JMenuItem
Change your internal for loop to this and it should work:
JMenuBar menuBar=new JMenuBar();
JMenu functionsMenu=new JMenu("Functions");
JMenuItem[] classes=new JMenuItem[myClasses.length];
for(int i=0;i<ClassInfo.classes.length;i++) {
    String[][] classMethods=ClassInfo.showMethodsForClass(ClassInfo.classes[i]);//  { {static} , {instance} }
    final String className=ClassInfo.classes[i].getSimpleName();
    JMenuItem[] staticMethodsItem=new JMenuItem[classMethods[0].length];
    JMenuItem[] instanceMethodsItem=new JMenuItem[classMethods[1].length];
    JMenu staticMenu=new JMenu("Static Methods");
    JMenu instanceMenu=new JMenu("Instance Methods");

    for(int a=0;a<classMethods[0].length;a++)   {
        final String methodName=classMethods[0][a];
        staticMethodsItem[a]=new JMenuItem(methodName);
        staticMethodsItem[a].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)  {
                ClassInfo.copyToClipBoard(ClassInfo.staticWriteableString(methodName,className));
            }
        });
        staticMenu.add(staticMethodsItem[a]);
    }

    for(int a=0;a<classMethods[1].length;a++)   {
        final String methodName=classMethods[1][a];
        instanceMethodsItem[a]=new JMenuItem(methodName);
        instanceMethodsItem[a].addActionListener(new ActionListener()   {
            public void actionPerformed(ActionEvent e)  {
                ClassInfo.copyToClipBoard(ClassInfo.instanceWriteableString(methodName));
            }
        });
        instanceMenu.add(instanceMethodsItem[a]);
    }

    classes[i]=new JMenu(className);
    classes[i].add(staticMenu); //add static method submenu to the new class submenu
    classes[i].add(instanceMenu);//add instance method submenu to the new class submenu
    functionsMenu.add(classes[i]); //Add a new class in the functions menu
}
menuBar.add(functionsMenu);


text:
Q: Is there any advantage in stacking multiple images vs a single long exposure? Suppose I have a source object that is not time varying, to be concrete let's say it's a galaxy. Is there anything additional that can be learned or done with multiple short exposure images of exactly the same field as compared to a single long exposure, given that the total integration time is identical? I'm thinking of things along the lines of noise suppression, background removal, image processing magic...
So far the only thing I can think of is that a long exposure could saturate the detector (I'm thinking CCD here). Short exposures could avoid this, allowing for accurate photometry across the entire image. I've tagged this [astronomy] since that's the area of application I'm most familiar with, but perspectives from other fields are welcome.

A: I don't know about astronomy, but one reason it can be useful in normal photography is to combat camera shake by auto-aligning the images before blending them. This can be useful if you want to take a really long exposure but there isn't a stable place to set up a tripod. The image alignment can be done in Photoshop or using a utility called align_image_stack. With patience it should even be possible to take hand-held long exposure shots this way, though I admit I haven't tried that.

A: Stacking is something that is done all the time in infrared astronomy. This is done because CCD technology doesn't work for wavelengths in the range of roughly 2 to 10 microns, and beyond, so they use infrared detector arrays like the HAWAII line of infrared arrays by TeleDyne. Typically, though somewhat less so as time goes on, the infrared arrays will have defects like stuck pixels, cross talk noise, etc.
To work around this, the users of such arrays will take an image, move the telescope by a fraction of the field of view, take another image, and repeat as necessary. This allows them to reject bad pixels and smooth out pattern noise. The other advantages of doing this are that it increases the dynamic range of the stacked image, as you asked about, and allows for the removal of transient signals like: asteroids, satellites, and cosmic ray hits. The LSST will use image pairs to aid in cosmic ray rejection.
The downside of this approach is that the process of reading the data out of the detector it adds an amount of noise to the signal (known as "read noise"). Because of this, your sensitivity will go up like the square root of the number of images (roughly, square root of time), instead of linearly with time. Because of this, if you want high dynamic range you're better off not just stacking, but also varying your exposure time - short image(s) for the bright parts of the field, and long images for the faint parts, with the rejection of the saturated pixels done in software. If you're taking this sort of approach with a CCD, you're going to want to rotate the fields between the long exposure because when CCDs saturate they tend to cross bleed along a row.
I don't know how possible this is in a non-professional setting, but an approach some cameras use is something called a "drift scan" (for example, the SDSS imaging detector). See, CCDs read out the charge from the pixels by shifting the whole image across the pixel array, and reading out when the charge reaches an edge of the chip. If you move the charge across the chip at the same rate the image of the sky is moving across the chip, you can continuously scan a strip of the sky.

A: The voice of bitter experience, here, to tell you about a problem that a properly working observatory shouldn't have to worry about. But I did the time I was working on a "serious" astronomy project.

Stacking medium length images provides some protection against faulty tracking. In the event of a tracking failure during a single long exposure there is little you can do to recover, but a few tracking failures during a run of five to twenty medium length frames will still leave you with more than half the data (and a headache in-so-far as combining sets of frames that have different relative pointing, but it can be done).

My experience came in the early 1990s when putting a cooled CCD behind a 14" scope putting the whole thing on a mountain without human oversight and letting schoolkids submit observing requests over the internet (by FTP, because this was before the web) was a really cool new idea. But for cost and alignment reasons the project was using software tracking. Written is vBasic. We could get 30 second runs all the time. Five minute runs with some regularity, and essentially never got more that twenty minutes without a tracking fault.
But by stacking ten or so three minute runs we were able to image down to the nineteenth magnitude even with the box on top of the physic building for testing. And we actually tracked a MACHO-micro-lensing event light curve and matched the big boys which was my first "real" science experience.

A: If your exposures are short enough (a fraction of a second), you can even combat turbulence in the atmosphere. The trick is to do very many short images then pick the ones where a (bright) point source is sharpest and only stack those.
The technique is called Lucky Imaging and can deliver images as sharp as the Hubble Space telescope from ground-based instruments.
As an aside, your question could be - what should be my criterion for when not to stack images? - because the advantages to doing so, in terms of bad pixel rejection, cosmic ray removal and dynamic range, are so great. For optical CCD images, the break-even point is normally when the readout noise becomes a negligible contributor to the signal to noise of whatever you are trying to measure. Another consideration can be how long it takes to read out the CCD, which results in "dead-time".
Lucky Imaging relies on special electron-multiplying CCDs that can be read out very rapidly with modest readout noise, at the expense of a dispersion in the gain (number of output electrons per input photon). Most other astronomical CCDs minimise readout noise at the expense of readout times of tens of seconds, but are highly linear.

A: I haven't done this for astronomy, but have used an astronomy CCD down a microscope for electroluminescence and have also used cooled imaging CCDs for spectroscopy.  Although I have often set the experiment up to measure potential time-variation, there are quite a lot of advantages even for an unchanging source.

*

*Dynamic range: If your CCD has 12 bits, you can represent $2^{12}$ different values.  That's quite a lot, but if you are interested in points that are $2^{10}\approx 1000$ times brighter than other points of interest, the dimmer ones will have only 100 counts when the brighter ones saturate.  You have essentially unlimited dynamic range adding in software.  This is often necessary in spectroscopy, where pixels are summed on-chip to reduce readout noise making saturation very likely.

*Charge bleeding: a very full pixel can leak charge into neighbouring pixels.  It doesn't happen fast unless it's saturated but it still happens.

*Cosmic rays and other random events: They're often called cosmic rays, but some also come from nuclear decay.  These are bright spots or tracks on single images.  Multiple images allow you to deal with these outliers (there are a few techniques, but for a simple example you could exclude the bottom n% and top n% of values when averaging/summing, on a per-pixel basis).

*Experimental issues: you can re-register images to deal with your instrument not being as stable as you'd like (if you have reference features), or you can discard images if a stray light source affected a subset of frames (someone turned the roomlights on, an aeroplane flew past your telescope, etc.).  This is also relevant if your sample died or your telescope tracked until there was an obstruction/light source in the field of view.

A: A significant increase in dynamic range can be achieved by taking exposures with different exposure settings.  Wind,vibration, periodic errors etc. Can be combined with all other techniques.  It is used in spectrum analyzers under the name of video averaging. Can also be used in radio astronomy. I wonder if it could have been adapted to address the reciprocity failure in film?


text:
Q: Center cursor on focus in div contentEditable (centered horizontally and vertically) I have table with many textarea's (already changed to div's with attribute contentEditable), also with CSS I done that the innerHTML is centered horizontally and also vertically. Everything is working fine, just one thing is not OK - when you enter div, so its focused, the cursor is in the left top corner, but when you start writting its moved to the center.
How can I do, that when you focus the div, the cursor will be right in the center?
See demo here
Thanks a lot.
EDITED:
Sorry, my fault, its not working only in Firefox.

A: In FF you need to reset your div to an inline-box and regulr vertical-align so it stands in the middle of the cell: DEMO
.termin:focus{/* only once focused, else nothing to click on if empty */
    height: auto;
    width:auto;
    display:inline-block;
    vertical-align:top;
}

You need to fix your valign to td too : vertical-align:center; does not exist :)
.terminy td {
    text-align: center;
    vertical-align:middle;/* fixed with a valid value*/
    height: 60px;
    background-color: #fff;
}


text:
Q: AWS Lake Formation AccessDenied I've enabled Lake Formation and tried to create a Database but no matter what I still get an error:
Insufficient Lake Formation permission(s): Required Create Database on Catalog
I'm using root account with all privileges. I even gave AWSLakeFormationDataAdmin privilege explicitly without success. I've added myself (user) to Data Lake Administrator but I cannot add myself to Database Creator (AWS Lake Formation > Permissions > Admins and Database Creators):
Resource does not exist or requester is not authorized to access requested permissions.
So basically the only thing I'm capable of is to register S3 location.
Is there something I do wrong?


text:
Q: Azure "easy auth" OpenID Connect scope I've tried setting up signaturgruppens eID demo (OIDC) using "Easy auth" in the authentication settings of a .NET function app.
Settings looks like following:

Metadata URL
https://pp.netseidbroker.dk/op/.well-known/openid-configuration
Client ID
0a775a87-878c-4b83-abe3-ee29c720c3e7
Client Secret
rnlguc7CM/wmGSti4KCgCkWBQnfslYr0lMDZeIFsCJweROTROy2ajEigEaPQFl76Py6AVWnhYofl/0oiSAgdtg==
When I get to the scopes section of this however I get:

I want to add the scopes "openid nemid mitid" but i can't figure out how and where this portal is?
When trying to access a securet endpoint i also get an error has occured because the scope is invalid:

So how do i add the scopes?

A: I found a solution.
Use the azure resource explorer (preview):
https://resources.azure.com/
Find the auth2 settings:
subscriptions/{subscription-id}/resourceGroups/{rg-name}/providers/Microsoft.Web/sites/{app-name}/config/authsettingsV2
Add the scopes in the customOpenIdConnectProviders:


text:
Q: Is this really considered an object? From c++ book Picture of text

To read something, we need somewhere to read into; that is, we need somewhere in the computer's memory to place what we read. We call such a "place" an object. An object is a region of memory with a type that specifies what kind of information can be placed in it. A named object is called a variable. For example, character strings are put into string variables and integers are put into int variables. You can think of an object as a "box" into which you can put a value of the object's type

An object is a region of memory with a type that specifies what kind of information can be placed in it? Here they give an example with ints and strings which are like built in datatypes, I already know some oop so I was kinda confused because like I thought an object was kinda its own separate entity with its own user created datatype? I get that all objects have their own region of memory but they're basically calling a variable of type int, age, with the value 42 an object. Is this correct?

A: This is the wording from the C++ standard [intro.object]:

The constructs in a C++ program create, destroy, refer to, access, and
manipulate objects. An object is created by a definition, by a
new-expression ([expr.new]), by an operation that implicitly creates
objects (see below), when implicitly changing the active member of a
union, or when a temporary object is created ([conv.rval],
[class.temporary]). An object occupies a region of storage in its
period of construction ([class.cdtor]), throughout its lifetime, and
in its period of destruction ([class.cdtor]).

There is more to read about objects, I just picked this paragraph from the intro so you can see that the term "object" in C++ is more general than "instance of a user defined class". Note how the last sentence is quite similar with what Bjarne wrote in the book. What you refer to (instance of a class) is called "class object".
A perhaps more readable introduction to objects in C++ can be found here: https://en.cppreference.com/w/cpp/language/object.
PS: I am not a historian, but I suppose that the term "object" was already in wide-spread use before Object Orientation came into existance. There have been objects before. They were not invented by OOP, just put into the focus. Also note that C++ is not a (pure) OOP language, but rather multi-paradigm.

A:
but they're basically calling a variable of type int, age, with the value 42 an object. Is this correct?

They're correct.

I already know some oop

Modern OOP nomenclature is different from nomenclature of C++.

and strings which are like built in datatypes

The std::string type is a class i.e. a "user defined" data type (although it is provided by the standard library).


text:
Q: QMainWindow:showMaximized only works the first time it is called I have a function button_max_slot that use showMaximized to maximize the window, and another function button_restore_slot to restore the window's size and place. the first time I call the button_max_slot it works great, then I use button_restore_function to restore window's size and place. But the second time I call the button_max_slot to maximize the window, it didn't work. I call self.isMaximized() and it returns true, but actually the window doesn't maximized.What should I do to fix this problem?Here is a minimal reproducible example:
from PyQt5 import  QtWidgets
import sys

class MyWindow(QtWidgets.QMainWindow):
    last_geometry = None
    def __init__(self):
        super().__init__()
        self.resize(960, 540)

        self.ButtonMax = QtWidgets.QPushButton(self)
        self.ButtonMax.setObjectName("ButtonMax")
        self.ButtonMax.setText("Max")
        self.ButtonMax.move(100, 100)

        self.ButtonRestore = QtWidgets.QPushButton(self)
        self.ButtonRestore.setText("Restore")
        self.ButtonRestore.setObjectName("ButtonRestore")
        self.ButtonRestore.move(300, 100)
        self.ButtonRestore.setEnabled(False)

        self.ButtonMax.clicked.connect(self.button_max_slot)
        self.ButtonRestore.clicked.connect(self.button_restore_slot)

    def button_max_slot(self):
        self.last_geometry = self.geometry()
        self.showMaximized()
        self.ButtonRestore.setEnabled(True)
        self.ButtonMax.setEnabled(False)

    def button_restore_slot(self):
        self.setGeometry(self.last_geometry)
        self.ButtonRestore.setEnabled(False)
        self.ButtonMax.setEnabled(True)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    myshow = MyWindow()
    myshow.show()
    sys.exit(app.exec_())

A: tl;dr
Use showNormal() instead of setGeometry() to restore the window state.
Explanation
While not intuitive, it's still possible to set a geometry of a window even if its state should not allow it, and that's because setting the state of a window is not the same as setting its geometry.
Simply put, setting the window state tells the underlying platform/window manager to "choose" the geometry of the window based on the specified state, while setting the geometry asks the system to explicitly set the position and size of the window. Whether the system allows it, is another story.
An important thing to consider is that a QWidget (even a top level one, including a QDialog or a QMainWindow) is not the actual window shown on the screen. What you see is the QWindow (an abstract representation of the system's window for that widget), which is what actually contains the QWidget (or any of its inherited classes). Setting the state acts on the QWindow, while setting the geometry normally acts on the contained widget, excluding the possible window frame.
For instance, I'm able to reproduce your issue on my Linux system, but ekhumoro cannot, even though we both are using Linux (we're both using similar window managers, but they're still different: he's on OpenBox, I'm on FluxBox). Furthermore, I get inconsistent behavior after pressing the "Max" button, even if using the system features.
The fact that you got a maximized window state even if it doesn't look like it is, is exactly related to that: the state is maximized, the geometry isn't (because you changed it).
Consider it the other way around: you can manually resize a window in order to precisely occupy the whole available screen size, but that doesn't make it maximized: you can still probably see the "maximize" button in it's title bar (not the "normalize" one), and maybe even the window borders that are normally hidden when the window is actually maximized.
Note that the inconsistent behavior shown on different OS or window managers relies on two sides: the OS/wm implementation and Qt attempts to use a "standardized" behavior across all systems.
The solution is simple: just restore the state using showNormal() instead of setGeometry().
It usually works on all systems, with the exception of some very specific window managers on linux (and maybe some "non standard" behavior in recent Windows/MacOS versions), but it's the accepted approach.
For those cases, you might consider storing and restoring the geometry by overriding the top level window's changeEvent(), checking if the event.type() is a WindowStateChange and eventually decide the behavior based on the current windowState() and the oldState() of that event.
Remember that window states are flags, so they can be an OR combination of Qt.WindowState enums.


text:
Q: Does anyone know about AppExchange App Analytics's Price? I currently consider use AppExchange App Analytics to analytics all my product. But I cannot found the price information about it, does anyone know about the detail? Where I can found such document?

A: Partners get app analytics as part of the partner benefits (so no extra cost). You do, however, need to raise a Partner Support case to have it enabled on your PBO/LMO as covered here - search for "log a case".


text:
Q: How to configure nginx to access website using www I have setup a raspberry pi web server. I'm using nginx and google domains. I have a conf file for that domain in sites-available I configured the server_name to my domain name www.domain.com .domain.com;
The problem is that I can only access the website using .domain.com. When I try using www.domain.com I get redirect to ISP page (unable to find..).

A: *

*Login to your domain provider's dashboard

*If you haven't already added an A record to your DNS settings select Manage DNS and add an A record pointing to your IP address of the host.

*You'll essentially need to add a CNAME record to your domain's DNS settings. The 'Name' field should be www

*Depending on your provider you may have to wait till about 2- 48hrs to allow it to propagate.


text:
Q: Make Bootstrap 4 navbar button always visible & right aligned on any screen size I'm using the latest Bootstrap 4 and MDB for a navbar.
How can I make this button visible on the right side near hamburger icon also?
I can't find a correct solution using only m*-auto. If I make it right on mobile screens, then it does not show right on the desktop and the other way round.
I don't want to put two buttons inside.

Navbar
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">

</button>

            Home (current)

            Features

            Pricing

            Dropdown link

                Action
                Another action
                Something else here

    <button class="btn btn-sm align-middle btn-primary" type="button">Always visible here!</button>

A: Put your button as the second item in the HTML (within the navbar) and then add the classes ml-auto mr-3 order-lg-last to it and also remove the ml-auto class from the ul element like shown in the code snippet below.
Positioning the button as the second item in the HTML will have it in front of the toggler i.e. it will appear on the left side of the toggler on small screens.
The ml-auto class (margin-left:auto) will push the button to the right and mr-3 give it 3 units of right margin while order-lg-last will re-order it as the last item on screens that are large (lg) or larger.
Here's the code snippet (click "run code snippet" and expand to full page for testing):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    Navbar
    <button class="btn btn-sm align-middle btn-primary ml-auto mr-3 order-lg-last" type="button">Always visible here!</button>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
            aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home (current)

                Features

                Pricing

                    Dropdown link

                    Action
                    Another action
                    Something else here

To control the right margin of the button on lg screens and up, you could add the mr-lg-0 class to the button. 0 means no margin i.e. the same right margin as the toggler normally has.
And if you want the button to be on the right side of the toggler, you'd use the following code (using the same basic logic as described above):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    Navbar
    <button class="navbar-toggler ml-auto" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
            aria-expanded="false" aria-label="Toggle navigation">

    </button>
    <button class="btn btn-sm align-middle btn-primary ml-3 order-lg-last" type="button">Always visible here!</button>

                Home (current)

                Features

                Pricing

                    Dropdown link

                    Action
                    Another action
                    Something else here


text:
Q: How can I do a proxy call on anchor protocol terra ethereum transfer. error: UNPREDICTABLE_GAS_LIMIT I want to make a smart contract that deposits UST on the eth anchor protocol, by using the deposit function. Here you can find the docs of this function I try to call. https://docs.anchorprotocol.com/ethanchor/ethanchor-contracts/router . The function gets called trough a proxy contract. I found the implementation address by reading the proxy contract on etherscan.
TestContracts on Ropsten testnet:
proxy: 0x7537aC093cE1315BCE08bBF0bf6f9b86B7475008
etherscan: https://ropsten.etherscan.io/address/0x7537aC093cE1315BCE08bBF0bf6f9b86B7475008
implementation (ROUTERV2): 0x2ba0010394eb3e41454c7d79c0fb6e0deb67284b
etherscan: https://ropsten.etherscan.io/address/0x2ba0010394eb3e41454c7d79c0fb6e0deb67284b
I imported the ROUTERV2 contract for calling the proxy with the abi of the implementation.
my execution order is:

*

*deploying the contract

*approving the contract for spending the tokens from the sender using ethers.

*approveUST function on smart contract (I am not sure if this is necessary)

*calling the depositStable function.

I get the following error when calling the depositStale function  UNPREDICTABLE_GAS_LIMIT;
Below You see the contract I try to make. It should take the UST of the user and deposit it on eth anchor.
Here is a github link to the hardhat repo of the contract so you can simulate the bug and hopefully help me solving this issue.
https://github.com/tijgersoftware/Terra-anchor
I thank you for taking the time to read my question!
contract Anchor {
    address public proxy;
    address public operator;
    address public USTAddress;

    constructor(
        address proxy_,
        address operator_,
        address USTAddress_
    ) public {
        proxy = proxy_;
        operator = operator_;
        USTAddress = USTAddress_;
    }

    function approveUST() public {
        ERC20(USTAddress).approve(
            address(this),
            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
        );
    }

    function initDepositStable(uint256 amount) public {
        RouterV2(proxy).initDepositStable(amount);
    }

    function depositUST(uint256 amount) public {
        // InterfaceOfImplementationContract(proxyAddress).MethodBeingCalled(
        //     parameter,
        //     parameter,
        //     parameter
        // );

        ERC20(USTAddress).approve(
            address(this),
            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
        );
        RouterV2(proxy).depositStable(operator, amount);
    }
}

tags: solidity, smart contracts, ethereum, anchor protocol, terra, brdige trasfer.


text:
Q: How to find a text inside SQL Server procedures / triggers? I have a linkedserver that will change. Some procedures call the linked server like this: [10.10.100.50].dbo.SPROCEDURE_EXAMPLE. We have triggers also doing this kind of work. We need to find all places that uses [10.10.100.50] to change it.
In SQL Server Management Studio Express, I didn't find a feature like "find in whole database" in Visual Studio. Can a special sys-select help me find what I need?

A: This will work for you:
use [ANALYTICS]  ---> put your DB name here
GO
SELECT sm.object_id, OBJECT_NAME(sm.object_id) AS object_name, o.type, o.type_desc, sm.definition
FROM sys.sql_modules AS sm
JOIN sys.objects AS o ON sm.object_id = o.object_id
where sm.definition like '%SEARCH_WORD_HERE%' collate SQL_Latin1_General_CP1_CI_AS
ORDER BY o.type;
GO

A: There are much better solutions than modifying the text of your stored procedures, functions, and views each time the linked server changes. Here are some options:

*

*Update the linked server. Instead of using a linked server named with its IP address, create a new linked server with the name of the resource such as Finance or DataLinkProd or some such. Then when you need to change which server is reached, update the linked server to point to the new server (or drop it and recreate it).

*While unfortunately you cannot create synonyms for linked servers or schemas, you CAN make synonyms for objects that are located on linked servers. For example, your procedure [10.10.100.50].dbo.SPROCEDURE_EXAMPLE could by aliased. Perhaps create a schema datalinkprod, then CREATE SYNONYM datalinkprod.dbo_SPROCEDURE_EXAMPLE FOR [10.10.100.50].dbo.SPROCEDURE_EXAMPLE;. Then, write a stored procedure that accepts a linked server name, which queries all the potential objects from the remote database and (re)creates synonyms for them. All your SPs and functions get rewritten just once to use the synonym names starting with datalinkprod, and ever after that, to change from one linked server to another you just do EXEC dbo.SwitchLinkedServer '[10.10.100.51]'; and in a fraction of a second you're using a different linked server.
There may be even more options. I highly recommend using the superior techniques of pre-processing, configuration, or indirection rather than changing human-written scripts. Automatically updating machine-created scripts is fine, this is preprocessing. Doing things manually is awful.

A: here is a portion of a procedure I use on my system to find text....
DECLARE @Search varchar(255)
SET @Search='[10.10.100.50]'

SELECT DISTINCT
    o.name AS Object_Name,o.type_desc
    FROM sys.sql_modules        m
        INNER JOIN sys.objects  o ON m.object_id=o.object_id
    WHERE m.definition Like '%'+@Search+'%'
    ORDER BY 2,1

A: You can find it like
SELECT DISTINCT OBJECT_NAME(id) FROM syscomments WHERE [text] LIKE '%User%'

It will list distinct stored procedure names that contain text like 'User' inside stored procedure. More info

A: select text
from syscomments
where text like '%your text here%'

A: This one i tried in SQL2008, which can search from all the db at one go.
Create table #temp1
(ServerName varchar(64), dbname varchar(64)
,spName varchar(128),ObjectType varchar(32), SearchString varchar(64))

Declare @dbid smallint, @dbname varchar(64), @longstr varchar(5000)
Declare @searhString VARCHAR(250)

set  @searhString='firstweek'

declare db_cursor cursor for
select dbid, [name]
from master..sysdatabases
where [name] not in ('master', 'model', 'msdb', 'tempdb', 'northwind', 'pubs')

open db_cursor
fetch next from db_cursor into @dbid, @dbname

while (@@fetch_status = 0)
begin
    PRINT 'DB='+@dbname
    set @longstr = 'Use ' + @dbname + char(13) +
        'insert into #temp1 ' + char(13) +
        'SELECT @@ServerName,  ''' + @dbname + ''', Name
        , case  when [Type]= ''P'' Then ''Procedure''
                when[Type]= ''V'' Then ''View''
                when [Type]=  ''TF'' Then ''Table-Valued Function''
                when [Type]=  ''FN'' Then ''Function''
                when [Type]=  ''TR'' Then ''Trigger''
                else [Type]/*''Others''*/
                end
        , '''+ @searhString +''' FROM  [SYS].[SYSCOMMEnTS]
        JOIN  [SYS].objects ON ID = object_id
        WHERE TEXT LIKE ''%' + @searhString + '%'''

 exec (@longstr)
 fetch next from db_cursor into @dbid, @dbname
end

close db_cursor
deallocate db_cursor
select * from #temp1
Drop table #temp1

A: [Late answer but hopefully usefull]
Using system tables doesn't always give 100% correct results because there might be a possibility that some stored procedures and/or views are encrypted in which case you'll need to use DAC connection to get the data you need.
I'd recommend using a third party tool such as ApexSQL Search that can deal with encrypted objects easily.
Syscomments system table will give null value for text column in case object is encrypted.

A: -- Declare the text we want to search for
DECLARE @Text nvarchar(4000);
SET @Text = 'employee';

-- Get the schema name, table name, and table type for:

-- Table names
SELECT
       TABLE_SCHEMA  AS 'Object Schema'
      ,TABLE_NAME    AS 'Object Name'
      ,TABLE_TYPE    AS 'Object Type'
      ,'Table Name'  AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%'+@Text+'%'
UNION
 --Column names
SELECT
      TABLE_SCHEMA   AS 'Object Schema'
      ,COLUMN_NAME   AS 'Object Name'
      ,'COLUMN'      AS 'Object Type'
      ,'Column Name' AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%'+@Text+'%'
UNION
-- Function or procedure bodies
SELECT
      SPECIFIC_SCHEMA     AS 'Object Schema'
      ,ROUTINE_NAME       AS 'Object Name'
      ,ROUTINE_TYPE       AS 'Object Type'
      ,ROUTINE_DEFINITION AS 'TEXT Location'
FROM  INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%'+@Text+'%'
      AND (ROUTINE_TYPE = 'function' OR ROUTINE_TYPE = 'procedure');

A: I use this one for work.  leave off the []'s though in the @TEXT field, seems to want to return everything...

SET NOCOUNT ON

DECLARE @TEXT   VARCHAR(250)
DECLARE @SQL    VARCHAR(250)

SELECT  @TEXT='10.10.100.50'

CREATE TABLE #results (db VARCHAR(64), objectname VARCHAR(100),xtype VARCHAR(10), definition TEXT)

SELECT @TEXT as 'Search String'
DECLARE #databases CURSOR FOR SELECT NAME FROM master..sysdatabases where dbid>4
    DECLARE @c_dbname varchar(64)
    OPEN #databases
    FETCH #databases INTO @c_dbname
    WHILE @@FETCH_STATUS  -1
    BEGIN
        SELECT @SQL = 'INSERT INTO #results '
        SELECT @SQL = @SQL + 'SELECT ''' + @c_dbname + ''' AS db, o.name,o.xtype,m.definition '
        SELECT @SQL = @SQL + ' FROM '+@c_dbname+'.sys.sql_modules m '
        SELECT @SQL = @SQL + ' INNER JOIN '+@c_dbname+'..sysobjects o ON m.object_id=o.id'
        SELECT @SQL = @SQL + ' WHERE [definition] LIKE ''%'+@TEXT+'%'''
        EXEC(@SQL)
        FETCH #databases INTO @c_dbname
    END
    CLOSE #databases
DEALLOCATE #databases

SELECT * FROM #results order by db, xtype, objectname
DROP TABLE #results

A: I've used these in the past:

*

*Searching all user stored procedures for a table name

*Search and replace SQL Server data in all columns of all tables
In this particular case, where you need to replace a specific string across stored procedures, the first link is probably more relevant.
A little off-topic, the Quick Find add-in is also useful for searching object names with SQL Server Management Studio.  There's a modified version available with some improvements, and another newer version also available on Codeplex with some other useful add-ins as well.

A: Any searching with select statement yield you only object name, where search keyword contains.
Easiest and efficient way is get script of procedure/function and then search in generated text file, I also follows this technique :) So you are exact pinpoint.

A: You can search within the definitions of all database objects using the following SQL:
SELECT
    o.name,
    o.id,
    c.text,
    o.type
FROM
    sysobjects o
RIGHT JOIN syscomments c
    ON o.id = c.id
WHERE
    c.text like '%text_to_find%'

A: SELECT ROUTINE_TYPE, ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Your Text%'

A: Just wrote this for generic full outer cross ref
create table #XRefDBs(xtype varchar(2),SourceDB varchar(100), Object varchar(100), RefDB varchar(100))

declare @sourcedbname varchar(100),
        @searchfordbname varchar(100),
        @sql nvarchar(4000)
declare curs cursor for
    select name
    from sysdatabases
    where dbid>4
open curs
fetch next from curs into @sourcedbname
while @@fetch_status=0
    begin
    print @sourcedbname
    declare curs2 cursor for
        select name
        from sysdatabases
        where dbid>4
        and name <> @sourcedbname
    open curs2
    fetch next from curs2 into @searchfordbname
    while @@fetch_status=0
        begin
        print @searchfordbname
        set @sql =
        'INSERT INTO #XRefDBs (xtype,SourceDB,Object, RefDB)
        select DISTINCT o.xtype,'''+@sourcedbname+''', o.name,'''+@searchfordbname+'''
        from '+@sourcedbname+'.dbo.syscomments c
        join '+@sourcedbname+'.dbo.sysobjects o on c.id=o.id
        where o.xtype in (''V'',''P'',''FN'',''TR'')
        and (text like ''%'+@searchfordbname+'.%''
          or text like ''%'+@searchfordbname+'].%'')'
        print @sql
        exec sp_executesql @sql
        fetch next from curs2 into @searchfordbname
        end
    close curs2
    deallocate curs2
    fetch next from curs into @sourcedbname
    end
close curs
deallocate curs

select * from #XRefDBs


text:
Q: ggplot2, x-axis does not display ticks accurately I´m creating a barplot for my poster and have run into an issue.
I have a factor on my x axis, and a numeric on my y axis. I want my x axis to display every level of my factor, but with a differerent name.
To do that, I used the scale_x_discrete command, which is supposed to allow me to do that. However, it just deletes all ticks. Please find below all the code required to reproduce the problem.
F_Value <- c(13.011, 8.827, 15.586, 7.223, 16.190, 9.844)
Pathway <- as.factor(1:6)
Transformation <- as.factor(c(1, 1, 2, 2, 3, 3))
Outlier <- as.factor(c("Outliers", "Outlier Removed",
                       "Outliers", "Outlier Removed",
                       "Outliers", "Outlier Removed"))
df <- as.data.frame(cbind(F_Value, Pathway, Transformation, Outlier))
df

ggplot(df,
       aes(x = Pathway,
           y = F_Value, f
           ill = factor(Outlier))) +
  geom_bar(stat = "identity",
           position = "dodge") +
  scale_x_discrete(labels = c("1" = "Raw", "2" = "Raw, Trimmed",
                              "3" = "Log", "4" = "Log, Trimmed",
                              "5" = "Normalised", "6" = "Normalised, Trimmed")) +
  scale_fill_discrete(name = "Outliers",
                      labels = c("Trimmed", "Not Trimmed")) +
  xlab("Pathway") +
  ylab("F-Statistic") +
  ggtitle("F-Statistics by Pathway") +
  theme_light()

A: Convert your x variable to character:
ggplot(df,
       aes(x = as.character(Pathway),
           y = F_Value, f
           ill = factor(Outlier))) +
  geom_bar(stat = "identity",
           position = "dodge") +
  scale_x_discrete(labels = c("1" = "Raw", "2" = "Raw, Trimmed",
                              "3" = "Log", "4" = "Log, Trimmed",
                              "5" = "Normalised", "6" = "Normalised, Trimmed")) +
  scale_fill_discrete(name = "Outliers",
                      labels = c("Trimmed", "Not Trimmed")) +
  xlab("Pathway") +
  ylab("F-Statistic") +
  ggtitle("F-Statistics by Pathway") +
  theme_light()


text:
Q: Android volley memory leak I have a service that use images from internal memory and updates them from the server.
My problem is that the simple fact of making an image request like this*, generates a small memory leak, which accumulates until the app crashes :(
Could anyone tell me how to get ride of it? Is it an issue of Cache?
My service is called every X time by alarm Manager.

    public void overwrite(final String urlImage, final int position ) {
    ImageRequest request = new ImageRequest(urlImage, //from URL matrix
            new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    System.out.println("SERVER_WALL GO--->> got overwrite Bitmap ");
                    }
                }
            }, 0, 0, null,
            new Response.ErrorListener() {
                public void onErrorResponse(VolleyError error) {
                    System.out.println("SERVER_WALL --->> : Error ");
                }
            });
    queue.add(request);
    return ;
}


text:
Q: Fetching credentials from AWS EC2 Parameter store and Set the Value in Configuration file I am fetching the value from aws parameter store and try to set the value in root env and Using the env file try to set it to config file.
** retrieveCredentials.js
**
const fetchCredentialsFromAWS = () => {
    return new Promise(async (resolve, reject) => {
        try {
            logger.info("AWS KMS Credentials")
            const ssmClient = new aws.SSM({
                region: 'region name'
            });
            const environment = 'stage'
            ssmClient.getParametersByPath({
                Path: `name/${stage}`,
                Recursive: true,
                WithDecryption: true,
            }, (err, data) => {
                if (data) {
        data.data.Parameters.forEach(item => {
        if (item.Name == 'username') {
         process.env.username = item.Valu
        }
           if (item.Name == 'password') {
         process.env.password=item.Value
           }
        if (item.Name == 'database') {
           process.env.database=item.Value
        }
    })
                    resolve({ status: "Success", code: 200, message: "Sucess" })
                } else {
                    resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: err })
                }
            });
        } catch (error) {
            resolve({ status: "NOT Valid", code: 202, message: "Validation Failed", data: null })
        }

    })

//config.js

        username: process.env.username,
        password: process.env.password,
        database: process.env.database,
        host: "localhost",

**Issues -
**Values are set in env and it is also set to the config file but it will set after the config file is read from the server and therefore it was read undefined before the value is set.
So, how to set the value so that config gets the details?
I try to set the value in the environment file and update the config file credentials using process.env.


text:
Q: rxjs: how to improve this case by rxjs operators in a functional reactive programming style? In my case, I have a function as following:
  private transformResData(data: Data[]): DataInfo[] {
    let userIDNames: Array<OBJIDName>;
    this.dataStoreService.userIDNames$.subscribe((res) => {
      userIDNames = res;
    })
    return data.map((each) => {
      return {
        id: each.id,
        userName: userIDNames.find(current => current.userId === each.referID).userName
      };
    })
  }

simply  speaking,  this function want to map the input data to a new form, and the output data containing a property userName, and input data only has property referId. I need to map referId to userName. Simple, yes?
And as you can see, the mapping relationship is obtained by rxjs as an Observable:
this.dataStoreService.userIDNames$ // Observable<Array<UserIDName>> of the id and name mapping

My current solution can work by subscribe to the Observable and get the data.
But I want to know how to do this in a more functional reactive programming way. My imagination is using rxjs operators like:
this.dataStoreService.userIDNames$.pipe(...)

The function still need to return plain array data instead of Observable.
How to do this? Thank you

A: You'll need to return an Observable or Promise, I removed the local variables and pass variable along the function chain.
private transformResData(data: Data[]): Observable<DataInfo[]> {
   return this.dataStoreService.userIDNames$.pipe(map(userIDNames => {
       return data.map((each) => ({
           id: each.id,
           userName: userIDNames.find(current => current.userId === each.referID).userName
         })
       })
    }))
}


text:
Q: How to assign values to any one or two prop using linq c# or inside generic method? public class Company
{
    public int id { get; set; }
    public int Name { get; set; }
    public int Address{ get; set; }

}

List<Company> listofCompany = new List<Company>();

listofCompany is already filled and having some data.I want to replace its id and Name using linq
I can able to do it using foreach like below
 foreach (var item in listofCompany )
                        {
                            item.id= 123;
                            item.Name= 999;
                        }

But is there any better way to do it without foreach because my foreach code is there inside other method which is a generic method like below -
MyData<T>(List<T> anylist){}

A: Assuming you're alright with generating new Company objects then you can use Select along with ToList.
listofCompany.Select(x => new Company
               {  Id = 123,
                  Name = 999,
                  Address = x.Address
               }).ToList();

Otherwise, if you want to modify the objects in place then you're better off with your current approach.
On another note, why is Name and Address represented as int? seems strange as usually it's represented as a string.