text:
Q: Data type used in action forms Hi can somebody explain that if i declare variables of other types (except string) in the form beans what problems I might face ?

A: Your request parameters are Strings. If you have different type of parameters in your form, when binding the request, Struts will perform conversions from String to your parameter types.
This is where problems can occur.
Imagine you have a property that is of type int and you request some String that fails to convert to an int (e.g. contains letters – but this is already a data validation issue).
Now, an int must always have a value since it is a primitive, so Struts will put 0 in it and fail silently. When you will use that field with the value 0 you won't know if you had an error or the user inserted 0 on his own. You can face this problems with other types of fields also.
You have to be in control of the binding, don't always count on Struts.

A: Take a look at http://jtute.com/struts/0401.html

SUMMARY: What data types should you
  use for an action form's properties?
  Here are some suggestions.

A: The information from the browser to the server goes over HTTP, and there is no awareness of data types or objects, so your best bet is to use String types.


text:
Q: Generic way of retrieving an object out of the database I am trying to make a part of my code generic.

The ungeneric code:
public static User GetUser(int id)
  {
     using (var db = new BroodNodigContext())
     {
        return db.Users.FirstOrDefault(u => u.Id == id);
     }
  }

The code which I need but chopped to it's brim:
public static object FooBar<T>(int id)
  {
     using (var db = new DatabaseContext())
     {
        return db.T.FirstOrDefault(t => t.Id == Id);
     }
  }

What I got:
public static object GetTypeOutOfDatabase<T>(int id)
  {
     using (var db = new DatabaseContext())
     {
        dynamic test = typeof(T);
        db.Set<test>();

        return null;
     }
  }

I was told That I could use db.Set<>() to make it generic, but I fail to use correctly.
Do you perhaps know how to make the T into a reference type (like User) so I can put it in the db.set<>()?

A: Entity framework provides a Find function which will look things up by primary Key.
NOTE this takes in an object[] which is used in the find method, just pass your id in an let EF work it's magic, as a hack I've provided params to make it easier to call
public static object FooBar<T>(params object[] id)
{
    using (var db = new DatabaseContext())
    {
        return db.Set<T>().Find(Id);
    }
}

This will work for your use case but later on you may find you need to generate your own custom expression which will be a bit more complicated

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use an arraylist without spaces ArrayList<String> values = new ArrayList<>();
    values.add("APAC");
    values.add("North America");
    values.add("South America");
    values.add("Europe");

System.out.println(values);

This will print :
[APAC, North America, South America, Europe]

Is there a way I can get the output as [APAC,North America,South America,Europe] without spaces after ','. There is a similar question here but it actually uses a StringBuilder and all that. Is there an easier way to get this output?

A: When you call
System.out.println(values);

Java will call the toString() method on values, and output the returned String.
We can call toString() manually, and then modify the returned String as we would any other. As such, providing ", " doesn't appear in your list, the following should work fine:
System.out.println(values.toString().replace(", ", ",");

A: Using google's guava:
System.out.println("["+Joiner.on(",").join(values)+"]");

The best place to put this would be in a subclass that override the toString method

A: With Java8 Stream-API:
System.out.println("[" + values.stream().collect(Collectors.joining(",")) + "]");

A: Create your own class extending ArrayList and override toString() Method. See
AbstractCollection#toString()

A: Extend ArrayList into your own class and override toString() method as your need.

A: Might not be the easiest solution for this simple case, but in general you might benefit from using some 3rd party collection library for this kind of operations.
Should you wish include Guava to your project this will allow you to rewrite the code above in the following way:
Joiner joiner = Joiner.on(",");
List<String> values = ImmutableList.of("APAC", "North America", "South America", "Europe");

String valuesString = joiner.join(values);
System.out.println(valuesString);

Also, if you're already using Java 8, then lambda expressions already introduce mkString function. See this blog post for good explanation: http://lauer.bz/blog/2013/07/scala-mkstring-in-java-8 on how to use it for collections on your project.


text:
Q: Video plugin installation stops in social engine after domain.com/install/manage/query I am facing an issue with social engine video plugin installation. I have installed some other plugins all were installed well . In the case of video plugin installation process stops in the step domain.com/install/manage/query. It shows a blank white page
I am using 4.7.0
Thanks in advance

A: try to enable error reporting in the .htaccess file in the SocialEngine's root folder, it may show you some sort of php errors and search for solutions.


text:
Q: Different result when using subquery and join : SQL-1454. Active Users Input:
Accounts table:
+----+----------+
| id | name     |
+----+----------+
| 1  | Winston  |
| 7  | Jonathan |
+----+----------+
Logins table:
+----+------------+
| id | login_date |
+----+------------+
| 7  | 2020-05-30 |
| 1  | 2020-05-30 |
| 7  | 2020-05-31 |
| 7  | 2020-06-01 |
| 7  | 2020-06-02 |
| 7  | 2020-06-02 |
| 7  | 2020-06-03 |
| 1  | 2020-06-07 |
| 7  | 2020-06-10 |
+----+------------+
Output:
+----+----------+
| id | name     |
+----+----------+
| 7  | Jonathan |
+----+----------+

Explanation:
User Winston with id = 1 logged in 2 times only in 2 different days, so, Winston is not an active user.
User Jonathan with id = 7 logged in 7 times in 6 different days, five of them were consecutive days, so, Jonathan is an active user.
Active users are those who logged in to their accounts for five or more consecutive days.
Write an SQL query to find the id and the name of active users.
Return the result table ordered by id
I have encountered some problems with my codes doing this question.
My codes:
SELECT DISTINCT a.id, a.name
FROM Accounts a
LEFT JOIN Logins l
ON a.id = l.id
JOIN Logins l1
ON l.id=l1.id AND DATEDIFF(l.login_date, l1.login_date) BETWEEN 1 AND 4
GROUP BY l.login_date
HAVING COUNT(DISTINCT l1.login_date) = 4

Input
{"headers":{"Accounts":["id","name"],"Logins":["id","login_date"]},"rows":{"Accounts":[[182,"Gavriel"],[119,"Naftali"],[31,"Yaakov"],[136,"Menachem"],[142,"Sarah"],[204,"Daniel"],[49,"Ezra"],[27,"David"]],"Logins":[[142,"2020-6-27"],[119,"2020-6-29"],[31,"2020-6-26"],[27,"2020-6-27"],[182,"2020-7-2"],[136,"2020-6-28"],[142,"2020-7-5"],[27,"2020-6-29"],[136,"2020-6-27"],[49,"2020-7-1"],[204,"2020-7-1"],[49,"2020-7-5"],[204,"2020-7-3"],[49,"2020-7-3"],[31,"2020-7-3"],[204,"2020-7-3"],[142,"2020-6-30"],[119,"2020-6-26"],[142,"2020-6-29"],[136,"2020-7-2"],[49,"2020-7-2"],[182,"2020-7-4"],[119,"2020-6-29"],[49,"2020-6-30"],[136,"2020-7-5"],[27,"2020-7-2"],[136,"2020-6-28"],[31,"2020-6-29"],[204,"2020-7-3"],[142,"2020-6-29"],[31,"2020-6-30"],[204,"2020-6-27"],[204,"2020-7-2"],[182,"2020-6-27"],[31,"2020-7-3"],[119,"2020-7-4"],[142,"2020-6-27"],[119,"2020-6-27"],[27,"2020-6-26"],[142,"2020-7-2"],[27,"2020-6-28"],[136,"2020-6-26"],[119,"2020-6-27"],[142,"2020-7-1"],[27,"2020-7-1"],[31,"2020-6-29"],[204,"2020-6-28"],[136,"2020-6-28"],[204,"2020-7-3"],[31,"2020-6-28"],[182,"2020-6-29"],[49,"2020-7-4"],[204,"2020-6-27"],[136,"2020-7-5"],[142,"2020-7-4"],[31,"2020-7-2"],[182,"2020-7-1"],[204,"2020-6-28"],[31,"2020-7-4"],[136,"2020-7-1"],[136,"2020-6-26"],[27,"2020-7-4"],[27,"2020-6-29"],[31,"2020-7-2"]]}}

My Output:

{"headers": ["id", "name"], "values": [[49, "Ezra"], [136, "Menachem"], [142, "Sarah"], [182, "Gavriel"]]}

Expected Output:
{"headers":["id","name"],"values":[[49,"Ezra"]]}

Correct Answer:
SELECT DISTINCT l1.id,
(SELECT name FROM Accounts WHERE id = l1.id) AS name
FROM Logins l1
JOIN Logins l2 ON l1.id = l2.id AND DATEDIFF(l2.login_date, l1.login_date) BETWEEN 1 AND 4
GROUP BY l1.id, l1.login_date
HAVING COUNT(DISTINCT l2.login_date) = 4

In my answer, I join the Accounts table instead of use subquery as in answer. However, I don't understand why my code will lead to such an different output.

A: Please try this query:
with data as (
select
id,l_date,
--lag(l_date) over(partition by id order by l_date) lag_date,
l_date - lag(l_date) over(partition by id order by l_date),
case when l_date - lag(l_date) over(partition by id order by l_date) > 1 then 1 else 0 end as session_change

from login
),
staging_data as (
select
id,l_date,sum(session_change)
over(partition by id order by l_date rows between unbounded preceding and current row) as session
from data )
select id
from staging_data
group by id,session having count(*) >=5


text:
Q: Same session in different browser tabs in jsp-servlet if some user login in my website then he/she will open other tab from current browser then it continue with his/her home page without enter login cardinals again.
Can be possible to do with using of jsp/servlet/httpsession?
i have two ideas but i don't know how to do?
1) I can use filter for first time when login page load and then i will check if session generated or not.
2) I can check in home page whether session valid or not if yes then i will display home page and if no then redirected to login page.


text:
Q: How do I get the user details straight after login using Identity on ASP.NET Core? I'm using ASP.NET Core Identity to do the authentication on my website and I'm trying to log user id to the DB as soon as they login but I don't seem to be able to access them using the following code. The GetResult() returns null here but it works fine if it's on the next page, but just not in the OnPostAsync method where it needs to be.
Input.UserIDOrLogonName does not contain the user id.
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(Input.UserIDOrLogonName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            var userId = _userManager.GetUserAsync(HttpContext.User)
                         .GetAwaiter().GetResult().UserId;
            _audit.RecordAction(AuditType.LoginSuccess, userId);
            return LocalRedirect(returnUrl);
        }

Is there any other way to get to the instance of the User?

A: For HttpContext.User, it will work for sub-request after loging.
If you want to log UserId, try to find the user by email like
if (result.Succeeded)
{
    var user = await _userManager.FindByEmailAsync(Input.Email);
    var userId = user.Id;
    _logger.LogInformation("User logged in.");
    return LocalRedirect(returnUrl);
}


text:
Q: Laravel Passing Variable from a controller to another Controller I'm trying to pass a variable from a controller to another controller I tried using
Redirect::to('dashboard/'.$ssid.'/')->with(compact('wname'))

but does not work any idea how can I achieve this?
here is my code
Route
Route::get('dashboard/{ssid}/', 'HomeController@showDash');

LoginController
public function post_index()
  {

  if(Auth::attempt($credentials)){
    $users = User::where('username','=',$email)->get();
      foreach ($users as $value):
        $activated = $value['a_status'];
        $wname = $value['wholename'];

      endforeach;

      if($activated == 1):
          $red= Redirect::to('dashboard/'.$ssid.'/')->with(compact('wholename'));
      else:
          $red= View::make('login');
      endif;
      return $red;
}

 }

HomeController
public function showDash($ssid,$wholename)
{
 foreach ($wholename as $userVal):
        $fn = $userVal['firstname'];
        $ln = $userVal['lastname'];
     endforeach;
return View::make('dashboard')->with(compact('fn'));

}

The error I'm having is that Missing argument 2 for HomeController::showDash() as per laravel's debugger..

A: Updated answer based on the comments:
public function post_index()
{

    if(Auth::attempt($credentials)){
    $users = User::where('username','=',$email)->get();
    foreach ($users as $value){
        $activated = $value['a_status'];
        $wname = $value['wholename'];
    }
    if($activated == 1) {
        Redirect::to('dashboard/'.$ssid.'/')->with(['wholename' => $wholename]);
    }

    return View::make('login');
}

public function showDash($ssid)
{
    $wholename = (Session::has('wholename')) ? Session::get('wholename') : [];
    foreach ($wholename as $userVal) {
        $fn = $userVal['firstname'];
        $ln = $userVal['lastname'];
    }
    return View::make('dashboard')->with(compact('fn'));
}

Everything else can stay as is.
Update: fixed erroneous space in 'whole name' (autocorrect did that, sorry).


text:
Q: Getting External Sybol Error DirectX9 This worked perfectly in a different project but I get this error after moving it over to a different project
https://i.imgur.com/Jxwx8kG.png
https://i.imgur.com/37invFF.png
I am compiling in x86 & Release
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hSecInstance, LPSTR nCmdLine, INT nCmdShow)

{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SetWindowToTarget, 0, 0, 0);

WNDCLASSEX wClass;
wClass.cbClsExtra = NULL;
wClass.cbSize = sizeof(WNDCLASSEX);
wClass.cbWndExtra = NULL;
wClass.hbrBackground = (HBRUSH)CreateSolidBrush(RGB(0, 0, 0));
wClass.hCursor = LoadCursor(0, IDC_ARROW);
wClass.hIcon = LoadIcon(0, IDI_APPLICATION);
wClass.hIconSm = LoadIcon(0, IDI_APPLICATION);
wClass.hInstance = hInstance;
wClass.lpfnWndProc = WinProc;
wClass.lpszClassName = lWindowName;
wClass.lpszMenuName = lWindowName;
wClass.style = CS_VREDRAW | CS_HREDRAW;

if(!RegisterClassEx(&wClass))
    exit(1);

tWnd = FindWindow(0, tWindowName);
if (tWnd)
{
    GetWindowRect(tWnd, &tSize);
    Width = tSize.right - tSize.left;
    Height = tSize.bottom - tSize.top;
    hWnd = CreateWindowEx(WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED, lWindowName, lWindowName,  WS_POPUP, 1, 1, Width, Height, 0, 0, 0, 0);
    SetLayeredWindowAttributes(hWnd, 0, 1.0f, LWA_ALPHA);
    SetLayeredWindowAttributes(hWnd, 0, RGB(0, 0, 0), LWA_COLORKEY);
    ShowWindow( hWnd, SW_SHOW);
}

DirectXInit(hWnd);

for (;;)
{
    if(PeekMessage(&Message, hWnd, 0, 0, PM_REMOVE))
    {
        DispatchMessage(&Message);
        TranslateMessage(&Message);
    }
    Sleep(1);
}
return 0;

}


text:
Q: Reference for the degenerate orthogonal Procrustes problem $\newcommand{\SOn}{\operatorname{SO}_n}$
$\newcommand{\On}{\operatorname{O}_n}$
$\newcommand{\Sym}{\operatorname{Sym}_n}$
$\newcommand{\Skew}{\operatorname{Skew}_n}$
$\newcommand{\dist}{\operatorname{dist}}$
$\newcommand{\Sig}{\Sigma}$
$\newcommand{\sig}{\sigma}$
$\newcommand{\al}{\alpha}$
$\newcommand{\id}{\operatorname{Id}}$
This question is a reference request. Consider the following claim.

Let $A $ be a $n \times n$ real matrix.
Then an orthogonal matrix $Q$ is a closest matrix to $A$ in $ O(n)$ (w.r.t the Euclidean Frobenius norm) if and only if it is an orthogonal polar factor of $A$, i.e. if $A=QP$, where $P=\sqrt{A^TA}$.

Question: Where can I find a reference for this claim? (I am quite sure this is well-known)

I ask for a reference for the coincidence of the set of orthogonal minimizers with the set of all possible factors in the polar decomposition.

Note that if $A$ is invertible, then there is a unique polar factor, which is also the unique minimizer. I specifically look for references which deal with the general (possibly singular) case.
(BTW, the more interesting direction is why every minimizer is a polar factor).
I tried to look e.g. in this book, but found no mention of this.


text:
Q: Checking whether any of the string from a list of strings is present in a paragraph(string)? I have a list of strings and a string value in my bean file.
Here is my bean file
public class DataBean {
List<String> combinations;
    private String story;

    public String getStory() {
            return story;
        }
        public void setStory(String story) {
            this.story = story;
        }

    public List<String> getCombinations() {
            return combinations;
        }
        public void setCombinations(List<String> combinations) {
            this.combinations = combinations;
        }

         public void addString(String value) {
            if (combinations == null) {
                combinations = new ArrayList<String>();
            }
            combinations.add(value);
       }

I want to check whether the story consists of any of the strings from the list combinations
If yes then print true and if no then print false.
I want to create this rule in my DRL file file but I couldn't understand the syntax. I am totally new at drools kindly help me with this.
I could create and execute simple rules but I am not able to figure out rules of such nature.

A: Unless you have grossly mis-stated the nature of your problem, there is no simple way of writing a rule telling you whether the story is made up from the strings in combinations. I suggest that you write a
public static boolean isComposed(){
    // ...
}

in class DataBean implementing the algorithm (see my comment) and use this on the RHS to check whether a fact of type DataBean contains data according to this condition.
Edit According to the comment below my answer (but not in agreement with the phrase "whether the story consists of any of the strings from the list) you can write the following rule:
rule "check for word"
when
    Wordlist( $words: words )
    $word: String() from $words
    $story: Story( $text: text, $text.contains( $word ) )
then
    // String $story.text has $word as a substring
end

with classes
class Wordlist { List<String> words; ... }
class Story { String text; ... }

Note that the contains in the rule is java.lang.String.contains, which simply tests whether the argument is a substring of the String object. The rule will fire once for each word from the list words that occurs in text.
Also, this will produce misleading results. If, for instance, the story contains the word "portmanteau" and the list is made up from "port", "or", "man" and "ant", you'll get four incorrect firings. You can "cook" the preceding rule by using
rule "check for word"
when
    Wordlist( $words: words )
    $word: String() from $words
    $story: Story( $text: text,
                   $text.matches( ".*+\\b" + $word + "\\b.*" ) )
then
    // String $story.text contains the $word
end

I add this to emphasize that a question must be stated precisely in order to elicit useful answers. Maybe neither of my proposals is what you are looking for.


text:
Q: Setting up IPSec/Firewall for printer with ipv4 address, allowing ipv6 I have an HP P4014dn printer with a publicly accessible static IPv4 address. It's also enabled with a link-local FE80 IPv6 address.
I've setup the IPSec/Firewall settings to allow traffic from only the IPv4 address ranges we use on our campus. But there is also a WiFi network available outside that uses IPv6 addresses only. All of the IPv4 address can access the printer fine, but I can't seem to figure out how to allow IPv6 addresses through.
When I go into the printer firewall settings, it asks to specify a local and remote address. Even when I set the remote IPv6 range of our Wifi network, and set the local to all possible IPv6, I still am unable to access the printer from the WiFi.
The settings require that both local and remote be in the same IPv4/IPv6 protocol version.

Thanks in advance.

A: If your printer has only a link-local IPv6 address, then it is reachable via that address only from other devices on that specific layer 2 link.
In order to reach the printer via IPv6 from outside the LAN it's on, it needs a routable IPv6 address, such as a global or ULA address.


text:
Q: Can I remove the Y-axis counter on chart.js? I have a chart.js graph that looks like this:

What I'm trying to do is remove this counter of the y-axis:

I read through the documentation and searched for it here on Stack Overflow, but I can't seem to find what I'm looking for.
Thank you in advance.

A: You can set the ticks display to false in the options object like this:
options: {
scales: {
    yAxes: [{
    ticks: {
      display: false
    }
  }]
}
}

Will give this result:

You can also use the callback to return an ampty string as tick which as side effect also removes the horizontal grid lines like this
options: {
scales: {
    yAxes: [{
    ticks: {
      callback: () => ('')
    }
  }]
}
}

result:


text:
Q: Get rendered height of an html table cell I'm working on a calendar for a webpage that is dynamically generated via javascript. However, I cannot seem to get the cells to all be the same height, unless they're all empty. I've put div's in each cell, set the width and height to fixed, set max-heights and max-widths, and no matter what, the table seems to ignore the CSS entirely and resize itself as it pleases. What makes the issue even more infuriating is that the difference between a filled table cell and an empty one is a mere 7 pixels.
My most recent idea was to write a javascript/jquery function that goes through the cells, finds the largest cell, and resizes all the other cells to be the same size as that one (I don't particularly care how big the cells are provided they are all the same width and height). However, I've discovered that jquery's height and width functions, when parsed to ints, simply return the CSS value set for height and width, or if no value was set (or the value was set as auto) return 0. Is there a function that will give me the absolute width and height of a table cell? Alternatively, is there a way to keep the dimensions of a table cell completely fixed (where regardless of content, they will not resize).
HTML:

        Sunday
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday

CSS:
table {
    padding: 15px;
    border-radius: 2px;
    background-color:#fff;
}
.list_spaces {
    border: 1px solid #e1e1e1;
    text-align: center;
}
.day_spaces {
    background-image: url("../../Content/linen.png");
    text-align: center;
    width: 100px;
    overflow: hidden;
}
.cal_spaces {
    width: auto;
    height: auto;
    vertical-align: 50px;
    border: 1px solid #e1e1e1;
    border-top: 1px solid #e1e1e1;
    border-bottom: 1px solid #e1e1e1;
    border-right: 1px solid #e1e1e1;
    border-left: 1px solid #e1e1e1;
    overflow: hidden;
}
.cal_date_nums {
    text-align: right;
    position: relative;
    font-size: 16px;
    color: #999999;
    opacity: 0.58;
    right: 12px;
    top: 12px;
}
.cal_event_links {
    margin-left: 5px;
    margin-right: 5px;
    margin-top: 5px;
    margin-bottom: 5px;
}
.cal_actual_links {
    text-align: left;
    font-size: 12px;

}
.fix_cells {
    width: 100px;
    height: 114px;
}

Javascript that generates the table:
    function loadCalendar(cd) {
    document.getElementById("my_disp").innerText = findMonthandYear(cd.getMonth(), cd.getFullYear());
    document.getElementById("my_disp").setAttribute("data-month", cd.getMonth());
    document.getElementById("my_disp").setAttribute("data-year", cd.getFullYear());
    var sd = findMonthStart(cd.getMonth(), cd.getFullYear());
    for (var i = 0; i < sd; i++) {
        document.getElementById("wk1").innerHTML += ((i === 0 || i === 6) ? "

	" : "

	");
    }
    var dc = 1;
    for (var i = sd; i < 7; i++) {
        document.getElementById("wk1").innerHTML += (((i === 0 || i === 6) ? "

" : "

") + dc + "

	");
        dc++;
    }
    var dim = getDaysInMonth(cd);
    for (var w = 2; w <= 6; w++) {
        for (var i = 0; i < 7; i++) {
            if (dc <= dim) document.getElementById("wk" + w).innerHTML += (((i === 0 || i === 6) ? "

" : "

") + dc + "

	");
            else document.getElementById("wk" + w).innerHTML += ((i === 0 || i === 6) ? "	" : "	");
            dc++;
        }
        if (dc > dim) {
            if (w !== 6) {
                for (var i = 0; i < 7; i++)
                    document.getElementById("wk6").innerHTML += ((i === 0 || i === 6) ? "

	" : "

	");
            }
            break;
        }
    }
    for (var i = 0; i < evntsInfo.evntsCount; i++) {
        var dtid = removeTimeFromDates(evntsInfo.evntsDates[i]);
        if (document.getElementById(dtid) != null)
            document.getElementById(dtid).innerHTML += "" + evntsInfo.evntsTitles[i] + "\n";
    }
    currentDayColoring();
    fixSizes();
}

    function currentDayColoring() {
        var cd = new Date();
        var dtid = (cd.getFullYear().toString() + "-" + parseM(cd.getMonth()).toString() + "-" + parseD(cd.getDate()).toString());
        if (document.getElementById(dtid) != null) {
            document.getElementById(dtid).parentElement.parentElement.style.backgroundColor = "#D7E4EA";
            document.getElementById(dtid).parentElement.firstChild.style.fontSize = "x-large";
        }
    }

    function fixSizes() {
        var mheight = 0;
        var spaces = document.getElementsByClassName("cal_spaces");
        for (var i = 0; i < spaces.length; i++) {
            if (spaces[i].offsetHeight > mheight)
                mheight = spaces[i].offsetHeight;
            console.log("mheight: " + mheight);
        }
        for (var i = 0; i < spaces.length; i++) {
            spaces[i].offsetHeight = mheight;
        }
    }


text:
Q: Send a value from Mainactivity and display the value in another activity I am trying to make a simple quiz app and I want to display the score value in another activity(another screen) i.e. when I press the submit button the score activity should open and display the total score.
I have tried using intents but it hasn't worked. I am new at android programming and there could be some silly mistakes.
This is the MainActivity.java file.
package com.example.android.conanquiz;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //Question 1 Methods
    public void question1_click(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.haibara:
                if (checked) {
                    String correct = "Right Answer";
                    display_answer1(correct);
                    score++;
                }
                break;
            default: {
                String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q1_o1);
                display_answer1(wrong);
            }
            break;
        }

    }

    private void display_answer1(String answer) {
        TextView quantityTextView = (TextView) findViewById(R.id.answer_1);
        quantityTextView.setText(answer);
    }

    //Question 2 Methods
    public void question2_click(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.true_op:
                if (checked) {
                    String correct = "Right Answer";
                    display_answer2(correct);
                    score++;
                }
                break;
            default: {
                String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q2_o1);
                display_answer2(wrong);
            }
            break;
        }

    }

    private void display_answer2(String answer) {
        TextView quantityTextView = (TextView) findViewById(R.id.answer_2);
        quantityTextView.setText(answer);
    }

    //Question 3 Methods
    public void question3_click(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.q3_op3:
                if (checked) {
                    String correct = "Right Answer";
                    display_answer3(correct);
                    score++;
                }
                break;
            default: {
                String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q3_o3);
                display_answer3(wrong);
            }
            break;
        }

    }

    private void display_answer3(String answer) {
        TextView quantityTextView = (TextView) findViewById(R.id.answer_3);
        quantityTextView.setText(answer);
    }

    //Question 4 Methods
    public void question4_click(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.q4_op1:
                if (checked) {
                    String correct = "Right Answer";
                    display_answer4(correct);
                    score++;
                }
                break;
            default: {
                String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q4_o1);
                display_answer4(wrong);
            }
            break;
        }

    }

    private void display_answer4(String answer) {
        TextView quantityTextView = (TextView) findViewById(R.id.answer_4);
        quantityTextView.setText(answer);
    }

    //Question 5 Methods

    public void question5_click(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch (view.getId()) {
            case R.id.q5_op3:
                if (checked) {
                    String correct = "Right Answer";
                    display_answer5(correct);
                    score++;
                }
                break;
            default: {
                String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q5_o3);
                display_answer5(wrong);
            }
            break;
        }

    }

    private void display_answer5(String answer) {
        TextView quantityTextView = (TextView) findViewById(R.id.answer_5);
        quantityTextView.setText(answer);
    }

    //Submit Button
   public void onClickSubmit(View view){
        Intent scoreActivity = new Intent(MainActivity.this,Score.class);
        scoreActivity.putExtra("sendScore", score);
        startActivity(scoreActivity);

    }

}

This is the other activity java(Score.java) file
package com.example.android.conanquiz;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class Score extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_score);

        Intent scoreActivity = getIntent();
        int totalScore = scoreActivity.getIntExtra("sendScore", 0);
        displayScore(totalScore);

    }

    public void displayScore(int score) {
        TextView scoreTextView = (TextView) findViewById(R.id.score);
        scoreTextView.setText(score);
    }

}

A:
Try to print score on button click using log. if score is not null than write below code.
From Activity

Intent intent = new Intent(getBaseContext(), Score.class);
intent.putExtra("EXTRA_SCORE", score);
startActivity(intent);

To Activity

 Intent intent = getIntent();
 int intValue = intent.getIntExtra("EXTRA_SCORE", 0);


text:
Q: Spotify Error: Exception when newActivity r=ActivityRecord{2e084abc token=android.os.BinderProxy@ I'm working through the tutorial on the Spotify website with Android Studio. I've managed to get to the end and run the app (BUILD SUCCESSFUL).
However, when the app opens on my real device, it crashes right away.
In the Android Monitor the first error is:
Exception when newActivity r=ActivityRecord{2e084abc token=android.os.BinderProxy@

I've googled it and this came up. After reading through the accepted answer and adding the code to my app, I get errors. I don't even know if I'm on the right track given that the Exceptions aren't exactly the same.
My question is: What is it causing this error? and how can I fix it?

A: The IDE I'm using is IntelliJ IDEA. When I added the code from the Spotify website, two red errors popped up.
First one was it suggested that I change the class to an abstract class. Changing this back to a normal class solved my problem.
Second one was the onLoginFailed() method. It takes an (int i), however the error 'Cannot resolve symbol i' pops up. I replaced it with an (Error error), It got rid of the error and the app runs fine.
Hope this helps someone.


text:
Q: Calling a Function to a Certain Parameter in Pygame I'm new to programming. I'm using python 3.4 and pygame cp34 on Windows 8. I've created this little guy and I'm seeing what I can do with it. What happens when I load this part of the code in my program (by calling the function with "guy()" in the main program loop), is that it seems to appear by default in the (0,0) parameter (upper left of the screen). According to all the instructions I've read on the internet, all I have to do is call, say, "guy(screen, 100, 100)" in the main program loop and the image should appear with the upper-left of the image starting at the 100,100 x y parameters. What happens instead is that the guy always stays in the upper-left corner of the screen at 0,0 regardless of my instructions. No error message. The instructions just get completely ignored. Is there something in my def that is preventing me from giving parameter instructions?
Again, the guy appears if called in the main program loop, but the parameters never change from the upper-left corner of the screen.
import pygame

g = pygame.Color('green')
c = pygame.Color('cyan')
b = pygame.Color('brown')
w = pygame.Color('white')
r = pygame.Color('red')
o = pygame.Color('orange')
e = pygame.Color('yellow')

data = [
 [c, c, c, w, c, c, c, w, c, c, w, c, c, c, w, w, c],
 [c, c, w, w, w, c, c, w, w, c, w, w, c, w, w, w, w],
 [c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, o, o, o, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, o, o, o, c, c, c, c, c, c],
 [c, c, c, c, c, e, c, c, g, e, g, c, c, e, c, c, c],
 [c, c, c, c, c, c, e, c, e, e, e, c, e, c, c, c, c],
 [c, c, c, c, c, c, c, e, c, e, c, e, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, r, r, r, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, r, r, r, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, r, r, r, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, b, c, b, c, c, c, c, c, c],
 [c, c, c, c, c, c, c, c, b, c, b, c, c, c, c, c, c],
 [g, g, g, g, g, g, g, r, r, g, r, r, g, g, g, g, g],
 [g, g, g, g, g, g, g, g, g, g, g, g, g, g, g, g, g],
 ]

 def guy(screen, x, y):
 for y, row in enumerate(data):
     for x, color in enumerate(row):
     pic = pygame.Rect(x*5,y*5,5,5)
     screen.fill(color, pic)

A: You're overriding the inputs x and y with the return value from enumerate. change to def guy(screen, x1, y1): and pic = pygame.Rect(x*5+x1,y*5+y1,5,5)


text:
Q: Add marker to google map using SQLite I'm working on an Hybride app using Ionic framework and i just want to know if i can add markers in google map using SQLite.
If yes! can you give me hint please.
And thank you

A: Looking at google map dev:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};

You can probably replace the lat and lng with your variables.
The variables is then retrieved from your SQLite database based on your query.
If you are using SQLite plugin for ionic, do remember to declare the plugin in your controller. You may want to read my other answers in tutorial for SQLite.
Save ,retrieve and upload data to a remote server---(AngularJs / Ionic)


text:
Q: Заполнение матрицы с помощью функции Хотелось бы узнать, как можно заполнить элементы матрицы, используя некоторую функцию, которая генерирует числа в заданном диапазоне. В C++ данный код выглядит так:
double func(int, int) {
    return rand() % 12;
}

Matrix::Matrix(int row, int col, double (*func)(int, int)) {
    ...
    ...
    for (int i = 0; i < this->row; i++) {
        for (int j = 0; j < this->col; j++) {
            this->arr[i * this->col + j] = func(i, j);
        }
    }
}

Как реализовать подобную логику в C#?


text:
Q: How to Zendesk all Data Connect to Power BI Desktop I have used the Zendesk system.
I have to Create a Power BI Report for Using Zendesk Ticket Data.
I have Manually Import data into Power BI with Zendesk Data.
then How to Connect Power BI to Zendesk.
And How to Get Zendesk API ? for Power BI.


text:
Q: Disabling adjacent meta keys in Emacs I'd like to change some of my Emacs keyboard habits, as some of the keyboard shortcut combinations (typically starting with C-x, M-x, etc) I do one-handed and they involve uncomfortable hand movements.  I'd like to change this behavior.
However, as I've been doing them for about 15 years, they're programmed into my muscle memory.  It's difficult for me to remember to change the way I type.
I was wondering if it is possible to do a fine-grained remapping in Emacs, even if it's one key at a time, so that (left-control)+x is disabled, but (right-control)+x is still fine, and the like.

A: You can change "ctrl-x" "meta-x" to other ergo key combo. For example:

*

*Caps Lock. You can remap the favorite "meta-x" to this single key. It is super fast and comfortable to type. For windows, autohotkey or keytweak can do the remap job. For Linux, you just change the key layout setting.

*Ctrl+/. If you have a hhkb keyboard, or you have changed "Caps Lock" to "CTRL". Ctrl+/ is a nice way to replace "Ctrl+x" or "Meta-x". Ctrl+/ is a minor key combo in emacs, so you can change the origin one. it is far easier to type than "Ctrl+x".

*"Alt"  is better than "Ctrl" because you can type it with thumbs.
ergoemacs has some nice keymap tricks. It use "Alt" as main function key. You can find it in https://code.google.com/p/ergoemacs/
I use this key binding happily and never consider other key-tweak plans again.

*Buy a better keyboard. Some keyboards change the layout making it easier to type "Ctrl x" "Meta x".
Kinesis keyboard is a ultimate solution. You may find more alternative with google.

*Colemak Maltron Dvorak. All of them have a different key layout. If you like to try a new layout. Do'nt forget them. It may help you to handle with "Ctrl x" problem.


text:
Q: Invalid read of size 4, valgrind fscanf I am working on an assignement but ran into a strange problem while debugging.

==30771== Invalid read of size 4
==30771==   at 0x4E9CC5D: __isoc99_fscanf (isoc99_fscanf.c:30)
==30771==   by 0x400728: main main.c:13)
==30771== Address 0x0 is not stack'd, malloc'd or (recently) free'd

I cant for the life of me figure out why I get this error in valgrind. The code works except for this.
I made a test project to isolate the error:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    FILE *myFile;
    myFile = fopen("../map1.map", "r");

    char *buff = malloc(51*sizeof(char));

    //Scanning for the amount of edges.
    if (fscanf(myFile, "%s", buff) != 1){
        printf("Something is wrong\n");
    }

    printf("%s", buff);

    fclose(myFile);

    char str[20];
    scanf("%s", str);
}

The file looks like this:
9
Nod1 Nod2

It compiles correctly and prints 9.
Compiled with these settings:
gcc -g -std=c99 -Wall -Werror -O0 main.c -o myProgram

run in valgrind with these settings:
valgrind --leak-check=yes --show-reachable=yes ./myProgram

Can anyone spot what I am doing wrong?

A: There is the concept of undefined behavior, if you are not very careful you can trigger such undefined behavior and then, you wont be able to tell whether the program is working or not.
I will post some code that I consider very robust and should not cause any valgrind reports at all, including the removal of the last statement which is doing nothing, every thing I changed was a probable the reason for the problem.
You MUST check that every function succeeded when they return a value, a more robust version of your own program is
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    FILE *file;
    const char *filepath;
    char *buffer;

    filepath = "../map1.map";
    file = fopen(filepath, "r");
    if (file == NULL) {
        fprintf(stderr, "error openning: %s\n", filepath);
        return -1;
    }

    buffer = malloc(51);
    if (buffer == NULL) {
        fprintf(stderr, "error, memory exhausted\n");
        fclose(file);

        return -1;
    }

    // Scanning for the amount of edges.
    if (fscanf(file, "%s", buffer) != 1){
        fprintf(stderr, "error, cannot read from the file\n");
    } else {
        fprintf(stdout, "%s\n", buffer);
    }
    // Release all resources
    fclose(file);
    free(buffer);

    return 0;
}

If you run this code with valgrind chances are that 0 errors will be reported regardless of whether the file exists or not. But you must be careful with,
fscanf(file, "%s", buffer)

because it can overflow buffer, so instead tell fscanf() to read a given number of bytes like this
fscanf(file, "%50s", buffer)

this, lets fscanf() scanf at most 50 bytes and leaves space for the terminating null character.


text:
Q: What is the etymology and the context of calling an unrelated woman "sister"? For specific context, the question arose out of discussing Han Solo calling Princess Leia "sister" in "Star Wars" Episode IV.
What is the etymology and context of using the term "sister" in this way? (unrelated woman that you're projecting a sense of familiarity onto).
Is it from the US Southern culture? From earlier decades of 20th century? Else?

A: Christian culture regards all of humanity (or, in the more up-tight versions of the religion, all Christians) to be brothers and sisters. (This does not imply a literal common parent, but rather a spiritual kinship.)
The use of "sister" to refer to an unrelated woman is certainly not practiced extensively in most of the (white) US, but the term is used in that sense in some religious sects, particularly in the US South. And, while I have little first-hand knowledge (and Urban Dictionary is useless here), I've been led to believe that the use is common in certain African-American subcultures.
Using the terminology in Star Wars, in the fashion it was used, would tend to re-enforce the sense that the speakers are members of a common cult or culture -- I don't think there's any deep hidden significance.

A: I am white English, aged 75, and my wife of many years is black Nigerian (Igbo). Amongst her friends and relatives she is always "sister" and I, to my initial confusion, am usually called "brother". This is a generally used term in Nigeria - whether the rest of English-speaking West Africa uses it, I don't know. Even the  Nigerian at my local hand car wash called me "brother" a few weeks back.

A: sister etymology

mid-13c., from Old English sweostor, swuster "sister". Used of nuns in
  Old English; of a woman in general from 1906; of a black woman
  from 1926; and in the sense of "fellow feminist" from 1912. Meaning
  "female fellow-Christian" is from mid-15c. Sister act "variety act
  by two or more sisters" is from vaudeville (1908).

Thus, no it is not exclusive to U.S Southern culture.  Its use from the etymology cited put its early use as 'not-related' to mid-medieval English

An unrelated woman regarded as bound to others by shared experiences
  or by membership of a particular group, and related senses. OED


text:
Q: Why does this PHP Curl PUT Request returns Code 500? I try to connect the following API via Curl (PHP): https://wiki.vg/Mojang_API#Example
I was successful with other CURL Requests, just the PUT request doesnt work.
I'm working on XAMPP, but I also tried the code on my server with the same result. The following Curl command works like a charm locally and on my server:
curl -X PUT -H "Authorization: Bearer [authtoken]" -F model=alex -F file="@test.png;type=image/png" https://api.mojang.com/user/profile/32143e660e624cd8b05b889f0af49e39/skin -i

However, if I try to convert this to PHP, I get error 400 or 500. I browser other threads the whole day without any result. This here is the raw code without all the other tests I tried:

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

        $post = array(
            'model' => 'alex',
            'file' => '\"@test.png;type=image/png\"'
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

        $headers = array(
            $this->accessToken
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        var_dump(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        curl_close($ch);

Some further notes:

*

*yes I'm sure Curl is installed since other API requests work

*yes I'm sure the auth token works, it works in other requests

*I recognized the payload requests the file as raw image file data and I pull over the png name - not sure if this is supposed to work

A: Ok that went quicker then I expected it. Should have asked easlier today.
I tried Curlfile before, but it looks like I did something wrong.
This comment from Barmer helped:
https://www.php.net/manual/en/class.curlfile.php
Thanks ^^


text:
Q: calling another function inside IVOR4 Handler (External Interrupt) - NXP Here is my question,
Can i do function call inside IVOR4 handler (Prologue and Epilogue ) in MPC5777C?  similar to this Machine_Check_Handler call ?
e_lis r0, Machine_check_handler@h
e_or2i r0, Machine_check_handler@l
mtlr r0 # Store LR

Idea is to calculate preemption time in External Interrupts, by adding Stop Watch start and End in Prologue and Epilogue section
if it is possible, share sample code which shows function calling in Prologue/Epilogue handler.
Any suggestion is highly appreciated


text:
Q: ios View disappears after navigation to other screens I have a custom view on the storyboard, which acts as a toolbar. This view has three buttons and I define custom views for each button in the ViewDidLoad.
When I navigate to a different view, then move backwards to this original screen, both the text and images on these buttons are missing. There's only an empty black bar. This happens for some devices but the views are displayed just fine and never disappear on other devices.
What I've tried:

*

*I've explicitly set the hidden property of these buttons to false in the ViewWillAppear
btn1.Hidden = false;
  btn2.Hidden = false;
  btn3.Hidden = false;

*I've also tried defining the buttons inside the ViewWillAppear instead of the ViewDidLoad, to see if that solves the problem. They still disappear.
Below is my code:
  public override void ViewWillAppear(bool value)
    {
        try
        {
            base.ViewWillAppear(value);

            //icon setup

            //the space between the image and modelFilterText
            var spacing = 0.3f;

            var icon1 = UIImage.FromBundle("Icons/Home/icon1.png");

            btn1.SetImage(icon1, UIControlState.Normal);
            btn1.SetTitle("ONE", UIControlState.Normal);
            btn1.SetTitleColor(UIColor.LightGray, UIControlState.Normal);
            btn1.Font = UIFont.FromName("BankGothicBT-Light", 12f);
            btnRequest.TouchUpInside += (object sender, EventArgs e) =>
            {
                NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);

                NavigationController.PushViewController(view1, true);
            };

            // lower the modelFilterText and push it left so it appears centered
            //  below the image

            var imageSize = btn1.ImageView.Image.Size;
            btn1.TitleEdgeInsets = new UIEdgeInsets(0.0f, -imageSize.Width, -(imageSize.Height + spacing),
                0.0f);

            // raise the image and push it right so it appears centered
            //  above the modelFilterText

            var titleSize = btn1.TitleLabel.Text.StringSize(btn1.TitleLabel.Font);
            btn1.ImageEdgeInsets = new UIEdgeInsets(-(titleSize.Height + spacing), 0.0f, 0.0f,
                -titleSize.Width);

            //Second Icon
            var icon2 = UIImage.FromBundle("Icons/Home/icon2.png");

            btn2.SetImage(icon2, UIControlState.Normal);
            btn2.SetTitle("TWO", UIControlState.Normal);
            btn2.SetTitleColor(UIColor.LightGray, UIControlState.Normal);
            btn2.Font = UIFont.FromName("BankGothicBT-Light", 12f);

            btn2.TouchUpInside +=
                (object sender, EventArgs e) =>
            {
                NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);
            };

            // lower the modelFilterText and push it left so it appears centered
            //  below the image

            var imgSize = btn2.ImageView.Image.Size;
            btn2.TitleEdgeInsets = new UIEdgeInsets(0.0f, -imgSize.Width, -(imgSize.Height + spacing), 0.0f);

            // raise the image and push it right so it appears centered
            //  above the modelFilterText

            var titleLength = btn2.TitleLabel.Text.StringSize(btn2.TitleLabel.Font);
            btn2.ImageEdgeInsets = new UIEdgeInsets(-(titleLength.Height + spacing), 0.0f, 0.0f,
                -titleLength.Width);

            //Third Icon
            var icon3 = UIImage.FromBundle("Icons/Home/icon3.png");

            btn3.SetImage(icon3, UIControlState.Normal);
            btn3.SetTitle("THREE", UIControlState.Normal);
            btn3.SetTitleColor(UIColor.LightGray, UIControlState.Normal);
            btn3.Font = UIFont.FromName("BankGothicBT-Light", 12f);

            btn3.TouchUpInside += (object sender, EventArgs e) =>
            {

                NavigationItem.BackBarButtonItem = new UIBarButtonItem("", UIBarButtonItemStyle.Plain, null);

                NavigationController.PushViewController(view3, true);
            };

            // lower the modelFilterText and push it left so it appears centered below the image

            var imagSize3 = btn3.ImageView.Image.Size;
            btn3.TitleEdgeInsets = new UIEdgeInsets(0.0f, -imagSize3.Width, -(imagSize3.Height + spacing),
                0.0f);

            // raise the image and push it right so it appears centered
            //  above the modelFilterText

            var titleLength3 = btn3.TitleLabel.Text.StringSize(btn3.TitleLabel.Font);
            btn3.ImageEdgeInsets = new UIEdgeInsets(-(titleLength3.Height + spacing), 0.0f, 0.0f,
                -titleLength3.Width);

        }
        catch (Exception ex)
        {
            Console.WriteLine("View will appear error " + ex.Message + ex.StackTrace);
        }

    }

The buttons appear and are properly drawn the first time. However, after I navigate away from this page and come back to it, there's only a black view at the bottom. No buttons.

A: I've learnt that the buttons don't actually disappear. They are obscured by the iOS toolbar.
For instance, if I navigate to a screen which has an iOS toolbar, then navigate backwards back to this home page, the NavigationController.SetToolbarHidden property is set to true for all the other screens after that.
So all I needed to do was set this to false in the ViewWillAppear of this Home Page, so it doesn't obscure my custom view.
NavigationController.SetToolbarHidden(true,false)


text:
Q: C Programming: Shared Memory Signal Hangs I have two programs one writes data to shared memory and the other reads from it. Writer is suppose to write data 0-9 in shared memory and then wait unit reader reads this data and display it on the screen and signals the writer process, then writer writes data 10-19 to shared memory and then wait until reader reads and display data to screen and signal writer to end process.
Writer code:
#define SHMKEY 75
int shmid;

void cleanup(int);

int main (void) {

    int *pint, *ppint, i;

    for (i=0;i<20;i++)  signal(i,cleanup);

    shmid=shmget(SHMKEY, 128,0666|IPC_CREAT);
    pint=(int *)shmat(shmid,0,0);
    ppint=pint;

    for(i=0;i<10;i++) {  *ppint++ = i };
    *pint=-1;
    kill(getpid(), SIGSTOP);

    for(i=10;i<20;i++) {  *ppint++ = i };
    *pint=-1;
    kill(getpid(), SIGSTOP);

    return 0;
}

void cleanup(int x) {
    shmctl(shmid,IPC_RMID,0);
    exit(0);
}

Reader Code:
#define SHMKEY 75

int main(int argc, char *argv[])  //expects pid of writer as clarg
{
    int i, *pint, *pint1, shmid;
    int pid= atoi(argv[1]);

    shmid=shmget(SHMKEY, 128,0666);
    pint=(int *)shmat(shmid,0,0);

    while(*pint != -1);
    for(i=0;i<10;i++)  printf("%d\n",*pint++);
    // Reset busy wait flag so it continues to wait
    *pint=0;
    kill(pid, SIGCONT);
    printf("Signal 1\n");

    while(*pint != -1);
    for(i=10;i<19;i++)  printf("%d\n",*pint++);
    kill(pid, SIGCONT);
    printf("Signal 2\n");
}

Outputs running two terminal windows:
$./writer &
[1] 9350

$ ./reader 9350
-1
1
2
3
4
5
6
7
8
9
Signal 1
(hangs)

I seems to be hanging after the second busy wait loop in the reader, but I don't understand why? since I send a signal before the busy wait to the writer to unset the flag *pint = -1.


text:
Q: Dynamically updating a Holoviz Panel layout Without going into the motivational details, I want to perform the following sequence of step using Panel:

*

*Display a panel.widgets.FileInput element.

*Once a file has been selected, then display a panel.widgets.MultiSelect element with items from the file, the first few of which are selected. The MultiSelect element appears below the FileInput element.

*On the basis of what is selected (both initially and through user interaction with the panel.widgets.MultiSelect element), display some items in a column to the right of the FileInput element.

Steps 1 and 2 work fine, but I can't get the 3rd thing to happen. Here is a minimum example that illustrates the problem when it is run:
import panel as pn
pn.extension()

# Create and organize basic elements to show where things go
file_input = pn.widgets.FileInput()
item_selector = pn.widgets.MultiSelect()
controls = pn.Column(file_input, "layout[0][1]")
layout = pn.Row(controls, pn.Column("layout[1][0]"))
print(layout)

# Set up selector object
@pn.depends(file_contents=file_input, watch=True)
def _item_selector(file_contents):
    # Dummy items for illustration purpose
    items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    item_selector = pn.widgets.MultiSelect(
        name="Choose items",
        options=items,
        size=12,
        width=120,
        value=items[:2],
    )
    layout[0][1] = item_selector

# Define interactivity based on selector object
@pn.depends(selected_items=item_selector, watch=True)
def _col(selected_items):
    col = pn.Column()
    for item in selected_items:
        col.append(item)
    layout[1] = col

layout

Any pointers to help clear up my misunderstandings would be much appreciated.

A: I figured out where I went wrong. In the function _item_selector() I set layout[0][1] to a new MultiSelect object, and the function _col() is affected by the original MultiSelect object set up on line 6. The code below fixes the problem
import panel as pn
pn.extension()

# Create and organize basic elements to show where things go
file_input = pn.widgets.FileInput()
item_selector = pn.widgets.MultiSelect()
controls = pn.Column(file_input, "")
layout = pn.Row(controls, pn.Column(""))

# Set up selector object
@pn.depends(file_contents=file_input, watch=True)
def _item_selector(file_contents):
    # Dummy file contents
    items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
    item_selector.options = items
    item_selector.value = ['a', 'c']
    item_selector.size = 12
    item_selector.width = 120
    layout[0][1] = item_selector

# Define interactivity based on selector object
@pn.depends(selected_items=item_selector, watch=True)
def _col(selected_items):
    col = pn.Column()
    for item in selected_items:
        col.append(item)
    layout[1] = col

layout

I'm sure this is not the most elegant approach to the problem I am trying to solve, and I would be interested in any feedback. In particular, as a newbie to Panel, I don't know that it is necessary to set up the layout beforehand on lines 5-8, or if this can be done dynamically as well.


text:
Q: Unable to select I want to select variables which are character and integer type using dplyr's select_if function. But the code below throws an error.
mpg %>% select_if(is.character | is.integer)

How do I solve this?
mpg %>% select_if(is.character) alone works well, how do I apply multiple conditions?

A: One way would be to use an anonymous function
library(dplyr)

mpg %>% select_if(function(x) is.character(x) | is.integer(x))

#   manufacturer model       year   cyl trans      drv     cty   hwy fl    class
#   <chr>        <chr>      <int> <int> <chr>      <chr> <int> <int> <chr> <chr>
# 1 audi         a4          1999     4 auto(l5)   f        18    29 p     compact
# 2 audi         a4          1999     4 manual(m5) f        21    29 p     compact
# 3 audi         a4          2008     4 manual(m6) f        20    31 p     compact
# 4 audi         a4          2008     4 auto(av)   f        21    30 p     compact
# 5 audi         a4          1999     6 auto(l5)   f        16    26 p     compact
# 6 audi         a4          1999     6 manual(m5) f        18    26 p     compact
# 7 audi         a4          2008     6 auto(av)   f        18    27 p     compact
# 8 audi         a4 quattro  1999     4 manual(m5) 4        18    26 p     compact
# 9 audi         a4 quattro  1999     4 auto(l5)   4        16    25 p     compact
#10 audi         a4 quattro  2008     4 manual(m6) 4        20    28 p     compact
# … with 224 more rows

OR using funs
mpg %>% select_if(funs(is.character(.) | is.integer(.)))

A: We could use the ~ as well
library(dplyr)
mpg %>%
   select_if(~ is.character(.x)|is.integer(.x))

Or with inherits
mpg %>%
   select_if(~ inherits(.x, c("character", "integer")))


text:
Q: Why is this always returning False? Why is this always returning "box1 won't fit in box2". def canBox1FitInBox2 always returns false even if it's not... What am I missing?
Even if the input is box1 = 1,1,1 and box2 = 10,10,10.
This is an exercise, I know there are probably a lot of better ways to do this but I need it to be done like this:
class Box:
    length = 0
    width = 0
    height = 0

    # This method will check the length, width, & height
    # then it will output which dimension is the longest
    def getLongestSide(self):
        self.max = self.length
        if self.width > self.max:
            self.max = self.width
        if self.height > self.max:
            self.max = self.height
        return self.max

    (This I Wrote)\
    # This method should output which dimension is the shortest
    def getShortestSide(self):
        self.min = self.length
        if self.width < self.min:
            self.min = self.width
        if self.height < self.min:
            self.min = self.height
        return self.min
        # TODO: Finish this method (^This I Wrote)\

from Box import Box

box1 = Box()
dimensions1 = input("Enter box1's dimensions ex. 1 2 3").split()
box1.length = int(dimensions1[0])
box1.width = int(dimensions1[1])
box1.height = int(dimensions1[2])

box2 = Box()
dimensions2 = input("Enter box2's dimensions ex. 1 2 3").split()
box2.length = int(dimensions2[0])
box2.width = int(dimensions2[1])
box2.height = int(dimensions2[2])

(This I Wrote)\
def canBox1FitInBox2(box1, box2):
    if box1.getLongestSide() <= box2.getShortestSide():
         return canBox1FitInBox2 == True
    else:
         return canBox1FitInBox2 == False
(This I Wrote)\
#TODO: Use the getLongestSide and getShortestSide methods in the Box Class to determine
if box1 will fit in box2 then return true or false.

#Hint: if the longest dimension of box1 is smaller than the shortest dimension of
box2, then box1 fits in box2

if canBox1FitInBox2(box1, box2) == True:
    print("box1 will fit in box2")
else:
    print("box1 wont fit in box2")

A: In your code, the function canBox1FitInBox2 is returning values after comparing the function called again canBox1FitInBox2 without arguments, with True and False using the comparison operator(==)
Thus, calling the function without argument is throwing some garbage value and it is being compared with True and False, and thus function is returning always False.
Simply do this:
if box1.getLongestSide() <= box2.getShortestSide():
     return True
else:
     return False

and your code will run fine.


text:
Q: C# Regex Pattern to remove comma inside double quote delimited string I can't be the first person to have this issue but hours of searching Stack revealed nothing close to an answer.  I have an SSIS script that works over a directory of csv files.  This script folds, bends and mutilates these files;  performs queries, data cleansing, persists some data and finally outputs a small set to csv file that is ingested by another system.
One of the files has a free text field that contains the value: "20,000 BONUS POINTS".  This one field, in a file of 10k rows, one of dozens of similar files, is the problem that I can't seem to solve.
Be advised: I'm weak on both C# and Regex.
Sample csv set:
4121,6383,0,,,TRUE
4122,6384,0,"20,000 BONUS POINTS",,TRUE
4123,6385,,,,
4124,6386,0,,,TRUE
4125,6387,0,,,TRUE
4126,6388,0,,,TRUE
4127,6389,0,,,TRUE
4128,6390,0,,,TRUE

I found plenty of information on how to parse this using a variety of Regex patterns but what I've noticed is the StreamReader.ReadLine() method wraps the complete line with double quotes:
"4121,6383,0,,,TRUE"

such that the output of the regex Replace method:

s = Regex.Replace(line, @"[^\""]([^\""])*[^\""]",
m => m.Value.Replace(",", ""));

looks like this:
412163830TRUE

and the target line that actually contains a double quote delimited string ends up looking like:

"412263840\"20000 BONUS POINTS\"TRUE"

My entire method (for your reading pleasure) is this:
        string fileDirectory = "C:\\tmp\\Unzip\\";
        string fullPath = "C:\\tmp\\Unzip\\test.csv";
        string line = "";
        //int count=0;
        List<string> list = new List<string>();

            try
        {
            //MessageBox.Show("inside Try Block");
            string s = null;
            StreamReader infile = new StreamReader(fullPath);
            StreamWriter outfile = new StreamWriter(Path.Combine(fileDirectory, "output.csv"));
            while ((line = infile.ReadLine()) != null)
            {
                //line.Substring(0,1).Substring(line.Length-1, 1);
                System.Console.WriteLine(line);
                Console.WriteLine(line);
                line =
                s = Regex.Replace(line, @"[^\""]([^\""])*[^\""]",
                                        m => m.Value.Replace(",", ""));
                System.Console.WriteLine(s);
                list.Add(s);

            }
            foreach (string item in list)
            {
                outfile.WriteLine(item);
            };
            infile.Close();
            outfile.Close();
            //System.Console.WriteLine("There were {0} lines.", count);
        }

        catch (Exception e)
        {

            Console.WriteLine(e.Message);
        }

        //another addition for TFS consumption

    }

Thanks for reading and if you have a useful answer, bless you and your prodigy for generations to come!
mfc
EDIT: The requirement is a valid csv file output.  In the case of the test data, it would look like this:
    4121,6383,0,,,TRUE
    4122,6384,0,"20000 BONUS POINTS",,TRUE
    4123,6385,,,,
    4124,6386,0,,,TRUE
    4125,6387,0,,,TRUE
    4126,6388,0,,,TRUE
    4127,6389,0,,,TRUE
    4128,6390,0,,,TRUE

A: I recommend using a CSV reader lib like others have suggested.
Install-Package LumenWorksCsvReader
https://github.com/phatcher/CsvReader#getting-started
However, if you just want to try something fast and dirty.  Give this a try.
If I understand correctly. You need to remove commas between double quotes within each line of a CSV file. This should do that.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string pattern = @"([""'])(?:(?=(\\?))\2.)*?\1";
        List<string> lines = new List<string>();
        lines.Add("4121,6383,0,,,TRUE");
        lines.Add("4122,6384,0,\"20,000 BONUS POINTS\",,TRUE");
        lines.Add("4123,6385,,,,");
        lines.Add("4124,6386,0,,,TRUE");
        lines.Add("4125,6387,0,,,TRUE");
        lines.Add("4126,6388,0,,,TRUE");
        lines.Add("4127,6389,0,,,TRUE");
        lines.Add("4128,6390,0,,,TRUE");

        StringBuilder sb = new StringBuilder();
        foreach (var line in lines)
        {
            sb.Append(Regex.Replace(line, pattern, m => m.Value.Replace(",", ""))+"\n");
        }
        Console.WriteLine(sb.ToString());
    }
}

OUTPUT
4121,6383,0,,,TRUE
4122,6384,0,"20000 BONUS POINTS",,TRUE
4123,6385,,,,
4124,6386,0,,,TRUE
4125,6387,0,,,TRUE
4126,6388,0,,,TRUE
4127,6389,0,,,TRUE
4128,6390,0,,,TRUE

https://dotnetfiddle.net/flmWG3

A: I haven't tried with numerous lines, but this would be my first approach:
namespace ConsoleTestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var before = "4122,6384,0,\"20,000 BONUS POINTS\",,TRUE";
            var pattern = @"""[^""]*""";
            var after = Regex.Replace(before, pattern, match => match.Value.Replace(",", ""));
            Console.WriteLine(after);
        }
    }
}


text:
Q: Phantomjs stops loading full page I'm using PhantomJS 1.9.7 under Debian to analyze page content. For some reason it stops loading page on any resource loading failure. For example, if it cannot load .js file, it finishes with status "fail". So I get

FAIL to load the address:xxxx caused by Operation canceled

in page.open() status handler.
How to make PhantomJS go on loading other resources even if some of them cannot be loaded?

A: It is quite possible that SSL is the culprit. You could try a variety of command line options to fix the loading error like:
--ignore-ssl-errors=true
--web-security=false

If you know the resource that fails to load every time, you could explicitly abort the loading by listening to the onResourceRequested event:
page.onResourceRequested = function(requestData, networkRequest){
    if (requestData.url.indexOf("yourScript.js") !== -1) {
        networkRequest.abort();
    }
};

You could also look what kind of error this is with onResourceError.

A: You can find the resources that are failing by printing the error to console.
page.onResourceError = function(resourceError) {
  console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
  console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};

And this should print something like
Unable to load resource (#19URL:http://www.google.com)
Error code: 5. Description: Operation canceled


text:
Q: I'm trying to make a Discord server nuke bot but I can't install the Discord module for Python How do I fix this?
ERROR: Could not build wheels for aiohttp, frozenlist, multidict, yarl, which is required to install pyproject.toml-based projects

I searched the internet to find a fix but nothing fixed the error.


text:
Q: BeautifulSoup children() vs descendants() I read a book that has the following:

from urllib.request import urlopen

from bs4 import BeautifulSoup

html = urlopen('http://www.pythonscraping.com/pages/page3.html')

bs = BeautifulSoup(html, 'html.parser')

for child in bs.find('table',{'id':'giftList'}).children:

    print(child)

This code prints the list of product rows in the giftList table, including the initial row of column labels. If you were to write it using the descendants() function instead of the children() function, about two dozen tags would be found within the table and printed, including img tags, span tags, and individual td tags.

I tested it and I did not see the two outputs had difference when using .children or .descendants. Can anyone please tell me what exactly it will print when using .children and using .descendants.

A: the difference lies in depth level. children will go to one level of depth max. descendants will print everything, going to the maximum depth every time.
if we take that excerpt from the sisters.html of the beautifulsoup docs

The Dormouse's story

for child in p.children:
      print(child)
>>>

for child in p.descendants:
      print(child)
>>>
>>> "The Dormouse's story"


text:
Q: jQueryUI Progress Bar I have never used the jQuery UI progress bar, but I'd like to make a function that would basically load the jQuery UI progress bar, run it for 5 seconds and then execute another function.
ie.
function test() {

show the jQuery UI progress bar for 5 seconds in div ("progressbar")

after 5 seconds has passed..... execute test2()

}

How can this be done?

A: You can do it like this:
<button onclick="test()">Test</button>

With animation:
function test(){
    var per = 0;
    progress(per);
    time = setTimeout(function(){ animate(per); }, 1000);
    setTimeout(function(){ $( "#progress" ).hide(); test2(); }, 5000);

}

function animate(per){

    clearTimeout(time);
    per = per+20;
    progress(per);

    time = setTimeout(function(){ animate(per); }, 1000);
}

function test2(){
    alert('test2');
}
function progress(per){
    $( "#progress" ).progressbar({
        value: per
    });
}

JSFiddle Example


text:
Q: Why not lump all service classes into a Factory method (instead of injecting interfaces)? We are building an ASP.NET project, and encapsulating all of our business logic in service classes.  Some is in the domain objects, but generally those are rather anemic (due to the ORM we are using, that won't change).  To better enable unit testing, we define interfaces for each service and utilize D.I..  E.g. here are a couple of the interfaces:
IEmployeeService
IDepartmentService
IOrderService
...

All of the methods in these services are basically groups of tasks, and the classes contain no private member variables (other than references to the dependent services).  Before we worried about Unit Testing, we'd just declare all these classes as static and have them call each other directly.  Now we'll set up the class like this if the service depends on other services:
public EmployeeService : IEmployeeService
{
   private readonly IOrderService _orderSvc;
   private readonly IDepartmentService _deptSvc;
   private readonly IEmployeeRepository _empRep;

   public EmployeeService(IOrderService orderSvc
                        , IDepartmentService deptSvc
                        , IEmployeeRepository empRep)
   {
      _orderSvc = orderSvc;
      _deptSvc = deptSvc;
      _empRep = empRep;
   }
   //methods down here
}

This really isn't usually a problem, but I wonder why not set up a factory class that we pass around instead?
i.e.
public ServiceFactory
{
   virtual IEmployeeService GetEmployeeService();
   virtual IDepartmentService GetDepartmentService();
   virtual IOrderService GetOrderService();
}

Then instead of calling:
_orderSvc.CalcOrderTotal(orderId)

we'd call
_svcFactory.GetOrderService.CalcOrderTotal(orderid)

What's the downfall of this method?  It's still testable, it still allows us to use D.I. (and handle external dependencies like database contexts and e-mail senders via D.I. within and outside the factory), and it eliminates a lot of D.I. setup and consolidates dependencies more.
Thanks for your thoughts!

A: One argument against this is that it doesn't make your dependencies clear. It shows that you depend on "some of the stuff in the service factory" but not which services. For refactoring purposes it can be helpful to know exactly what depends on what.
Dependency injection should make this kind of thing easy, if you're using an appropriate framework - it should just be a matter of creating the right constructor, defining what implements which interface, and letting it sort everything out.

A: Such a factory is essentially a Service Locator, and I consider it an anti-pattern because it obscures your dependencies and make it very easy to violate the Single Responsibility Principle (SRP).
One of the many excellent benefits we derive from Constructor Injection is that it makes violations of the SRP so glaringly obvious.

A: If most of your classes depend on this three interfaces you could pass an object around that wraps them together, BUT: if most of the classes just depend on one or two of them then it's not a good idea since those classes will have access to objects they don't need and they have no business with and some programmers will always call the code they are not supposed to call just because it's available.
Btw, it's not a factory unless you always create a new object in the Get[...]Service() methods and doing that just for passing a few methods around is bad. I'd just call it ServiceWrapper and turn them into the properties EmployeeService, DepartmentService and OrderService.


text:
Q: Adding multiple values to a key in Ruby as well as delete just one value associated I want  to add values and delete values to the hash like below
h= {:a =>[ 1,3, 4],
    :b =>[ 3, 6],
    :c =>[ 4, 8, 87]
   }

and how do I delete just one value pertaining to a key?
remove c, 87
h= {:a =>[ 1,3, 4],
    :b =>[ 3, 6],
    :c =>[ 4, 8]
   }

Can I do this in ruby? I am new to ruby, Can someone help me out?

A: Use a Nil Guard
You need to guard against missing keys and values in your Hash. There are a number of ways to do this, but on any recent Ruby the &. operator ensures that a method doesn't raise an exception if called on nil. The following works fine:
h = {
  a: [1, 3, 4],
  b: [3, 6],
  c: [4, 8, 87]
}

h[:c]&.delete 87; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}

h[:x]&.delete 101; h
#=> {:a=>[1, 3, 4], :b=>[3, 6], :c=>[4, 8]}


text:
Q: Why is my code not working faster after I edited it? I'm new to computer science and programming. I'm taking a free online class in coding, and one of the assignments was to write a program that will generate the 1000th prime number.
FYI, this is in Python 2.5.4
Here is the original code I copied (and edited a little bit) from another thread on this forum:
def isprime(n):

    if n<2:
        return False
    else:
        for i in range(2,(n/2+1)):
            if n%i==0:
                return False
        else:
            return True

def nthprime(n):
    x=[]
    j=2
    while len(x)<n:
        if (isprime(j)) == True:
            x.append(j)
        j =j+1
    return(x[n-1])

print nthprime(1000)

However, I thought I could make the program faster by rewriting the isprime(n) function as follows:
def isprime(n):# First the primality test
    i=1
    if n<2:
        return False
    if (n!=2 and (n/2*2==n)):
        return False
    if n==3:
        return True
    if n==5:
        return True
    else:
        while i <= (n/2+1):
            i+=2
            if n%i==0:
                return False
        else:
              return True

That way, when it is only checking if n is divisible by odd integers (by this point in the code, we already know n is odd, and therefore not divisible by any even integers).
I thought that rewriting it this way would make the program work twice as fast (since it's only checking half as many numbers), but it seems to be taking the same amount of time, or even slightly longer, than what it was taking before.
Also, is there any way to rewrite the second block of code to get rid of the:
if n==3:
    return True
if n==5:
    return True

The only reason I included that is because I realized my algorithm was generating "false" for 3 and 5, even though they are prime.

A: I see what you were going for with your optimizations, but I think the logic you've implemented isn't what you were going for. Think instead about other ways you can reduce the number of numbers you have to check.
The first one I'd recommend is instantly ruling out even numbers:
def isprime(n):
    if n < 2 or n % 2 == 0:
        return False
    # ...

The other big spot you're checking way more than you need to is in the factor checking that you fall back on when the optimizations fail. You don't need to go all the way to n / 2; The largest factor you need to worry about is sqrt(n) (once you've passed root n, you start checking factors whose pair you've already checked, e.g. if you're checking n = 6, once you check 2, you've already checked 3). Here's the corresponding optimization:
def isprime(n):
    # ...
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False

All together, here's the new isprime (EDIT: with tips from comments):
def isprime(n):
    if n == 2: return True
    if n % 2 == 0: return False

    for i in xrange(3, int(n ** 0.5) + 1, 2):
        if n % i == 0: return False

    return True

Calculating nthprime(5000), these 2 optimizations took my time from 8.497 seconds to 0.108 seconds.
EDIT: demo


text:
Q: In Primefaces inputText required=true, how can I remove ui-state-error as soon as something is entered? When submitting a form that includes a required inputText, the styles that indicate not validated fields remain in place until submitting again. I want the styles to disappear as soon as the field is edited.
<p:inputText value="#{data.bezeichnung}"
             id="bezeichnung"
             styleClass="panelInputField input_mandatory"
             required="true"
             title="Bezeichnung"/>

A: After a lot of trying around, I found the easiest answer to add a "onkeyup" as follows:
                    <p:inputText value="#{data.bezeichnung}" id="bezeichnung"
                         styleClass="panelInputField input_mandatory"
                         required="true"
                         onkeyup="$(this).removeClass('ui-state-error');"
                         title="Bezeichnung"/>

If the jquery code needs to be in a more general place, the following might work as well: (it may be helpful to know the escaping codes used here)
    onfocus="$('.ui-state-error').removeClass('ui-state-error');"
    onkeyup="$('input[name="form:bezeichnung"]').removeClass('ui-state-error');"
    onkeyup="$('input[name$=bezeichnung]').removeClass('ui-state-error');"


text:
Q: Viewing a raw pointer as a range in range-based for-loop How can I make a raw pointer behave like a range, for a for-range loop syntax.
double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;// will not execute if the pointer is null

Motivation:
It is now vox populi that an boost::optional (future std::optional) value can be viewed as a range and therefore used in a for range loop http://faithandbrave.hateblo.jp/entry/2015/01/29/173613.
When I rewrote my own simplified version of it:
namespace boost {
    template <class Optional>
    decltype(auto) begin(Optional& opt) noexcept{
        return opt?&*opt:nullptr;
    }

    template <class Optional>
    decltype(auto) end(Optional& opt) noexcept{
        return opt?std::next(&*opt):nullptr;
    }
}

Used as
boost::optional<int> opt = 3;
for (int& x : opt) std::cout << x << std::endl;

While looking that code I imagined that it could be generalized to raw (nullable) pointers as well.
double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;

instead of the usual if(dptr) std::cout << *dptr << std::endl;. Which is fine but I wanted to achieve the other syntax above.
Attempts
First I tried to make the above Optional version of begin and end work for pointers but I couldn't. So I decided to be explicit in the types and remove all templates:
namespace std{ // excuse me, this for experimenting only, the namespace can be removed but the effect is the same.
    double* begin(double* opt){
        return opt?&*opt:nullptr;
    }
    double* end(double* opt){
        return opt?std::next(&*opt):nullptr;
    }
}

Almost there, it works for
for(double* ptr = std::begin(dptr); ptr != std::end(dptr); ++ptr)
    std::cout << *ptr << std::endl;

But it doesn't work for the supposedly equivalent for-range loop:
for(double& d : dptr) std::cout << d << std::endl;

Two compilers tell me: error: invalid range expression of type 'double *'; no viable 'begin' function available
What is going on? Is there a compiler magic that forbids the ranged-loop to to work for pointers. Am I making a wrong assumption about the ranged-loop syntax?
Ironically, in the standard there is an overload for std::begin(T(&arr)[N]) and this is very close to it.

Note and a second though
Yes, the idea is silly because, even if possible this would be very confusing:
double* ptr = new double[10];
for(double& d : ptr){...}

would iterate over the first element only. A more clear and also realistic workaround would be to do something like workaround proposed by @Yakk:
for(double& d : boost::make_optional_ref(ptr)){...}

In this way it is clear that we are iterating over one element only and that that element is optional.
Ok, ok, I will go back to if(ptr) ... use *ptr.

A: Because the way that range-based for works is (from §6.5.4):

begin-expr and end-expr are determined as follows
  — if _RangeT is an array type, [..]
  — if _RangeT is a class type, [..]
  — otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin
  and end are looked up in the associated namespaces (3.4.2). [ Note: Ordinary unqualified lookup (3.4.1)
  is not performed. —end note ]

What are the associated namespaces in this case? (§3.4.2/2, emphasis mine):

The sets of namespaces and classes are determined in the following way:
  (2.1) — If T is a fundamental type, its associated sets of namespaces and classes are both empty.

Thus, there is no place to put your double* begin(double*) such that it will be called by the range-based for statement.
A workaround for what you want to do is just make a simple wrapper:
template <typename T>
struct PtrWrapper {
    T* p;
    T* begin() const { return p; }
    T* end() const { return p ? p+1 : nullptr; }
};

for (double& d : PtrWrapper<double>{dptr}) { .. }

A: It is a useful lie to think that for(:) loops are implemented by "calling std::begin and std::end in a ADL-activated context".  But that is a lie.
The standard instead basically does a parallel implementation of the std::begin and std::end in itself.  This prevents the language's low level constructs from depending on its own library, which seems like a good idea.
The only lookup for begin by the language is the ADL-based lookup.  Your pointer's std::begin won't be found, unless you are a pointer to something in std.  The std::begin( T(&)[N} ) isn't found this way by the compiler, but instead that iteration is hard-coded by the language.
namespace boost {
  template<class T>
  T* begin( optional<T>&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T* begin( optional<T&>&&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T const* begin( optional<T> const&o ) {
    return o?std::addressof(*o):nullptr;
  }
  template<class T>
  T* end( optional<T>&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  T* end( optional<T&>&&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  T const* end( optional<T> const&o ) {
    return o?std::next(begin(o)):nullptr;
  }
  template<class T>
  boost::optional<T&> as_optional( T* t ) {
    if (t) return *t;
    return {};
  }
}

now you can:
void foo(double * d) {
  for(double& x : boost::as_optional(d)) {
    std::cout << x << "\n";
}

without having to repeat the type double.
Note that an rvalue optional to a non-reference returns a T const*, while an rvalue optonal to a T& returns a T*.  Iterating over a temporary in a writing context is probably an error.

A: TL;DR
This construct can be used in a range for loop:
std::views::counted(raw_ptr, !!raw_ptr)

Details
C++20 offers a plethora of ways to create ad-hoc iterables, using the ranges library. For example:
#include <ranges>
#include <iostream>

int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int *raw_ptr = a;

    for(int i : std::views::counted(raw_ptr, 10))
        std::cout << i << ' ';
    std::cout << '\n';

    for(int i : std::views::counted(raw_ptr, 1))
        std::cout << i << ' ';
    std::cout << '\n';

    std::cout << "empty for null pointer pointer\n";
    raw_ptr = nullptr;
    for(int i : std::views::counted(raw_ptr, 0))
        std::cout << i << ' ';
    std::cout << '\n';

    std::cout << "Exit\n";
}

Prints
1 2 3 4 5 6 7 8 9 10
1

empty for null pointer

Exit

Similarly std::views::subrange could be used with the (start, end] pointers. Check the library for more info.


text:
Q: Java - Store byte array as String in DB and create byte array using String value I have a byte array with the value [B@6c89db9a I have stored this value in a MySQL db as a string representation - mybyteArray.toString()
I would like to retrieve the saved value from the database and create a new byte array using the string value of the original byte array.
I have tried the examples Java Byte Array to String to Byte Array
and byte to string and vice versa
However i am not getting the original byte array value. It is generating a different value. Can anyone please advise?

A: For the record:
another solution would be to store the base64 encoded byte array, see
https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
The question is too old, so I'm not going to elaborate on this .

A:
I have a byte array with the value [B@6c89db9a I have stored this value ...

That's not a value. It's a completely useless (outside of Java) hashcode. The toString() method of an array does not print the contents of an array. Arrays do not override toString() and therefore Object.toString() is called.
If you wish to store an array of arbitrary bytes in MySQL you would want to use a BLOB type (or maybe VARBINARY? it's been a while since I've used MySQL but it appears from a quick google they're basically the same in modern versions) in your table, and store the bytes:

create table example (some_bytes BLOB);

Your prepared statement would look like:
String query = "INSERT INTO example (some_bytes) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(query);

And you'd insert those bytes via:
pstmt.setBytes(1, myByteArray);
pstmt.execute();

Edit to add from comments: You have some bytes in an array. If those bytes represent a string of characters and you know what the character set is, you convert them to a String using the String constructor that takes a character set:
String myString = new String(bytes, knownCharset);

For example, if they represent a UTF-8 string you would use:
String myString = new String(byteArray, Charset.forName("UTF-8"));

A: According to Object.toString()-

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.
In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Therefore what you are saving does not contain the real value of your byte array.

A: You can try two functions below to finish your transform jobs:
    public static byte[] toBytes(String s) {
    try {
      return s.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("UTF-8 not supported?", e);
      return null;
    }
    }

      public static String toString(final byte [] b, int off, int len) {
          if (b == null) {
             return null;
          }
          if (len == 0) {
             return "";
          }
          try {
            return new String(b, off, len, "UTF8");
          } catch (UnsupportedEncodingException e) {
          System.out.println("UTF-8 not supported?", e);
          return null;
          }
      }


text:
Q: How should i go about building the web based file manager in python I have my desktop and in that i have the virtual machine where i have the django site working.
Now i have the external USB drive connected to the host where i have all the data.
I want to build the web interface for managing the files in that external drive. The main function i want to do is to

*

*move the files from one folder to another via web interface

*have the same folder structure in other folder named Archive so that when i select the folder and click archive then system should move that folder to that location

Can anyone give me some direction on how should i proceed. I don't want the code but just guide lines on how should i approach the problem and tools /packages to use

A: Moving files around over a web interface is essentially the same operation you would perform using the CLI, except that the user running the underlying webserver must have file system permissions to perform the operation.
Look at these modules:

*

*shutil

*path.py
They are a level above os.rename & company.

A: since file operations can take quite some time, you should consider using something like celery to do the actual work in the background. This keeps your views fast, so they won't time out if the moving/copying is taking longer.


text:
Q: Configure module logger to flask app logger My flask application uses a module which gets a logger like this:
import logging
logger = logging.getLogger("XYZ")
...
logger.debug("stuff")

Without having to modify anything in the module, can I configure flask such that the module will get flask's app.logger when it makes the getLogger("XYZ") call?

A: This solution worked to me:
import logging

logger = logging.getLogger('werkzeug')
logger.debug('stuff')

The default Flask configuration seems to use the logger name werkzeug. Adding or changing handlers for this logger changes the way Flask logs.
PS.: Python 3.5, Flask 0.12.2

A: The Flask logger is accessible during a request or CLI command via current_app.
Example usage:
from flask import current_app, Flask
app = Flask('HelloWorldApp')

@app.route('/')
def hello():
    current_app.logger.info('Hello World!')
    return "Hello World!"

if __name__ == '__main__':
    app.run()

A: If you want use your Flask apps logging instance that is already established then all you have to do is import the current app and give it a name for that module.
init.py
from flask import Flask

my_app = Flask(__name__)

my_other_module.py where I want to use Flask app logger
from flask import current_app as my_app

class myClass():
   def __init__(self):
       constructor stuff....

   def my_class_method(self):
      my_app.logger.info("log this message")

A: Yes, you can configure it.
By default flask logger's name is your app name, but flask has setting LOGGER_NAME.


text:
Q: Search a data in table using datepicker in extjs I created a table where I need to sort the values using the dates, so I used the datepicker but its not working how to sort the data using the date picker.
 The exact output is if i select the date "17-09-01" I need to get the columns which have these dates.
once if i given some date on textbox, based on textbox value I need to filter related records from all columns. Can you tell me how to achieve?
What change I need to do?
You can view my code in Fiddle

A: Try this you can search using date, name and email id
In the Below code u want to add gridfilters plugins.
 items: [{
        xtype: 'grid',
        title: 'Sample Data',
        itemId: 'myGridItemId',
        flex: 1.2,
        plugins: 'gridfilters',
        margin: '0 10 0 0',
        bind: {
            store: '{mystore}',
            selection: '{users}'
        },

 columns: [{
             text: 'Name',
            dataIndex: 'name',
             flex: 0.5,
                filter: {
           type: 'string',
            itemDefaults: {

             }
         }
         }, {
            text: 'Email',
             dataIndex: 'email',
             flex: 1,
                filter: {
             type: 'string',
             itemDefaults: {

             }
        }
               },{
                type: 'Date',
            text: 'Date',
                dataIndex: 'date',
                flex: 2,
                filter: {
             type: 'string',
             itemDefaults: {

             }
         }
              }]

A: I have made following changes to your code to make it work.

*

*In a model, specify the date field properly with dateFormat.
                {
                    name: 'date',
                    type: 'date',
                    dateFormat: 'y-m-d'
                }

*In a grid, better use datecolumn with format property.
         {
            //Use xtype datecolumn for dates and specify the format
            xtype: 'datecolumn',
            text: 'Date',
            dataIndex: 'date',
            flex: 2,
            format: 'y-m-d'
        }

*Avoid using storeId on store, though you had not specified it but were trying to retrieve store by it.
        handler: function (picker, date) {
          //var store = Ext.getStore('storeId');
          var store = picker.up('#myGridItemId').getStore();
          // clear current filters
          store.clearFilter();
         // filter store
         var date = Ext.first('#selectedDate').getValue();
         store.filter("date", date);
        }

*Here's the modified code. Read my comments for more.


text:
Q: Amann and Escher's analysis and Pugh's RMA. I started studying real analysis with Rudin's book, but it's really terse, i somehow made it through the first chapter (After reading 3 times :D) and solved some problems but here we are, i feel like i really didn't understand that chapter. So, i found two texts to study analysis and leave Rudin's PMA, they are :

*

*Amann and Escher's, 'Analysis' (3 volumes)

*Pugh's 'Real Mathematical Analysis'

Both are rigorous and intuitive. (Am i correct? This is what reviews says so?)
I liked Amann and Escher's analysis, but by reading reviews on Amazon and a answer on this platform, it says that they present the material in a generalized form and i am afraid that i miss the usual special case way and well i maybe at a disadvantage in that sense.
My Questions :
1)Should I just study Amann and Escher's analysis alone?
2) Or study from Pugh's RMA
3) Is reading Amann and Escher's analysis enough or am i going to miss some stuffs for a usual analysis course?

A: I think Abbott, Understanding Analysis, or Bartle, Sherbert, Introduction to Real Analysis are two modern classics that are often used instead of Rudin. Amann is great, but I think it might be a bit too much if it's the first time you see this material, especially if you would like something that explains the context a bit more than baby Rudin.


text: Q: What's the recommended way to represent distributions of complex-valued random variables in Tensorflow Probability? I don't see any existing classes for complex Normal or complex Wishart distributions in the Tensorflow Probability api docs. Is this because it's easy to synthesize these distributions from existing apis? If so I would appreciate an example or a reference.


text:
Q: How to make the question mark inline with the text Code:
# -*- coding: utf-8 -*-
import base64
import io
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table

from dash.dependencies import Input, Output, State

app = dash.Dash(
    __name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}], suppress_callback_exceptions=True
)
server = app.server

app.layout = html.Div(children=[html.Label("Select Model"), html.Abbr("\u2753", title="Hello, I am hover-enabled helpful information.")])

if __name__ == "__main__":
    app.run_server(port=8069, debug=True)#, dev_tools_ui=False,dev_tools_props_check=False)

I am unable to make it inline with this html.Label tag. Is there any way to do it?

A: You could set float = 'left' in the html.Label style like this:
app.layout = html.Div(children=[html.Label("Select Model", style = {'float': 'left'}), html.Abbr("\u2753", title="Hello, I am hover-enabled helpful information.")])