text:
Q: If statement not working yet used correctly     class SignUp : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private var etEmail: String? = null
private var etPass: String? = null
private var etPass2: String? = null
private lateinit var btn: Button

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_sign_up)
    // Initialising
    auth= Firebase.auth
    etEmail = findViewById<EditText>(R.id.et_email).text.toString().trim()
    etPass = findViewById<EditText>(R.id.pass).text.toString()
    etPass2 = findViewById<EditText>(R.id.et_pass2).text.toString()
    btn = findViewById(R.id.btn_create)

    //Dialog
    val dialog = Dialog(this)
    dialog.setContentView(R.layout.custom_dialog)

    btn.setOnClickListener {
        dialog.show()

        if (isValid(etEmail, etPass, etPass2)){
            Toast.makeText(this,"Done", Toast.LENGTH_SHORT).show()
        }
        dialog.dismiss()
    }

}
private fun isValid(email: String?, pass: String?, pass2: String?): Boolean{
    return if (email.isNullOrEmpty() && pass.isNullOrEmpty()){
        Toast.makeText(this, "Fill in the blanks", Toast.LENGTH_SHORT).show()
        false
    }else if (pass != pass2){
        Toast.makeText(this, "Password do not match", Toast.LENGTH_SHORT).show()
        false
    }else{
        true
    }
}

I am trying to check if the user has entered his email and password. But when I test the app it brings up this toast ' Fill in the blanks ' in the private is valid function yet I have entered an email and password.

A: Your error is in this part:
etEmail = findViewById<EditText>(R.id.et_email).text.toString().trim()
etPass = findViewById<EditText>(R.id.pass).text.toString()
etPass2 = findViewById<EditText>(R.id.et_pass2).text.toString()

You retrieve String values before any changes were made by user.
You should get them only after user finished typing and clicked the button, so like this:
btn.setOnClickListener {
    dialog.show()

    val etEmail = findViewById<EditText>(R.id.et_email).text.toString().trim()
    val etPass = findViewById<EditText>(R.id.pass).text.toString()
    val etPass2 = findViewById<EditText>(R.id.et_pass2).text.toString()

    if (isValid(etEmail, etPass, etPass2)){
        Toast.makeText(this,"Done", Toast.LENGTH_SHORT).show()
    }
    dialog.dismiss()
}

This way you can remove this part completely:
private var etEmail: String? = null
private var etPass: String? = null
private var etPass2: String? = null

When you have private var fields in your view class, it's usually a code smell. Of course sometimes you have to do that for very specific functionality, but you should avoid it as much as possible.

A: Here's another way you could do this:
private val etEmail get() = findViewById<EditText>(R.id.et_email).text.toString().trim()
private val etPass get() = findViewById<EditText>(R.id.pass).text.toString()
private val etPass2 get() = findViewById<EditText>(R.id.et_pass2).text.toString()

So they still behave like properties and you don't have to change your click listener code, but every time you read them they look up the current contents of each EditText. They're basically lookup functions.
Because they call findViewById you have to make sure you only access them after the Activity has its view set up (e.g. through setContentView) - but since you're only reading those properties through button clicks, which definitely can only happen after that, you're good. It's similar to lateinit - you just have to be mindful of when the property is read, and make sure that it will be safe to do so at that point

A: Since you need to cast EditText to toString (So it will never be null)
For myself I don't see the point to use .isNullOrEmpty()
instead I will use isEmpty() so the value you pass can't not be null
to make it less confusion.
Please consider Using ViewBinding It would make your code more clean and more easy to manage and it's guarantee that you will get right view from your xml file. and it will never be null.
In your case I would do something like this
class SignUp : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var binding: ActivitySignUpBinding
private fun String.isEmailValid() : Boolean = android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivitySignUpBinding.inflate(layoutInflater)
    setContentView(binding.root)
    // Initialising
    auth = Firebase.auth
    //Dialog
    val dialog = Dialog(this)
    dialog.setContentView(R.layout.custom_dialog)

    binding.btn_create.setOnClickListener {
        dialog.show()
        val emailText = binding.et_email.text.toString()
        val passwordText = binding.pass.text.toString()
        val confirmPasswordText = binding.et_pass2.text.toString()
        val result = isValid(emailText,passwordText,confirmPasswordText)
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show()
        if(result == "Done")//todo{}
        dialog.dismiss()
    }

}

private fun isValid(email: String, password: String, confirmPassword: String): String {
    if (email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) return "Fill in the blanks"
    if (password != confirmPassword) return "Password do not match"
    if (email.isEmailValid()) return "Done"

    return "Invalid Email"
}

}

For your problem like everybody said. because you init EditText value to
variable before you click button. that's why value always be "" or empty strings. because of it is default value of EditText.text.toString().


text:
Q: PHP function to list folders and file, but detect when is a folder or file How would I edit the following function below...
To allow for the files only to be linked and the folders to be with h1 tags?
For example what I want as the out put is

folder name

File.txt
File.txt
File.txt

folder name

File.txt
File.txt
File.txt

Here is the PHP function from another Stackoverflow answer I found that needs editing.
function listFolderFiles($dir){
    $ffs = scandir($dir);
    echo '
';
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            echo '
'.$ff;
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '
';
        }
    }
    echo '
';
}

I am unsure how to 'detect' that the $ff variable is a folder or file?

A: This should work for you! Directorys are in h1 and files in a tags:
(I'm checking with the functionis_dir if it's a directory an if it is i'm outputing the name in h1 and otherwise in a tags)
<?php
    function listFolderFiles($dir){
        $ffs = scandir($dir);
        echo '
';
            foreach($ffs as $ff){
                if($ff != '.' && $ff != '..'){
                    echo '
';

                        if(is_dir($dir.'/'.$ff))
                            echo "
" . $ff . "
";
                        else
                            echo "" . $ff . "
";

                        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
                    echo '
';
                }
            }
        echo '
';
    }

?>

If you don't want it in a list use this:
<?php
    function listFolderFiles($dir){
        $ffs = scandir($dir);
            foreach($ffs as $ff){
                if($ff != '.' && $ff != '..'){

                        if(is_dir($dir.'/'.$ff))
                            echo "
" . $ff . "
";
                        else
                            echo "" . $ff . "
";

                        if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
                }
            }

    }

?>

A: Using Spl
 $dir = new FilesystemIterator( __DIR__, FilesystemIterator::SKIP_DOTS );
 foreach ($dir as $fileinfo) {
    if( !$fileinfo->isDir()){
        echo ''.$fileinfo->getFilename().'';
    }else{
        echo '
'.$fileinfo->getFilename().'
';
    }
 }

Haven't tested it.  But it should do the trick, this is the OOP way to do it.  The benefit is you can bypass all the checks for dots and if you like the "/" instead of the "\" on Windows there's a flag for that.
FilesystemIterator::UNIX_PATHS

Flags are bitwise so to use more then one you do like this.
$dir = new FilesystemIterator( __DIR__, FilesystemIterator::SKIP_DOTS |  FilesystemIterator::UNIX_PATHS );

A: In this portion, you need to modify:
// If $ff is a directory
if(is_dir($dir.'/'.$ff)) {
        // This is where you echo the folder name
        echo '
'.$ff.'
';
        // This will list what's in the directory
        listFolderFiles($dir.'/'.$ff);
    }

A: $dir = scandir('your path');
    foreach($dir as $d) {
        if(is_file($d)) {
            echo $d . ' is file
';
        } else if(is_dir($d)) {
            echo $d . ' is directory
';
        }
    }

just see php manual.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I parse the variable number of arguments to a function? I want to pass a variable number of arguments to a function,  the first argument represents a command, and the remaining arguments represent the arguments to the command. For example:
def do(*argv):
    command = argv[0]

    match command:
        case "doNothing":
            print("do nothing")
        case "create":
            arg = argv[1]
            print(arg)
        case "add":
            arg1 = argv[1]
            arg2 = argv[2]
            print(arg1 + arg2)
        case default:
            return "something wrong with the input to do()"

do("create", [1,2])

and run it
$ python ./my.py
  File "/home/t/my.py", line 8
    match command:
          ^
SyntaxError: invalid syntax

How can I parse the variable number of arguments?

A: for Python >= 3.10:
there is match - case support. see example in documentation
msg = 2
match msg:
    case 0:
        print('no')
    case 1:
        print('no')
    case 2:
        print('yes')

#output:==> "yes"

for Python < 3.10:
it does NOT support "swich - case" like Javascript
match ____:
    case ___:
      ....

instead, use if - elif - else
try this:
def do(*argv):
    command = argv[0]
    if command == "doNothing":
        print("do nothing")
    elif command == "create":
        arg = argv[1]
        print(arg)
    elif command == "add":
        arg1 = argv[1]
        arg2 = argv[2]
        print(arg1 + arg2)
    else:
        return "something wrong with the input to do()"

do("create", [1,2])
# argv is ["create", [1,2]]
# so,
#       arg = argv[1]
#        print(arg)
#
# will print [1, 2]


text:
Q: Is there any way I can completely hide docks while working on a maximized window I use docky and GLX cairo dock, I really love dock but one thing that really keeps me from using dock is the fact that none of these give you the option to completely hide them while you an option to hide them completely while you are working on a maximized window, so it gets annoying when you want to click somwhere and your mouse hovers over the dock area and dock pops up.
Is there any way I can completely hide these docks while working on a maximized window.I remember rocket dock on windows can do this by default.
And what about the dock in Mac, is it the same?

A: If you mean fullscreen windows (like media players, games, etc.) then I'm afraid there is no way for it to work like in Windows. From what I have read there is no way to programatically check if a fullscreen app is running or not. (Thus it's also impossible to have your IM status go to occupied when you start a fullscreen application)
The only solution there would be to have your dock always stay in background. But then you may need to move a window away from its place to see the dock.
Another idea is to start fullscreen apps like games in another X-Display. That way your dock or libnotify messages won't pop up and get in your way.
Additionally you could pause your game and switch back to your dektop to chat or whatever...this can be tricky usually because most games forbid to just Alt+Tab out of it.
You can do that by going to another terminal i.e. Ctrl+Alt+F2 for the second.
And then login and type xinit -- myapp :1 where "myapp" should be replaced by the program you'd like to start. The program starts now in another x instance on display 1 (displays start at :0). The instance will be killed automatically when your program terminates. To get back to your Desktop press Ctrl+Alt+F7

A: *

*Open Docky Configuration Window. (right click on Docky on Docky menu bar. click on settings)

*Chose "Window Dodge" in combo box in "Hiding" option.

A: It's not in the Docky settings, but can be done vie the gconf registry. Start "gconf-editor", go to "apps/docky-2/Docky/items/DockyItem" and uncheck "ShowDockyItem". Then restart Docky.
(Credits for this go to : https://www.reddit.com/r/linux4noobs/comments/18udfw/how_do_you_hideremove_the_docky_icon_from_a_docky)


text:
Q: Show that $ Ax^2 + x + 1 = 0 $ has roots greater than $1$ given $-1Not sure how to answer this question, i tried putting the numbers in the quadratic formula and got $x = 2-2\sqrt{A}/2a$? Any help would be much appreciated.

A: The problem was changed!
The original problem was:

Show that $Ax^2 + x + 1 = 0$ has roots greater than 1 given $-1<A<0$

One of roots it's
$$\frac{-1-\sqrt{1-4a}}{2a}.$$ We'll prove that
$$\frac{-1-\sqrt{1-4a}}{2a}>1$$ or
$$-1-\sqrt{1-4a}<2a$$ or
$$-\sqrt{1-4a}<2a+1,$$
which is obvious for $1+2a>0,$ but for $1+2a\leq0$ we need to prove that
$$1-4a>(2a+1)^2$$ or
$$a(a+2)<0,$$ which is obvious.
The second problem:

Show that $-Ax^2 - x + 1 = 0$ has roots greater than 1 given $-1<A<0$

It's wrong, of course. Try $A=-\frac{1}{2}.$

A: The posted question was revised a few times.

First assume the equation (as it was given initially, before the edits) is
$$ax^2+x+1=0$$
with $-1 < a < 0$, and that the goal is to prove that the equation has a root greater than $1$.

Since the discriminant is
$$D=(1)^2-4(a)(1)=1-4a$$
and $a < 0$, it follows that $D > 0$, hence the equation has two distinct real roots.

Let $u,v$ be the roots.

By Vieta's formulas,

*

*$u+v=-{\large{\frac{1}{a}}}$.$\\[4pt]$

*$uv={\large{\frac{1}{a}}}$.

From $a < 0$, we get ${\large{\frac{1}{a}}} < 0$.

Thus $uv < 0$, hence one of $u,v$ is positive, and the other is negative.

From $-1 < a < 0$, we get $-{\large{\frac{1}{a}}} > 1$.

Thus, $u+v > 1$, hence, since one of $u,v$ is negative, the other one must be greater than $1$.

That resolves the original version of the problem.

Next assume the equation is
$$-ax^2-x+1=0$$
but to make it work out (and to show a few more ideas), assume the restriction on $a$ is $-{\large{\frac{1}{4}}} < a < 0$.

For this version of the problem, the goal is to show that both roots are greater than $1$.

Some of the reasoning is the same as in the previous version . . .

Since the discriminant is
$$D=(1)^2-4(-a)(1)=1+4a$$
and $a > -{\large{\frac{1}{4}}}$, it follows that $D > 0$, hence the equation has two distinct real roots.

Let $u,v$ be the roots.

By Vieta's formulas,

*

*$u+v=-{\large{\frac{1}{a}}}$.$\\[4pt]$

*$uv=-{\large{\frac{1}{a}}}$.

From $a < 0$, we get $-{\large{\frac{1}{a}}}> 0$, so $u+v > 0$, and $uv > 0$.

Since $u+v > 0$, at least one of $u,v$ must be positive,

Since $uv > 0$, and at least one of $u,v$ is positive, they must both be positive.

Without loss of generality, assume $0 < u \le v$.

From $-{\large{\frac{1}{4}}} < a < 0$, we get $-{\large{\frac{1}{a}}} > 4$, so $uv > 4$, hence we must have $v > 2$.

Noting that $u+v=uv$, we get $u={\large{\frac{v}{v-1}}}$, which is greater than $1$,
since $v > v-1 > 0$.

Thus, both roots are greater than $1$, as was to be shown.

A: the assertion is equivalent to the statement that: $1 \lt  b$ is a sufficient condition that for the line $y = b(1+x)$ to meet the parabola $y = x^2$ at a point to the right of the line $x =1$
In fact, since for all values of $b$ the line passes through $(-1,0)$, the geometric condition requires the line to have a slope greater that $\frac12$, so that it lies above the line joining $(-1,0)$ to $(1,1)$


text:
Q: End interval when route changes in Angular 2 I start a timer in an Angular 2 component which is inside a router outlet.
setInterval(() => {
    ...
}, 10000);

When I leave the route in which the component is embedded the timer isn't quit. How can I achieve that?

A: This should do it:
routerOnActivate() {
  this.timer = setInterval(()=>{
                ...
            }, 10000);
}

routerOnDeactivate() {
  clearInterval(this.timer);
}

A: Maybe for what you want is better OnDeactivate from angular2/router (and maybe also OnActivate depending on your usecase) because you said you want to end the timer when the user leaves the route If I understand it correctly.
export Compnent implements OnInit, OnDeactivate {
    private timer;

    ngOnInit(){
        this.timer = setInterval(_ => {
            // disco
        }, 10000);
    }

    routerOnDeactivate() {
        clearInterval(this.timer);
    }
}

A: You could clear the interval from this hook.
Mine is controlled from the component/view.
export classTestInterval implements OnInit, OnDestroy{
     public timerInterval:any;
     ngOnInit(){
       // Need interval scope in the component could be from somewhere else, but we need scope to be able to clear it on destruction of component.
       this.timerInterval = setInterval(function(){...},10000);
     }
     ngOnDestroy() {
        // Will clear when component is destroyed e.g. route is navigated away from.
        clearInterval(this.timerInterval);
     }
}


text:
Q: How to convert attr to executable code? (Javascript) <input type="text" name="borderColor" id="myInput">

var myInput = document.getElementById("myInput");

document.getElementById('selector').style.myInput.name= "(style value)";
// want to use the .name attr after style here

Checked something about eval(), but seems not the right thing. Please help. Thanks a lot!


text:
Q: What does 05 9,14 * * 1-5 mean in airflow? I am new to Airflow and was just wondering if anyone could help me decode this schedule_interval timing.
dag = DAG('mya-dag', default_args=default_args, schedule_interval='05 9,14 * * 1-5')

Does this mean my dag runs twice a day, every day, Monday-Friday, at 9:05 and 4:00PM?

A: This is a cron expression which says "At 09:05 AM and 02:05 PM, Monday through Friday"
You can use a cron interpreter in the future for something like this (such as https://bradymholt.github.io/cron-expression-descriptor/)
I hope that helps!


text:
Q: R: Rolling calculation of column values (avoid loop) I want to incrementally grow a new column, based on values of the previous row & same column. You could do it with a loop, like so:
df <- data.frame(a = 2000:2010,
                 b = 10:20,
                 c = seq(1000, 11000, 1000),
                 x = 1000)
for(i in 2:nrow(df)) df$x[i] <- (df$c[i]) * df$a[i-1] / df$x[i-1] + df$b[i] * df$a[i]
df
      a  b     c        x
1  2000 10  1000  1000.00
2  2001 11  2000 26011.00
3  2002 12  3000 24254.79
4  2003 13  4000 26369.16
5  2004 14  5000 28435.80
6  2005 15  6000 30497.85
7  2006 16  7000 32556.20
8  2007 17  8000 34611.93
9  2008 18  9000 36665.87
10 2009 19 10000 38718.65
11 2010 20 11000 40770.76

(As you see, new values in column x use values of column x of the previous row.)
However, as I do this for a Shiny app, I need to have fast calculation, thus using loops is not optimal. Is there a way of doing this which avoids loops, ideally making use of dplyr's piping?
This reply (Referring to previous row in calculation) suggests a way using sapply - however, I am unable to do this mathematically...

A: There are a few options.
Use vectors
During each loop, it's expensive to do df$x because it takes memory to do it. Instead, you can pre-assign vectors and subset the vectors.
#easiest - extract the vectors before the loop
C <- df[['c']] #used big C because c() is a function
a <- df[['a']]
b <- df[['b']]
x <- df[['x']]

for(i in seq_along(x)[-1]) x[i] <- C[i] * a[i-1] / x[i-1L] + b[i] * a[i]

Use a function
Turning your loop into a function will improve performance due to the optimization from compiling.
f_recurse = function(a, b, C, x){
  for (i in seq_along(x)[-1]) x[i] <- C[i] * a[i-1] / x[i-1L] + b[i] * a[i]
  x
}

f_recurse(df$a, df$b, df$c, df$x)

Use Rcpp
Finally, if the response is still too laggy, you can try to use Rcpp. Note, Rcpp updates in place so while I return a vector, there's really no need - the df$x has also been updated.
library(Rcpp)
cppFunction('
NumericVector f_recurse_rcpp(IntegerVector a, IntegerVector b, NumericVector C, NumericVector x){
for (int i = 1; i < x.size(); ++i){
 x[i] = C[i] * a[i-1] / x[i - 1] + b[i] * a[i];
}
return(x);
}
')

f_recurse_rcpp(df$a, df$b, df$c, df$x)

Performance
In all, we get close to a 1,000 times performance increase. The table below is from bench::mark which also checks for equality.
# A tibble: 4 x 13
  expression                                 min  median `itr/sec` mem_alloc
  <bch:expr>                             <bch:t> <bch:t>     <dbl> <bch:byt>
1 OP                                      8.27ms   8.8ms      106.   62.04KB
2 extract                                 6.21ms  7.49ms      126.   46.16KB
3 f_recurse(df$a, df$b, df$c, df$x)       13.1us  28.8us    33295.        0B
4 f_recurse_rcpp(df$a, df$b, df$c, df$x)   8.6us    10us    98240.    2.49KB

And here's an example with a 1,000 row data.frame and then 10,000 row
df <- data.frame(a = sample(1000L),
                 b = sample(1001:2000),
                 c = seq(1000, 11000, length.out = 1000),
                 x = rep(3, 1000L))

# A tibble: 4 x 13
  expression                                 min   median `itr/sec` mem_alloc
  <bch:expr>                             <bch:t> <bch:tm>     <dbl> <bch:byt>
1 OP                                      23.9ms  24.38ms      39.4    7.73MB
2 extract                                  6.5ms   7.71ms     123.    69.84KB
3 f_recurse(df$a, df$b, df$c, df$x)      265.7us  271.9us    3596.    23.68KB
4 f_recurse_rcpp(df$a, df$b, df$c, df$x)  17.4us   18.9us   51845.     2.49KB

df <- data.frame(a = sample(10000L),
                 b = sample(10001:20000),
                 c = seq(1000, 11000, length.out = 10000),
                 x = rep(3, 10000L))

# A tibble: 4 x 13
  expression                                  min   median `itr/sec` mem_alloc
  <bch:expr>                             <bch:tm> <bch:tm>     <dbl> <bch:byt>
1 OP                                     353.17ms 412.62ms      2.42  763.38MB
2 extract                                  8.75ms   8.95ms    107.    280.77KB
3 f_recurse(df$a, df$b, df$c, df$x)        2.58ms   2.61ms    376.    234.62KB
4 f_recurse_rcpp(df$a, df$b, df$c, df$x)   98.6us  112.7us   8169.      2.49KB


text:
Q: setState not updating font awesome icon I'm trying to dynamically render font awesome icon in myself written checkbox component. When I'm trying to update state of a  with font awesome icon after clicking on it it is not updating. I've tried to move render to separate function and tried to use react-fontawesome but nothing helps. The state is updating but font awesome icons are the same svg code in html.
...
state = {
 checked: this.props.checked
}

toggleCheck = () => {
  this.setState({ checked: !this.state.checked });
};

render () {

  const iconUnchecked = 'far fa-square';
  const iconChecked = 'fas fa-check-square';
  const iconClass = this.state.checked ? iconChecked : iconUnchecked;

  return (

  );
}

A: As I understood the font awesome js manipulates DOM and React manipulates virtual DOM. When font awesome js doing its own stuff React can't rerender it after state change. Im still on React 15 and maybe it's not the issue in React 16. I just found a solution for me to put every   with font awesome in a div with unique key. This way React see that div must change because key was changed.

A: Try that one https://jsfiddle.net/n5u2wwjg/30533/
For me seems to work
Check exactly jsfiddle it works, but not a snippet. Snippet is just to satisfy editor.

class TodoApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: this.props.checked
    }
    this.toggleCheck = this.toggleCheck.bind(this);
  }

  toggleCheck() {
    this.setState({ checked: !this.state.checked });
  }

  render() {
    const iconUnchecked = 'far fa-square';
   const iconChecked = 'fas fa-check-square';
   let iconClass = this.state.checked ? iconChecked : iconUnchecked;

    return (

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

.done {
  color: rgba(0, 0, 0, 0.3);
  text-decoration: line-through;
}

input {
  margin-right: 5px;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" integrity="sha384-+d0P83n9kaQMCwj8F4RJB66tzIwOKmrdb46+porD/OvrJ+37WqIM7UoBtwHO6Nlg" crossorigin="anonymous">

A: I too faced the same trouble. As 200Ok mentioned it correctly, svg--inline-fa is not a virtual DOM so it never gets updated. The best way to solve the problem is to wrap the font awesome elements that would contain the decisive classes.


text:
Q: Python Write a JSON temporary file from a dictionary I'm working on a python(3.6) project in which I need to write a JSON file from a Python dictionary.
Here's my dictionary:
{'deployment_name': 'sec_deployment', 'credentials': {'type': 'type1', 'project_id': 'id_001',}, 'project_name': 'Brain', 'project_id': 'brain-183103', 'cluster_name': 'numpy', 'zone_region': 'europe-west1-d', 'services': 'Single', 'configuration': '', 'routing': ''}

And I need to write credentials key to a JSON file.
Here's how I have tried:
tempdir = tempfile.mkdtemp()
saved_umask = os.umask(0o077)
path = os.path.join(tempdir)
cred_data = data['credentials']
with open(path + '/cred.json', 'a') as cred:
    cred.write(cred_data)
credentials = prepare_credentials(path + '/cred.json')
print(credentials)
os.umask(saved_umask)
shutil.rmtree(tempdir)

It's not writing a JSON formatted file, then generated file is as:
{
  'type': 'type1',
  'project_id': 'id_001',
}

it comes with single quotes instead of double quotes.

A: Use the json module
Ex:
import json
with open(path + '/cred.json', 'a') as cred:
    json.dump(cred_data, cred)

A: Actually this should be with the more Python 3 native method.
import json,tempfile
config = {"A":[1,2], "B":"Super"}
tfile = tempfile.NamedTemporaryFile(mode="w+")
json.dump(config, tfile)
tfile.flush()
print(tfile.name)

To break this down:

*

*We load tempfile, and ensure that there's a name with NamedTemporaryFile

*We dump the dictionary as a json file

*We ensure it has been written to via flush()

*Finally we can grab the name to check it out

Note that we can keep the file for longer with delete=False when calling the NamedTemporaryFile


text:
Q: delete method in marketo always return invalid content type I have this code for deleting leads in marketo but I always get an error saying that I had invalid content type I used the same method using the post and get and it works but in delete it keeps returning the error:
def client = new RESTClient('https://XXX-XXX-XXX.mktorest.com')
client.headers['Authorization'] = 'Bearer '+"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx:xx"
def response = client.delete(path:'/rest/v1/leads.json',
        contentType : 'application/json' )
println response.data

response:
[errors:[[code:612, message:Invalid Content Type]], requestId:36df#14c6da14e9e, success:false]

A: It looks like you're not sending any payload. Has the payload been omitted from the excerpt?
The particular API is documented here. Have a close look at the payload structure as it is a required property (the list of lead IDs to be deleted).

A: For anyone out there who needs to know what the payload to delete leads on the Marketo REST API should look like, here is a sample.
You can delete multiple leads by adding more objects with the "id" property to the "input" array.
{
  "input": [
    {
      "id": 123456789
    },
    {
      "id": 123456790
    }
  ]
}


text:
Q: passing own data to trading view I was working with trading view(https://www.tradingview.com/chart/?symbol=NASDAQ:AAPL&source=unauth_header&feature=launch_chart) charting library, It shows the data for the currency pair as intended.
I have looked into the following guideline
tradingview charting library
Now what I am looking for is to plot the chart with my own data. Is there any widget or any way I can provide my own data to tradingview and it will create the candlestick chart with the data provided.

A: yes you can feed your data with custom DataFeed.
you should set datafeed property of your widgetOptions like this
let options={
... other options
datafeed:new UDFCompatibleDatafeed('url api url'),
... other options
}
_chart = new widget(this.options);


text:
Q: What is the "*debug* buffer" in Kakoune? I'm just starting with the Kakoune editor and somehow I was shown the message error during startup, see *debug* buffer for details when I loaded a file with kak.
I don't know if I'm too stupid to ask this, but I don't know how do I "see debug buffer". The :debug option seems to be there to write something to the debug buffer, not read it.

A: It turns out that there's a buffer called "debug", to visit it you must
:buffer *debug*

Thanks to @danr on #kakoune @ freenode IRC.


text:
Q: No CSV File is created after Process Execution I am not new to Powershell, but I am new to making scripts in Powershell myself.
I had to make a simple script which takes all of our employees at work and a bit of info about them, and then output a CSV file with this information. But when I run the code below, nothing happens. The ISE simply executes the process, a second passes and it's done. Then no CSV file is created.
PROCESS {
    $path = Split-Path -parent "C:\Users\omitted\Desktop"
    $pathexist = Test-Path -Path $path
    If($pathexist -eq $false) {
        New-IOItem -type directory -Path $path
    }
    $csvreportfile = $path + "\ALLADUsers_.csv"

    #import the AD Module
    Import-Module ActiveDirectory

    Get-ADUser -SearchBase "OU=Medarbejdere,OU=Users,OU=omitted,DC=omitted,DC=local" -Properties MemberOf -Filter * |
        Select-Object @{ Label = "First Name";   Expression = { $_.GivenName } },
                      @{ Label = "Last Name";    Expression = { $_.Surname } },
                      @{ Label = "Display Name"; Expression = { $_.DisplayName } },
                      @{ Label = "Logon Name";   Expression = { $_.SamAccountName } },
                      @{ Label = "Job Title";    Expression = { $_.Title } },
                      @{ Label = "Description";  Expression = { $_.Description } },
                      @{ Label = "Department";   Expression = { $_.Department } } |

        #Export CSV Report
        Export-Csv -Path $csvreportfile -NoTypeInformation
}

What did I do wrong?

A: Try this:
#moved the Parent parameter to the end to more clearly distinguish Path's value from Parent (switch).
$path = Split-Path -Path "C:\Users\omitted\Desktop" -Parent

#Since we don't refer to $PathExist again, skipped the assignment and put the test directly in the condition
If(Test-Path -Path $path) {
    #Corrected Type; was `New-IOItem`
    New-Item -type directory -Path $path
}

#use Join-Path when joining paths, to avoid issues with too many/too few slashes
$csvreportfile = Join-Path $path "ALLADUsers_.csv"

#import the AD Module
Import-Module ActiveDirectory

#Added other properties which wouldn't be returned by default (see https://social.technet.microsoft.com/wiki/contents/articles/12037.active-directory-get-aduser-default-and-extended-properties.aspx for a list of all properties / those in Cyan are the only ones which don't need to be listed on the Properties parameter)
Get-ADUser -SearchBase "OU=Medarbejdere,OU=Users,OU=omitted,DC=omitted,DC=local" -Properties MemberOf, Title, Description, Department -Filter * |
    Select-Object @{ Label = "First Name";   Expression = { $_.GivenName } },
                  @{ Label = "Last Name";    Expression = { $_.Surname } },
                  @{ Label = "Display Name"; Expression = { $_.DisplayName } },
                  @{ Label = "Logon Name";   Expression = { $_.SamAccountName } },
                  @{ Label = "Job Title";    Expression = { $_.Title } },
                  @{ Label = "Description";  Expression = { $_.Description } },
                  @{ Label = "Department";   Expression = { $_.Department } } `
| Export-Csv -Path $csvreportfile -NoTypeInformation #moved this so that the pipeline feeds into export-csv; the whitespace had made this statement invalid previously

I've added comments inline explaining the changes I've made.
Regarding the PROCESS section, that's not needed if you're running this directly in the script's body.  I'd normally include this if I were defining a function/cmdlet (see https://ss64.com/ps/syntax-function-input.html).


text:
Q: phonegap: some click events don't work (though work in safari) I'm testing web app using PhoneGap Develper Application (actually the same result with deployed app on iOs simulator):
Some elements in the app are not clickable (click event doesn't fire). Though it all works in mobile safari on THE SAME device. It is strange to me because web view in PG uses the same engine to render the app.
Any thoughts what can be the reason for this? This happens o iOs7 (it seems that it was working on iOs5), tested Android version is ok too.

A: On backend Phonegap actually uses the instance of native browser . It is not actually any app it is instance of native (Safari ) browser. so all the actions will work fine in safari. Same is with android . In that it has chrome as it's native browser.

A: It was my mistake, I didn't included Fastclick library. It all works with Fastclick.


text:
Q: How to list folder contents in Qml? I'm trying to rewrite a part of the notes-app in order to store notes directly in the file system.
But I'd like to be able to list files in a folder, not in order to display them, but to process them in a javascript function.

A: Here's a quick example of how to display the contents of a folder using a FolderListModel:
import QtQuick 2.0
import Qt.labs.folderlistmodel 1.0
import Ubuntu.Components 0.1
import Ubuntu.Components.ListItems 0.1 as ListItem

MainView {
    id: root
    width: units.gu(50)
    height: units.gu(75)

    Page {
        id: home
        visible: true
        title: "Files"

        FolderListModel {
            id: folderModel
            folder: "/"
            nameFilters: [ "*" ]
        }

        ListView {
            anchors.fill: parent
            model: folderModel
            delegate: ListItem.Standard {
                text: model.fileName
            }
        }
    }
}

It looks like:

Now of course, you want to do something with this information. Unfortunately, you can't iterate over the model as simply as you'd like to as explained in this post on the Beru developer's blog. He helpfully shows how to use the Repeater component:
    Repeater {
        model: folderModel

        Component {
            Item {
                Component.onCompleted: {
                    // Do something interesting here...
                    console.log(fileName)
                }
            }
        }
    }


text:
Q: passing values from pipeline to shell script I have a pipeline where i have TARGETENVIRONMENT as QA and PROD.In the first step I am converting TARGETENVIRONMENT and storing that value in variable Ajob and Bjob.These values Ajob and Bjob are job names where i need to get the build number for processing further.
def Ajob = "ProjectBuild_ABD_${TARGET_PLATFORM.toUpperCase()}_fe"
def Bjob = "ProjectBuild_ABD_${TARGET_PLATFORM.toUpperCase()}_be"

In the next step I am storing the build numbers of these jobs.When i
def fe = sh returnStdout: true, script: '/usr/sfw/bin/wget -qO- http://fiesccet01.emea.nsn-net.net:9095/job/${Ajob}/lastBuild/buildNumber'
def be = sh returnStdout: true, script: '/usr/sfw/bin/wget -qO- http://fiesccet01.emea.nsn-net.net:9095/job/${Bjob}/lastBuild/buildNumber'

The script is not taking these values ${Ajob} and ${Bjob}.How to pass these variables in the script.

A: Can you try this:
def fe = sh returnStdout: true, script: "/usr/sfw/bin/wget -qO- http://fiesccet01.emea.nsn-net.net:9095/job/${Ajob}/lastBuild/buildNumber"
def be = sh returnStdout: true, script: "/usr/sfw/bin/wget -qO- http://fiesccet01.emea.nsn-net.net:9095/job/${Bjob}/lastBuild/buildNumber"

The difference is that the strings are using double quotes, which apply string interpolation, i.e. replace variables, in contrast to single quotes, which don't.


text:
Q: How to copy redshift cluster parameter group workload management settings from existing one? Is there a way to copy Redshift workload management settings from existing one?
I have a complex WLM configuration in my redshift parameter group, which I want to copy to another configuration. Doing it manually is error prone. Is there a way to copy it automatically?
Here is my WLM config JSON, which I copied from Redshift console's WLM config page:
[
  {
    "query_group": [
      "defaulton",
      "lab4on"
    ],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "concurrency_scaling": "off",
    "priority": "normal",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "query_group": [
      "lab1",
      "lab2",
      "lab3normal",
      "lab4off",
      "lab5",
      "lab6reads",
      "defaultoff"
    ],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "concurrency_scaling": "off",
    "priority": "normal",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "query_group": [
      "lab3highest"
    ],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "concurrency_scaling": "off",
    "priority": "highest",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "query_group": [
      "lab3lowest"
    ],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "concurrency_scaling": "off",
    "priority": "lowest",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "query_group": [
      "lab6writes"
    ],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "concurrency_scaling": "off",
    "priority": "highest",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "query_group": [],
    "query_group_wild_card": 0,
    "user_group": [],
    "user_group_wild_card": 0,
    "priority": "normal",
    "queue_type": "auto",
    "auto_wlm": true
  },
  {
    "short_query_queue": false
  }
]

I could copy it to a new parameter group following below steps, but would like to simplify it if possible.

*

*copy the json from existing param group as above to a nodepad editor

*remove all nextline and space characters from this json

*replace all doublequotes(") with backslash doublequotes (\")

*create below json file in my local e.g. modify_pg.json
[
    {
        "ParameterName": "wlm_json_configuration",
        "ParameterValue": "<input_formatted_json_here>"
    }
]

*replace <input_formatted_json_here> above with the formatted text in my editor (created in step# 3 above)

*create a new parameter group in Redshift, e.g. myclusterparametergroup

*run below CLI command to modify WLM of this parameter group with the json file

aws redshift modify-cluster-parameter-group --parameter-group-name myclusterparametergroup --parameters file://modify_pg.json

Below is my final modify_pg.json file, which I am able to use in my new parameter group. But is there a way to simplify this?
[
    {
        "ParameterName": "wlm_json_configuration",
        "ParameterValue": "[{\"query_group\":[\"defaulton\",\"lab4on\"],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"concurrency_scaling\":\"off\",\"priority\":\"normal\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"query_group\":[\"lab1\",\"lab2\",\"lab3normal\",\"lab4off\",\"lab5\",\"lab6reads\",\"defaultoff\"],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"concurrency_scaling\":\"off\",\"priority\":\"normal\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"query_group\":[\"lab3highest\"],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"concurrency_scaling\":\"off\",\"priority\":\"highest\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"query_group\":[\"lab3lowest\"],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"concurrency_scaling\":\"off\",\"priority\":\"lowest\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"query_group\":[\"lab6writes\"],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"concurrency_scaling\":\"off\",\"priority\":\"highest\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"query_group\":[],\"query_group_wild_card\":0,\"user_group\":[],\"user_group_wild_card\":0,\"priority\":\"normal\",\"queue_type\":\"auto\",\"auto_wlm\":true},{\"short_query_queue\":false}]"
    }
]

A: I've done this several times for clients and you are nearly there.  The same way you are modifying the PG using the AWS CLI, you can extract the JSON from the existing PG using the AWS CLI.
aws redshift describe-cluster-parameters ...

You will get back a JSON that has the parameter value for a specified PG.  It is then just a matter of modifying the returned values to the string format you need.  This requires some programming or scripting - I'll go with Linux scripting as this is a popular option.  Command line tools you will likely want:

*

*sed

*tr

*jq (tag line for this tool is "sed for json")

The process you will follow will be something like

*

*extract parameters using aws cli

*create shell variable with the parameters you want and the values
you want each to have. jq is great for this

*create the new PG if needed

*modify the JSON shell variable to remove \n and spaces -
replacement_text=$(echo $wlm_configuration | sed -e 's/"/\\"/g' |
tr -d '\n ') create top JSON for PG as a shell variable (same as
your modify_pg.json)

*run aws cli to modify the new PG - combine these 2 JSONs right on
the command line by using option: --parameters $(echo $modify_pg |
tr -d '\n ' | sed -e "s/<<WLM_CONFIGURATION>>/$replacement_text/g")

Now you can do this in python using boto3 or in java or ... This is just one path.


text:
Q: How to linearize this difficult constraint with binary variables? I would like to linearize the constraint $y_i \cdot q_i \leq y_i \cdot a$ where $a$ is constant, $y_i$ is a binary variable and $q_i$ is a continuous non negative variable.
Thanks !

A: Effectively $y_i$ implies $q_i \leq a$, which is $q_i \leq a \cdot y_i + M(1-y_i)$ where $M$ is your favorite sufficiently-large small-M constant (i.e, what normally but dangerously is called a big-M constant).


text:
Q: HLSL: Returning an array of float4? I have the following function in HLSL:
float4[] GetAllTiles(float type) {
    float4 tiles[128];
    int i=0;

    [unroll(32768)] for(int x=0;x<MapWidth;x++) {
        [unroll(32768)] for(int y=0;y<MapHeight;y++) {

            float2 coordinate = float2(x,y);
            float4 entry = tex2D(MapLayoutSampler, coordinate);
            float entryType=GetTileType(entry);
            if(entryType == type) {
                tiles[i++]=entry;
            }

        }
    }

    return tiles;
}

However, it says that it can't define a return type of float4[]. How do I do this?

A: In short:
You can't return an array of floats defined in the function in HLSL.
HLSL code (on the GPU) is not like C code on the CPU. It is executed concurrently on many GPU cores.
HLSL code gets executed at every vertex (in the vertex shader) or every at pixel (in the pixel shader). So for every vertex you give the GPU, this code will be executed.
This HLSL introduction should give you a sense of how a few lines of HLSL code get executed on every pixel, producing a new image from the input:
http://www.neatware.com/lbstudio/web/hlsl.html
In your example code, you are looping over the entire map, which is probably not what you want to do at all, as the function you posted will be executed at every pixel (or vertex) given in your input.
Transferring your logic from the CPU to the GPU via HLSL code can be very difficult, as GPUs are not currently designed to do general purpose computation. The task you are trying to do must be very parallel, and if you want it to be fast on the GPU, then you need to express the problem in terms of drawing images, and reading from textures.
Read the tutorial I linked to get started with HLSL :)

A: Return a structure with the array in it.   You can send parametres in as a raw array, but it must be in a structure if its the return value. :)
What Olhovsky said is true tho,   if your converting from c to direct c/compute you should have the iterations layed out as separate threads,   But dont forget that a gpu also has a lot of series power as well, and u need to take that into account for your budget for maximum efficiency.  For example, the least amount of threads you need is the amount of cores on your gpu.  For a gtx980, its 2048.


text:
Q: How to pass table name a parameter in Azure data factory I'm a new user in the Azure data factory. I tried to perform copy activity in between Azure database as the source and Azure data warehouse as a target . In that, I am not able to perform an update into target using data factory.  In which Source as Azure SQL server and target as the Azure data warehouse.  And how to update the field in data warehouse table in Azure using ADF when the data warehouse is a sink

A: From your pasted link I assume what expected is incrementally copy data from Azure sql database to Azure data warehouse.
In this case no need to modify the sink database, instead finish the modification before loading into sink table.
I followed the steps in this article, in which the target is: Azure Blob storage, I changed it to: Azure data warehouse. And the test result is successfully implemented data copying from Azure database to Azure data warehouse incrementally.


text:
Q: Multikey maps with lower and upper bound iteration for all keys Let's say I'm using a map that uses three strings as a key.  Here's a quick example struct:
struct ExampleMapKey
{
 std::string key0;
 std::string key1;
 std::string key2;

 bool operator<(const ExampleMapKey& other) const
 {
  if (key0 < other.key0) return true;
  else if (key0 > other.key0) return false;

  if (key1 < other.key1) return true;
  else if (key1 > other.key1) return false;

  return key2 < other.key2;
 }
}

Now, this works fine until I decide I want to use lower_bound and upper_bound.  If I want to find the range of values formed by any key0, any key1 starting with "ab", and any key2 starting with "cd", using those 2 functions with ExampleMapKey("", "ab", "cd") and ExampleMapKey("", "ac", "ce") respectively will have me iterating through keys that don't fulfill my requirements.  Or will I miss keys that do?  Either way, it's wrong.
It seems what I need is a data structure that explicitly indexes by each key, and will also allow me to perform potentially complicated lower_bound and upper_bound iterations.  Is there such a thing?  I'm not necessarily using strings, nor am I limited to only 3 keys, so it needs to be STL-style or similarly generic.

A: *

*Boost Multi-index Containers Library can be of help.
Update: After rereading your question, I think you may have to do what is taught in db classes; you would have to use one of the indices to create a temporary result, and prune that result, based on your second constraint (alternatively, you can run each constraint on each index, joining the results). Boost Multi-index Containers will only allow lookup on one index at a time AFAIK.

*For the particular type of query that you asked, you might be able to come up with a very specialized data structure that can help, by adding indices on partitions of indices. That is for example, you take the 2nd index, split it in half, rewrite a 3rd index for the first half, and for the 2nd half. Then you split each half and repeat. This way, you can select a section of the 2nd index, and then subsequently select a part of the 3rd index that is within (approximately) that part of the 2nd index. But I don't know of any library that does this.

*Another approach might be some sort of multi-dimensional data structure, though I am not familiar with using such a structure with non-numeric keys. For example, imagine your keys were integers, you could use a 3D kd-tree or other spatial index, and query for a cubic range. For example: (using libssrckdtree, seems it might work with strings too):

Codes for (3):
#include <ssrc/spatial/kd_tree.h>

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <cassert>

#include <string>

typedef std::array<std::string, 3> Point;

typedef ssrc::spatial::kd_tree<Point, Point> Tree;

int main()
{
  Tree tree;

  Point point = {{"any1","aa1","cc1"}};
  tree[point] = point;

  point = {{"any2","ab1","cc1"}};
  tree[point] = point;

  point = {{"any3","ab1","cd1"}};
  tree[point] = point;
  point = {{"any4","ab1","cd2"}};
  tree[point] = point;
  point = {{"any5","ab1","cd3"}};
  tree[point] = point;

  point = {{"any22","ac1","cc1"}};
  tree[point] = point;

  point = {{"any33","ac1","cd1"}};
  tree[point] = point;
  point = {{"any44","ac1","cd2"}};
  tree[point] = point;
  point = {{"any55","ac1","cd3"}};
  tree[point] = point;

  point = {{"any6","aa1","cd2"}};
  tree[point] = point;
  point = {{"any7","aa1","cd3"}};
  tree[point] = point;

  Point lower{ { "any0", "ab", "cd" } }, upper{ { "any9", "ac", "cd2" } };

  for(Tree::const_iterator it = tree.begin(lower, upper), end = tree.end();
      it != end; ++it)
  {
    Point point = it->first;
    Point value = it->second;
    std::cout << point[0] << ", " << point[1] << ", " << point[2] << std::endl;
  }

  return 0;
}

Output:
any3, ab1, cd1
any4, ab1, cd2

A: In such std::map there wouldn't be a single range, it would be set of ranges.
Consider such keys (sorted as defined by your comparator object):
#0 {"aa", "aa", "cb" },
#1 {"aa", "ab", "cd" },
#2 {"aa", "abb", "cdd" },
#3 {"ab", "aa", "cb" },
#4 {"ab", "ab", "cd" },
#5 {"ab", "abb", "cdd" },

Ranges matching your constraints are: {1.2} and {4,5}.
With std::map<> you have to find range for every key0, then within given key0 - do lower/upper_bound for key1, Then do the same for key2. But to do so - redefine your map from:
std::map<ExampleKey, T>

to
std::map<std::string, std::map<std::string, std::map<std::string, T> > >:

And to find all matching ranges do:
for (auto it0 = theMap.begin(); it0 != theMap.end(); ++it0)
{
    auto it1lower = it0->second.lower_bound("ab");
    auto it1upper = it0->second.upper_bound("ac");
    for (auto it1 = it1lower; it1 != it1upper; ++it)
    {
       auto it2lower = it1->second.lower_bound("cd");
       auto it2upper = it1->second.upper_bound("ce");
       // and now we have on of matching ranges:
    }
}


text:
Q: ReCaptcha Internal Error Using the captcha I got a response from Google servers, but it's not
working... (it worked for over a month both locally and on my
webservers)
false
'An internal error occurred: 4B5A0C43DD500.AB40323.5957'

How can I solve this? Is something changed on google's side starting from Dec. 30th?


text:
Q: huey django version compatibility I checked huey's documentation and searched online, but couldn't find version compatibility information of huey with django. Can someone please provide me this information?

A: The Huey docs say that it supports officially supported Django versions.
In May 2017, the officially supported Django versions are Django 1.8 LTS, Django 1.10 and Django 1.11.


text:
Q: Sending a file to an API - C# I'm trying to use an API which sends a fax.
I have a PHP example below:
(I will be using C# however)
<?php
//This is example code to send a FAX from the command line using the Simwood API
//It is illustrative only and should not be used without the addition of error checking etc.

$ch = curl_init("http://url-to-api-endpoint");
$fax_variables=array(
'user'=> 'test',
'password'=> 'test',
'sendat' => '2050-01-01 01:00',
'priority'=> 10,
'output'=> 'json',
'to[0]' => '44123456789',
'to[1]' => '44123456780',
'file[0]'=>'@/tmp/myfirstfile.pdf',
'file[1]' => '@/tmp/mysecondfile.pdf'
);
print_r($fax_variables);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fax_variables);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec ($ch);
$info = curl_getinfo($ch);
$result['http_code'];
curl_close ($ch);
print_r($result);

?>

My question is - in the C# world, how would I achieve the same result?
Do i need to build a post request?
Ideally, i was trying to do this using REST - and constructing a URL, and using HttpWebRequest (GET) to call the API

A: Anytime you are sending data you should use a POST.  This is regardless of the technology involved.  All of the standard http methods (POST, GET, PUT, DELETE) are supported by the idea of REST.
See this wiki entry.

UPDATE: For more info
There are lots of different options.  One way, as you described, is to just use the HttpWebRequest object to craft the request and send it.  Here's an example of posting data using that method (link), another is here.
An alternative method is to use WCF.  Microsoft has some documentation on that here.  And O'Reilly has a book on it here.

A: I have been interacting with HTTP/S URLs from C# by invoking the Curl utility with the required command line parameters. See this SO answer for more guidance. Curl is purpose-built for this kind of requirement, is tried and true, and can be used from the command-line and batch files to test URLs and Post fields. Let Curl do what it's best at, and leave your C# code for your business logic.

A: Based on the published specs, the HttpWebRequest object is what you should be using to communicate with the Simwood api using C#.


text:
Q: Swap RootViewController with MVVMCross I need to implement a login/logout using MVVMCross, iOS only to start. After the user logs in, I want to close the view and make the "real" first view the root controller. For logout, I want to do the same in reverse. Whenever the LoginViewModel is requested, clear the root and replace it.
This Remove ViewController from stack indicates there is a ClearTop parameter, but it looks like it is gone in v3?
I then found this What is the best way to handle GoBack for the different MvvmCross (v3) platforms and I implemented this Presenter:
        public override void Close(IMvxViewModel toClose)
        {
            if (toClose is LoginViewModel)
            {
                ClearBackStack();
                Show(new MvxViewModelRequest() { ViewModelType = typeof(FirstViewModel)});
                return;
            }
            base.Close(toClose);
        }

        public override void Show(MvxViewModelRequest request)
        {
            if (request.ViewModelType == typeof (LoginViewModel))
            {
                ClearBackStack();
            }
            base.Show(request);
        }

Is this the correct way to handle this? Is there an easier mechanism (pre-v3 like)? Should I be overriding ChangePresentation instead?
Also, is there a mechanism to call ShowViewModel from a View? Do I need to resolve the IMvxViewDispatcher or is there a more straight forward method?

A: Yes, if you want to do custom presentation techniques then the easiest way is to implement your own view presenter.
For an introduction and some links on this, see How can I implement SplitView in another view in MvvmCross?
You are free to write code directly in your views, including navigation logic using resolved IoC objects. However, mvvmCross tries to encourage you to put this logic in the viewmodels - especially so that the 'logic' is more easily shared between platforms.


text:
Q: iOS Swift Couchbase Lite Primary Key and Class Configuration I was going through couchbase-lite to use it in my next iOS app. I have created a model named Surah for now. Definitely, I will have more model classes later.
Basically I have four questions here.

*

*How do I add _id as my primary key in couchbase-lite?

*As I will be having more classes how will I handle those? As I am creating
MutableDocument, How will that differentiate each my classes?

*As I can see I have to iterate through each of my items to batch insert, won't that become slow for the large datasets?

*How do i convert results from a query with large data to a array of Model Class. (in this case of array of Surah)
class Surah: Decodable {
enum Keys: String, CodingKey {
    case _id
    case index
    case englishName
    case englishMeaning
    case name
    case place
    case count
}

var _id = ""
var index = 1
var page = 1
var numberOfAyahs = 1
var englishName = ""
var englishMeaning = ""
var name = ""
var place = ""
var isFavorite = false

var dictionary: [String: Any] {
    return ["_id": _id, "index": index, "page": page]
}

required init() {}

required init(_id: String, index: Int, name: String, englishName: String, englishMeaning: String, place: String, count: Int) {
    self._id = _id
    self.index = index
    self.name = name
    self.englishName = englishName
    self.englishMeaning = englishMeaning
    self.place = place
    self.numberOfAyahs = count
}

required convenience init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: Keys.self) // defining our (keyed) container
    let _id: String = try container.decode(String.self, forKey: ._id)
    let index: Int = try container.decode(Int.self, forKey: .index)
    let name: String = try container.decode(String.self, forKey: .name)
    let englishName: String = try container.decode(String.self, forKey: .englishName)
    let englishMeaning: String = try container.decode(String.self, forKey: .englishMeaning)
    let place: String = try container.decode(String.self, forKey: .place)
    let count: Int = try container.decode(Int.self, forKey: .count)
    self.init(_id: _id, index: index, name: name, englishName: englishName, englishMeaning: englishMeaning, place: place, count: count)
}}

Code for Database Queries
let surahs = try JSONDecoder().decode([Surah].self, from: data!)

                                        DispatchQueue.global(qos: .background).async {
                                            //background code
                                            do {
                                                if let db = App.shared.database {
                                                    try db.inBatch {
                                                        for item in surahs {
                                                            let doc = MutableDocument(data: item.dictionary)
                                                            doc.setString("users", forKey: "type")
                                                            doc.setValue(Keys._id, forKey: item._id)
//                                                            doc.setValue(Keys.englishName, forKey: item.englishName)
                                                            try db.saveDocument(doc)

                                                            let index = IndexBuilder.valueIndex(items:
                                                                ValueIndexItem.expression(Expression.property("_id")), ValueIndexItem.expression(Expression.property("type")))
                                                            try db.createIndex(index, withName: "TypeNameIndex")
                                                            print("saved user document \(doc.string(forKey: "englishName"))")
                                                        }
                                                    }
                                                }
                                            } catch let error {
                                                DispatchQueue.main.async {
                                                    seal.reject(error)
                                                }
                                            }
                                            DispatchQueue.main.async {
                                                seal.fulfill(surahs)
                                            }
                                        }

A: *

*Not sure what you mean by "primary key".  You can always find a doc
by its id.  The name of the field that contains it is Meta.id.
The field's value is mutableDoc.getId().  As you've noticed, you
can also explicitly set the id at creation

*Couchbase doesn't store classes, it stores JSON documents.  If you
have documents of different types (different internal structures,
analogous to different SQL tables), give them a type field and use
it in your query

*Use Database.inBatch()

*The same way you would convert any JSON document to a corresponding
class: gson, Jackson, Moshi, etc


text:
Q: I Am Working On Flutter App And Facing Some Issue Regarding Entity To Model Conversion I Am Working On Flutter App And Facing Some Issue Regarding Entity To Model Conversion
This is my Parent Partner class
  final int? id;
  final String? displayName;

  Partner(
      {this.id,
      required this.displayN``your text``ame,
      });
}

This my child PartnerModel class
  PartnerModel.search({super.id, super.displayName}) : super.search();

  PartnerModel(
      {super.id,
      super.displayName,
      });

And this is my PurchaseOrder class
  final DateTime? dateOrder;
  final DateTime? createDate;
  final String? origin;
  final Partner? vendor;

  const PurchaseOrder(
      {
      required this.dateOrder,
      this.createDate,
      this.origin
      required super.assignedUser,
      required this.vendor,
      });
}

And this is my PurchaseOrderModel class
  const PurchaseOrderModel(
      {
      required super.dateOrder,
      required super.createDate,
      required super.origin,
      required super.vendor,
      super.linePurchaseOrder})
      : super();

In PurchaseOrder class i created a vendor entity with Partner Type In PuchaseOrderModel
vendor type should remain Partner or change to PartnerModel because i am facing some issues.
I have created custom entity type Partner and i am facing issue in PurchaseOrderModel because it inherits from PurchaseOrder which has Partner Type vendor but in POModel it expects PartnerModel.
What is the best solution.


text:
Q: Dividir filtros agrupados en pandas Tengo esta informacion:
Lo que necesito es poder devolver total de property_type por barrios y que % ocupan del total de propiedades
Df para testeo
Reducción de info:
import numpy as np
import pandas as pd
datos = pd.read_csv('dataset/datos_properati.csv', parse_dates= ['created_on'])
df = pd.DataFrame(datos)
df_filtered = df[df.property_type != "store"]

df_filtered.property_type[df_filtered.property_type !=
'apartment'].groupby(df_filtered.barrio).value_counts()

df_filtered.barrio.value_counts()

Ej: En Belgrano tengo 1117 propiedades de las cuales 60 son house y 20 PH (El resto son apartment pero no me sirven para el caso por eso los filtro)
Necesito poder mostrar Que hay 60 apartment sobre 1117 propiedades y que representan el 5.37%.
¿Como podría hacer eso?

A: Propongo esta respuesta que acabo de obtener, en caso de que tengan una mejor, subanla
import numpy as np
import pandas as pd
datos = pd.read_csv('dataset/datos_properati.csv', parse_dates= ['created_on'])
df = pd.DataFrame(datos)
df_filtered = df[df.property_type != "store"]

dfNuevo =
pd.DataFrame(df_filtered.property_type.groupby(df_filtered.barrio).value_counts())

dfNuevo['Porcentaje'] =
round((df_filtered.property_type.groupby(df_filtered.barrio).value_counts() * 100) /
df_filtered.property_type.groupby(df_filtered.barrio).count(),2)

dfNuevo


text:
Q: Python: how to sort an array with integers and letters? When I have a list of integers and letters,
I want to sort these elements by some order.
For example,
ex_array = [1, 3, 2', 2, 1', 3', 3]

should be sorted to
sorted(ex_array) = [1', 1, 2', 2, 3', 3, 3]

In this case the order of letters is given by
1' < 1 < 2' < 2 < 3' < 3.

I can make a code when consisting of only integers.
But I don't know how to compare the symbols with primed with unprimed.
Could you tell me what to do in Python?

A: Sort by the integer value of each element, as well as whether that element is an integer:
>>> a = [1, 3, '2', 2, '1', '3', 3, '10', 10, 'potato', "1'", lambda: None, '-3', -3, -4]
>>> sorted(a, key=lambda x: (int(''.join(v for i,v in enumerate(str(x)) if v.isdigit() or (i==0 and v=='-')) or 0), isinstance(x, int)))
[-4, '-3', -3, 'potato', '1', "1'", 1, '2', 2, '3', 3, 3, '10', 10, <function <lambda> at 0x000000DAD51DB9D8>]

If two elements have the same integer value, the string will be placed before the integer.


text:
Q: Possible to turn off dynamic text in MKMapView? In my app, if the user slides 'Text Size' (under Settings > General > Text Size) to a large value, the city labels in the MKMapView are enlarged. I am sure this is intended and desired in many or most cases, but for my application, the large labels are obfuscating the map annotations itself. This makes it difficult to relate map annotations/overlays (which are the central focus of the app) to their exact position on the map.
Is there are way to opt out of the dynamic text in the map so that the Text Size changes will not affect it?

A: Well, if you look into the documentation you can see that to support dynamic size you have to use the new UIFont methods introduced in iOS 7 on an object. To not support dynamic size, you would probably have to change the font of the said labels to a fixed size. That being said, The MapKit Framework provides no way to change the font of these labels to the best of my knowledge. However a quick web search pointed me to the MKOverlay and MKAnnotation classes as the only thing related to font and MKMapView.
UPDATE: As Pointed Out By Apple(https://devforums.apple.com/message/931571#931571) the only way to change it is to adjust the font labels, using the new API's in iOS 7.


text:
Q: Match partial string in Excel VBA I am working in a VB macro where in the AUT Excel contains 5 sheets. In 3rd sheet I have 6 columns
In the 5th sheet. I have 3 Input boxes and 3 output boxes.
If user enters partial string from column 1 , column 2 and column 3 in inputbox1 , inputbox2 and inputbox 3, corresponding results should get displayed in outputbox1, outputbox2, outputbox3
But the code doesn't work if the input string is comparing with the data which has more values. So its like kind of hard coding this values in the if condition which is not feasible.
    `text3 Like "*NB" Or text3 Like
    "*NS" Or text3 Like "*NF" Or text3 Like "*PE")`

I got this code snippet from the answers which is not displaying the results
`If (text1 Like ("*" & text4 & "*") And text2 Like ("*" & text5 & "*") And text3 Like ("*" & text6 & "*")) Then`

Please letme know if anything i need to add in the IF condition to match the partial string

A: Probably you need Like operator....
https://learn.microsoft.com/en-us/dotnet/articles/visual-basic/language-reference/operators/like-operator

A: Why not use Find and FindNext instead. This will find the first instance that matches input1 and then test if input2 and input3 are also satisfied. If so it sets the values that you wanted. If not it finds the next possible match.
Set Sheet1 = Worksheets(1)

Dim c As Range
Dim firstAddress As String
With Sheet1.Columns(1)
    Set c = .Find(input1, lookat:=xlPart)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            If sheet3.Cells(c.Row, 2).Value2 = input2 And sheet3.Cells(c.Row, 3).Value2 = input3 Then
                Sheet5.Cells(13, 3).Value2 = Sheet1.Cells(c.Row, 5).Value2
                Sheet5.Cells(13, 6).Value2 = sheet2.Cells(c.Row, 6).Value2
                Sheet5.Cells(13, 9).Value2 = sheet3.Cells(c.Row, 4).Value2
                Exit Do
            Else
                Set c = .FindNext(c)
            End If
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With

A: Did you tried as below
If (input1 Like ("*" & output4 & "*") And input2 Like ("*" & output5 & "*") And input3 Like ("*" & output6 & "*"))


text:
Q: How to get the List URL in a SharePoint Designer workflow I've gotten as far as below:

But I don't know what they want me to choose in the "Find the List Item" section.  I don't want anything from the list item... I want the URL of the list.  Suggestions?
NOTE  I actually have "Current List" selected for my Data source.  I was just trying something else out when I took the screen shot...

A: The "Current Item -> Path" gives you the site relative URL to the list it's in, and you can add the site URL in a string varable to embed it elsewhere.

A: Construct the URL manually in designer :

*

*Type the majority of the URL in manually : http://server/site/list/DispForm.aspx?ID=

*Add or Change Lookup

*Select Data source: Current Item

*Select Field from source: ID

*Final link will look like this: http://server/site/list/DispForm.aspx?ID=[%Current Item:ID%]

A: In SPD2010 there is a lookup that will give you the DispForm URL of the current Item.  The URL will display like this http://Server/Site/Lists/ListName/DispForm.aspx?ID=1

A: Just see the screen shot below and select the Current Item there.


text:
Q: Minimum value of the function $\sin5x/\sin^5x$ I recently came across a question as follows:

Find the minimum value of the function $\sin5x/\sin^5x$.

I  tried differentiating the function but the calculation was messy. The resulting differentiated equation had many roots, difficult for me to identify which ones actually correspond to the minimum. Taking the second derivative  resulted in a horrendous calculation. Would someone please help me to find any easier solution?

A: hint
The derivative is
$$5\frac{\cos(5x)\sin(x)-\cos(x)\sin(5x)}{\sin^{10}(x)}\sin^4(x)$$
$$=\frac{-5\sin(4x)}{\sin^6(x)}$$
Your function is $2\pi-$periodic, even and satisfies
$$f(\pi-x)=f(x)$$
So, you just need to find the minimum at $[0,\frac{\pi}{2}]$.

A: We have: $\dfrac{\sin (5x)}{\sin^5x}= \dfrac{16\sin^5x-20\sin^3x+5\sin x}{\sin^5x}= 16-\dfrac{20}{\sin^2x}+\dfrac{5}{\sin^4x}=16-20t+5t^2=f(t), t = \frac{1}{\sin^2x} \ge 1$. You can take it from here as you have a quadratic function in $t \ge 1$.

A: $$\sin 5x=\Re(e^{ix})^5=5\cos^4x\sin x-10\cos^2x\sin^3x+\sin^5x=16\sin^5x-20\sin^3x+5\sin x$$ and we want to maximize
$$16-20t^{-1}+5t^{-2}$$ over $[0,1]$, where $t:=\sin^2x$.
By canceling the derivative,
$$20t^{-2}-10t^{-3}$$ gives the root $t=\frac12$ and the minimum value
$$16-20\cdot2+5\cdot4=-4.$$


text:
Q: Z score stats question Weight of people question:
Mean: 82kg, standard deviation 18kg.
75% of all people are at least how many kg?
Using the table, I get a z score of 0.67 or 0.68. So my answer is either 94.06 kg or 94.24 kg both of which were marked as incorrect. Am I doing something wrong, or thinking about it incorrectly?
0.68 = (x-82)/18 -> x=94.24

A: The 25th percentile of the standard normal is $-0.6744898$
So, 75% of people will be no more than $0.6744898$ standard deviations below the mean. That is, they will be greater than
$$ 82 - 18 \times 0.6744898 = 69.85918 $$
Your thinking was on the right track but you looked up the 75th percentile instead of the 25th (i.e. the value where 75% are $\geq$).


text:
Q: Exiting the recv loop after a fixed timeout I am using recv to receive a message on the socket from the server.
size_t b_received = 0;
char headers[2048];
while ((b_received = recv(socket_fd,
                              &headers[pos],
                              sizeof(headers) - pos - 1, 0)) > 0) {
    pos += b_received;
}

Sometimes, the server takes too long to send a message and my program is stuck and waiting for the next message.
Is there a way I could just end this loop if the server does not send me the next message after 5 seconds?

A: You can use the setsockopt function to set a timeout on receive operations:
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Try this to stop the socket :
#include <sys/socket.h>

int shutdown(int socket, int how);

More information here


text:
Q: How to build connection string in C# to remote SQL Server using intermediate Jump server? In Visual Studio, I am trying to build a connection to a remote SQL Server. To access this server manually:

*

*I need to connect to the VPN

*then RDP to Jump server

*then RDP to SSMS on the existing server

*Open SSMS & perform operation.

How can I achieve this using VS and C#?
Note: without Jump, remote connection to other SQL Servers via VPN is possible, but this server needs me to connect intermediate Jump server 1st. Port, Firewall settings are proper.
Your answers will be really helpful & appreciated. Thank you.


text:
Q: How to read data from an Ajax web service with Qt? I would like to process some data in a Qt application. This data can be found on a web page which uses Ajax to dynamically update itself.
For example, the page itself is www.example.com, and it uses Ajax to load data from www.example.com/data, which is a plain text file. If I view www.example.com in a browser, I can clearly see when the data is updated.
The brute force solution would be to just call the QWebView's load(QUrl("www.example.com/data")) every couple of seconds, or every time its loadFinished() signal is emitted, but that would be a waste of bandwidth, an I will be downloading the same data over and over. The time between updates could theoretically be a few seconds, but it could also be minutes, hours, or longer.
Is there a possibility to only reload the data when the page is updated?

A: The traditional AJAX model uses the following sequence of events:

*

*Browser opens connection

*Browser sends request

*Server sends response

*Server closes connection

Because the connection is closed, there is no way for the server to notify your browser if any data have changed. In order to get this information, you have no option but to query the server periodically.
As you mentioned in your question, this is not very efficient since you can waste a lot of bandwidth if nothing changes for a long while.
WebSockets is a more up-to-date technology that tries to overcome this inefficiency and Qt has a module that caters for this.
Unfortunately, it's not universal yet so, if you want to use WebSocket technology on a third-party server, you need to have traditional AJAX code to fall back on in case WebSockets are not supported.
EDIT:
Unfortunately, WebSockets are not the golden solution. It's still up to the server to have been programmed to send out notifications of changes. If the server does not have this feature, it won't matter if you're using WebSockets or traditional AJAX, you'll still have to keep querying for changes.


text:
Q: knitr::include_graphics in bookdown, is not rendering the image I am trying to include a .png file in a file that I am rendering using bookdown. knitr::include_graphics() should be the way to go.
The code:
```{r fig1, fig.cap='My Caption', echo=FALSE, message=FALSE, warning=FALSE}
knitr::include_graphics("./Figures/My Figure.png")
```

In the .Rmd file, I can run my r block, and it renders the image below. So, the path should be correct. However, when I knit the chapter, or render the entire book, the figure is not rendered.
Could it be that some of my other options are overriding the figure? Below are my YAML header of the index.Rmd file, and the code in my _output.yml file.
---
title: "My Title"
author: "My Name"
date: "`r Sys.Date()`"
output:
  bookdown::gitbook:
    split_by: section
  bookdown::pdf_book:
    keep_tex: no
documentclass: book
classoption: openany
bibliography: [Mybib.bib]
csl: Mycsl.csl
biblio-style: apalike
link-citations: yes
description: "My Description"
---

bookdown::gitbook:
  config:
    toc:
      before: |

Short Title

bookdown::pdf_book:
  latex_engine: xelatex
  citation_package: natbib
bookdown::epub_book: default

A: You have spaces in the image file path.
Spaces in file names are not a problem within R, and that is why you were able to see the image within RStudio. However, knitr is a bit more complex as it actually executes a number of different programs (R, pandoc & LaTeX).
As explained within the guidance to knitr, the knitr:: includegraphics function actually executes different results depending on whether the output is HTML, PDF or md. When building a PDF, it is passing the images through LaTeX and uses the function \includegraphics{} to insert the picture. As explained here:

"The file name of the image should not contain white spaces nor multiple dots"

Removing spaces will fix the problem, and it would generally be good practise to avoid them in R even if they technically are allowed.
Credit to @pzhao for initially highlighting the problem.


text:
Q: How to determine if user is accessing from LAN? I need my PHP script to determine if the user is accessing it from the LAN or not.
I have used $_SERVER['REMOTE_ADDR'] till now, to determine if the user's ip falls within a private ip range, but it fails with ipv6.
Current code used...
if( filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) ){
    echo "NOT private or reserved ip";
}else{
    echo "private or reserved ip";
}

... but it seems to fail by reporting my ipv6 as not private or reserved.

A: I'm not sure what "unicast" means, but according to Abstract, this is what you need:
RFC4193#3.1
You may compare Global ID and Subnet ID with same values for your server.


text:
Q: Dynamically map in React depending on the props received I have a component that takes the props. If it's "1", it should use dataOne selector in order to use the right selector with filters. If it's "2" then use dataTwo and so on.
For example:
const [dataSet] = useState(route.params.dataSet);

  const dataOne = useSelector(selectDataOne);
  const dataTwo = useSelector(selectDataTwo);
  const dataThree = useSelector(selectDataTwo);
  const dataFour = useSelector(selectDataTwo);

The problem is that I want to map through one of these selectors depending on the prop and I want an elegant solution for it as dataSet[0].map while dataSet === "dataOne" will not work of course. What would be the alternative? What would be the prefer way to do so? Create a separate component with the switch statement? I want an elegant solution instead of spamming ternary operators like:
{dataSet == "1" && dataOne.map etc.}
{dataSet == "2" && dataTwo.map etc.}

What would be the best way to take the name from the props and map through it?
EDIT: For now I have this working solution, but not sure if it's the prettiest one:
const Data = (dataSet: string) => {
switch (dataSet) {
case "1":
return dataOne.map((c: any, i: number) => {
const card = c.dataSet === 1 && ;
      if (i === dataOne.length - 1) {
        return (
          <View key={i} style={styles.lastMargin}>
            <Card key={i} data={c} isOperating={c.isOperating} />
          </View>
        );
      }

      return card;
    });
  case "2":
    return dataTwo.map((c: any, i: number) => {
      const card = c.dataSet === 2 && <Card key={i} data={c} isOperating={c.isOperating} />;

      if (i === dataTwo.length - 1) {
        return (
          <View key={i} style={styles.lastMargin}>
            <Card key={i} data={c} isOperating={c.isOperating} />
          </View>
        );
      }

      return card;
    });
  case "3":
    return dataThree.map((c: any, i: number) => {
      const card = c.dataSet === 3 && <Card key={i} data={c} isOperating={c.isOperating} />;

      if (i === dataThree.length - 1) {
        return (
          <View key={i} style={styles.lastMargin}>
            <Card key={i} data={c} isOperating={c.isOperating} />
          </View>
        );
      }

      return card;
    });
  case "4":
    return dataFour.map((c: any, i: number) => {
      const card = c.dataSet === 4 && <Card key={i} data={c} isOperating={c.isOperating} />;

      if (i === dataFour.length - 1) {
        return (
          <View key={i} style={styles.lastMargin}>
            <Card key={i} data={c} isOperating={c.isOperating} />
          </View>
        );
      }

      return card;
    });
}

};

A: You definitely shouldn't repeat your render logic. One way to do this could be by mapping each prop to a selector, getting the right one into a variable, and then using that in the render.
// map each prop to a selector
const selectorsMap = {
  "1": dataOne,
  "some-value": dataTwo,
  ...
};

// access the correct selector based on the prop
const data = selectorMap[dataSet];

return data.map(...);


text:
Q: Sorting list with string and integers I'm using CSV to sort the players highest sore. I have the name and scores in a list like this:
['4', 'Score One']
['8', 'Score Two']
['6', 'Score Three']

Which has been created from looping through the file, finding the maximum score and making a new list with this score and the player name.
for row in reader:
        highscores = ([row[-1], row[0]])

When I print (sorted(highscores)) the same list is returned to me. What I want it to sort as is:
['8', 'Score Two']
['6', 'Score Three']
['4', 'Score One']

If someone could explain to me why sorted doesn't work and what I could do to fix it, that'd be great.

A: Your problem is that each element of highscores is actually a list of strings, not a number.  These rows do not have a useful ordering.
Use the key argument to sorted, to get an integer score from each row:
>>> highscores = [['4', 'Score One'],
['8', 'Score Two'],
['6', 'Score Three']]
>>> sorted(highscores, key=lambda x: int(x[0]))
[['4', 'Score One'], ['6', 'Score Three'], ['8', 'Score Two']]


text:
Q: Show $\int_{0}^{\frac{\pi}{2}}\frac{x^{2}}{x^{2}+\ln^{2}(2\cos(x))}dx=\frac{\pi}{8}\left(1-\gamma+\ln(2\pi)\right)$ Here is an interesting, albeit tough, integral I ran across. It has an interesting solution which leads me to think it is doable. But, what would be a good strategy?.
$$\int_{0}^{\frac{\pi}{2}}\frac{x^{2}}{x^{2}+\ln^{2}(2\cos(x))}dx=\frac{\pi}{8}\left(1-\gamma+\ln(2\pi)\right)$$
This looks rough. What would be a good start?.  I tried various subs in order to get it into some sort of shape to use series, LaPlace, something, but made no real progress.
I even tried writing a geometric series. But that didn't really result in anything encouraging.
$$\int_{0}^{\frac{\pi}{2}}\sum_{n=0}^{\infty}(-1)^{k}\left(\frac{\ln(2\cos(x))}{x}\right)^{2k}$$
Thanks all.

A: In addition to the nice set of references by Raymond Manzoni, here is my proof of the identity. Frankly, I have not seen these references yet, thus I am not sure if this already appears in one of them.
Here I refer to the following identity
$$ \binom{\alpha}{\omega} = \frac{1}{2\pi} \int_{-\pi}^{\pi} \left(1 + e^{i\theta}\right)^{\alpha} e^{-i\omega \theta} \; d\theta, \ \cdots \ (1) $$
whose proof can be found in my blog post.
Now let $x$ be a real number such that $|x| < \frac{\pi}{2}$. Then simple calculation shows that
$$ \log\left(1+e^{2ix}\right) = \log(2\cos x) + ix \quad \Longleftrightarrow \quad \Im \left( \frac{-x}{\log\left(1+e^{2ix}\right)} \right) = \frac{x^2}{x^2 + \log^2(2\cos x)},$$
hence we have
$$ \begin{align*}I
&:= \int_{0}^{\frac{\pi}{2}} \frac{x^2}{x^2 + \log^2(2\cos x)} \; dx
= -\int_{0}^{\frac{\pi}{2}} \Im \left( \frac{x}{\log\left(1+e^{2ix}\right)} \right) \; dx \\
&= -\frac{1}{8}\int_{-\pi}^{\pi} \Im \left( \frac{\theta}{\log\left(1+e^{i\theta}\right)} \right) \; d\theta
= \frac{1}{8}\Re \left(  \int_{-\pi}^{\pi} \frac{i\theta}{\log\left(1+e^{i\theta}\right)} \; d\theta \right).
\end{align*}$$
Differentiating both sides of $(1)$ with respect to $\omega$ and plugging $\omega = 1$, we have
$$ \frac{1}{2\pi} \int_{-\pi}^{\pi} (-i\theta) \left(1 + e^{i\theta}\right)^{\alpha} e^{-i\theta} \; d\theta = \alpha \left(\psi_0(\alpha) - \psi_0(2)\right). $$
Now integrating both sides with respect to $\alpha$ on $[0, 1]$,
$$ \begin{align*}
-\frac{1}{2\pi} \int_{-\pi}^{\pi} \frac{i\theta}{\log \left(1 + e^{i\theta}\right)} \; d\theta
&= \int_{0}^{1} \alpha \left(\psi_0(\alpha) - \psi_0(2)\right) \; d\alpha \\
&= \left[ \alpha \log \Gamma (\alpha) \right]_{0}^{1} - \int_{0}^{1} \log \Gamma (\alpha) \; d\alpha - \frac{1}{2}\psi_0(2) \\
&= -\frac{1}{2}\left( 1 - \gamma + \log (2\pi) \right),
\end{align*}$$
where we have used the fact that
$$ \psi_0 (1+n) = -\gamma + H_n, \quad n \in \mathbb{N}$$
and
$$ \begin{align*}
\int_{0}^{1} \log \Gamma (\alpha) \; d\alpha
& = \frac{1}{2} \int_{0}^{1} \log \left[ \Gamma (\alpha) \Gamma (1-\alpha) \right] \; d\alpha \\
&= \frac{1}{2} \int_{0}^{1} \log \left( \frac{\pi}{\sin \pi \alpha} \right) \; d\alpha \\
&= \frac{1}{2} \left( \log \pi - \int_{0}^{1}  \log \sin \pi \alpha \; d\alpha \right) \\
&= \frac{1}{2} \log (2\pi).
\end{align*} $$
Therefore we have the desired result.

A: To learn more about this very interesting integral I'll just provide the interesting links (the story itself is interesting since it was an experimental discovery first from Glasser and Oloa) :

*

*page 28 of Bailey & Borwein 'Computer-Assisted Discovery and Proof'

*Oloa's paper of 2007 'Some Euler-type integrals and a new rational series for Euler's constant' at google or Les Mathématiques-net (or in the link 'EULER_TYPE_INTEGRALS_2007.pdf' here)

*Glasser & Mana 'The Laplace transform of the psi function'

*Dixit 2009 'The Laplace transform of the psi function'

*Amdeberhan & Moll 2010 'The Laplace transform of the digamma function: an integral due to Glasser, Manna and Oloa

*Vildanov 2010 'Generalization of the Glasser - Manna - Oloa integral and some new integrals of similar type'

*Coffey 2012 'Certain logarithmic integrals, including solution of Monthly problem #tbd, zeta values, and expressions for the Stieltjes constants'

*Weisstein has references too (see eq. (24))
Fine reading !


text:
Q: Constructor injection of a View Model instance used as an Action method parameter When a view model is created you can populate the options (e.g. used in a dropdown list) into a setter property of the view model.
The problem is that when that view model is later passed as a parameter (by the framework!) into an action method, those property values has not become automagically
repopulated, so if you need to redisplay the form because of validation errors, you need to repopulate those options again.
One potential solution, which I am asking for specifically in this question, is how to make the MVC framework instantiate the view model with constructor injection, which would provide the view model constructor with an implementation of some kind of data access object (e.g. a repository) that can be used for retrieving the options when they are requested by the view (e.g. in the helper method "DropDownListFor") ?
I think the solution might have something to do with implementations of IModelBinderProvider or IModelBinder but after having experimented with these things from example code snippets here and there on the net, I am still looking for a completely working example, with downloadable executable code without any missing piece of how putting all things together.
If you are looking for some alternative discussion about how to populate a select list, e.g. with  "Dependecy Lookup" instead of "Dependecy Injection" you may want to check out the following discussion:
Best way to populate SelectList for ViewModel on GET/POST
Best way to populate SelectList for ViewModel on GET/POST
Some days ago I wrote the following follow-up-question in that thread about the "Dependecy Injection" I am now looking for in this thread:
https://stackoverflow.com/a/8674525/310457
(which provides a code example about the problem I am looking for a solution of)
But instead of hoping that someone will find that old thread with a less specific title, I have created this new question with a more specific subject about what I am looking for.
And I will also provide a link from that thread into this new question for anyone that want to follow-up regarding this specific solution I am looking for.

A: I'm assuming you want to have your ViewModels automatically injected with something via their Constructor - for example some kind of configuration object that the View will use to determine what to show. I'm also assuming that this approach is causing a "No parameterless constructor defined for this object" error when MVC tries to automatically create and bind a model instance, from the arguments of your Controller Action. Let's also then assume that we will use a DI framework to inject the SiteConfig object into our Controllers automatically at runtime.
This means that the only problem we have to solve is how to get the injected object from our Controller into its Actions' ViewModels when they are automatically bound.
So let's define a base model for others to inherit from.
BaseViewModel
public class BaseViewModel
{
    public ISiteConfig SiteConfig { get; set; }

    public BaseViewModel(ISiteConfig siteConfig)
    {
        this.SiteConfig = siteConfig;
    }
}

And now let's create a model that inherits from it.
IndexViewModel
public class IndexViewModel : BaseViewModel
{
    public string SomeIndexProperty { get; set; }

    public IndexViewModel (ISiteConfig siteConfig) : base(siteConfig) {}
}

And now let's define a Base Controller that our Controllers will inherit from.
BaseController
public abstract class BaseController : Controller
{
    protected BaseController(ISiteConfig siteConfig)
    {
        _siteConfig = siteConfig;
    }

    private readonly ISiteConfig _siteConfig;

    public ISiteConfig SiteConfig
    {
        get
        {
            return _siteConfig;
        }
    }
}

Now we define our actual controller.
HomeController
public HomeController: BaseController
{
    public HomeController(ISiteConfig siteConfig): base(siteConfig) {}
}

Assuming we're using Ninject for DI, Ninject would be configured to automatically create the Controller and pass a concrete ISiteConfig object into its Constructor at runtime.
Now we add our Action to the Controller.
Index Action
public ActionResult Index(IndexViewModel model)
{
    return View(model);
}

And so this is the point where without doing anything else, MVC will explode with a "Parameterless Constructor" error if you try to call the Index Action, because MVC can't find a ViewModel constructor that takes no arguments.
And so, the answer. We need to override the default ModelBinder.
BaseViewModelBinder
public class BaseViewModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        if (modelType == typeof(BaseViewModel) || modelType.IsSubclassOf(typeof(BaseViewModel)))
        {
            var baseControl = controllerContext.Controller as BaseController;
            if (baseControl == null)
            {
                throw new Exception("The Controller must derive from BaseController");
            }

            var instance = Activator.CreateInstance(modelType, baseControl.SiteConfig);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, modelType);
            return instance;
        }
        else
        {
            return base.CreateModel(controllerContext, bindingContext, modelType);
        }
    }
}

And we need to set this as the default model binder in global.asax.cs :
protected void Application_Start()
{
    ...
    ModelBinders.Binders.DefaultBinder = new BaseViewModelBinder();
}

That's all. As you can see, when you view the Index Action now, MVC will use our custom model binder. It will realise that the IndexViewModel derives from BaseViewModel, and so will attempt to spin up an IndexViewModel  instance using the ISiteConfig it can find in the Action's Controller (because the Controller derives from BaseController).


text:
Q: bash - Moving all files which names end on one of given substrings I have file with names. My task is to move to another folder all files which names end on name from given file.
mapfile -t names< lists.txt
for element in "${names[@]}";
do
mask="*"$element
echo $mask
find source -type f -name "$mask" -exec mv -t target {} +
done

This is my code, but it doesn't work. Please, explain me how to fix it. It this problem of Cygwin emulator?

A: I am not familiar with the mv -t option that you are using here, but I would suggest rewording the find command as below:
find source -type f -name "$mask" -exec **mv '{}' target \;**


text:
Q: jQuery event triggers I have a select box with an onchange listener.  This functions 100% when human uses it.
I've added a modal dialog with jQueryUI to create a new option on to said list.
This works 100% as well.
However, Upon adding said new option to the list, I am trying to 'fake' the change event to trigger so the user doesn't have to do it.   It never seems to fire.
Can I use the trigger like this?
//##### ADDC ####//
$( "#add" ).click(function(){
    $( "#addform" ).dialog({
        autoOpen: true,
        height: 200,
        width: 350,
        modal: true,
        buttons: {
            "Add": function() {
                var f = $('#folder').val();
                var request = $.ajax({
                    url: "process.it"
                    ,  type: "POST"
                    ,  data: {  f  : f   }
                });
                request.done(function(msg) {
                    $("#version").append( $('<option></option>').val(msg).html(msg) ).val(msg);
                    $("#version").focus();
                });
                $( this ).dialog( "close" );
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        },
        close: function() {
            $('#version').trigger('change');
        }
    });
    return false;
});

//###### CHANGE ###############
$('#version').change(function() {
    var promise = getFolders(mypath);
    promise.success(function (data) {
        promise.done(function(msg) {
            if(msg=="false"){
                //error check
            } else {
                var myOptions = msg.split(",");
                var mySelect = $('#version');

                mySelect
                    .find('option')
                    .remove()
                    .end();
                $.each(myOptions, function(x,y) {
                    if(x==0){
                        x=-1;
                        y="Select Version";
                        mySelect.append($('<option></option>').val(x).html(y));
                    }
                    else {
                        mySelect.append($('<option></option>').val(y).html(y));
                    }
                });
                mySelect.focus();
            }
        });
    });
});

I've pulled out a TON of code, so if there's so brackets out of place, its simply typos here to show the core of the function.  Again, both work save for the adder calling the changer:
The key line is:
close: function() {
            $('#version').trigger('change');
        }

html looks like
  <select id="version"></select>  <a href="#" id="add">

When the modal closes (or other place), I want it to fire the onchange to effectively re-pull from source (the promise ajax lookup, function not listed here...) instead of what it does now, which is simply append the option to the list and select it.
I've tried this trigger block of code in a could places and it still won't fire.
So, how do I fake the onchange from the system?  I'm using a modern build of both jQuery and UI (maybe 1 point release out)

A: I think you are triggering the change before the response from the server. If you want to trigger the change after the, have your add method close the dialog in the 'done' function.
 buttons: {
        "Add": function() {
            var f = $('#folder').val();
            var request = $.ajax({
                url: "process.it"
                ,  type: "POST"
                ,  data: {  f  : f   }
            });
            request.done(function(msg) {
                $("#version").append( $('<option></option>').val(msg).html(msg) ).val(msg);
                $("#version").focus();
                $( this ).dialog( "close" );
            });

        },

Here is an example - http://jsfiddle.net/AMZ3n/2/


text:
Q: How can I extract some patterns of sub text from a gibberish looking text using regular expressions? I have some text where the age and gender of a person is mentioned in some of the records (not all) as 28M, or 35 F, or 29 male, or 57Female, etc.
I wrote the following regular expression to check if there is any pattern that matches a number followed by a M in an input string, and if yes to print it out, but the code does not print anything:
import re

text = 'Decision: Standard\r\n\r\n 36M NS\r\nBasic - 500th MP tdb addd cib 250th\r\n\r\nDue Date: Settlement date'

test_search = re.search('[0-9]+M', text)

if test_search:
    print("Age: "+test_search.group(0)+", Gender: "+test_search.group(1))

I expected it to have printed Age: 36, Gender: M. However, it does nothing - no error, no output, nothing.
I tried re.match('[0-9]+F', text), nothing happened there either.
Also, I thought I have to write as many regular expressions as there are patterns (one each for 28M, 35 F, 29Male, 57 female, etc). Is that the correct approach? Or is there a way to search/find/match all of these patterns at once?

A: You may use this regex to match all the cases you have mentioned in question:
results = re.findall(r'(?i)(\d+)\s*([mf]|(?:fe)?male)\b', text)

RegEx Demo
Details:

*

*(?i): Ignore case modifier

*(\d+): Match and capture 1+ digits in group #1

*\s*: Match 0 or more whitespaces

*([mf]|(?:fe)?male): Match or capture M or F or male or female in group #2

*\b: word boundary

A: You can use this regex
([0-9]+)\s?([M|Male|F|Female]+) and capture the age and name in seperate capturing groups.
Python Demo
import re

test_str = r"Decision: Standard\\r\\n\\r\\n 36M NS\\r\\nBasic - 500th MP tdb addd cib 250th\\r\\n\\r\\nDue Date: Settlement date 29 male 57Female 35 F"

pattern = r"([0-9]+)\s?([M|Male|F|Female]+)"

def return_gender_dict(match_obj):
    return { 'age': match_obj[0], 'gender': match_obj[1][0].upper() }

matches = re.findall(pattern, test_str, flags=re.MULTILINE | re.IGNORECASE)

result = [return_gender_dict(match) for match in matches]

print(result)

Outputting:
[{'age': '36', 'gender': 'M'}, {'age': '29', 'gender': 'M'}, {'age': '57', 'gender': 'F'}, {'age': '35', 'gender': 'F'}]

A: Try the following re
(\d\d)(M|F|Male|Female|\sM|\sF|\sMale|\sFemale)