text:
Q: Is this code defensive programming, or bad practice? I have this debate with my colleague about this piece of code:
var y = null;
if (x.parent != null)
    y = x.parent.somefield;

My point of view is that in the place where the code is, x.parent should not POSSIBLY be null. And when it is null, we have a serious problem and I want to know it! Hence, the null check should not be there and let the down stream exception happen.
My colleague says this is defensive programming. And the null check makes sure the code doesn't break the application.
My question is, is this defensive programming? Or a bad practice?
Note: the point is not who is right. I'm trying to learn from this example.

A: I wouldn't call it defensive programming at all - I'd call it "la la la I can't hear you" programming :) Because the code appears to be effectively ignoring a potential error condition.
Obviously we don't have any idea of what comes next in your code, but since you didn't include an else clause, I can only assume that your code just carries on even in the case that x.parent is actually null.
Bear in mind that "should not possibly be null" and "is absolutely, positively guaranteed to never be null" are not necessarily the same thing; so in that case it could lead to an exception further down the line when you try to de-reference y.

The question is then - what is more acceptable within the context of the problem you are trying to solve (the "domain") and that kind of depends on what you intend to do with ylater on.

*

*If y being null after this code is not a problem (let's say you do a defensive check later on for y!=null) then that's OK - although personally I don't like that style - you end up defensively checking every single de-reference because you can never be quite sure if you're a null reference away from crashing...

*If y cannot be null after the code because it will cause an exception or missing data later on, then it's simply a bad idea to continue when you know that an invariant is not correct.

A: It looks like your colleague is misunderstanding "defensive programming" and/or exceptions.
Defensive Programming
Defensive programming is about protecting against certain kinds of errors.
In this case x.parent == null is an error because your method needs to use x.parent.SomeField. And if parent were null, then the value of SomeField would clearly be invalid. Any calculation  with or task performed using an invalid value would yield erroneous and unpredictable results.
So you need to protect against this possibility. A very good way to protect is by throwing a NullPointerException if you discover that x.parent == null. The exception will stop you from getting an invalid value from SomeField. It will stop you doing any calculations or performing any tasks with the invalid value. And it will abort all current work up until the the error is suitably resolved.

Note the exception is not the error; an invalid value in parent that is the actual error. The exception is in fact a protection mechanism. Exceptions are a defensive programming technique, they're not something to be avoided.

Since C# already throws an exception, you don't actually have to do anything. In fact it turns out that your colleague's effort "in the name of defensive programming", is actually undoing built-in defensive programming provided by the language.
Exceptions
I've noticed many programmers are unduly paranoid about exceptions. An exception itself isn't an error, it's simply reporting the error.
Your colleague says: "the null check makes sure the code doesn't break the application". This suggests he believes that exceptions break applications. They generally don't "break" an entire application.

Exceptions could break an application if poor exception handling puts the application in an inconsistent state. (But this is even more likely if errors are hidden.) They can also break an application if an exception 'escapes' a thread. (Escaping the main thread obviously implies your program has terminated rather ungracefully. But even escaping a child thread is bad enough that the best option for an operating system is to GPF the application.)

Exceptions will however break (abort) the current operation. And this is something they must do. Because if you code a method called DoSomething which calls DoStep1; an error in DoStep1 means that DoSomething cannot do its job properly. There is no point in going on to call DoStep2.
However, if at some point you can fully resolve a particular error, then by all means: do so. But note the emphasis on "fully resolve"; this doesn't mean just hide the error. Also, just logging the error is usually insufficient to resolve it. It means getting to the point where: if another method calls your method and uses it correctly, the 'resolved error' will not negatively affect the caller's ability to do its job properly. (No matter what that caller may be.)
Perhaps the best example of fully resolving an error is in the main processing loop of an application. Its job is to: wait for a message in the queue, pull the next message off the queue and call appropriate code to process the message. If an exception was raised and not resolved before getting back to the main message loop, it needs to be resolved. Otherwise the exception will escape the main thread and the application will be terminated.
Many languages provide a default exception handler (with a mechanism for the programmer to override/intercept it) in their standard framework. The default handler will usually just show an error message to the user and then swallow the exception.
Why? Because provided you haven't implemented poor exception handling, your program will be in a consistent state. The current message was aborted, and the next message can be processed as if nothing is wrong. You can of course override this handler to:

*

*Write to log file.

*Send call-stack information for troubleshooting.

*Ignore certain classes of exception. (E.g. Abort could imply you don't even need to tell the user, perhaps because you previously displayed a message.)

*etc.

Exception Handling
If you can resolve the error without an exception first being raised, then it is cleaner to do so. However, sometimes the error cannot be resolved where it first appears, or cannot be detected in advance. In these cases an exception should be raised/thrown to report the error, and you resolve it by implementing an exception handler (catch block in C#).

NOTE: Exception handlers server two distinct purposes: First they provide you a place to perform clean-up (or rollback code) specifically because there was an error/exception. Second, they provide a place to resolve an error and to swallow the exception. NB: It's very important in the former case that the exception be re-raised/thrown because it has not been resolved.

In a comment about throwing an exception and handling it, you said: "I wanted to do that but I was told it creates exception handling code everywhere."
This is another misconception. As per the previous side-note you only need exception handling where:

*

*You can resolve an error, in which case you're done.

*Or where you need to implement rollback code.

The concern may be due to flawed cause-and-effect analysis. You don't need rollback code just because you're throwing exceptions. There are many other reasons that exceptions can be thrown. Rollback code is required because the method needs to perform clean-up if an error occurs. In other words the exception handling code would be required in any case. This suggests the best defence against excessive exception handling is to design in such a way that the need for clean-up on errors is reduced.
So don't "not throw exceptions" to avoid excessive exception handling. I agree excessive exception handling is bad (see design consideration above). But it is far worse to not rollback when you should because you didn't even know there was an error.

A: Interesting question. From my point of view, whether or not to include the check is a matter of how well the data is validated, where does it come from and what can happen when the check fails.
"x.parent should not POSSIBLY be null" is a serious assumption. You need to be very sure of it to play safe, of course there is the classic "it will never happen"....... until it happens, that's why I think it's interesting to review the possibilities.
I see two different things to think about.
Where does the data comes from?

*

*If it comes from another method in the same class, or from some related class, since you have more or less full control about it, it's logical to relax your defenses, as you can reasonably assume that it's very unlikely to have bad data to begin with, or if it happens it's reasonably easy to catch the bug early during debugging/testing and even place some unit tests for it.

*The opposite case would be if it's data entered by the user, or read from a file, or from a URL, anything external generally speaking. Since you cannot control what the program is dealing with: by all means, validate it as thoroughly as you can before using it in any way, as you're exposed to bogus/missing/incomplete/incorrect/malicious information that may cause problems down the path.

*An intermediate case can be when the input comes from another layer/tier within the same system. It's more difficult to decide whether to do a full validation or take it for granted, since it's another piece of internal software, but might be replaced or modified independently at a later time. My preference goes towards validating again when crossing boundaries.
What to do with the validation?

*

*Using an if (as in your sample) to simply skip over some assignment or usage may be fine for some cases. For instance, if the user is entering some data and this just shows a tooltip or other minor info, it's possibly safe to skip. But if the piece of code does something important, that in turn fills some mandatory condition or executes some other process, it's not the right approach as it will cause problems for the next code run. The thing is, when you skip over some code, it must be safe to do so, without any side effects or unwanted consequences, otherwise you would be hiding some error, and that's quite difficult to debug in later development stages.

*Abort the current process gracefully is a good choice for early validations, when the failure is totally expected and you know precisely how to respond to it. An example could be a missing required field, the process gets interrupted and a message is shown to the user asking for the missing info. It's not OK to simply ignore the error, but also not serious enough to throw an exception that disrupts the normal program flow. Of course, you may still use an exception, depending on your architecture, but in any case catch it and recover gracefully.

*Throw an exception is always a choice when the "impossible" really happened. It's in those cases where you cannot possibly provide a reasonable response for either continuing with some variation or cancel just the current process, it may be due to a bug or bad input somewhere, but the important thing is that you want to know it and have all the details about it, so the best possible way is to make it to blow up as loudly as possible, so that the exception bubbles up and reaches a global handler that interrupts everything, saves to a log file/DB/whatever, sends a crash report to you and finds a way to resume execution, if that's feasible or safe. At least if your app crashes, do so in the most graceful way, and leave traces for further analysis.
As always, it depends on the situation. But just using an if to avoid coding an exception handler is for sure a bad practice. It must always be there, and then some code may rely on it - whether appropriate or not - if it's not critical to fail.

A: In short, I'd say this is NOT a defensive programming. I agree with those who thinks this code hides the system error instead of exposing and fixing. This code violates the 'fail fast' principle.
This is true if and only if x.parent is a mandatory non-null property (which seems to be obvious from the context.) However, if x.parent is an optional property (i.e. can reasonably have a null value) then this code can be allright depending on your business logic expressed.
I'm always considering usage of empty values (0, "", empty objects) instead of nulls which require tons of irrelevant if statements.

A: After some years of thinking about this issue, I use the following "defensive" programming style - 95% of my methods return string as a success / failed result.
I return string.Empty for success, and informative text string if failed. While returning the error text, I write it to log at the same time.
public string Divide(int numA, int numB, out double division)
{
    division = 0;
    if (numB == 0)
        return Log.Write(Level.Error, "Divide - numB-[{0}] not valid.", numB);

    division = numA / numB;
    return string.Empty;
}

Then I use it:
private string Process(int numA, int numB)
{
    double division = 0;
    string result = string.Empty;
    if (!string.IsNullOrEmpty(result = Divide(numA, numB, out divide))
        return result;

    return SendResult(division);
}

When you have Log monitoring system, it lets the system show go on, but     notifies the administration.


text:
Q: Problem with linking Class into specific memory region using Linker Script I have a problem with linking class to specific memory region via Linker Script
I've figure out how to link variables and functions that are out of the class but I have no idea how to link the class into the memory region specified in the linker script
My linker script is very simple:
SECTIONS
{
  . = 0x1000000;
  .text : { *(.text) }
  . = 0x8000000;
  .data : { *(.data) }
  .bss : { *(.bss) }
}

And the main code:
#include <iostream>     // system
#include "mem.h"

using namespace std;

unsigned int A = 0xFFFF1234;
unsigned int B = 0x00001234;

void Function_A(void)
{
    printf("This is execution of the void Function A \n");
}

void Function_B(int x)
{
    x = x + 1;
    printf("This is execution of the void Function B with variable x:%d \n",x);
}

int main(int argc, char* argv[])
{
    system("clear");

    unsigned int * pA = &A;
    unsigned int * pB = &B;

    printf("Original Data A ---> 0x%08x\n",A);
    printf("Original Data B ---> 0x%08x\n\n",B);

    printf("Pointer to A variable ---> %p\n",pA);
    printf("Pointer to B variable ---> %p\n\n",pB);

    void (*pFunction_A)(void) = &Function_A;
    void (*pFunction_B)(int)  = &Function_B;

    MemAssembly * pMemAssembly;
    pMemAssembly->MemDump();

    // Testing function pointers
    pFunction_A();
    pFunction_B(100);
    (*pFunction_B)(200);

    printf("Pointer to Function_A ---> %p\n",pFunction_A);
    printf("Pointer to Function_B ---> %p\n\n",pFunction_B);

    // Address is not linked !!!????
    printf("Pointer to MemAssembly Class ---> %p\n\n",pMemAssembly);

    return 0;
}

Now, when I execute I get this:
Original Data A ---> 0xffff1234
Original Data B ---> 0x00001234

Pointer to A variable ---> 0x8000004
Pointer to B variable ---> 0x8000008

RAX_Accumulator ---> Read A : 0x00000000ffff1234
RAX_Accumulator ---> Read B : 0x0000000000001234

This is execution of the void Function A
This is execution of the void Function B with variable x:101
This is execution of the void Function B with variable x:201
Pointer to Function_A ---> 0x10000e9
Pointer to Function_B ---> 0x1000103

Pointer to MemAssembly Class ---> 0x7f282ab46764

The mem.h looks as follows:
#ifndef MEM_H
#define MEM_H

#include <inttypes.h>

extern "C" unsigned long _MEMORY_READ_A(void);
extern "C" unsigned long _MEMORY_READ_B(void);

class MemAssembly{

    public:
        MemAssembly();
        ~MemAssembly();

        int AssemblyMemoryDump(void);

        void MemDump(void)
        {
            printf("RAX_Accumulator ---> Read A : %#018" PRIx64 " \n",_MEMORY_READ_A());
            printf("RAX_Accumulator ---> Read B : %#018" PRIx64 " \n\n",_MEMORY_READ_B());
        }

};

#endif /* MEM_H */

And the assemblies
section .text

global _MEMORY_READ_A
_MEMORY_READ_A:
    mov eax, [0x08000000 + 4]
    ret

global _MEMORY_READ_B
_MEMORY_READ_B:
    mov eax, [0x08000000 + 8]
    ret

So my question is: How should I modify linker script, mem.h or the assemblies in order to load my class into specific memory region rather than using dynamic allocation ???
Instead of this one:
Pointer to MemAssembly Class ---> 0x7f282ab46764

Read address specified in the linker script ???

A: Thanks Peter for the help
Here what I did:
Added MemAssembly section in ASM
section .MemAssembly

    global global_MemAssembly
    global_MemAssembly:

Link it with 0xb000000
SECTIONS
{
  . = 0x1000000;
  .text : { *(.text) }
  . = 0x8000000;
  .data : { *(.data) }
  .bss : { *(.bss) }
  . = 0xB000000;
  .MemAssembly : { *(MemAssembly)}
}

Using Test class
class MemAssembly{

    public:
        MemAssembly();
        ~MemAssembly();

        int x,y,z,t;
        long a,b,c,d;
        long long dx,dy,dz,dt;

        void MemDump(void)
        {
            printf("x  ---> %p y  ---> %p z  ---> %p t  ---> %p\n", &x, &y, &z, &t);
            printf("a  ---> %p b  ---> %p c  ---> %p d  ---> %p\n", &a, &b, &c, &d);
            printf("dx ---> %p dy ---> %p dz ---> %p dt ---> %p\n\n", &dx, &dy, &dz, &dt);
        }
};

When I call MemDump() using usign dynamic:
MemAssembly * pMemAssembly

I get:
x  ---> 0x7ffd7cc36040 y  ---> 0x7ffd7cc36044 z  ---> 0x7ffd7cc36048 t  ---> 0x7ffd7cc3604c
a  ---> 0x7ffd7cc36050 b  ---> 0x7ffd7cc36058 c  ---> 0x7ffd7cc36060 d  ---> 0x7ffd7cc36068
dx ---> 0x7ffd7cc36070 dy ---> 0x7ffd7cc36078 dz ---> 0x7ffd7cc36080 dt ---> 0x7ffd7cc36088

But when I've used:
extern MemAssembly global_MemAssembly;
MemAssembly * pMemAssembly = &global_MemAssembly;

I get:
x  ---> 0xb000000 y  ---> 0xb000004 z  ---> 0xb000008 t  ---> 0xb00000c
a  ---> 0xb000010 b  ---> 0xb000018 c  ---> 0xb000020 d  ---> 0xb000028
dx ---> 0xb000030 dy ---> 0xb000038 dz ---> 0xb000040 dt ---> 0xb000048

Which is what I've expected

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Datatables merge? I am using the jQuery data plugin, and with initialising my page, I do an AJAX call to fill the table. Then, every 1.5 seconds I do another AJAX call to get the new info, I then clear the table, and fill it again.
Is there a way for me to check if the new JSON from the new AJAX call is different to the current, and then edit just those cell(s) to the new value, so I don't have to completely refresh my table every time?
Thanks!


text:
Q: jQuery DataTables and IE/Chrome/Safari: table overlaps footer instead of pushing it down This only happens on Google Chrome and Safari (not a problem on Firefox).
If I have  table that with multi-line data, it ends up expanding the table's height -- then instead of pushing down the DIV containing my footer, the table actually overlaps the footer. On Firefox the footer is pushed down as I'd expect.
Can anyone give me suggestion how to resolve this?
Will be glad to include specific code -- the overall structure is as follows:

        //datatables being built here

        //footer code here

A: Do you have some code to show us?
It might be as simple as:
#main {
float: left;
clear: both;
}

or

#main table {
float: left;
clear: both;
}


text:
Q: How to install python dependency when using google-cloud-ml-engine notebook? I am on google-cloud-ml notebook. Trying to install pandas_ml in order to import it.
I read https://cloud.google.com/ml-engine/docs/notebooks/dependencies tried both options (terminal and a separate installation notebook). None of those solutions work for me
#either
pip install pandas_ml #terminal
#or
!pip install pandas_ml #notebook

A: Solved!
since I'm using Python 3.5 I had to use pip3 instead of pip

A: !pip will install your packages on the system level and not in your notebook kernel. Try this instead:
import sys
!{sys.executable} -m pip3 install pandas_ml

Eventually, Google MLE notebooks will support %pip.
More information can be found on Jake VanderPlas's blog: Installing Python Packages from a Jupyter Notebook.


text:
Q: React.js private route related issue when trying to signup or login I am getting this error "Cannot update a component (BrowserRouter) while rendering a different component (Login). To locate the bad setState() call inside Login" whenever I try to signUp or log in. I think this is occurring because of react router. But i couldn't find where I messed up. Here is the code (index.js).
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
 );
 reportWebVitals();

Here is App.js
import "./App.css";
import Header from "./Components/Shared/Header/Header";
import "bootstrap/dist/css/bootstrap.min.css";
import Footer from "./Components/Shared/Footer/Footer";
import { Route, Routes } from "react-router-dom";
import Home from "./Components/Pages/Home/Home";
import Login from "./Components/Pages/Login/Login";
import Register from "./Components/Pages/Login/Register";
import Contact from "./Components/Pages/Contact/Contact";
import NotFound from "./Components/Pages/NotFound/NotFound";
import Blogs from "./Components/Pages/Blogs/Blogs";
import Manage from "./Components/Pages/Manage/Manage";
import Add from "./Components/Pages/Add/Add";
import Myitems from "./Components/Pages/Myitems/Myitems";
import SingleInventory from "./Components/Pages/SingleInventory/SingleInventory";
import RequireAuth from "./Components/RequireAuth";

function App() {
return (

  <Routes>
    <Route path="/" element={<Home></Home>}></Route>
    <Route
      path="/products/:id"
      element={
        <RequireAuth>
          <SingleInventory></SingleInventory>
        </RequireAuth>}
    ></Route>
    <Route path="/manage" element={<Manage></Manage>}></Route>
    <Route path="/add" element={<Add></Add>}></Route>
    <Route path="/myitems" element={<Myitems></Myitems>}></Route>
    <Route path="/blogs" element={<Blogs></Blogs>}></Route>
    <Route path="/contact" element={<Contact></Contact>}></Route>
    <Route path="/login" element={<Login></Login>}></Route>
    <Route path="/register" element={<Register></Register>}></Route>
    <Route path="*" element={<NotFound></NotFound>}></Route>
  </Routes>

     );
   }

export default App;

Here Login.js
import { Icon } from "@iconify/react";
import React, { useState } from "react";
import { Button, Form } from "react-bootstrap";
import {
useSignInWithEmailAndPassword,
useSignInWithFacebook,
useSignInWithGoogle,
}   from "react-firebase-hooks/auth";
import { Link, useLocation, useNavigate } from "react-router-dom";
import auth from "../../../firebase.init";
import logo from "../../../images/login.svg";

const Login = () => {
const navigate = useNavigate();
const location = useLocation();

const from = location.state?.from?.pathname || "/";

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [signInWithEmailAndPassword, user, loading, error] =
useSignInWithEmailAndPassword(auth);

const [signInWithGoogle, gUser, gLoading, gError] = useSignInWithGoogle(auth);
const [signInWithFacebook, fbUser, fbLoading, fbError] =
useSignInWithFacebook(auth);

const handleFormSubmit = (e) => {
e.preventDefault();
signInWithEmailAndPassword(email, password);
};

 const handleGoogleLogin = () => {
   signInWithGoogle();
  };
 const handleFbLogin = () => {
  signInWithFacebook();
 };
 if (user || fbUser|| gUser) {
 navigate(from, { replace: true });
 }
 return (

        Log in

      <Form className=" mx-auto" onSubmit={handleFormSubmit}>
        <Form.Group className="mb-3" controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            name="email"
            placeholder="Enter email"
            onBlur={(e)=>setEmail(e.target.value)}
          />
        </Form.Group>

        <Form.Group className="mb-3" controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            name="password"
            placeholder="Password"
            onBlur={(e)=>setPassword(e.target.value)}
          />
        </Form.Group>

Forget password

        <Button className="w-100" variant="primary" type="submit">
          Log in
        </Button>
      </Form>

        Don't have an account?
        <Link className="text-decoration-none" to="/register">
          Sign Up
        </Link>

        <Icon onClick={handleGoogleLogin} icon="logos:google-icon" />
        <Icon
          onClick={handleFbLogin}
          className="text-primary"
          icon="fa6-brands:facebook"
        />
        <Icon icon="logos:github-icon" />

     );
  };

  export default Login;

A: It's because you try to navigate out in the open within the Login component.
if (user || fbUser|| gUser) {
 navigate(from, { replace: true });
 }

By invoking navigate here, you're causing an update in the navigation context, which in turn can trigger a rerender while Login is still rendering. To avoid this, you want to use a useEffect hook so that this is checked after the first render/as a side effect.
Wrap it in a useEffect to only navigate when one of those values changes:
useEffect(() => {
 navigate(from, { replace: true });
}, [user, fbUser, gUser]);


text:
Q: delete characters in notepad++ after # I have a chunk of HTML files that need removal of code.

should baiscally become

Basically in all the files, there are anchors starting with # and followed by a random 8 digit word. Need to remove the anchor from all the files.
Have been trying to do this using RegEx but not being able to. Any help would be awesome.

A: Have a try with:
Find what: #\w{8}
Replace with: nothing


text:
Q: Solving parametric equation I am trying to solve these  equations
t + (a*Sin[t/b - h] + a)*Tan[θ] == x

k + (a*Sin[t/b - h] + a) == y

where a, b, h, and θ are the coefficients.
I want the equation in the form of y[x].

A: You could solve for a in the first equation and then substitute the result into the second equation:
sol = Solve[t + (a*Sin[t/b - h] + a)*Tan[θ] == x, a][[1]]
(* {a -> ((t - x) Cot[θ])/(-1 + Sin[h - t/b])} *)

FullSimplify[k + (a*Sin[t/b - h] + a) /. sol]
(* k + (-t + x) Cot[θ] *)

Or notice that (a*Sin[t/b - h] + a) is equal to -(t - x) Cot[θ] and substitute that into the second equation.

A: It seems only be possible to solve analytically for x[y] :
ergt = Solve[ k + (a*Sin[t/b - h] + a) == y ,  t ] /. C[1] -> 0(*restrict solution [0,2Pi]*)
(*{{t -> h - ArcSin[(a + k - y)/a]}, {t ->h - \[Pi] + ArcSin[(a + k - y)/a]}} *)

Now it is possible to solve for x[y] (2 solutions):
{Solve[t + (a*Sin[t/b - h] + a)*Tan[\[Theta]] == x /. ergt[[1]], x][[1]]
,
Solve[t + (a*Sin[t/b - h] + a)*Tan[\[Theta]] == x /. ergt[[2]],x][[1]]}
(*{{x -> h - ArcSin[(a + k - y)/a] - k Tan[\[Theta]] +y Tan[\[Theta]]},
{x ->h - \[Pi] + ArcSin[(a + k - y)/a] - k Tan[\[Theta]] +y Tan[\[Theta]]}}*)

If necessary, you could further use InverseFunction for given parametervalues
 a,b,h,k,\[Theta]

A: Solving first for $t$
solt = Solve[y == a (Sin[t/b - h] + 1) + k, t] /. {C[1] -> 0}

and then after substitution
x - t - a (Sin[t/b - h] + 1) Tan[theta] /. solt // FullSimplify

we get at the implicit forms $(f(x,y(x))=0)$
-b h + x + b ArcSin[(a + k - y)/a] + (k - y) Tan[theta] == 0

and
-b h + b Pi + x - b ArcSin[(a + k - y)/a] + (k - y) Tan[theta] = 0

Follows an example with numerical values.
a = 1; b = 1; h = 0 Pi/4; k = 1; theta = Pi/4;
gr1 = ContourPlot[-b h + x + b ArcSin[(a + k - y)/a] + (k - y) Tan[theta] == 0, {x, -4, 4}, {y, 0, 4}, ContourStyle -> {Thick, Blue}];
gr2 = ContourPlot[-b h + b \[Pi] + x - b ArcSin[(a + k - y)/a] + (k - y) Tan[theta] == 0, {x, -4, 4}, {y, 0, 4}, ContourStyle -> {Thick, Blue}];
Show[gr1, gr2]


text:
Q: postgres regex_replace everything between the third and last forward slash I have some URLs within a Postgres table that currently look like this:
http://blue.website.com/categoryA/sectionA/title/6534566234
http://yellow.website.com/categoryA/sectionB/title/36476586
http://green.website.com/categoryB/sectionB/title/34646634

I am trying to create a regex that can be used to transform the URLs to look like this:
http://blue.website.com/6534566234
http://yellow.website.com/36476586
http://green.website.com/34646634

I was able to figure out how to use regex_replace to replace everything up to the last / with nothing:
select regexp_replace('http://blue.website.com/categoryA/sectionA/title/6534566234', '^.*/', '')

regexp_replace|
--------------|
6534566234    |

However, I'm not sure how to extend this to replace everything between the 3rd / and the last / with nothing.

A: Replace with blank (ie "remove") each term separately, using look arounds to target the right parts:
select regexp_replace('http://blue.website.com/categoryA/sectionA/title/6534566234', '(?<!/)/[^/]+(?=/)', '', 'g')

See live demo.
The regex (?<!/)/[^/]+(?=/) works as follows:

*

*/[^/]+ matches a slash followed by non-slashes

*(?<!/) the preceding char is not a slash. This prevents matching the part after //, which you want to keep

*(?=/) requires the following char to be a slash. This prevents matching the final term, which you want to keep

The final parameter 'g' is the global flag - means replace all matches (not just the first, as would be the case if this parameter were not specified)


text:
Q: Why does this Perl variable keep its value What is the difference between the following two Perl variable declarations?
my $foo = 'bar' if 0;

my $baz;
$baz = 'qux' if 0;

The difference is significant when these appear at the top of a loop. For example:
use warnings;
use strict;

foreach my $n (0,1){
    my $foo = 'bar' if 0;
    print defined $foo ? "defined\n" : "undefined\n";
    $foo = 'bar';
    print defined $foo ? "defined\n" : "undefined\n";
}

print "==\n";

foreach my $m (0,1){
    my $baz;
    $baz = 'qux' if 0;
    print defined $baz ? "defined\n" : "undefined\n";
    $baz = 'qux';
    print defined $baz ? "defined\n" : "undefined\n";
}

results in
undefined
defined
defined
defined
==
undefined
defined
undefined
defined

It seems that if 0 fails, so foo is never reinitialized to undef. In this case, how does it get declared in the first place?

A: First, note that my $foo = 'bar' if 0; is documented to be undefined behaviour, meaning it's allowed to do anything including crash. But I'll explain what happens anyway.

my $x has three documented effects:

*

*It declares a symbol at compile-time.

*It creates an new variable on execution.

*It returns the new variable on execution.

In short, it's suppose to be like Java's Scalar x = new Scalar();, except it returns the variable if used in an expression.
But if it actually worked that way, the following would create 100 variables:
for (1..100) {
   my $x = rand();
   print "$x\n";
}

This would mean two or three memory allocations per loop iteration for the my alone! A very expensive prospect. Instead, Perl only creates one variable and clears it at the end of the scope. So in reality, my $x actually does the following:

*

*It declares a symbol at compile-time.

*It creates the variable at compile-time[1].

*It puts a directive on the stack that will clear[2] the variable when the scope is exited.

*It returns the new variable on execution.

As such, only one variable is ever created[2]. This is much more CPU-efficient than then creating one every time the scope is entered.
Now consider what happens if you execute a my conditionally, or never at all. By doing so, you are preventing it from placing the directive to clear the variable on the stack, so the variable never loses its value. Obviously, that's not meant to happen, so that's why my ... if ...; isn't allowed.

Some take advantage of the implementation as follows:
sub foo {
   my $state if 0;
   $state = 5 if !defined($state);
   print "$state\n";
   ++$state;
}

foo();  # 5
foo();  # 6
foo();  # 7

But doing so requires ignoring the documentation forbidding it. The above can be achieved safely using
{
   my $state = 5;
   sub foo {
      print "$state\n";
      ++$state;
   }
}

or
use feature qw( state );  # Or: use 5.010;

sub foo {
   state $state = 5;
   print "$state\n";
   ++$state;
}

Notes:

*

*"Variable" can mean a couple of things. I'm not sure which definition is accurate here, but it doesn't matter.

*If anything but the sub itself holds a reference to the variable (REFCNT>1) or if variable contains an object, the directive replaces the variable with a new one (on scope exit) instead of clearing the existing one. This allows the following to work as it should:
my @a;
for (...) {
    my $x = ...;
    push @a, \$x;
}

A: See ikegami's better answer, probably above.
In the first example, you never define $foo inside the loop because of the conditional, so when you use it, you're referencing and then assigning a value to an implicitly declared global variable. Then, the second time through the loop that outside variable is already defined.
In the second example, $baz is defined inside the block each time the block is executed. So the second time through the loop it is a new, not yet defined, local variable.


text:
Q: How to display the start situation in an xskakloop How can I display the start situation, for example the normal chessboard structure, in an xskakloop?
So to speak as "Move 0".

\documentclass[margin=5mm, varwidth]{standalone}
\usepackage{xskak}
\usepackage{chessboard}
\setchessboard{showmover=false, margin=false}

\begin{document}
\section{Start situation :)}
\newchessgame
\chessboard[tinyboard]

\section{Loop has no start situation :(}
\newchessgame
\mainline{1.d4 Nf6 2.c4 g6 3.Nc3 Bg7}

\xskakloop[step=1]{%
\begin{tabular}{c}
\chessboard[tinyboard,
setfen=\xskakget{nextfen}]
\\
\xskakget{opennr}\xskakget{lan}%
\end{tabular}\quad}%
\end{document}


text:
Q: selector inside jquery .next() method is not selecting correct element I have added two divs using jquery.I use corresponding selector inside jquery .next()  to target them. I always get second div.
HTML:

this is my p

jquery:
    $(function(){
      $('p.myp').after('
first div added with jquery
');
      $('p.myp').after('
second div added with jquery
');
      console.log($('p.myp').next('div.firstDiv').text());

      console.log($('p.myp').next('div.secondDiv').text());
    });

jsbin:
http://jsbin.com/lomol/4/edit

A: next() selects only the next element, the selector passed is just a filter, it doesn't search any further than the next immediate sibling.
When you use after() twice, the first element inserted is pushed down, so it's no longer the next immediate element, the markup you end up with is

this is my p

second div added with jquery

first div added with jquery

There are many other ways to get the element, using an ID, creating the elements with a reference etc.
$(function () {
    var first = $('
', {
        'class' : 'firstDiv',
        text    : 'first div added with jquery'
    });
    var second = $('
', {
        'class' : 'secondDiv',
        text    : 'second div added with jquery'
    });

    $('p.myp').after(first);
    $('p.myp').after(second);

    console.log(first.text());
    console.log(second.text());
});

FIDDLE

A: Which is not surprising as secondDiv will always be the next element. You may see how it works:

*

*Initially you have the following markup:

this is my p

*Then you insert firstDiv after p.myp:
$('p.myp').after('

');

And your markup becomes the following:

this is my p

*Then you insert secondDiv after p.myp:
$('p.myp').after('

');

And your markup becomes:

this is my p

From the above you may see that secondDiv now is the next element after
.


text:
Q: dual monitor, ubuntu 14.04, second monitor isn't detected, using VGA-HDMI adapter I tried to connect an old monitor Acer P193W to my acer apire z3-605 using VGA-HDMI adapter. After connecting the monitor I went to settings > displays and there was just built-in monitor. Tried changing to proprietary drivers through software & updates from fglrx. nothing
lshw -short
/0/100/1/0             display        Sun XT [Radeon HD 8670A/8670M/8690M]
/0/100/2               display        3rd Gen Core processor Graphics Controller

from xorg.conf
Section "ServerLayout"
Identifier "amd-layout"
    Screen 0 "amd-screen" 0 0
EndSection

Section "Device"
    Identifier "intel"
    Driver "intel"
    Option "AccelMethod" "uxa"
    BusID "PCI:0@0:2:0"
EndSection

Section "Device"
    Identifier "amd-device"
    Driver "fglrx"
    BusID "PCI:1:0:0"
EndSection

Section "Monitor"
    Identifier "amd-monitor"
    Option "VendorName" "ATI Proprietary Driver"
    Option "ModelName" "Generic Autodetecting Monitor"
    Option "DPMS" "true"
EndSection

Section "Screen"
    Identifier "amd-screen"
    Device "amd-device"
    Monitor "amd-monitor"
    DefaultDepth 24
    SubSection "Display"
        Viewport   0 0
        Depth     24
    EndSubSection
EndSection

from xrandr
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 8192 x 8192
eDP1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 580mm x 360mm
   1920x1080      59.7*+
   1680x1050      69.9     60.0     59.9
   1600x1024      60.2
   1400x1050      74.8     70.0     60.0
   1600x900       60.0
   1280x1024      75.0     60.0
   1440x900       59.9
   1280x960       60.0
   1360x768       59.8     60.0
   1152x864       75.0     75.0     70.0     60.0
   1280x720       60.0
   1024x768       75.0     70.1     60.0
   832x624        74.6
   800x600        72.2     75.0     60.3     56.2
   640x480        72.8     75.0     60.0     59.9
   720x400        70.1
VGA1 disconnected (normal left inverted right x axis y axis)

from lspci
00:02.0 VGA compatible controller: Intel Corporation 3rd Gen Core processor Graphics Controller (rev 09)
01:00.0 Display controller: Advanced Micro Devices, Inc. [AMD/ATI] Sun XT [Radeon HD 8670A/8670M/8690M]

I just don't get it. Did I buy wrong adapter? Do I have to update drivers? To be sure I re-installed ubuntu to 14.04 x64, couldn't find any other thread answering my question.


text:
Q: Setting a Bitmap as intent extra causes error I need to put a bitmap into an intent extra:
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(Globals.KEY_IMAGE, this.imageBitmap);

Unfortunately I get the following error:
E/JavaBinder﹕ !!! FAILED BINDER TRANSACTION !!!
I guess it is because the size of an extra is limited to 1mb. How else could i get that bitmap from one activity to another?

A: Either:

*

*Don't use multiple activities here, but instead use one activity, perhaps with multiple fragments, or

*Carefully pass the Bitmap via a static data member, making sure to set that data member to null after the new activity has the Bitmap, to prevent a major memory leak


text:
Q: верстка сайта под мобильное устройство В так называемой ПК версии (не знаю, как правильно сказать подругому) все выглядит хорошо, но вот когда просматриваю сайт на андроиде или же через гуглхром на ПК с применением toggle device mod, то вижу жуть жуткую. Пытался прописать обычное свойство

font-size:12px;

но все равно не то, что надо. Ссылка на сайт. прошу подтолкнуть в нужном направлении.
Черным выделен пример некорректности. и там, и там задан размер 12px

A: Если надо что бы сайт был под мобильные устройства, то попробуй в head добавить:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

и прочитай про медиа-запросы
а лучше посмотри видео на Youtube

A: решением будет добавление css свойствa
.name_author table a {
    font-size: 100%;
}

Тогда ссылки внутри таблицы и ссылки на автора будут одинакового размера.
Пока пробовал найти решение, наткнулся на то, что "искажает" размер "а" именно таблица. При чём, если "а" добавить display: inline-block, то font-size: 32px нужно делать, чтобы выровнять до оригинала (и это уже будет 2 решение данного вопроса). Наверное, где-то с % ошибка.


text:
Q: Finding the transfer function of a opamp circuit with 3 opamps I have the following circuit:

I know that \$\text{sig}_+\$ is a voltage that is \$n\$ times bigger than the voltage at \$\text{sig}_-\$.

Question: If \$R_g\$ is a coil with the value \$63\space\text{mH}\$ and \$R_3\$ is a capacitor with value \$10\space\text{nF}\$ and \$R_f=R_1=R_2=R_4=10\space\text{k}\Omega\$ and \$n=10\$ what is the gain of this circuit at \$f=10^6\space\text{Hz}\$?

A: Well, I am trying to analyze the following circuit (assuming an ideal opamp):

simulate this circuit – Schematic created using CircuitLab
When we use and apply KCL, we can write the following set of equations:
$$
\begin{cases}
\text{I}_8=\text{I}_1+\text{I}_4\\
\\
\text{I}_1=\text{I}_2\\
\\
\text{I}_2=\text{I}_3\\
\\
\text{I}_5=\text{I}_3+\text{I}_9\\
\\
0=\text{I}_4+\text{I}_7\\
\\
\text{I}_5=\text{I}_6\\
\\
\text{I}_6=\text{I}_7+\text{I}_8+\text{I}_9
\end{cases}\tag1
$$
When we use and apply Ohm's law, we can write the following set of equations:
$$
\begin{cases}
\text{I}_1=\frac{\text{V}_1-\text{V}_2}{\text{R}_1}\\
\\
\text{I}_2=\frac{\text{V}_2-\text{V}_3}{\text{R}_2}\\
\\
\text{I}_3=\frac{\text{V}_3-\text{V}_4}{\text{R}_3}\\
\\
\text{I}_4=\frac{\text{V}_1-\text{V}_5}{\text{R}_4}\\
\\
\text{I}_5=\frac{\text{V}_4-\text{V}_6}{\text{R}_5}\\
\\
\text{I}_6=\frac{\text{V}_6}{\text{R}_6}\\
\\
\text{I}_7=\frac{\text{V}_7-\text{V}_5}{\text{R}_7}
\end{cases}\tag2
$$
Substitute \$(2)\$ into \$(1)\$, in order to get:
$$
\begin{cases}
\text{I}_8=\frac{\text{V}_1-\text{V}_2}{\text{R}_1}+\frac{\text{V}_1-\text{V}_5}{\text{R}_4}\\
\\
\frac{\text{V}_1-\text{V}_2}{\text{R}_1}=\frac{\text{V}_2-\text{V}_3}{\text{R}_2}\\
\\
\frac{\text{V}_2-\text{V}_3}{\text{R}_2}=\frac{\text{V}_3-\text{V}_4}{\text{R}_3}\\
\\
\frac{\text{V}_4-\text{V}_6}{\text{R}_5}=\frac{\text{V}_3-\text{V}_4}{\text{R}_3}+\text{I}_9\\
\\
0=\frac{\text{V}_1-\text{V}_5}{\text{R}_4}+\frac{\text{V}_7-\text{V}_5}{\text{R}_7}\\
\\
\frac{\text{V}_4-\text{V}_6}{\text{R}_5}=\frac{\text{V}_6}{\text{R}_6}\\
\\
\frac{\text{V}_6}{\text{R}_6}=\frac{\text{V}_7-\text{V}_5}{\text{R}_7}+\text{I}_8+\text{I}_9
\end{cases}\tag3
$$
Now, using an ideal opamp, we know that:

*

*$$\text{V}_\text{k}=\text{V}_{+_1}=\text{V}_{-_1}=\text{V}_2$$

*$$\text{n}\cdot\text{V}_\text{k}=\text{V}_{+_2}=\text{V}_{-_2}=\text{V}_3$$

*$$\text{V}_x:=\text{V}_{+_3}=\text{V}_{-_3}=\text{V}_5=\text{V}_6$$
So we can rewrite equation \$(3)\$ as follows:
$$
\begin{cases}
\text{I}_8=\frac{\text{V}_1-\text{V}_\text{k}}{\text{R}_1}+\frac{\text{V}_1-\text{V}_x}{\text{R}_4}\\
\\
\frac{\text{V}_1-\text{V}_\text{k}}{\text{R}_1}=\frac{\text{V}_\text{k}-\text{n}\cdot\text{V}_\text{k}}{\text{R}_2}\\
\\
\frac{\text{V}_\text{k}-\text{n}\cdot\text{V}_\text{k}}{\text{R}_2}=\frac{\text{n}\cdot\text{V}_\text{k}-\text{V}_4}{\text{R}_3}\\
\\
\frac{\text{V}_4-\text{V}_x}{\text{R}_5}=\frac{\text{n}\cdot\text{V}_\text{k}-\text{V}_4}{\text{R}_3}+\text{I}_9\\
\\
0=\frac{\text{V}_1-\text{V}_x}{\text{R}_4}+\frac{\text{V}_7-\text{V}_x}{\text{R}_7}\\
\\
\frac{\text{V}_4-\text{V}_x}{\text{R}_5}=\frac{\text{V}_x}{\text{R}_6}\\
\\
\frac{\text{V}_x}{\text{R}_6}=\frac{\text{V}_7-\text{V}_x}{\text{R}_7}+\text{I}_8+\text{I}_9
\end{cases}\tag4
$$
Now, we can solve for the transfer function:
$$\displaystyle\mathcal{H}:=\frac{\text{V}_\text{o}}{\text{V}_\text{i}}=\frac{\text{V}_7}{\text{V}_\text{k}}=\frac{\text{n}\text{R}_7\left(\text{R}_6\left(\text{R}_1+\text{R}_2+\text{R}_3\right)+\text{R}_1\text{R}_5\right)+\text{n}\text{R}_4\text{R}_6\left(\text{R}_2+\text{R}_3\right)-\text{R}_7\left(\text{R}_1+\text{R}_2\right)\left(\text{R}_5+\text{R}_6\right)-\text{R}_3\text{R}_6\left(\text{R}_4+\text{R}_7\right)}{\text{R}_2\text{R}_4\left(\text{R}_5+\text{R}_6\right)}\tag5$$

Now, applying this to your circuit we need to use (from now on I use the lower case letters for the function in the 'complex' s-domain where I used Laplace transform):

*

*$$\text{R}_2=\text{sL}\tag6$$

*$$\text{R}_6=\frac{1}{\text{sC}}\tag7$$

*$$\text{R}:=\text{R}_1=\text{R}_3=\text{R}_4=\text{R}_5=\text{R}_7\tag8$$
So, the transfer function becomes:
$$\mathcal{h}\left(\text{s}\right)=\frac{\text{v}_\text{o}\left(\text{s}\right)}{\text{v}_\text{i}\left(\text{s}\right)}=\frac{\text{C}\left(\text{n}-1\right)\text{R}^2\text{s}+2\text{Lns}+3\left(\text{n}-1\right)\text{R}}{\text{Ls}\left(\text{CRs}+1\right)}-1\tag9$$
Because we are working with sinusodial signals, we can write \$\text{s}=\text{j}\omega\$ where \$\text{j}^2=-1\$ (the imaginary unit) and \$\omega=2\pi\text{f}\$ with \$\text{f}\$ is the frequency in Hertz. So, we can write:
$$\underline{\mathcal{h}}\left(\text{j}\omega\right)=\frac{\text{C}\left(\text{n}-1\right)\text{R}^2\left(\text{j}\omega\right)+2\text{Ln}\left(\text{j}\omega\right)+3\left(\text{n}-1\right)\text{R}}{\text{L}\left(\text{j}\omega\right)\left(\text{CR}\left(\text{j}\omega\right)+1\right)}-1\tag{10}$$
Now, we can find the amplitude by finding the absolute value of \$(10)\$ and using your given values:
$$\left|\underline{\mathcal{h}}\left(\text{j}\omega\right)\right|=\frac{1}{7}\sqrt{49-\frac{767436000000000}{\omega^2+100000000}+\frac{900000000000000}{\omega^2}}\tag{11}$$
So, at \$\text{f}=10^6\space\text{Hz}\$ we have \$\omega=2\pi\cdot10^6\space\text{rad/sec}\$, we get:
$$\left|\underline{\mathcal{h}}\left(\text{j}\cdot2\pi\cdot10^6\right)\right|=\frac{1}{7}\sqrt{49-\frac{767436000000000}{\left(2\pi\cdot10^6\right)^2+100000000}+\frac{900000000000000}{\left(2\pi\cdot10^6\right)^2}}=$$
$$\frac{\sqrt{\frac{225+1325689 \pi ^2+1960000 \pi ^4}{1+40000 \pi ^2}}}{7 \pi }\approx1.0337\tag{12}$$

I used Mathematica to solve the transfer function:
In[1]:=FullSimplify[
 Solve[{I8 == I1 + I4, I1 == I2, I2 == I3, I5 == I3 + I9,
   0 == I4 + I7, I5 == I6, I6 == I7 + I8 + I9, I1 == (V1 - Vk)/R1,
   I2 == (Vk - n*Vk)/R2, I3 == (n*Vk - V4)/R3, I4 == (V1 - Vx)/R4,
   I5 == (V4 - Vx)/R5, I6 == (Vx)/R6, I7 == (V7 - Vx)/R7}, {I1, I2,
   I3, I4, I5, I6, I7, I8, I9, V1, V4, Vx, V7}]]

Out[1]={{I1 -> (Vk - n Vk)/R2, I2 -> (Vk - n Vk)/R2, I3 -> (Vk - n Vk)/R2,
  I4 -> (((R1 - n R1 + R2) R5 - (-1 + n) (R1 + R2 + R3) R6) Vk)/(
   R2 R4 (R5 + R6)), I5 -> ((-R3 + n (R2 + R3)) Vk)/(R2 (R5 + R6)),
  I6 -> ((-R3 + n (R2 + R3)) Vk)/(R2 (R5 + R6)),
  I7 -> (((-1 + n) R1 R5 - R2 R5 + (-1 + n) (R1 + R2 + R3) R6) Vk)/(
   R2 R4 (R5 + R6)),
  I8 -> (((R1 - n R1 + R2 + R4 - n R4) R5 - (-1 + n) (R1 + R2 + R3 +
         R4) R6) Vk)/(R2 R4 (R5 + R6)),
  I9 -> ((-R3 - R5 - R6 + n (R2 + R3 + R5 + R6)) Vk)/(R2 (R5 + R6)),
  V1 -> ((R1 - n R1 + R2) Vk)/R2, V4 -> ((-R3 + n (R2 + R3)) Vk)/R2,
  Vx -> ((-R3 + n (R2 + R3)) R6 Vk)/(R2 (R5 + R6)),
  V7 -> ((n (R2 + R3) R4 R6 - (R1 + R2) (R5 + R6) R7 +
      n (R1 R5 + (R1 + R2 + R3) R6) R7 - R3 R6 (R4 + R7)) Vk)/(
   R2 R4 (R5 + R6))}}

In[2]:=FullSimplify[(((n (R2 + R3) R4 R6 - (R1 + R2) (R5 + R6) R7 +
      n (R1 R5 + (R1 + R2 + R3) R6) R7 - R3 R6 (R4 + R7)) Vk)/(
   R2 R4 (R5 + R6)))/Vk]

Out[2]=(n (R2 + R3) R4 R6 - (R1 + R2) (R5 + R6) R7 +
 n (R1 R5 + (R1 + R2 + R3) R6) R7 - R3 R6 (R4 + R7))/(R2 R4 (R5 + R6))

I also found the amplitude function for the transfer function using Mathematica:
In[3]:=FullSimplify[
 Sqrt[(ComplexExpand[
      Re[-1 + (3 (-1 + n) R + 2 L n (I*w) + C1 (-1 + n) R^2 (I*w))/(
        L (I*w) (1 + C1 R (I*w)))]])^2 + (ComplexExpand[
      Im[-1 + (3 (-1 + n) R + 2 L n (I*w) + C1 (-1 + n) R^2 (I*w))/(
        L (I*w) (1 + C1 R (I*w)))]])^2],
 Assumptions -> L > 0 && C1 > 0 && n > 0 && w > 0 && R > 0]

Out[3]=Sqrt[(L^2 (1 - 2 n)^2 w^2 + C1^2 (-1 + n)^2 R^4 w^2 +
 R^2 (9 (-1 + n)^2 + 4 C1 L (-1 + n^2) w^2 +
    C1^2 L^2 w^4))/(L^2 w^2 (1 + C1^2 R^2 w^2))]

Now, using your values we get:
In[4]:=L = 63*10^(-3);
C1 = 10*10^(-9);
R = 10000;
n = 10;
FullSimplify[Sqrt[(
 L^2 (1 - 2 n)^2 w^2 + C1^2 (-1 + n)^2 R^4 w^2 +
  R^2 (9 (-1 + n)^2 + 4 C1 L (-1 + n^2) w^2 + C1^2 L^2 w^4))/(
 L^2 w^2 (1 + C1^2 R^2 w^2))]]

Out[4]=1/7 Sqrt[49 + 900000000000000/w^2 - 767436000000000/(100000000 + w^2)]

And, we can use the limit:
In[5]:=FullSimplify[
 Limit[1/7 Sqrt[
   49 + 900000000000000/w^2 - 767436000000000/(100000000 + w^2)],
  w -> 2*Pi*10^6]]

Out[5]=Sqrt[(225 + 1325689 \[Pi]^2 + 1960000 \[Pi]^4)/(1 +
 40000 \[Pi]^2)]/(7 \[Pi])

In[6]:=N[%5]

Out[6]=1.0337


text:
Q: SSIS - Unable to infer the XSD from the XML file SSIS. The XML contains multiple namespaces Context: I have an XML file that I'm having trouble loading to SSIS because I keep raising the multiple namespaces error. Unable to infer the XSD from the XML file. The XML contains multiple namespaces.
The data in the file came from one of our Sharepoint API endpoints. Here is a snippet of the top of the XML file below.
I'm not an expert in XML - I don't understand why SSIS thinks there's multiple namespaces when it looks like there's only one xmlns="" that I see: xmlns="http://www.w3.org/2005/Atom"
<?xml version="1.0" encoding="utf-8"?><feed
xml:base="https://tlc.sharepoint.us/sites/tlc_PWA/_api/PD/"
xmlns="http://www.w3.org/2005/Atom"
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices"
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">

Question: From the other SO posts deleting or moving around this ns seemed to solve the issue for others but not for me. Can someone please help me resolve this issue so I can generate the XSD? I suspect some clashing formats may be confusing SSIS, not sure.


text:
Q: Keep mobile browser from showing elements outside body? Im making a website where i have a square rotated 45deg in the top right corner, and some of it is outsite of the body. On  desktop you not able to see it, but when i go on mobile i can zoom out and the right site of the body just gets bigger.
The red is what you able to see on you screen and this is how it looks on desktop and how i want it to look on mobile device.
http://imgur.com/ktPDPAN
But on mobile it looks like this, again where the red is what you able to see
http://imgur.com/XAFILRd
I got overflow-x hidden on body, so theres no scrollbar but the user is still able to zoom out and see the site like the second picture on mobile device.
I tried with meta tag, but its not really making any different, except that the site starts zoomed in, but user still able to zoom out.
like:

Html

        SOME TEXT

CSS
body {
margin: 0;
padding: 0;
overflow-x: hidden;
overflow-y: scroll;
 }

.bg {
background: url('../gfx/bg.png') top left;
}

#box-top-right {
position: absolute;
top: 75px;
right: -97px;
width: 400px;
height: 60px;
line-height: 60px;
text-align: center;
background: #ce180b;
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
color:white;
}

#wrapper {
width: 1200px;
position: absolute;
margin-top: -50px;
 }

A: I'd just put a container inside the body and set that to overflow:hidden;
Keep the rotated square within the container div.
Keep the width of the container at whatever you need,

And css:
html,body{
  width:100%;
  height:100%;
}
.container{
  width:100%;
  height:100%;/* depends, maybe it could be stretched by something else? */
  overflow-x:hidden;
  position:relative;
}
.rotated-thingy{
  position: absolute;
  top: 10px;
  right: 10px;/* or whatever appropriate here */
}

Sometimes elements html and body are not exactly treated the same way as the div's are.


text:
Q: Adapt my function store() in update() in Laravel The function store() is
       $date_start = $request->get('date_seance');
       $fk_motorbike = $request->get('fk_motorbike');

       $conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_revision_start', "<=" , $date_start)
            ->whereDate('date_revision_end', ">=", $date_start)
            ->first();

        $conflictTraining = Training::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_seance', "=" , $date_start)
            ->first();

        if(isset($conflictTraining) || isset($conflictRevision)){
            return redirect()->route('trainings.index')
                 ->with('error', 'Duplicate ');
        }

        else{
            Training::create($request->all());
                return redirect()->route('trainings.index')
                    ->with('success', 'Add');
    }

I want to adapt my function store()for the method update(), because I want to modify my different values of my fields.
I know to change the value of the date_seance but the function update() doesn't change the others values ex: hour_start, hour_end, fk_motorbike, fk_former, it's a problem...
public function update(trainingsRequest $request, $id)
    {
        $date_seance = $request->get('date_seance');
        $hour_start = $request->get('hour_start');
        $hour_end = $request->get('hour_end');
        $fk_motorbike = $request->get('fk_motorbike');
        $fk_former = $request->get('fk_former');

        $conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_revision_start', "<=" , $date_seance)
            ->whereDate('date_revision_end', ">=", $date_seance)
            ->where('hour_start', "<=" , $date_seance)
            ->where('hour_end', "<=" , $date_seance)
            ->first();

        $conflictTraining = Training::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_seance', "=" , $date_seance)
            ->where('hour_start', "<=" , $date_seance)
            ->where('hour_end', "<=" , $date_seance)
            ->first();

        if(isset($conflictTraining) || isset($conflictRevision)){
            return redirect()->route('trainings.index')
                 ->with('error', 'Duplicate ');
        }

        else{
            $trainings = Training::find($id);
            $trainings->date_seance = $request->get('date_seance');
            $trainings->hour_start = $request->get('hour_start');
            $trainings->hour_end = $request->get('hour_end');
            $trainings->fk_motorbike = $request->get('fk_motorbike');
            $trainings->fk_former = $request->get('fk_former');
            $trainings->save();
            return redirect()->route('trainings.index')
                    ->with('success', 'update')->withInput();
        }
    }

I know the problem is here:
 if(isset($conflictTraining) || isset($conflictRevision)){
            return redirect()->route('trainings.index')
                 ->with('error', 'Duplicate ');
        }

I have tried this but without success:
 if( (isset($conflictTraining) && $conflictTraining->id !== intval($id))
        || (isset($conflictRevision) && $conflictRevision->id !== intval($id)) ){
            return redirect()->route('trainings.index')
             ->with('error', 'Duplicate date! ');
        }

Thank you for your help.

A: Because you are looking to update a Training, you don't want to check to see if the incoming form id is the same for the Revision in the if-check.  The id that is coming in (that you are comparing to) is for a Training.  So the if-check should look more like this:
if( (isset($conflictTraining) && $conflictTraining->id !== intval($id))
    || isset($conflictRevision)) ){
        return redirect()->route('trainings.index')
         ->with('error', 'Duplicate date! ');
    }

Leaving out the id check from the Revision above will not make a false hit (id of Revision will likely never === the incoming id of the Training, and if it does, it is wrong since it is comparing the wrong id)
The conflict check for Revision, however, may also be causing you problems.  This line:
 $conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
        ->whereDate('date_revision_start', "<=" , $date_seance)
        ->whereDate('date_revision_end', ">=", $date_seance)
        ->where('hour_start', "<=" , $date_seance)  // <--Suggest remove this
        ->where('hour_end', "<=" , $date_seance)  // <--Suggest remove
        ->first();

is checking against an hour start of the Revision model.  If there is no hour_start/end in that model, OR if you are just checking to see if the seance is the same day as the Revision, this might cause problems.  I would remove the query to check against hour_start and hour_end.
Same thing might apply to the Training query.  If you want to get granular to the point of checking if the new training from the form is at the same hour, this is fine.  But if so, this is a much more detailed check - IE does the new training start at the same time, or finish at the same time.  This will not, however, check to see if the training hits in the middle of the old training the way you have it set up (both check for <=).  You may wish to consider just checking if the new training is on same day as old training and any potential revision.  IE remove the where checks on time for the training query to make this simpler - once you get it working, maybe add in more strict query parameters like the hour of start / finish.
IE I suggest removing this for now till you get it working:
->where('hour_start', "<=" , $date_seance)
->where('hour_end', "<=" , $date_seance)


text:
Q: What does the Polarisation Vector signify?
...The electric field produced by the $i$-th laser is described by
$$\vec{E_i}=E_{0,i}\vec{ε_i}\cos(\vec{k_i}\cdot\vec{r}-\omega t)$$
with the amplitude $E_{0,i}$, the wave vector $\vec{k_i}$
and the unit-length polarization vector $\varepsilon_i$
...
A typical setup is shown in Fig. 2a. Here, all three beams are polarized in the $z$ direction,
propagate in the $$ plane and intersect at equal angles of $120°$.

This is from the 2021 IPhO problem 3. The main problem I am encountering is that I can't visualise where the polarisation vector is pointing and thus can't decide how the waves add up. Also what does the polarisation vector signify? Is it like the oscillation axis? It's not related to the hard part of the question anyway, but I just wanted to know where it points since we already have a wave vector showing propagation. The Wikipedia page also didn't help me much

A: The polarization vector here represents the direction of the electric field. In this problem, it is $\hat{\mathbf{z}}$ for all three lasers. It's important to consider here since field amplitudes will add; in the middle, the polarization vector allows us to see that the electric field contributed by each laser is the same, and will add accordingly.
Note that the magnetic field of each laser will not all point in the same direction, unlike the electric field.


text:
Q: embed pdf file from google docin wordpress i am not looking for a plugin solution as i dont want to use a plugin just for this.i am using wordpress >4.0
i am tiring to embed a pdf file i get the embed code form google docs which is like this:
<iframe src="https://docs.google.com/document/d/laksdldjlsakdjuikjasoius/pub?embedded=true"></iframe>

when i put the code in the html view of my wordpress page creator and click update the page is refreshed and the code disappeared as if wordpress is deleting the code.
the code works fine if used in another simple (non-wordpress) html page.
So what seems to be the issue.?
I dont want to host the document form my site instead i want to use the docs which i have on Google docs but this doesn't seem to work.

A: The WordPress WYSIWYG strips out some HTML tags (one of which is the <iframe>). See this related post on WordPress Stack Exchange.
You can either write your own shortcode to handle iframes, or use a plugin. Either way, you're going to need to pass the src attribute of the iframe into the editor, without embedding it within the actual <iframe> tag, or modify the way TinyMCE strips out tags.


text:
Q: first-network sample to run, deploy and invoke on REST protocol After installing all the prerequisites, I tried cloning/downloading Hyperledger fabric sample first-network on Hyperledger Fabric v1.0 using this command:
git clone --tag v1.0.6 https://github.com/hyperledger/fabric-samples.git

I was able to successfully start the network using the instructions at  Building Your First Network.
My question is, I need to be able to open up first-network's REST API so that I could invoke/deploy chaincodes using REST protocol on a private network/intranet. Something like this:
GET http(s)://10.10.4.244:7050/chaincode
{
    "jsonrpc": "2.0",
    "result": {
        "status": "OK",
        "message": "mycc"
    },
    "id": 1
}

Is there a way to do this using Hyperledger Fabric first-network Sample?
Thank you very much.

A: FabricV0.6 provided REST-API, but it's removed from fabric since v1.0. Our project utilizing composer-rest-server(provided by hyperledger composer) to interact with blockchain via REST-API.


text:
Q: Use a column in the jointable on the where I've 3 tables on this piece of code, the tables are :
Users - With information about the users
Widgets - With information about the widgets
user_widgets - use for the m-n relationship between the previous tables
The last table, other than the ids of the other 2 tables have 2 extra fields : read and write
The code i've used to connect to these tables are
 Widget.belongsToMany(User, { through:User_widget, foreignKey: 'widget_id' });
 User.belongsToMany(Widget, { through:User_widget, foreignKey: 'user_id' });

The User_widget has an alias as "perms", so when i call
User.findOne ... then(function(user){
   user.getWidgets().then(function(widgets) {

In the widgets object returned I have the perms object with the 2 fields read and write, so all works fine.
My problem is I need to filter the Widgets so that i get only the widgets in which I have read perms.
I've tried with
user.getWidgets({
   where : {
      read : false
   }})

but it produces a sql query like
SELECT "widget"."id", "widget"."name", "perms"."widget_id" AS "perms.widget_id", "perms"."user_id" AS "perms.user_id", "perms"."read" AS "perms.read", "perms"."write" AS "perms.write"
FROM "widgets" AS "widget"
WHERE "widget"."read" = false
INNER JOIN "user_widget" AS "perms" ON "widget"."id" = "perms"."widget_id" AND "perms"."user_id" = '5';

I need a query like this :
SELECT "widget"."id", "widget"."name", "perms"."widget_id" AS "perms.widget_id", "perms"."user_id" AS "perms.user_id", "perms"."read" AS "perms.read", "perms"."write" AS "perms.write"
FROM "widgets" AS "widget"
INNER JOIN "user_widget" AS "perms" ON "widget"."id" = "perms"."widget_id" AND "perms"."user_id" = '5' AND "perms"."read" = false;

A: Try:
user.getWidgets({
  through: {
    where : {
      read : false
    }
  }
})


text:
Q: Creating equirectangular projection from 3d spatial model? Apologies if this is not the right group for this question, but I think there may be people here who can help. (I'm open to suggestions for better places to ask.)
I have a program that contains a model of a planet. The model contains the surface of the planet and objects that have height e.g. mountains. The program accepts the (3d) coordinates of a viewer and the direction the viewer is looking and computes what the viewer would see on a flat screen (using the rules of perspective).
What I would like it to do now is to compute the equirectangular 2:1 projection corresponding to the viewer's position - i.e. the full-sphere panorama at the viewpoint. The maths involved presents no difficulties to me but I want to avoid a pixel-by-pixel calculation of the projection when I am sure this has been done before.
How can I create an equirectangular projection from a 3d spatial model?
My search so far has been limited to what Google mostly turns up i.e. the panoramic photgraphers where the assumption is that your source data is captured on a camera that rotated about its null parallax point. I have considered simulating taking photos in this way (including the overlapping, sigh) and using a stitcher like Autopano, but this will not work because stitchers only find control points in images with "texture" which my images would not have. I suspect the people I need to talk to are game programers but I haven't found them yet.
My projections will be gigapixels in size so the implementation needs to be efficient.


text:
Q: string is showing spaces where there are extra comma while splitting I have a following string in text format.
XSP,6919,LONWW38ST,,1,GBP,2055.94,382.94,,EK,BHX,,0,HYD,,0,C=IN,061114,4,45,10,2014,,251114,2,48,10,2014,,19,DNS,,,,,20131212112902,,,,,1345,EK,1,,061114,1325,071114,0015,BHX,,DXB,3,EK,EK,,40,77W,M,M,,LCA,Y,2,,071114,0345,071114,0840,DXB,3,HYD,,EK,EK,,526,345,M,M,,LCA,Y,,,,,,,,,,,,,,,,,,,,,3115,BA,3,,251114,0655,251114,1215,HYD,,LHR,5,BA,BA,,276,788,Y,M,,LCA,Y,4,,251114,1825,251114,1935, R,Y,1,2,,,,,MLSOWGB1,RP,,,ADT,3,4,,,,,YOW,RP,,,ADT,5,,,,,,XOW,RP,,,ADT,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

I read the string using following code
    string fileName = @"C:\Test.txt";

    string str = string.Empty;
    string s;
    if (File.Exists(fileName))
    {
        StreamReader sr = new StreamReader(fileName);
        String line;

        while ((line = sr.ReadLine()) != null)
        {
            if (line.Trim() != string.Empty)
            {
                string[] text = line.Split(',');
                Response.Write(text[0]);

            }
        }
    }
    else
    {
       s = "File does not exists";
    }

But the string is showing spaces where there are extra comma (,) when I am splitting the string. I want to ignore that space ans show the string in Grid View and also save in Database.
Please Help!
Thanks

A: You can use the second parameter of the Split method:
string[] text = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

However, I'd expect that doing that in this case is a bad idea. The "duplicate" comma probably means that the column is empty (assuming you're parsing a CSV file).
You may want to look for a good CSV parsing library instead - parsing a CSV isn't as easy as it looks on first glance :)


text:
Q: I want to create lookup data using apache_beam.utils.shared module but it gives error TypeError: cannot create weak reference to 'list' object `
import apache_beam as beam
from apache_beam.utils import shared
from log_elements import LogElements

class GetNthStringFn(beam.DoFn):
  def __init__(self, shared_handle):
    self._shared_handle = shared_handle

  def process(self, element):
    def initialize_list():
      # Build the giant initial list.
      return [str(i) for i in range(1000000)]

    giant_list = self._shared_handle.acquire(initialize_list)
    yield giant_list[element]

with beam.Pipeline() as p:
  shared_handle = shared.Shared()

  (p | beam.Create([2, 4, 6, 8])

     | beam.ParDo(GetNthStringFn(shared_handle))

     | LogElements())

`
I tried example given in apache beam documentation.
Link https://beam.apache.org/releases/pydoc/2.24.0/apache_beam.utils.shared.html
but got below error
File "/opt/playground/backend/executable_files/4a6babb9-9ea4-4a70-881d-559057592090/4a6babb9-9ea4-4a70-881d-559057592090.py", line 39, in process
    giant_list = self._shared_handle.acquire(initialize_list)
  File "/usr/local/lib/python3.7/site-packages/apache_beam/utils/shared.py", line 312, in acquire
    return _shared_map.acquire(self._key, constructor_fn, tag)
  File "/usr/local/lib/python3.7/site-packages/apache_beam/utils/shared.py", line 253, in acquire
    result = control_block.acquire(constructor_fn, tag)
  File "/usr/local/lib/python3.7/site-packages/apache_beam/utils/shared.py", line 149, in acquire
    self._ref = weakref.ref(result)
TypeError: cannot create weak reference to 'list' object [while running 'ParDo(GetNthStringFn)']

A: You don't reference the good link and version, the Beam version 2.24.0 is too old.
Check with this code and this link :
# Several built-in types such as list and dict do not directly support weak
# references but can add support through subclassing:
# https://docs.python.org/3/library/weakref.html
class WeakRefList(list):
  pass

class GetNthStringFn(beam.DoFn):
  def __init__(self):
    self._shared_handle = shared.Shared()

  def setup(self):
    # setup is a good place to initialize transient in-memory resources.
    def initialize_list():
      # Build the giant initial list.
      return WeakRefList([str(i) for i in range(1000000)])

    self._giant_list = self._shared_handle.acquire(initialize_list)

  def process(self, element):
    yield self._giant_list[element]

p = beam.Pipeline()
(p | beam.Create([2, 4, 6, 8])
   | beam.ParDo(GetNthStringFn()))

To be able to execute this code, you need to install the Beam 2.42.0 version. You can install it with pip in your virtual env.


text:
Q: c# uwp current finger holding coordinates on mobile In C# UWP, how to get current finger holding coordinates on mobile?
I have been using this:
    private void mainGridHolding(object sender, HoldingRoutedEventArgs e)
    {
        var coordinateY = e.GetPosition(mainGrid).Y;
    }

But, I don't want to execute it all the time whenever user holding the screen.
And also, this event fire after the popup is shown, so I get the wrong informations.
Like there is a property for Pointer location:
var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

Is there any property that holds the information about current touch?


text:
Q: Merging array items with null values considered I have an array with data from different tables (at least 9 tables).I want to iterate through the array and kind of merge them in a way that the first item is taken from all arrays, then second and so on.
I'll better explain now with an example below.

So suppose I have an input array like the below :

var arrData = [{
    "Id": 1,
    "Name": 'Ken',
    "Age": '',
    "Hobbies": [{
      'HobbyId': 1,
      'HobbyName': 'Swimming'
    }, {
      'HobbyId': 2,
      'HobbyName': 'Reading'
    }],
    "Skills": [{
      'SkillId': 1,
      'SkillName': 'PHP'
    }, {
      'SkillId': 2,
      'SkillName': 'MySQL'
    }],
    "Language": [{
      'LangId': 2,
      'LangName': 'English'
    }, {
      'LangId': 3,
      'LangName': 'Chinese'
    }]
  },
  {
    "Id": 2,
    "Name": 'Mike',
    "Age": '20',
    "Hobbies": [],
    "Skills": [],
    "Language": []
  },
  {
    "Id": 3,
    "Name": 'Charlie',
    "Age": '25',
    "Hobbies": [{
      'HobbyId': 5,
      'HobbyName': 'Dance'
    }, {
      'HobbyId': 6,
      'HobbyName': ''
    }, {
      'HobbyId': 7,
      'HobbyName': 'Writing'
    }],
    "Skills": [],
    "Language": [{
      'LangId': 7,
      'LangName': 'English'
    }]
  }
];

console.log(arrData);

My resulting array should be something as below :
[
    [1,"Ken",'',1,'Swimming',1,'PHP',2,'English'],
    [1,"Ken",'',2,'Reading',2,'MySQL',3,'Chinese'],
    [2,"Mike",'20','','','','','',''],
    [3,"Charlie",'25','5','Dance','','',7,'English'],
    [3,"Charlie",'25','6','','','','',''],
    [3,"Charlie",'25','7','Writing','','','',''],
]

Here you may notice that the loop for an item iterates for the maximum number of times found in array for that item.
So for the 3rd item with Id = 3 and Name = 'Charlie' the loop iterates for 3 times as there are 3 (maximum) item in Hobbies array.
The is just a sample array and in reality I will have 9 arrays and my code should be very dynamic to handle it.
I have achieved 90% of the output but I am only stuck where I should pass empty values for the items not found in the array.
For example in the sample above Mike has no items for Hobbies,Skills or Language, in that case I still have to pass empty values.
Or if you see Charlie has 3 Hobbies, no skills and 1 Language, my array should have 3 items but as the Skills is empty is should have empty values for them and for the second and third item for charlie it should have empty values for Language.
I hope this makes sense.
I have tried some code as below and I'll explain at the bottom.

$(function() {
  // Handler for .ready() called.

  var finalData = [],
    arr = [],
    arrHeader = [],
    cnt = 0,
    generateMaxRows = 0;
  //finalData.push({"Id":"","Name":'',"Age" : '','HobbyId':'Hobbies','HobbyName':'', 'SkillId':'Skills','SkillName':'','LangId':'Language','LangName':''});

  var arrHeader = [{
    "Id": "Id",
    "Name": 'Name',
    "Age": 'Age',
    "Hobbies": [{
      'HobbyId': 'HobbyId',
      'HobbyName': 'HobbyName'
    }],
    "Skills": [{
      'SkillId': 'SkillId',
      'SkillName': 'SkillName'
    }],
    "Language": [{
      'LangId': 'LangId',
      'LangName': 'LangName'
    }]
  }];
  var arrData = [{
      "Id": 1,
      "Name": 'Ken',
      "Age": '',
      "Hobbies": [{
        'HobbyId': 1,
        'HobbyName': 'Swimming'
      }, {
        'HobbyId': 2,
        'HobbyName': 'Reading'
      }],
      "Skills": [{
        'SkillId': 1,
        'SkillName': 'PHP'
      }, {
        'SkillId': 2,
        'SkillName': 'MySQL'
      }],
      "Language": [{
        'LangId': 2,
        'LangName': 'English'
      }, {
        'LangId': 3,
        'LangName': 'Chinese'
      }]
    },
    {
      "Id": 2,
      "Name": 'Mike',
      "Age": '20',
      "Hobbies": [],
      "Skills": [],
      "Language": []
    },
    {
      "Id": 3,
      "Name": 'Charlie',
      "Age": '25',
      "Hobbies": [{
        'HobbyId': 5,
        'HobbyName': 'Dance'
      }, {
        'HobbyId': 6,
        'HobbyName': ''
      }, {
        'HobbyId': 7,
        'HobbyName': 'Writing'
      }],
      "Skills": [],
      "Language": [{
        'LangId': 7,
        'LangName': 'English'
      }]
    }
  ];

  jQuery.each(arrData, function(key, val) {
    arr = [];
    generateMaxRows = 1;
    jQuery.each(val, function(k, v) {
      if (Array.isArray(v)) {
        generateMaxRows = (v.length > generateMaxRows) ? v.length : generateMaxRows;
      }
    });

    for (var row = 0; row < generateMaxRows; row++) {
      arr = [];
      jQuery.each(arrHeader[0], function(header_key, header_val) {

        jQuery.each(val, function(row_key, row_val) {
          if (row_key == header_val) // Not an array.
          {
            arr.push(row_val);
          } else {
            if (Array.isArray(header_val)) {
              if (Array.isArray(row_val)) {
                jQuery.each(header_val[0], function(head_key, head_val) {
                  console.log(head_val);
                  jQuery.each(row_val[row], function(subrow_key, subrow_val) {
                    if (subrow_key == head_val) {
                      arr.push(subrow_val);
                    }
                  });

                });
              }
            }
          }
        });

        //   console.log(arr);

      });
      finalData.push(arr);
    }
  });

  console.log(JSON.stringify(finalData));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I have done a static array as arrHeader which will have a definition of array items that is to be compared with input array.
I have achieved 90% of the output except the  point where I have to pass null values where the arrHeader has an item but arrData does not.
Below is my real example helper array(arrHeader).
var arrHeader= {
        "ItemMasterNumber": "ItemMasterNumber",
        "IM_Description": "IM_Description",
        "IM_FirstProcessDate": "IM_FirstProcessDate",
        "IM_Alias": "IM_Alias",
        "IM_MasterPrice": "IM_MasterPrice",
        "IM_Category": "IM_Category",
        "IM_Version": "IM_Version",
        "IM_Type": "IM_Type",

        "ItemProducts" : [{
        "PO_Id" : "PO_Id",
        "PO_Code" : "PO_Code",
        "PO_Name" : "PO_Name",
        "PO_Type" : "PO_Type",
        "PO_TaxClassification" : "PO_TaxClassification",
        "PO_Bundle" : "PO_Bundle",
        "PO_PricingMechanism" : "PO_PricingMechanism",
        "PO_StoreVisible" : "PO_StoreVisible",
        "PO_NotSoldSeparately" : "PO_NotSoldSeparately",
        "PO_EnableDate" : "PO_EnableDate",
        "PO_AvailaibilityRule" : "PO_AvailaibilityRule",
        "PO_DisableDate" : "PO_DisableDate",
        "PO_MinOrderQty" : "PO_MinOrderQty",
        "PO_ExpectedReleaseDate" : "PO_ExpectedReleaseDate",
        "PO_Description" : "PO_Description",
        "PO_GrantOfferingType" : "PO_GrantOfferingType"
        }],

        "ItemFeatureSet": [{
                "FS_Id": "FS_Id",
                "FS_Code": "FS_Code",
                "FS_Name": "FS_Name",
                "FS_Description": "FS_Description",
                "FS_EnablementType": "FS_EnablementType"
            }],
        "ItemFeatures": [{
                "FE_Id": "FE_Id",
                "FE_Name": "FE_Name",
                "FE_Value": "FE_Value"

            }],
        "ItemCharges": [{
                "CH_ChargeId": "CH_ChargeId",
                "CH_Name": "CH_Name",
                "CH_Description": "CH_Description",
                "CH_Type": "CH_Type",
                "CH_ProvisioningTag": "CH_ProvisioningTag",
                "CH_Currency": "CH_Currency",
                "CH_CustomerSegment": "CH_CustomerSegment",
                "CH_ExtendedCustomerSegment": "CH_ExtendedCustomerSegment",
                "CH_Region": "CH_Region",
                "CH_Active": "CH_Active"

            }],
        "ItemChargeAttributes": [{
                "CA_Id": "CA_Id",
                "CA_ListPrice": "CA_ListPrice",
                "CA_FairValueBasis": "CA_FairValueBasis",
                "CA_FairValueMethod": "CA_FairValueMethod",
                "CA_FairValueLow": "CA_FairValueLow",
                "CA_FairValueHigh": "CA_FairValueHigh",
                "CA_EffectiveStartDate": "CA_EffectiveStartDate"
            }],
        "ItemPackages": [{
                "PA_PackageId": "PA_PackageId"
            }],
        "ItemPackagesComponents": [{
                "PA_ComponentId": "PA_ComponentId",
                "PA_Type": "PA_Type",
            }],
        "ItemOffers": [{
                "OF_OfferId": "OF_OfferId",
                "OF_Name": "OF_Name",
                "OF_Description": "OF_Description",
                "OF_Level": "OF_Level",
                "OF_Type": "OF_Type",
                "OF_CustomerSegment" : "OF_CustomerSegment",
                "OF_SalesChannel" : "OF_SalesChannel",
                "OF_ListPriceOffer" : "OF_ListPriceOffer",
                "OF_Region" : "OF_Region",
                "OF_CountryCode" : "OF_CountryCode",
                "OF_EffectiveStartDate": "OF_EffectiveStartDate",
                "OF_EffectiveEndDate": "OF_EffectiveEndDate"
            }],
        "ItemOffersComponents": [{
                "OC_Id": "OC_Id",
                "OC_Quantity": "OC_Quantity",
                "OC_AdjustmentAmount": "OC_AdjustmentAmount"
            }]
    };

Can you please help me out with this?
Any help is very much appreciated.
Thanks!

A: You could use arrHeader with arrays for nested properties. For zeroes, the actual index is used.

var arrHeader = [
        'Id',
        'Name',
        'Age',
        ['Hobbies', 0, 'HobbyId'],
        ['Hobbies',  0, 'HobbyName'],
        ['Skills',   0, 'SkillId'],
        ['Skills',   0, 'SkillName'],
        ['Language', 0, 'LangId'],
        ['Language', 0, 'LangName']
    ],
    data = [{ Id: 1, Name: "Ken", Age: "", Hobbies: [{ HobbyId: 1, HobbyName: "Swimming" }, { HobbyId: 2, HobbyName: "Reading" }], Skills: [{ SkillId: 1, SkillName: "PHP" }, { SkillId: 2, SkillName: "MySQL" }], Language: [{ LangId: 2, LangName: "English" }, { LangId: 3, LangName: "Chinese" }] }, { Id: 2, Name: "Mike", Age: "20", Hobbies: [], Skills: [], Language: [] }, { Id: 3, Name: "Charlie", Age: "25", Hobbies: [{ HobbyId: 5, HobbyName: "Dance" }, { HobbyId: 6, HobbyName: "" }, { HobbyId: 7, HobbyName: "Writing" }], Skills: [], Language: [{ LangId: 7, LangName: "English" }] }],
    result = data.reduce(function (r, a) {
        var max = arrHeader.reduce(function (m, k) {
                return Array.isArray(k) ? Math.max(m, (a[k[0]] || []).length) : m;
            }, 1),
            i;

        for (i = 0; i < max; i++) {
            r.push(arrHeader.map(function (k) {
                return Array.isArray(k) ? k.reduce(function (v, l) {
                    return (v || {})[l || i] || '';
                }, a) : a[k];
            }));
        }
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: This is a c code to find the average in an array of 50 elements using a function #include <stdio.h>
#include <stdlib.h>
float Findaverage(float n,float numbers[]) {
    float sum = 0;
    for (int j = 0; j < n; j++) {
        sum += numbers[j];
    }
    printf("The average number of the array is: %f", sum/n);

}

int main() {
    int sum = 0;
    float numbers[50];
    float average;
    printf("Enter 50 elements: ");
    // taking input and storing it in an array
    for(int i = 0; i < 50; ++i) {
        scanf("%f", &numbers[i]);
    }
    average = Findaverage(50,numbers[50]);
    printf("\nThe average number of the array is: %f", average );

    return 0;
}

The output gives an error "passing 'float' to parameter of incompatible type 'float *'; take the address with &". Why is this?

A: For starters the function Findaverage returns nothing.
You need to add this statement to the function
return sum / n;

And the first parameter shall have an integer type instead of the type float.
float Findaverage(float n,float numbers[]) {
                  ^^^^^

Secondly in this call of the function
average = Findaverage(50,numbers[50]);

the argument numbers[50] having the type float instead of the type float * is invalid. You need to write
average = Findaverage(50,numbers);

The function can be declared and defined the following way
double Findaverage( const float numbers[], size_t n )
{
    double sum = 0.0;

    for ( size_t i = 0; i < n; i++ )
    {
        sum += numbers[i];
    }

    return n == 0 ? 0.0 : sum / n;
}

And the function can be called like
double average = Findaverage( numbers, sizeof( numbers ) / sizeof( *numbers ) );

A: Change
average = Findaverage(50,numbers[50]);

to
average = Findaverage(50,numbers);

numbers[50] refers to a single array element, not the entire array.  It's also one past the end of your array (which is indexed from 0 to 49).


text:
Q: MongoDB poor write speed for collection with 500K documents with pymongo System Information:
OS: Ubuntu 20.04 LTS
System: 80 GB RAM, 1 TB SSD, i7-12700k
The documents in this collection are on average 16KB, and there are 500K documents in this collection. I noticed that as the collection grows larger, the time taken to insert documents also grows larger.

In what ways could I improve the speed of writes?
It is taking 10 Hours to insert 150k documents. Which is around what the graph predicted when we integrate the line:
def f(num):
    return 0.0004*num+0.9594

sum=0
for i in range(500,650):
    sum+=f(i*1000)

>> sum/3600
>> 9.61497

Potential upgrades in my mind:

*

*Use the C++ mongo engine for writes

*Allocate more RAM to Mongod

Logs
iotop showing mongod using < 1% of the IO capacity with write speeds around 10-20 KB/s
htop showing the mongod is only using ~ 16GB of RAM \
Disks showing that some 300GB of SSD is free
EDIT:
Psudo code:
docs=[...]
for doc in docs:
   doc["last_updated"]=str(datetime.now())

   doc_from_db = collection.find_one({"key":doc["key"]})

   new_dict = minify(doc)
   if doc_from_db is None:
      collection.insert_one(new_dict)
   else:
      collection.replace_one({"key":doc["key"]},new_dict,upsert=true)

A: When it comes to writes there are a few things to consider, the most impactful one which I'm assuming is the issue here is index size / index complexity / unique indexes.
It's hard to give exact advice without more information so I'll detail the most common bottlenecks when it comes to writes from my experience.

*

*As mentioned indexes, if you have too many indexes. unique indexes. or indexes on very large arrays (and the document you insert have large arrays) these all heavily impact insert performance. This behavior also correlates with the graph you provided as inserting becomes worse and worse the larger the index gets. There is no "real" solution to this issue, you should reconsider which indexes and which indexes cause the bottleneck (focus on unique /array indexes). For example if you have an index that enforces uniqueness then drop it and enforce uniqueness at the application level instead.

*write concern and replication lag, if you are using a replica set and you require a majority write concern this can definitely cause issues due to the sync lag that happens and grows, usually this is a side affect of a different issues, for example because of #1 (large indexes) the insert takes too long which causes sync lag which delays even further the write concern.

*unoptimized hardware (Assuming you're hosted on cloud), you'd be surprised how much you can optimize write performance by just changing the disk type and increasing IOPS. this will give immediate performance. obviously at the cost of $$$.

*no code was provided so I would also check that, if it's a for loop then obviously you can parallelize the logic.
I recommend you test the same insert logic on an indexless collection to pinpoint the problem, i'd be glad to help think of other issues/solutions once you can provide more information.

EDIT:
Here is an example of how to avoid the for loop issue by using bulkWrite instead in python using pymongo.
from pymongo import InsertOne, DeleteOne, ReplaceOne
from pymongo.errors import BulkWriteError

docs = [... input documents ]
requests = []
for doc in docs:
    requests.append({
       ReplaceOne({"docId": doc["docID"]}, doc, { upsert: True})
   })

try:
    db.docs.bulk_write(requests, ordered=False)
except BulkWriteError as bwe:
    pprint(bwe.details)

A: You can enable profiling in Database, but according to previous comments and your code, just python code profiling may be enough, for example can you show the output of similar example?
https://github.com/Tornike-Skhulukhia/cprofiler_python_example/blob/main/demo.py
But before that, please check that you have index on field that you are doing searches against using find_one command in current code, otherwise database may need to do full collection scan to just find 1 document, meaning if you have more documents, this time will also increase a lot.


text:
Q: sql How to achive this view table I want to achieve this view from the following table.
(a)  I want to get two columns with group1 having distinct values where c3= yes and group2 where it has sum(c2) according to group1.
(b)  group 3 is the sum(c4) according to group1 and group4 is sum(c5) according to group 1 .How can it be done ?
c1   |   c2   | c3   | c4 | c5
--------------|---------------
A    |   2    |yes   | 1   | 2
B    |   1    |yes   | 2   | 1
A    |   2    |yes   | 1   | 2
B    |   1    |yes   | 2   | 1
C    |   2    |no    | 4   | 4
C    |   1    |no    | 4   | 4

result :

group1 | group2| group3| group4
--------------------------------
A      | 4     | 2     | 4
B      | 2     | 4     | 2

part a was resolved by this query
SELECT c1 as group1, SUM(c2) as group2 FROM table
WHERE c3="yes"
GROUP BY c1

answered by Theo Babilon
but how to resolve part b and get a whole complete view ?

A: SELECT c1 as group1, SUM(c2) as group2, SUM(c4) as group3, SUM(c5) as group4
FROM table
WHERE c3 = "yes"
GROUP BY c1

A: use this query
SELECT c1 as group1, SUM(c2) as group2, SUM(c4) as group3, SUM(c5) as group4
FROM table
WHERE c2 = 'yes'
GROUP BY c1


text:
Q: Enunciate Json Generated Filename I have several same name data types in my code in different namespaces. When generating the XML Enunciate names these files as xml_namespaceID_datatype.xml this works correctly. Unfortunately the JSON files generated are named as json_datatype.json and do not keep the namespaceID. This is problematic as multiple same name datatypes are not kept.
How do I alter the naming of JSON files produced to retain the namespaceID?


text:
Q: Produce lnk file on GNU/Linux to transfer to windows I'll explain my goal first to avoid "XY Problem" misunderstandings.
I want to be able to produce a file (on Linux) that, when downloaded to a Windows machine and double clicked, will open a (ms office, but it shouldn't matter IIUC) file with a known path (on the local windows machine) preset by the server.
It seems what I'm trying to do is possible if I include the path of the file I want to open (and neither of the other details regarding the volume it's stored in etc) in the lnk file.
I first checked the lnk file format specs trying to generate the file in a python script but that's not my piece of cake (I never wrote code to handle binary files before). Besides, there are many features of that format that I want to ditch, but I still have to grok their flags/fields/lenghts/termination etc.
Then I stumbled upon the winedump utility and some .lnk files created by WINE in my ~/.wine folder.
There must be some function in the WINE codebase that is able to generate a lnk file, but I couldn't find it.
Where is it?
Is it in the form of a command like win's mklink?
If not (and I guess it's a function somewhere if it's not) can you point it to me so that I can write a wrapper command?
Or is there any library that can write lnk files and run on GNU/Linux?

A: These are untested by me but I did find 2 tools on this site which does describe the 2 tools as follows:

This application allow you to create Windows Shortcut files (extension .LNK) without needing a Windows OS.

The first app is a C app, the second is a Bash shell script. Here's the Shell script, mslink.sh:
#!/bin/bash

#############################################################################################
# mslink.sh v1.0
#############################################################################################
# Ce script permet de créer un Raccourci Windows (Fichier .LNK)
# Script créé en se basant sur la doc
#   http://msdn.microsoft.com/en-us/library/dd871305.aspx
#############################################################################################

OPTIONS=$(getopt -q -n ${0} -o hl:o:p -l help,lnk-target:,output-file:,printer-link -- "$@")

eval set -- ${OPTIONS}

IS_PRINTER_LNK=0
while true; do
  case "$1" in
    -h|--help) HELP=1 ;;
    -l|--lnk-target) LNK_TARGET="$2" ; shift ;;
    -o|--output-file) OUTPUT_FILE="$2" ; shift ;;
    -p|--printer-link) IS_PRINTER_LNK=1 ;;
    --)        shift ; break ;;
    *)         echo "Option inconnue : $1" ; exit 1 ;;
  esac
  shift
done

if [ $# -ne 0 ]; then
  echo "Option(s) inconnue(s) : $@"
  exit 1
fi

[ ${#LNK_TARGET} -eq 0 ] || [ ${#OUTPUT_FILE} -eq 0 ] && echo "
Usage :
 ${0} -l cible_du_fichier_lnk -o mon_fichier.lnk [-p]

Options :
 -l, --lnk-target               Précise la cible du raccourci
 -o, --output-file              Enregistre le raccourci dans un fichier
 -p, --printer-link             Génère un raccourci de type imprimante réseau
" && exit 1

#############################################################################################
# Fonctions
#############################################################################################

function ascii2hex() {
    echo $(echo -n ${1} | hexdump -v -e '/1 " x%02x"'|sed s/\ /\\\\/g)
}

function gen_IDLIST() {
        ITEM_SIZE=$(printf '%04x' $((${#1}/4+2)))
        echo '\x'${ITEM_SIZE:2:2}'\x'${ITEM_SIZE:0:2}${1}
}

function convert_CLSID_to_DATA() {
    echo -n ${1:6:2}${1:4:2}${1:2:2}${1:0:2}${1:11:2}${1:9:2}${1:16:2}${1:14:2}${1:19:4}${1:24:12}|sed s/"\([A-Fa-f0-9][A-Fa-f0-9]\)"/\\\\x\\1/g
}

#############################################################################################
# Variables issues de la documentation officielle de Microsoft
#############################################################################################

HeaderSize='\x4c\x00\x00\x00'                           # HeaderSize
LinkCLSID=$(convert_CLSID_to_DATA "00021401-0000-0000-c000-000000000046")   # LinkCLSID
LinkFlags='\x01\x01\x00\x00'                            # HasLinkTargetIDList ForceNoLinkInfo

FileAttributes_Directory='\x10\x00\x00\x00'                 # FILE_ATTRIBUTE_DIRECTORY
FileAttributes_File='\x20\x00\x00\x00'                      # FILE_ATTRIBUTE_ARCHIVE

CreationTime='\x00\x00\x00\x00\x00\x00\x00\x00'
AccessTime='\x00\x00\x00\x00\x00\x00\x00\x00'
WriteTime='\x00\x00\x00\x00\x00\x00\x00\x00'

FileSize='\x00\x00\x00\x00'
IconIndex='\x00\x00\x00\x00'
ShowCommand='\x01\x00\x00\x00'                          # SW_SHOWNORMAL
Hotkey='\x00\x00'                               # No Hotkey
Reserved='\x00\x00'                             # Valeur non modifiable
Reserved2='\x00\x00\x00\x00'                            # Valeur non modifiable
Reserved3='\x00\x00\x00\x00'                            # Valeur non modifiable
TerminalID='\x00\x00'                               # Valeur non modifiable

CLSID_Computer="20d04fe0-3aea-1069-a2d8-08002b30309d"               # Poste de travail
CLSID_Network="208d2c60-3aea-1069-a2d7-08002b30309d"                # Favoris réseau

#############################################################################################
# Constantes trouvées à partir de l'analyse de fichiers lnk
#############################################################################################

PREFIX_LOCAL_ROOT='\x2f'                            # Disque local
PREFIX_FOLDER='\x31\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'        # Dossier de fichiers
PREFIX_FILE='\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'          # Fichier
PREFIX_NETWORK_ROOT='\xc3\x01\x81'                      # Racine de serveur de fichiers réseau
PREFIX_NETWORK_PRINTER='\xc3\x02\xc1'                       # Imprimante réseau

END_OF_STRING='\x00'

#############################################################################################

# On retire l'anti-slash final s'il y en a un
LNK_TARGET=${LNK_TARGET%\\}

# On sépare le chemin racine du lien de la cible finale
# On distingue aussi si le lien est de type local ou réseau
# On définie la valeur Item_Data suivant le cas d'un lien réseau ou local

IS_ROOT_LNK=0
IS_NETWORK_LNK=0

if [[ ${LNK_TARGET} == \\\\* ]]; then
    IS_NETWORK_LNK=1
    PREFIX_ROOT=${PREFIX_NETWORK_ROOT}
    Item_Data='\x1f\x58'$(convert_CLSID_to_DATA ${CLSID_Network})

        TARGET_ROOT=${LNK_TARGET%\\*}
        if [[ ${LNK_TARGET} == \\\\*\\* ]]; then
                TARGET_LEAF=${LNK_TARGET##*\\}
        fi
        if [ ${TARGET_ROOT} == \\ ]; then
                TARGET_ROOT=${LNK_TARGET}
        fi
else
    PREFIX_ROOT=${PREFIX_LOCAL_ROOT}
    Item_Data='\x1f\x50'$(convert_CLSID_to_DATA ${CLSID_Computer})

    TARGET_ROOT=${LNK_TARGET%%\\*}
        if [[ ${LNK_TARGET} == *\\* ]]; then
        TARGET_LEAF=${LNK_TARGET#*\\}
        fi
    [[ ! ${TARGET_ROOT} == *\\ ]] && TARGET_ROOT=${TARGET_ROOT}'\'
fi

if [ ${IS_PRINTER_LNK} -eq 1 ]; then
    PREFIX_ROOT=${PREFIX_NETWORK_PRINTER}
    TARGET_ROOT=${LNK_TARGET}
    IS_ROOT_LNK=1
fi

[ ${#TARGET_LEAF} -eq 0 ] && IS_ROOT_LNK=1

#############################################################################################

# On sélectionne le préfixe qui sera utilisé pour afficher l'icône du raccourci

if [[ ${TARGET_LEAF} == *.??? ]]; then
    PREFIX_OF_TARGET=${PREFIX_FILE}
    TYPE_TARGET="fichier"
    FileAttributes=${FileAttributes_File}
else
    PREFIX_OF_TARGET=${PREFIX_FOLDER}
    TYPE_TARGET="dossier"
    FileAttributes=${FileAttributes_Directory}
fi

# On convertit les valeurs des cibles en binaire
TARGET_ROOT=$(ascii2hex ${TARGET_ROOT})
TARGET_ROOT=${TARGET_ROOT}$(for i in `seq 1 21`;do echo -n '\x00';done) # Nécessaire à partir de Vista et supérieur sinon le lien est considéré comme vide (je n'ai trouvé nul part d'informations à ce sujet)

TARGET_LEAF=$(ascii2hex ${TARGET_LEAF})

# On crée l'IDLIST qui représente le cœur du fichier LNK

if [ ${IS_ROOT_LNK} -eq 1 ];then
    IDLIST_ITEMS=$(gen_IDLIST ${Item_Data})$(gen_IDLIST ${PREFIX_ROOT}${TARGET_ROOT}${END_OF_STRING})
else
    IDLIST_ITEMS=$(gen_IDLIST ${Item_Data})$(gen_IDLIST ${PREFIX_ROOT}${TARGET_ROOT}${END_OF_STRING})$(gen_IDLIST ${PREFIX_OF_TARGET}${TARGET_LEAF}${END_OF_STRING})
fi

IDLIST=$(gen_IDLIST ${IDLIST_ITEMS})

#############################################################################################

if [ ${IS_NETWORK_LNK} -eq 1 ]; then
    TYPE_LNK="réseau"
    if [ ${IS_PRINTER_LNK} -eq 1 ]; then
        TYPE_TARGET="imprimante"
    fi
else
    TYPE_LNK="local"
fi

echo "Création d'un raccourci de type \""${TYPE_TARGET}" "${TYPE_LNK}"\" avec pour cible "${LNK_TARGET} 1>&2

echo -ne ${HeaderSize}${LinkCLSID}${LinkFlags}${FileAttributes}${CreationTime}${AccessTime}${WriteTime}${FileSize}${IconIndex}${ShowCommand}${Hotkey}${Reserved}${Reserved2}${Reserved3}${IDLIST}${TerminalID} > "${OUTPUT_FILE}"


text:
Q: How to use input string as variable call in python? I am a beginner python learner. I was wondering if it was possible to create a basic massage encrypting system without using any modules. I want my programm to check and use variable name that is in string.
let's say,
a = 'l'
b = '5'
c = 'o'

x = input("Enter your massage: ")

print(x, 'THE_USER INPUT matching the variable name and values')

I know I can do this with while or if, but it would take forever. Also, how do you separate each string letters before you match the variable.
I am using python 3. Thanks :)

A: I have no idea if this is what you are trying to do, but here goes:
a = 'l'
b = '5'
c = 'o'

x = input("Enter your message: ")
values = [globals().get(var, '') for var in list(x)]

print "".join(values)

EXAMPLE
Enter your message: abc
l5o

A more appropriate way to do this would likely be:
replacements = { 'a': 'l', 'b': '5', 'c': 'o' }

x = input("Enter your message: ")
print "".join([replacements.get(val, "") for val in x])

A: use string.translate  this is a much more correct way to do what it sounds like you want
from string import maketrans

in_tab  = "abcdefghijklmnopqrstuvwxyz "
out_tab = "5QR&*(=-;Wwz%$^#@!yY~:123xq"

t = maketrans(in_tab,out_tab)
print ("Hello World".translate(t))

A: In case you meant substituting every occurrence of a given character by another one, have a look at the str.translate function.
You could extend your example code as follows:
import string

in = input("Enter your message: ")
mapping = string.maketrans('abc', '15o')
out = in.translate(mapping)
print(out)

Every a is substituted by a 1, every b by 5, every c by o.