text:
Q: How to force a runtime constant to be a compile time constant? So I am working on a chemistry based project and ran into this tricky problem. I have a bunch of functions doing chemistry type calculations and want to pass avogadros number as a default parameter for a function. Let me just let the code talk:
class Constants
{
    //must be readonly to b/c Math.Pow is calculated at run-time
    public static double readonly avogadrosNum = 6.022*Math.Pow(10,-22);
}

class chemCalculations
{   //getting default parameter must be a compile-time constant
    public double genericCalc(double avogadrosNum = Constants.avogadrosNum);
}

Edit: was unaware of exponential format, thanks guys

A: Just define avogadros number as scientific notation:
class Constants
{
    public double const avogadrosNum = 6.022e-22;
}

A: For a compile-time constant, you need to use the const keyword. But, to use it, your expression itself needs to be a compile-time constant too, as you noticed: you cannot use functions such as Math.Pow.
class Constants
{
    public const double avogadrosNum = 6.022E-22;
}

If you cannot or do not want to rework your constant to a compile-time constant, you cannot use it in compile-time contexts, but you could work around that by overloading, so that a runtime value can be used as sort of a default argument:
class chemCalculations
{
    public double genericCalc() {
        return genericCalc(Constants.avogadrosNum);
    }
    public double genericCalc(double avogadrosNum) {
        // real code here
    }
}

(By the way, the value of the constant is either wrong, or has a highly misleading name. It should most likely be 6.022E+23.)

A: You can't, in general. Anything which involves a method call is not going to be a compile-time constant, as far as the compiler is concerned.
What you can do is express a double literal using scientific notation though:
public const double AvogadrosNumber = 6.022e-22;

So in this specific case you can write it with no loss of readability.
In other settings, so long as the type is one of the primitive types or decimal, you can just write out the constant as a literal, and use a comment to explain how you got it. For example:
// Math.Sqrt(Math.PI)
public const double SquareRootOfPi = 1.7724538509055159;

Note that even though method calls can't be used in constant expressions, other operators can. For example:
// This is fine
public const double PiSquared = Math.PI * Math.PI;

// This is invalid
public const double PiSquared = Math.Pow(Math.PI, 2);

See section 7.19 of the C# 5 specification for more details about what is allowed within a constant expression.

A: You can do it in exponential format: 6.022E-22


text:
Q: How to delete centos update files that have been downloaded but not installed on a VM? I have a centos 7 VM in VirtualBox that I'm using for development on an OSS project. I'm not worried about updates to the VM, but the VM has downloaded pending (important) updates and has now grown to fill the entirety of my host partition's free space ... enough that I cannot manage snapshots and the host OS is complaining at me.
How can I delete these update files from the CentOS VM, and how can I set them to not download again automatically?
(I estimate the VM should be around 20GB ... it's now over 50GB.)

I tried the following commands, based on an answer, and got the output below. I still haven't freed up the space on my host OS...
[user@centos7host ~]$ yum clean packages
Loaded plugins: fastestmirror, langpacks
Cleaning repos: base epel extras github_git-lfs github_git-lfs-source ius
              : updates
0 package files removed
[user@centos7host ~]$ yum clean metadata
Loaded plugins: fastestmirror, langpacks
Cleaning repos: base epel extras github_git-lfs github_git-lfs-source ius
              : updates
19 metadata files removed
0 sqlite files removed
0 metadata files removed
[user@centos7host ~]$ yum clean headers
Loaded plugins: fastestmirror, langpacks
Cleaning repos: base epel extras github_git-lfs github_git-lfs-source ius
              : updates
0 header files removed
[user@centos7host ~]$ yum clean all
Loaded plugins: fastestmirror, langpacks
Cleaning repos: base epel extras github_git-lfs github_git-lfs-source ius
              : updates
Cleaning up everything
Maybe you want: rm -rf /var/tmp/yum-user-vce72D, to also free up space taken by orphaned data from disabled or removed repos
[user@centos7host ~]$ df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   43G   15G   29G  34% /
devtmpfs                 2.2G     0  2.2G   0% /dev
tmpfs                    2.3G     0  2.3G   0% /dev/shm
tmpfs                    2.3G  9.4M  2.3G   1% /run
tmpfs                    2.3G     0  2.3G   0% /sys/fs/cgroup
tmpfs                    2.3G   24K  2.3G   1% /tmp
/dev/sda1               1014M  282M  733M  28% /boot
tmpfs                    454M   28K  454M   1% /run/user/1000
[user@centos7host ~]$ rm -rf /var/tmp/yum-user-vce72D/
[user@centos7host ~]$ df -h
Filesystem               Size  Used Avail Use% Mounted on
/dev/mapper/centos-root   43G   15G   29G  34% /
devtmpfs                 2.2G     0  2.2G   0% /dev
tmpfs                    2.3G     0  2.3G   0% /dev/shm
tmpfs                    2.3G  9.4M  2.3G   1% /run
tmpfs                    2.3G     0  2.3G   0% /sys/fs/cgroup
tmpfs                    2.3G   24K  2.3G   1% /tmp
/dev/sda1               1014M  282M  733M  28% /boot
tmpfs                    454M   32K  454M   1% /run/user/1000
[user@centos7host ~]$

A: The following commands can be used:

*

*To clean the package list:
yum clean packages

*To delete metadata for each enabled repository, use the following command:
yum clean metadata

*To delete package headers, use the following command:
yum clean headers

*To clean all cached information, use the following command:
yum clean all

More info found: Here
I would disable the update daemon: PackageKit

*

*To disable auto update to happen via PackageKit, we need to stop the "packagekit" service and disable it permanently.
systemctl stop packagekit
systemctl mask packagekit

Create symlink from /etc/systemd/system/packagekit.service to /dev/null.

More information on how to do that is: Here

redpajama_set_name: RedPajamaStackExchange


text:
Q: python-ValueError: unconverted data remains: (UTC) I have a problem converting rfc2822 date to datetime object
Here's my code
from datetime import datetime

messages = {(m["subj"].upper(),datetime.strptime(m["date"],"%a, %d %b %Y %H:%M:%S %z")) for m in messages}

And here's the error
ValueError: unconverted data remains:  (UTC)

Message data structure:
{
    "subj": "к20 7",
    "date": "Sun, 14 Feb 2021 22:10:59 +0300"
}


text:
Q: Getting subsets from Subsonic Collections I am using Subsonic Collections to pull a list of timesheet entries from our database and then databinding them to ASP.net user controls I created on a page.
Is it possible to break one large collection into multiple subsets based on a certain parameter?
For example, each of our timesheet entries contain a job code for the particular job they are related to.  I would like to pull one large collection of entries for a particular employee by their employeeid and within a specified time range.  Then I would segment that collection into multiple smaller collections based on the entries' job code, this way I have the freedom to bind different collections to different controls based on the jobcode that the entries share.
It would also be nice since I wouldn't first have to pull a list of job codes the employee has data for, and then run multiple database calls to populate each collection (qry.AddWhere("job_code", job_code); qry.ExecuteReader();)

A: You can use LINQ to slice your big collection and use it as a data source for the grids. Something like this:
var dbResults = new TimesheetCollection()
    .Where(Timesheet.Columns.EmployeeID, empId)
    .Load();

grid1.DataSource = dbResults.Where(t => t.JobCode == jc1);
grid2.DataSource = dbResults.Where(t => t.JobCode == jc2);

This way you're not hitting the database multiple times. You can get the list of job codes for the employee via:
// IEnumerable<int> of jobs
var jobs = dbResults.Select(t => t.JobCode).Distinct();

However, note that the grid DataSources are now IEnumerable<Timesheet> instead of a TimesheetCollection object, if that matters.

A: Should be able to do this
Dim bigCollection as TimeSheetCollection
Dim job1Collection as New TimeSheetCollection = Nothing
Dim job2Collection as New TimeSheetCollection = Nothing

bigCollection = New TimeSheetCollection().Where("employeeid",employeeID).Load()
job1Collection = bigCollection.Where("job_code",jc1).Load()
job2Collection = bigCollection.Where("job_code",jc2).Load()

A: Sorry for the delayed response, I didn't set the question up right so I would get notifications of any responses, then I ended up forgetting about the post all together!  When I researched the topic again, low and behold I found my question again.
Corey,
Load() seems to pull more records from the database and append them to the collection.
I have a table that contains 14 rows.  5 of the rows have a type of "MEAL", the other 9 have a type of "OTHER".  When I run the following code:
Dim allActivities As New OnsScheduleActivityCollection
allActivities.LoadAndCloseReader(OnsScheduleActivity.FetchAll())

Dim justMeals As New OnsScheduleActivityCollection
justMeals = allActivities.Where("ActivityType", "MEAL").Load()

Response.Write(allActivities.Count & "
")
Response.Write(justMeals.Count & "
")

The response displays: 19 19
When I use Filter() in place of Load() the response displays:
5 5
That would be ok except that I don't actually want to modify the main collection, I just want to get a subset that I store in the new collection (justMeals) but leave the main collection (allActivities) in its original condition  My desired result would be to have the response display "14 5".  14 for the number of rows in allActivies and 5 in justMeals.
Is this at all possible?
Mike


text:
Q: Why My dropdown menu has not gone after click my browser body? When i am click my 'services li' my dropdown menu show and hide but when i am click  My browser body my dropdown menu not hide. I am try to my best efforts but not solve this problem. Please solve this problem anyone expert person.
<!DOCTYPE html>

    <title>Dropdown Menu</title>
    <link rel="stylesheet" href="css/all.min.css">
    <link rel="stylesheet" href="css/fontawesome.min.css">
    <link rel="stylesheet" href="style.css">

Home

About Us

Portfolio

Services

Web Design

About Us

Portfolio

Web Design

About Us

Portfolio

Services

Contacts Us

Contacts Us

nav ul li{
    cursor: pointer;

}
nav{
    padding-bottom: 20000px;

}

nav ul li:selected{

    background: red
}

nav ul::after {
    content: "";
    display: block;
    clear: both;
}
nav ul  {  padding: 0;
    margin: 0;
    background: green;

}

nav ul li {
    float: left;
    padding-right: 40px;
    list-style: none;
    padding: 10px 30px;
    position: relative;

}
nav ul lia {
    font-size: 22px;
    padding: 0px;
    text-decoration: none;
    color: #fff;
}
nav ul ul li{
    float: none
}
nav ul  ul {
    position: absolute;
    top: 100%;
    left:0;
    background: #ff4d4d;
    width:240px ;
   display: none;
}

nav ul  ul ul{
    display: block
}
nav ul .anika{
    display: block;
}
nav ul li:hover{

    background: pink
}
nav ul li:hover > a{

    color: black;
}
nav ul li:nth-child(3):hover{

    background: red
}
nav ul li:nth-child(3):hover > a{

    color: yellow
}
nav ul ul ul{
    position: absolute;
    top: 0px;
    left: 100%;
    background: navy;
    opacity: 0;
    transition: all 1s;
}
nav ul ul li:hover ul{
    opacity: 1
}

A: This is working for me. I think this is the easiest way to use it.

$('html,body').click(function() {
  $('#container').hide();
});

$('#menu').click(function(event) {
  event.stopPropagation();
});

$('#toggle').click(function(event) {
  $('#container').toggle();
});
#container {
  display: none;
}

  Toggle Menu First

A

B

C

D

E


text:
Q: If Else in react component always run else condition I am trying to build a contact form where an if else statement checks the validity of the email address entered, then with a nested if else checks whether the honeypot filed has a value and sends an ajaxj post request to an aws api gateway.
The ajax post runs without problem, but the outer else is always run.
Here the code:
import React from 'react'

import './style.scss'

const $ = require('jquery')
class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        name: '',
        email:'',
        subject:'',
        message:'',
        honeypot:'',
        result:'',
        alertType:'',
        formErrors:{
            email:'',
            name:'',
            message:''
        },
        isFormValid:false,
        emailValid:false,

    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  }

  handleChange(event) {
    const target = event.target
    const value = target.value
    const name = target.name
    this.setState({ [name]: value })

  }

  handleSubmit(event) {
    event.preventDefault();
    var URL = "https://someaddress/";
    var form =this
    var data = {
        name: this.cleanInput(this.state.name.trim()),
        email: this.cleanInput(this.state.email.trim()),
        subject: this.cleanInput(this.state.subject.trim()),
        message: this.cleanInput(this.state.message.trim()),

    }
    this.validateField('email',data.email)

    data.message = "Bilgiler şunlar:\nAdı:"+data.name+"\nEmail Adresi: "+data.email+"\nKonu:"+data.subject+"\nMesaj:"+data.message
    data.subject = "[Bestpet Web Sitesinden Doldurulan Form] "+data.subject;
    data.email = "info@atlaspet.com.tr";
    if(this.state.emailValid ===true){
      if (this.state.honeypot=== ''){

         $.ajax({
           type: "POST",
           url: URL,
           dataType: "json",
           contentType: "application/json",
           data: JSON.stringify(data),
           success: function(){
            form.setState({name:'',email:'',message:'',subject:'',result:'Form başarıyla gönderildi.',alertType:'alert alert-success'})
           },
           error: function () {
             // show an error message
            form.setState({result: 'Sorunlar oluştu. Formu gönderemedik.',alertType:'alert alert-danger'});
           },
         });
        } else {console.log("Hi there, I guess you are not human baby");}
    } else { form.setState({result: 'Lütfen girmiş olduğunuz email adresini kontrol ediniz.',alertType:'alert alert-danger'})}
  }

 validateField(fieldName, value) {
    let fieldValidationErrors = this.state.formErrors;
    let emailValid = this.state.emailValid;
   ;

    switch (fieldName) {
      case 'email':
        emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        fieldValidationErrors.email = emailValid ? true : false;
        break;
      default:
        break;
    }
    this.setState({
      formErrors: fieldValidationErrors,
      emailValid: fieldValidationErrors.email
    }, this.validateForm);
    console.log(this)
  }

 validateForm() {
    this.setState({ isFormValid: this.state.emailValid });
  }

 cleanInput(input){
    var search = [
      '', // Strip out javascript
      '<[/!]*?[^<>]*?>', // Strip out HTML tags
      '', // Strip style tags properly
      '<![sS]*?--[ \t\n\r]*>', // Strip multi-line comments
    ]
    var text = input
    // console.log(search.length)
    //var output = preg_replace($search, '', input);
    for (let i = 0; i < search.length; i++) {
      text = text.replace(new RegExp(search[i], 'gi'), '')
    }
    return text
  }

  render() {
    return (

                      <form onSubmit={this.handleSubmit}>

{this.state.result!=='' && this.state.result}

                          <input name="honeypot" type="text" style={{display:"none"}} value={this.state.honeypot} onChange={this.handleChange}/>

                                                    Name:
                                                     {this.state.formErrors.name!=='' &&
'Sizinle iletişim kurabilmemiz için bir isim girmelisiniz'
}

                                                    <input name="name" type="text" value={this.state.name} className ="form-control required" onChange={this.handleChange} />

                                                email
                                                    <input type="text" name="email" className="form-control required" value={this.state.email} onChange={this.handleChange}/>

                                                        Subject
                                                            <input type="text" name="subject" className="form-control required" value={this.state.subject} onChange={this.handleChange}/>

                                                        Message
                                                            <textarea name="message" rows="6" className="form-control required" value={this.state.message} onChange={this.handleChange}/>

                                                        <input type="submit" value="Submit" className="btn btn-sm btn-block btn-primary"/>

                      </form>

    );
  }
}

export default ContactForm

The section of code I have problems with is in handleSubmit function.
Thanks for help in advance and a happy new year to all.

A: I have moved the validity check to handleChange function and it is now working as intended.
Thanks a lot!


text:
Q: Git: add and commit if untracked or modified? What is the most acceptable way in a Bash script to add and commit to a Git repository files that exist and are untracked or changed?
git add -A "$dir" returns an error if the file does not exist, but returns 0 even if nothing was added. Then a subsequent git commit -m "Update $dir" might produce an error there is nothing to commit. My solution seems clunky, and I am not sure it is rigorous (in that git add … will never add anything when git ls-files … returns nothing):
[[ -n $(git ls-files --exclude-standard -om $dir) ]] &&
  git add -A "$dir" &&
  git commit -m "Update $dir"

Fuller example
This Bash script illustrates several functions to allow for a different commit message on initial commit of a file versus committing a change. Note it does not work well for directories since changed files as well as untracked files would be committed by commit_if_untracked. My current use case involves single files (thus -A below is unneeded, and --exclude-standard is arguably unneeded assuming I would want an error if I tried to commit a file that is ignored), but the above example with a directory was about as distilled as I could make an example!
#!/usr/bin/env bash

main () {
  command_that_might_create_or_change_$file

  commit_if_untracked "$file" "Initial $file"
  commit_if_modified  "$file" "Update $file"
}

# Usage: commit_if_* <file> <msg>
commit_if_untracked () {
  # [[ $(git ls-files --exclude-standard -o) =~ ($'\n'|^)$1($'\n'|$) ]] || return 0
  [[ -n $(git ls-files --exclude-standard -o $1) ]] || return 0
  git add -A "$1" && git commit -m "$2"
}
commit_if_modified () {
  [[ -n $(git ls-files --exclude-standard -m $1) ]] || return 0
  git add -A "$1" && git commit -m "$2"
}
commit_if_untracked_or_modified () {
  [[ -n $(git ls-files --exclude-standard -om $1) ]] || return 0
  git add -A "$1" && git commit -m "$2"
}

main

A: In writing this question I learned I could use git status --porcelain to shorten the code slightly. I am still hoping there is a better way.
For the first case that simply adds and commits only if there would be something to commit:
[[ -z $(git status --porcelain) ]] ||
  git add -A "$dir" && git commit -m "Update $dir"

To handle a different commit message depending on presence of untracked files that would be committed:
[[ ! $(git status --porcelain $dir) =~ (^|$'\n')\\?\\? ]] ||
  git add -A "$dir" && git commit -m "Initial $dir"
[[ -z $(git status --porcelain) ]] ||
  git add -A "$dir" && git commit -m "Update $dir"

Note the [[ ! … ]] || … could be slightly simplified to [[ … ]] && … if you are not using set -o errexit, or it could be written with if and elif to solve that issue and also avoid a redundant git status call if the first found untracked files:
if [[ $(git status --porcelain $dir) =~ (^|$'\n')\\?\\? ]]; then
  git add -A "$dir" && git commit -m "Initial $dir"
elif [[ -z $(git status --porcelain) ]]; then
  git add -A "$dir" && git commit -m "Update $dir"
fi


text:
Q: Coherent Sheaf supported in a point Hi guys, I'm studying Cech cohomology of sheaves and I've the following doubt:
If you have a coherent sheaf $\mathcal{F}$ in a compact complex variety $X$ then the cohomology groups are finite dimensional vector spaces (that's ok).
But it's true that we can reduce ("contract" or something) the analysis of the whole space to the support of the sheaf (to study there the cohomology)?
For example, suppose that $\mbox{Supp}(\mathcal{F})=\{p\}$ is a single point. What we can say about the cohomology of $X$ and the cohomology of $\{p\}$? It's true that the stalk $\mathcal{F}_p$ is a finite dimensional vector space?
Thank you very much!

A: Let $P\in X$ be the only point such that $\mathcal{F}_P\ne 0$ and consider the immersion $i:\{P\} \rightarrow X$ and consider the sheaf $\mathcal{S}: \{P\} \mapsto \mathcal{F}_P$; consider now the morphism of sheaves $\phi: \mathcal{F} \rightarrow i_* \mathcal{S}$ such that $\phi(X)$ is the canonical map to the stalk and for any $U\subsetneq X$ open $\phi(U)=0$. Then $\phi$ induces isomorphisms on the stalks, hence $\phi$ is an isomorphism of sheaves and hence we are done.


text:
Q: xfce4 boots into an xterm-like environment Most probably after a forced reboot, whenever I load xfce4 on my Ubuntu 13.04 I get this environment that looks like a buffed-up xterm, where I have an invisible mouse cursor: when I move around I cannot see a cursor but when it happens to go hover over a press-able button, the button changes color. I tried quitting that and starting X by startx but the only thing I got was a black screen. I proceeded as following:

*

*Tried uninstalling and reinstalling xfce4 by:

*

*sudo apt-get remove --purge xfce4

*sudo apt-get install xfce4

*It did not work so I also tried:

*

*sudo apt-get remove --purge libxfce4util-common

*sudo apt-get install xfce4

*It also did not work so after removing xfce4 I also tried removing and reinstalling xorg:

*

*sudo apt-get remove --purge xserver-xorg

*sudo apt-get install xserver-xorg

*sudo dpkg-reconfigure xserver-xorg

*Unfortunately this did not work either so I tried deleting also ~/.XAuthority* but this did not work either.

*I also attempted to startx after reinstalling xorg and before installing xfce4 but I was again getting just a black screen which makes very worried.

Any ideas?

A: I tried logging in as root, as opposed to the regular user I was logging in before, and everything was working fine. This seemed to indicate that it was more of a configuration issue than an xfce4 corruption.
Therefore I logged in again as the regular user that had the problem and deleted the configuration folder, after terminating xfce4 process:
mv ~/.cache/sessions ~/.cache/sessions.bak

Then I restarted xfce4 and everything was working great! Hope that proves helpful for some people.


text:
Q: Levi decomposition in disconnected linear algebraic group (characteristic 0)? For algebraic groups or Lie groups, the subject of Levi decompositions tends to be surrounded by some mystery in the literature (and in an older question raised here).   While I postpone further my intention to post a careful note on my homepage someday, I'm curious about the status of disconnected algebraic groups in this discussion.  Take the ground field $K$ to be algebraically closed of characteristic 0 throughout.

If $G$ is a disconnected linear algebraic group over $K$, of positive dimension, does it always have a Levi decomposition; if so, what can be said about conjugacy of Levi subgroups?

First I have to outline briefly the history of the concept of Levi decomposition.  This was first carried out for a finite dimensional Lie algebra $\mathfrak{g}$ and makes sense over an arbitrary field of characteristic 0:   Levi's theorem says that the solvable radical of $\mathfrak{g}$ has as a semidirect complement some semisimple subalgebra, while Mal'cev showed the conjugacy of any two such "Levi subalgebras" under special automorphisms of $\mathfrak{g}$ (which can be defined algebraically).   This is treated efficiently in modern language by Bourbaki in Chapter I, 6.8 of their treatise  Lie Groups and Lie Algebras.
To carry this over to connected Lie groups (real or complex), one then has to use the nice correspondence between Lie subgroups and Lie subalgebras.   (But this is developed using exponentials.)    In the 1950s Chevalley experimented with linear algebraic groups in characteristic 0, using a sort of formal exponentiation process to imitate the Lie group framework.
Borel works some of this out in somewhat more modern language in II.7.9 of his Benjamin notes, reproduced in his GTM 126 second edition.   For the Lie algebra $\mathfrak{g}$ of a connected algebraic group $G$, the basic observation is that any Lie subalgebra equal to its derived algebra is algebraic, i.e., is the Lie algebra of some connected closed subgroup of $G$.   (And this subgroup is unique, since we are in characteristic 0.)   In particular, a semisimple Levi subalgebra of $\mathfrak{g}$ is the Lie algebra of a connected semisimple subgroup $H$ of $G$ whose intersection with the solvable radical is finite.
(In some sources the product of subgroups here is supposed to be semidirect, but this is artificial for cases like the general linear group.)   Using Jordan decomposition, this becomes the more useful decomposition of $G$ into a semidirect product of a connected reductive subgroup and the unipotent radical.
The conjugacy theorem for $\mathfrak{g}$ then carries over to the group in a natural way.    Unfortunately, there seems to be no complete account of this in a textbook, though Demazure-Gabriel translate some of it into scheme language in II, Section 6.  In any event, my question above doesn't seem to be answered directly, since the characteristic 0 correspondence between closed subgroups and their Lie algebras requires connected subgroups.
Footnote:  In prime charactertistic things tend to fall apart in general, as indicated in my 1967 note here.  But a recent paper by George McNinch offers numerous useful refinements here.

A: The only argument I know for the existence of a Levi decomposition over fields of characteristic 0 and its uniqueness up to $k$-rational conjugacy works without a connectedness hypothesis, as an application of Hochschild cohomology; it is probably discussed in Jantzen's book, which hopefully someone else can confirm. The main point is that a (possibly disconnected) reductive linear algebraic group over a field of characteristic 0 has completely reducible linear representation theory.  I thought this argument is explained elsewhere on MO, but I cannot find it, so here is the argument.
Consider a field $k$ of characteristic 0 and a linear algebraic group $G$ over $k$, possibly disconnected.  Let $U$ be the unipotent radical of $G^0$; it is a characteristic subgroup (and its formation commutes with any extension of the ground field), so it is equal to the unipotent radical of $G$ as well.  We want to show that the exact sequence of $k$-groups
$$1 \rightarrow U \rightarrow G \rightarrow \overline{G} \rightarrow 1$$
splits over $k$ as a semi-direct product, where $\overline{G}$ has reductive identity component, and that any two splittings are related by $U(k)$-conjugacy.
Using a filtration of $U$ by its (characteristic!) derived series, we reduce to the case where $U$ is commutative provided that we also show ${\rm{H}}^1(k,U)=0$ in the commutative case too (so that $k$-rational conjugators can be lifted through stages of the resulting composition series of $G$).  Now $U$ is a vector group on which the $\overline{G}$-action is linear (since in characteristic 0 the automorphism functor of affine $n$-space as a $k$-group is represented by ${\rm{GL}}_n$), so the ${\rm{H}}^1(k,U)$-vanishing aspect is just additive Hilbert 90 (or whatever it should be called).  Hence, we're trying to show that any extension of a possibly disconnected $\overline{G}$ over $k$ by a linear representation $V$ splits over $k$ as a semi-direct product when $\overline{G}^0$ is reductive, with any two splittings related by
$V(k)$-conjugacy.
Observe that $G \rightarrow \overline{G}$ is a $V$-torsor for the etale topology.
For any vector group $V$ over $k$, we claim that
any $V$-torsor over an affine $k$-scheme $S = {\rm{Spec}}(A)$
is trivial (i.e., has a global cross-section).
Indeed, we can use a composition series arising from a basis of $V$ to reduces to the case that $V = k$, which is to say $\mathbf{G}_{\rm{a}}$-torsors over $S$ (for the etale topology).
It must be a classical fact that such torsors are trivial, or note that such
torsors "are" (necessarily quasi-coherent) $O_S$-linear extensions of $O_S$ by itself for the etale topology yet quasi-coherent sheaves for the etale and Zariski topologies coincides
(by descent theory)
and $A$-linear extensions of $A$ by itself clearly split.
Thus, the quotient map $G \rightarrow \overline{G}$ admits a section over $k$ as a map of affine scheme.  Hence, as in the more classical setting of group cohomology,
the obstruction to modifying a section to be a homomorphic section (over $k$) is a
canonically associated class in the Hochschild cohomology group
${\rm{H}}^2(\overline{G},V)$ that imitates group cohomology
by using ``algebraic cochains'', and if this class vanishes then
the set of $V(k)$-conjugacy classes of such splittings is a torsor for
${\rm{H}}^1(\overline{G},V)$.  It therefore suffices to show that all higher Hochschild cohomology of $\overline{G}$ with coefficients in a linear representation vanishes.  The formation of such Hochschild cohomology groups commutates with extension of the ground field, so we can also now assume $k$ is algebraically closed (which ensures that all
finite etale $k$-groups are constant and that all $k$-tori are split).
But in general Hochschild cohomology for an affine algebraic group scheme $H$ over a field (as a functor on the category of not necessarily finite-dimensional algebraic linear representations for the group) is the derived functor of the functor of $H$-invariants, so if $H$ has completely reducible finite-dimensional linear representation theory
then the higher cohomology vanishes (as every linear representation is a direct limit of finite-dimensional ones, and the formation of Hochschild cohomology commutes with direct limits).
Thus, we are reduced to the assertion that over an algebraically closed field $k$ of characteristic 0, for any linear algebraic group $\overline{G}$ over $k$ with reductive identity component, the finite-dimensional linear representation theory of $\overline{G}$ is completely reducible.  By the usual Hom trick, it is the same as showing the functor of $\overline{G}$-invariants is right-exact.  For this formulation, it clearly suffices first to treat $\overline{G}^0$, and then to treat the finite constant component group.  The case of finite constant groups goes via averaging since ${\rm{char}}(k)=0$, and the connected reductive case reduces separately to tori (also standard, valid in any characteristic) and then finally semisimple groups (for which it suffices to treat the analogue for the Lie algebra since ${\rm{char}}(k)=0$, so we win since ${\rm{char}}(k)=0$ and the Lie algebra is semisimple by various means, one of which is Levi's original theorem!).
QED
It is only at the final step, for treating the case of the finite etale component group and connected semisimple groups that we use ${\rm{char}}(k)=0$ rather than that $k$ is just a perfect field.

A: See G. P. Hochschild: Basic Theory of Algebraic Groups and Lie Algebras (Graduate Texts in Mathematics)-Springer (1981) VIII, Theorem 4.3


text:
Q: How to get the text value of a control through its parent window I have the following wxDialog parent window:

I have created that parent window by the following code:
settingsFrm settingsWindow(this, "Settings");
settingsWindow.ShowModal();

I have tried to use FindWindowByName to get the value of the first text ctrl as follow:
wxLogMessage(dynamic_cast<wxTextCtrl*>(settingsWindow->FindWindowByName("keywords_txt"))->GetValue());

But unfortunately, it doesn't work and gives me a runtime error.
I don't know if that method suitable to do what I want.
How to get the value/other of a control through its parent window?

A: From your comments, it seems like you expect the function to find the control from the name of the variable in your code which is not how it works and would be pretty much impossible.
FindWindowByName() uses the window name (and, as a fallback, label, but this is irrelevant here because text controls don't have labels anyhow), so for it to work you need to set the window name when creating the control, using the corresponding parameter of its ctor. This is very rarely useful in C++ code, however, as it's simpler to just store a pointer to the control in some variable and use this instead.
FindWindowByName() can often be useful when creating controls from XRC, however. If you do this, then you should specify names for your controls in XRC and pass the same name to this function.

A: How did you create the TextCtrl instance? You should have something like wxTextCtrl m_textCtrl1 = new wxTextCtrl(/// arguments); Accessing the value should be very easy, as wxString text = m_textCtrl1->GetValue(); You definitely don't need FindWindowByName just for what you are trying to do here.


text:
Q: $\pi$ and rapid series for the inverse tangent I design an educational program to demonstrate convergence rate in computation of $\pi$ by using the Machin like formula. According to Weisstein, the Hwang's equation (see eq. (32) in http://mathworld.wolfram.com/Machin-LikeFormulas.html):
$$\begin{align}
  \frac{1}{4}\pi = & 183{{\cot }^{-1}}239+32{{\cot }^{-1}}1023-68{{\cot }^{-1}}5832 \\
 & +12{{\cot }^{-1}}110443-12{{\cot }^{-1}}4841182-100{{\cot }^{-1}}6826318 \\
\end{align}$$
is the most efficient Machin like formula to compute pi. I used three series for the inverse tangent ($\cot^{-1}x = \tan^{-1}\frac{1}{x}$):
$$\tag{1}\tan^{-1}x=\sum\limits_{n=1}^{\infty }{\frac{{{\left( -1 \right)}^{n}}{{x}^{2n+1}}}{2n+1}},$$
$$\tag{2}\tan^{-1}x=\sum\limits_{n=1}^{\infty }{\frac{{{2}^{2n}}{{\left( n! \right)}^{2}}}{\left( 2n+1 \right)!}\frac{{{x}^{2n+1}}}{{{\left( 1+{{x}^{2}} \right)}^{n+1}}}},$$
$$\tag{3}\tan^{-1}x=2\sum\limits_{n=1}^{\infty }{\frac{1}{2n-1}\frac{{{a}_{n}}\left( x \right)}{a_{n}^{2}\left( x \right)+b_{n}^{2}\left( x \right)}},
$$ where
$$\begin{align}
& {{a}_{1}}\left( x \right)=2/x, \\
& {{b}_{1}}\left( x \right)=1, \\
& {{a}_{n}}\left( x \right)={{a}_{n-1}}\left( x \right)\left( 1-4/{{x}^{2}} \right)+4{{b}_{n-1}}\left( x \right)/x, \\
& {{b}_{n}}\left( x \right)={{b}_{n-1}}\left( x \right)\left( 1-4/{{x}^{2}} \right)-4{{a}_{n-1}}\left( x \right)/x. \\
\end{align}$$
Eq. (1) is the Maclaurin series, eq. (2) is the Euler's series, eq. (3) is from the paper Abrarov & Quine arXiv:1706.08835. It appears to be that eqs. (2) and (3) are more rapid than eq. (1). I want to ask you two questions. Is eq. (3) more efficient than eq. (2)? Are there other series for the inverse tangent with rapid convergence?

A: The Hwang equation is not the most efficient Machin like formula to compute $\pi$. The following formula
$${\pi \over 4} = 32 \, \hbox{arctan}({1\over 40}) - \hbox{arctan}\biggl(
{38035138859000075702655846657186322249216830232319
\over
2634699316100146880926635665506082395762836079845121}\biggr)
$$
has a Lehmer's measure around $1.16751$ thus beating Hwang's formula (with Lehmer's measure $1.51240$).
Abrarov and Quine gave a formula with Lehmer's measure $0.245319$ last summer, together with the relevant algorithms, in their paper An iteration procedure for a two-term Machin-like formula for pi with small Lehmer's measure. That formula provides 16 new digits of $\pi$ per term increment thus beating the famous Chudnovsky formula.
At $k=27$ the Abrarov-Quine formula gives a fraction that has a numerator with $522\,185\,807$ digits and a denominator with $522\,185\,816$ digits. This type of fractions with huge numbers can also be obtained from the Borwein's integral as shown in the preprint by Uwe Bäsel and Robert Baillie Sinc integrals and tiny numbers such that a formula for $\pi$ can be written with $453\,130\,145$ and $453\,237\,170$ digits in numerator and denominator, respectively.

A: This is not exactly an answer, but R. P. Brent has an excellent survey of computing everything under the Sun (including $\arctan.$)

A: The efficiency of such series depends not just on the rate of convergence but on the bit size of the terms.
If $\sum_{k=0}^{\infty} T(k)$ converges linearly, you can always rewrite it as $\sum_{k=0}^{\infty} U(k)$ where $U(k) = \sum_{j=0}^{N-1} T(N k + j)$
to get a series that converges $N$ times faster.
But nothing has really been gained since the terms now cost $N$ times more to compute.

A: Arctangent formula (3) that can also be written as
$$\tan^{-1}\left(x\right)=i\sum\limits_{n=1}^{\infty}{\frac{1}{2n-1}}\left(\frac{1}{\left(1+2i/x\right)^{2n-1}}-\frac{1}{\left(1-2i/x\right)^{2n-1}}\right)$$
is more rapid in convergence than the equation (2). Therefore, it is more efficient in computation. Here is a link: How to compare convergence of two equations for the arctangent function?


text:
Q: Simple MS SQL count question I have this SQL
DECLARE @url varchar(100)
SET @url = 'http://mysite.com/%'

SELECT
[UserSessionSequenceID]
      ,[SiteID]
      ,[Referer]
      ,[Timestamp]
,ROW_NUMBER() over (PARTITION BY [Referer] ORDER BY referer DESC) AS sort
  FROM [tblSequence]
WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15

Want to count unique referer - problem is that this SQL returns ALL matches and count those one by one.
I only want the count for each unique referer (and still exsluding the @url with like).
How to do that?

A: SELECT
      [Referer], Count([Referer]) as RefCount
  FROM [tblSequence]
WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15
GROUP BY [Referer]

Putting Order back in (should that really be required) depends on your exact requirements.

A: Use DENSE_RANK not ROW_NUMBER if you require row data instead of an aggregate

A:  DECLARE @url varchar(100)
 SET @url = 'http://example.com/%'

  SELECT
  distinct [UserSessionSequenceID]
  ,[SiteID]
  ,[Referer]
  ,[Timestamp]
 ,count(*) over (PARTITION BY [Referer] ORDER BY referer DESC) AS sort
  FROM [tblSequence]
  WHERE [Referer] IS NOT NULL AND [Referer] NOT LIKE @url AND siteID = 15


text:
Q: Expand div full height I would like to expand the black box (id: column-content) to the full height without scroll bars.
I try alot of things but nothing works.
Here is the url: http://goo.gl/I5f0u59
Any idea? Thanks.

A: #column-content {
  bottom:0;
  position:fixed;
  top:0;
}

A: You can use the viewport units vh and vw (viewport-height and viewport-width)
in your case:
#column-content
{
    height: 100vh;
    box-sizing: border-box;
    /*
    change width, since we use border-box
    old width + padding
    */
    width: 480px;
}

As you see, this will make your column content box-sizing:border-box this will prevent the container from becoming bigger than 100vh because of the padding-top and bottom. The content can still lead to an overflow. You will also have to set a new width, like shown above.
The support for this usecase is ok See here


text:
Q: Django: Where to store a lot of methods called on model.save()? I am using Django 1.9. I have a model that represents the number of patients at a doctor's practice in a given month, broken down by age and sex:
class PracticeList(models.Model):
    practice = models.ForeignKey(Practice)
    date = models.DateField()
    male_0_4 = models.IntegerField()
    female_0_4 = models.IntegerField()
    male_5_14 = models.IntegerField()
    female_5_14 = models.IntegerField()
    ... etc
    total_list_size = models.IntegerField()
    prescribing_needs = JSONField(null=True, blank=True)

I use the value of the integer fields to drive various measures adjusted for age and sex. There are a large and unpredictable number of these, hence using a JSONField for prescribing_needs. I initially calculated and set these on the model's save method:
    def save(self, *args, **kwargs):
        self.total_list_size = self.male_0_4 + self.female_0_4 + ....
        antibiotics = 1.2 * self.male_0_4 + 1.1 * self.female_0_4 + ...
        # plus 40-50 other calculations
        self.prescribing_needs = {
            'antibiotics': antibiotics ...
        }
        super(PracticeList, self).save(*args, **kwargs)

This worked, but made my models file unmanageably long. So my question is quite simple: What is the Django Way to split out the method to calculate all these measures on save?
Right now I've simply created a new file called model_calculations.py in the same directory as models.py:
def set_prescribing_needs(c):
    antibiotics = 1.1 * c.male_0_4 + 1.1 * female_0_4 ...
    prescribing_needs = {
        'antibiotics': antibiotics
    }
    return prescribing_needs

And I just import this file into models.py and do:
def save(self, *args, **kwargs):
    self.prescribing_needs = model_calculations.set_prescribing_needs(self)
    super(PracticeList, self).save(*args, **kwargs)

Is this OK, or is there a more Djangoish place to store these methods?

A: That is an OK way to do it and is the Django way of doing it. There are two things I would look for.
When you have some functions that are used in multiple apps, put those functions in a main/model_calculations.py, core/model_calculations.py, or whatever app you have that is shared across your whole project.
If you find that some of these functions are used outside of your models, I would put them in a utils.py file.
As long as these functions are used just in a single app, and only used in models, where you're currently storing them is fine.


text:
Q: How can I query SEDE for Favorites tagged with  Since we currently don't have a way to search our favorites, I built a SEDE Query to List of Favorites for a UserId that are Tagged with TagName.
The query takes two inputs:

*

*UserId (int)

*TagName (varchar)

However, I'm having problems doing a substring search on TagName within Posts.Tags.
SELECT Posts.id as [Post Link], Posts.Tags as [Tagged With]

FROM Votes, Posts

WHERE
     (Votes.PostId=Posts.Id) AND
     (Votes.VoteTypeId = 5) AND
     (Votes.UserId=##User:int##) AND
     ('##TagName##' LIKE Posts.Tags);

If a question tagged pythonxml, Posts.Tags contains a string like this: <python><xml>.
No matter what I try for values of ##TagName##, I can only find questions with a single tag (see screenshot)...

I have tried queries with the following TagName inputs:

*

*<python> (returns favorites that have a single tag: python)

*%<python>% (returns nothing)

*%python% (returns nothing)

Perhaps I have misunderstood the format of the source, but I haven't figured out a better way to make the TagName queries.  There are a lot of questions with multiple tags, but unless we have a wildcard (or substring) search capability on Posts.Tags, I'm not sure how we can get the right information.
Should I be able to do a wildcard search on Posts.Tags in SEDE?  If so, how should I modify my existing query?

A: I almost feel like this should have been a question on SO since its a problem with your SQL not Data.SE
Basically you've got your like clause backwards
Try
SELECT Posts.id as [Post Link], Posts.Tags as [Tagged With]

FROM Votes, Posts

WHERE
     (Votes.PostId=Posts.Id) AND
     (Votes.VoteTypeId = 5) AND
     (Votes.UserId=##User:int##) AND
     (Posts.Tags like '%##TagName##%' );

Another approach is to use the denormalized tags table and not use the like clause at all if you just want question tagged with at least the python as opposed to questions that have a tag that contains the word python (e.g. ironpython python3.x)
SELECT p.id as [Post Link], p.Tags as [Tagged With]
FROM
        Votes v
        INNER JOIN Posts p
        ON v.PostID = p.id
        INNER JOIN PostTags pt
        ON p.id = pt.PostId
        INNER JOIN tags t
        on pt.TagID = t.ID
WHERE
     v.VoteTypeId = 5 AND
     v.UserId=##User:int## AND
     t.TagName = '##TagName##' ; --Only those tagged with Python (so ironPython will be ignored)


text:
Q: Read each row once while multiple processes insert into the same Oracle table? I have a table into which multiple processes insert data very rapidly throughout the day. Assume that at least one process is performing an insert at any given moment.
I need to read from this table during the day, while the inserts are happening. I need to read every row but I only need to read each row once.
My questions are:

*

*Is it possible for a single process to read from the table this way without affecting insert performance?

*Could there be more than one process reading data from the table at the same time?

A: Oracle implements multi-version read consistency so readers don't block writers (nor do readers block other readers).  You can have as many processes reading data as you'd like without affecting insert performance.
Of course, in reality, your hardware and your application probably imposes some sort of constraint on this theory.  If your system is CPU bound, for example, and you introduce so many readers that a significant fraction of the CPU is being given to the readers at the expense of the writers, you'll likely encounter some performance issues.  If you are reading rows long enough after they have been inserted that they've been aged out of the buffer cache (and the file system cache if that's in play), readers will add I/O to the system which may impact performance if your system is I/O bound.


text:
Q: `function go()` vs `go = function()` I ran into what seems to be a silly issue with some Javascript:
go = function () {
    alert("Go!");
}

$(function () {
    go();
});

When the page loads I get an error:

Webpage error details
User Agent: Mozilla/4.0 (compatible;
  MSIE 8.0; Windows NT 6.1; WOW64;
  Trident/4.0; SLCC2; .NET CLR
  2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0;
  .NET4.0C; .NET4.0E; .NAP 1.1)
  Timestamp: Thu, 17 Mar 2011 20:18:03
  UTC
Message: Object doesn't support this
  property or method Line: 1 Char: 1
  Code: 0 URI:
  http://localhost:61710/Scripts/number.js

When I change the go initializer to this:
function go() {
    alert("Go!");
}

...everything works just fine.
What am I missing? Also, is there a reason to use one form of function initializer over the other?
Edit:
I get this error when I run the code in an instance of IE8 using the built-in Visual Studio web server (Start without Debugging). When I run the code in a separate instance of IE8 without Visual Studio, it works just fine. Perhaps Visual Studio forces IE to use stricter JS compiler settings?

A: You should declare the variable first:
var go = function () {
    alert("Go!");
}

One reason to use this form is that it can help and avoid polluting the global namespace with your functions (see an example of this notion here).

A: The difference (and may help you decide which is better over another) is that
go = function () {
    alert("Go!");
}

is defined at parse-time whereas
function go() {
    alert("Go!");
}

is defined at run-time.
P.S., it works for me, however you may need to do:
var go = ...

rather than
go = ...

A: work fine for me:
http://jsfiddle.net/vEKgX/
although try this instead:
var go = function () {
    alert("Go!");
}

$(go);


text:
Q: StackPanel visibility not updated when dependency property changed I'm currently developping an universal app in C#/XAML with MVVM (not MVVM Light) and I have trouble for the XAML part.
I'd like to display one or another StackPanel when a dependency property changed in my ViewModel. I think the code speaks for itself.
<StackPanel Visibility="{Binding MyProperty, Converter={StaticResource BooleanToVisibilityConverter}}">
    <!-- Some content -->
</StackPanel>

<StackPanel Visibility="{Binding MyProperty, Converter={StaticResource InvertBooleanToVisibilityConverter}}">
    <!-- Some another content -->
</StackPanel>

And here is the definition of the dependency property.
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register(
    "MyProperty",
    typeof (bool),
    typeof (MyViewModel),
    new PropertyMetadata(true));

public bool MyProperty
{
    get { return (bool) GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); OnPropertyChanged(); // Implemented by ReSharper }
}

I guess you figure it out that MyProperty is a boolean that I convert into a Visibility via the converters. So, when MyProperty changed in the ViewModel, the view isn't updated.
I already tried to use the UpdateSourceTrigger property but it's not working. Also, I have no binding error and converters are working fine (I only see one StackPanel at the app launch).
Please keep in mind that I don't want to use the code behind part unless there is no other solution.
Thanks for your help.

A: I finaly gave up and used the code behind part and it's working fine now.

A: Are your <StackPanel>s part of some UserControl?  If not, why are you using DependencyProperty?
Your implementation is quite off as well.
Lets assume for a minute that this is not part of a Custom Control (correct me -- if I'm wrong, I will rewrite the solution)
So you have a ViewModel and you want to hook up some Properties to it.  You really don't need to implement DependencyProperty to do what you want to do, but I will entertain you by implementing it your way.
This is a sample ViewModel with 1 (one) property
using Windows.UI.Xaml;
using System.ComponentModel;

// very simple view model
class MyViewModel : DependencyObject, INotifyPropertyChanged
{

    // implement INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // register
    public static DependencyProperty FooterTitleProperty = DependencyProperty.Register("FooterTitle", typeof(string), typeof(MyViewModel),
         new PropertyMetadata(string.Empty, OnFooterTitlePropertyChanged));

    // the actual property
    public string FooterTitle
    {
        get { return (string) GetValue(FooterTitleProperty); }
        set
        {
            SetValue(FooterTitleProperty, value);
        }
    }

    // this will fire when the property gets change
    // it will call the OnPropertyChanged to notify the UI element to update its layout
    private static void OnFooterTitlePropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        MyViewModel mvm = dependencyObject as MyViewModel;
        mvm.OnPropertyChanged("FooterTitle");
    }
}

To test out the code we will make a very simple XAML form
<Grid x:Name="ContentPanel">
    <StackPanel>
        <TextBlock x:Name="tb" Text="{Binding FooterTitle}" FontSize="48"></TextBlock>
        <Button Content="Test Property" Click="Button_Click_1"></Button>
    </StackPanel>
</Grid>

When you click on the button we will change the Textbox's Text
public sealed partial class MainPage : Page
{
    // create the view model
    MyViewModel vm = new MyViewModel();

    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        // set the text we initial want to display
        vm.FooterTitle = "default text";

        // set the DataContext of the textbox to the ViewModel
        tb.DataContext = vm;
    }

    // after the button is click we change the TextBox's Text
    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        // change the text
        vm.FooterTitle = "Test Property Has Changed.";

        // what happens is the Setter of the Property is called first
        // after that happens it launches the `OnFooterTitlePropertyChanged` event
        // that we hook up with the Register function.

        // `OnFooterTitlePropertyChanged` launches the INotifyPropertyChanged event
        // then finally the TextBox will updates it's layout
    }
}

At this point you can guess you really don't need the DependencyProperty and say why can't I just launch the INotifyPropertyChanged in the Setter instead?  Well you can and it is probably the prefer method.
If all these is part of a UserControl then I can see using a DependencyProperty then in the OnFooterTitlePropertyChanged event you can set the
name_of_textbox.Text = FooterTitle;

A: I think property name should be given with OnPropertyChanged method, like this;
public bool MyProperty
{
    get { return (bool) GetValue(MyPropertyProperty); }
    set {
              SetValue(MyPropertyProperty, value);
              OnPropertyChanged("MyProperty");
        }
}

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.data.inotifypropertychanged.propertychanged


text:
Q: Can I pass a undefined variable parameter in python? I wish to change a string like function.
let my function string is like 'x**2+2*x+1'.but I want to change x by r.
And I don't want to use x as a str during this replacement.
To do this I make a method whose parameter are formula and vav i.e., variable
So, I tried This:
def ModifyFormula(formula,vav):
    vav=str(vav)
    san_vav='r'
    formula=formula.replace(vav,san_vav)
    return formula
ModifyFormula('x**2+2*x+1',x)

But I got NameError: name 'x' is not defined, It is pretty obvious that is a error due to a undefined in last line of the code .
How I can approach the goal to 'r**2+2*r+1' without using x as str ?

A: It's not possible.
The last line will always be decoded.


text:
Q: Alternative for many if/then AMPscript statements? I'm guessing there is a more efficient way for me to handle the following scenario and am looking for some advice.
Say I have 20 different Cities, abbreviated in my database by 3 letters.  LOS, for example is Los Angeles.  I have to dynamically populate the city name in an email based on these three letters.  Assuming I can't change the data itself, is there a better way to handle it than a series of if/thens?
%%[if @cityCode == "LOS"  then]%%
Los Angeles
%%[ ELSEIF @CityCode == "SEA"  then]%%
Seattle
%%[endif]%%

A: You can load the city codes in a Data Extension and do a lookup.
%%[

var @cityCode, @city
set @cityCode = AttributeValue("cityCode")
set @city = Lookup("cities", "city", "cityCode", @cityCode)

]%%

cityCode: %%=v(@cityCode)=%%

City: %%=v(@city)=%%

A: In my experience, using a lookup table is a cleaner, less confusing way to avoid dozens of IF statements.  However, if you can't or don't want to; try IndexOf(). The code below has been tried and tested.
I don't have any city codes, but let's pretend these are some. The spaces in between the codes serve as delimiters (you could use almost any symbol, as long as it's not in ANY of the codes).  IndexOf() brings back the number at which the code appears. If a number greater than zero is returned, the code was found. If a zero is returned, then the code was not found.
SET @MyCityCode = "FD0"

SET @ListOfCodes =  " AF2 AG2 AH2 AI2 AJ2 AK2 BF2 BG2 BH2 BI2 BJ2 BK2 CF2 CG2 CH2 CI2 CJ2 CK2 FA0 FB0 FC0 FD0 FE0 FF0 FG0 FH0 FI0 FJ0 FK0 "

IF  IndexOf(@ListOfCodes, @MyCityCode) > 0  THEN
   /* My city is in the list */
ELSE
   /* My city is NOT in the list */
ENDIF


text:
Q: M2: How to give the product a "ready for shipment" duration? I have products with a different shipping duration. How can I make it this visible on the product page. At the moment I only find a option to give the customer the information product is "in stock" or "out of stock".
How can I give the information "ready for shipment in 3/10/14 days" for each product?
Thank you
Regards

A: You need to do customization for this. You can create attribute and can add message-text in attribute like : ready for shipment in 3/10/14 days.
One more option to create attribute with date range. On this you can customize when to display this attribute but you need to do customize for this option.


text:
Q: What does "solutions in need of problems" mean? Can anybody explain it for me, please? I know what "in need of" means, but I am confused with the whole phrase. http://www.macmillandictionary.com/dictionary/british/in-need-of-something
"Silicon Valley is criticized for creating solutions in need of problems, showering consumers with referral codes and discounts to gain traction. Entrepreneurs don't have that luxury in secondary and tertiary cities, where typical consumers have different mindsets and needs from their coastal, urban counterparts. For the "rest of America," immediate practicality matters just as much as long-term vision."
Source: https://venturebeat.com/2017/05/22/the-trick-to-a-successful-company-start-it-outside-silicon-valley/?google_editors_picks=true

A: The definition of solution in this context is an instance or method of solving a problem (Definition 3 here http://www.dictionary.com/browse/solution).
Usually, therefore, a problem comes first, then a solution for that problem is found afterwards. However, if you say that someone has "solutions in need of problems", you are saying that they have come up with a "solution" to a problem that doesn't exist. In your context it is saying that a product does something that is not (at least immediately) useful; that the "problem" it purports to "solve" is in fact not a problem at all.


text:
Q: how to use the return type of "fgetc" blow the code? #include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}

here in the code,the fgetc(fp) use the int as this return type,so why we use "printf("%c",c);" rather than "print("%d",c);"

A: In a printf format string, %c means "convert the int argument to an unsigned char and print the character it is the code for."
%d means "convert the int argument to a decimal numeral and print that numeral."

A: %c will print it as a character
%d will print it as a decimal representation.
Example:
void printAsChar(const char *x)
{
    while(*x)
    {
        printf("%c\n", *x++);
    }
}

void printAsDecimal(const char *x)
{
    while(*x)
    {
        printf("%d\n", *x++);
    }
}

int main(void)
{
    printAsChar("hello");
    printf("------------\n");
    printAsDecimal("hello");
}

https://godbolt.org/z/rx8oqaMnT
result:
h
e
l
l
o
------------
104
101
108
108
111

104 is an ASCII code of 'h', 101 code of 'e' etc


text:
Q: what is difference between /etc/shadow and /etc/passwd Both files /etc/shadow and /etc/passwd seem to be the same, they just report some information about accounts. What is the difference between them?

A: From The Linux Documentation Project - 6.6. Linux Password & Shadow File Formats:

Traditional Unix systems keep user account information, including
one-way hashed passwords, in a text file called /etc/passwd. As this
file is used by many tools (such as ls) to display file ownerships,
etc. by matching user id #'s with the user's names, the file needs to
be world-readable. Consequentally, this can be somewhat of a security
risk.
Another method of storing account information, one that I always use,
is with the shadow password format. As with the traditional method,
this method stores account information in the /etc/passwd file in a
compatible format. However, the password is stored as a single "x"
character (ie. not actually stored in this file). A second file,
called /etc/shadow, contains encrypted password as well as other
information such as account or password expiration values, etc. The
/etc/shadow file is readable only by the root account and is therefore
less of a security risk.

A: Short answer:
passwd stores general user info and shadow stores user passwd info.
Somewhat longer answer:
passwd is the file where the user information (like username, user ID, group ID, location of home directory, login shell, ...) is stored when a new user is created.
shadow is the file where important information (like an encrypted form of the password of a user, the day the password expires, whether or not the passwd has to be changed, the minimum and maximum time between password changes, ...) is stored when a new user is created.
Some interesting extra info: passwd and shadow

A: /etc/shadow
file stores actual password in encrypted format for user's account with additional properties related to user password i.e. it stores secure user account information. All fields are separated by a colon (:) symbol FOR MORE
/etc/passwd
file stores essential information, which is required during login i.e. user account information. /etc/passwd is a text file, that contains a list of the system's accounts, giving for each account some useful information like user ID, group ID, home directory, shell, etc. FOR MORE


text:
Q: Is there any way to tell if any givin Number will either blow up or tend towards a Value when squared? Ok so as a Set Up, i want to do the all time classy, the Mandelbrot set. As far as i know, the equation
$$Z \rightarrow Z²+C$$
Just asks the question "Ok givin any Complex Number, if you Square the Non Complex terme and then Add the Complex compnent, is this new number something REALLY huge or does it tend towards a Value ?
Of course, normaly this Equation is based on Iterations so you do that a bunch of times and bam, either your Value is huge for small.
But, there is sort of a Problem for me. At the moment, my code spits out this:Image
I dont want to be a downer but that doest really look right. My guess is that the Problem is how huge the values get once you square them a few times. And since Computers are pretty dumb, at some point Values might switch from Positive to negative and so on.
So, to the question, please tell me there is a fancy Algorithm that can just tell me if Z will be huge or small D:
Thanks !

A: The 'normal' Mandelbrot set is derived by plotting the values of $c \in \mathbb C$ such that the sequence $z_{n+1} = z_n^2 + c, z_0 = 0$ remains bounded.
You can verify the sequence diverges when either (a) $|c| > 2$, or, (b), when $|c| \leqslant 2$, and at some stage $|z_n| > 2$.  This allows you to determine when to stop testing the $z_n$.
I don't believe there is any shortcut other than simply trying repeatedly to check on which $c$ led to divergence or not.
Using standard double arithmetic you can create reasonable images as illustrated (1)

or (2)


text:
Q: \endscname error using package matlab-prettifier I'm trying to prepare a beamer document using the matlab-prettifier package but I come across errors whenever I include a frame where I use code. I always get the following log:
! Missing \endcsname inserted.
<to be read again>
               \relax
l.2 ...atlab-editor, basicstyle=\mlttfamily,\tiny]

The control sequence marked <to be read again> should
not appear between \csname and \endcsname.

! Extra \endcsname.
\KV@split ...csname \KV@prefix \@tempa \endcsname
                                              \ifx \@tempc \relax \KV@er...
l.2 ...atlab-editor, basicstyle=\mlttfamily,\tiny]

I'm ignoring this, since I wasn't doing a \csname.

! Package keyval Error: \relax \fontsize {6}{7}\selectfont  undefined.

Here's a minimal example:
\documentclass{beamer}
\usepackage[T1]{fontenc}
\usepackage[framed,numbered]{matlab-prettifier}

\begin{document}

\begin{frame} [fragile]
\frametitle{STEP 2: Parameters extraction - application}
\begin{lstlisting}[style=Matlab-editor, basicstyle=\mlttfamily,\tiny]
par_out.T(1:r, 1:r*p)    = Eaa_FB(1:r, :)/Eaa_BB;
par_out.Q(1:r, 1:r)      = (Eaa(1:r, 1:r) - par_out.T(1:r,
1:r*p)*Eaa_FB(1:r, :)')/m;
par_out.P0(1:r*p, 1:r*p) = Ps(1:r*p, 1:r*p, 1);

%% Idiosyncratic components
% Get kalman output and initialise estimation
for i=1:n
ind_start  = r*p+1+(i-1)*q;
ind_vec    = ind_start:ind_start+q-1;
as_i       = as(ind_vec, :);
Ps_i       = Ps(ind_vec, ind_vec, :);
PPs_lag1_i = PPs_lag1(ind_vec, ind_vec, :);
as_i_t     = as_i(:, 2:end);
as_i_t_1   = as_i(:, 1:end-1);
end
\end{lstlisting}
\end{frame}

\end{document}

A: Your problem is a simple comma that is not allowed there. Just use \mlttfamily\tiny.
\documentclass{beamer}
\usepackage[framed,numbered]{matlab-prettifier}

\begin{document}

\begin{frame} [fragile]
\frametitle{STEP 2: Parameters extraction - application}
\begin{lstlisting}[style=Matlab-editor, basicstyle=\mlttfamily\tiny]
par_out.T(1:r, 1:r*p)    = Eaa_FB(1:r, :)/Eaa_BB;
par_out.Q(1:r, 1:r)      = (Eaa(1:r, 1:r) - par_out.T(1:r,
1:r*p)*Eaa_FB(1:r, :)')/m;
par_out.P0(1:r*p, 1:r*p) = Ps(1:r*p, 1:r*p, 1);

%% Idiosyncratic components
% Get kalman output and initialise estimation
for i=1:n
ind_start  = r*p+1+(i-1)*q;
ind_vec    = ind_start:ind_start+q-1;
as_i       = as(ind_vec, :);
Ps_i       = Ps(ind_vec, ind_vec, :);
PPs_lag1_i = PPs_lag1(ind_vec, ind_vec, :);
as_i_t     = as_i(:, 2:end);
as_i_t_1   = as_i(:, 1:end-1);
end
\end{lstlisting}
\end{frame}

\end{document}


text:
Q: How to dynamically change content inside Modal Bottomsheet android I have a Bottomsheet xml which contains two elements, Follow and Copy link.. when I click on Follow, it should be changed to Unfollow dynamically. I tried using setText, not worked.
Please guide me how to change text of bottomsheet dialogues.
Here is my Bottomsheet xml file
<LinearLayout app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_width="match_parent"
android:layout_height="180dp"
android:orientation="vertical"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
    android:id="@+id/bottom_sheet_follow"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:clickable="true"
    android:focusable="true"
    android:orientation="horizontal"
    android:foreground="?android:attr/selectableItemBackground"
    android:padding="16dp">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/ic_mode_follow_grey_24dp"
        />
    <TextView
        android:id="@+id/followTView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="16dp"
        android:text="Follow"/>
</LinearLayout>
<LinearLayout
    android:id="@+id/bottom_sheet_copy"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:clickable="true"
    android:focusable="true"
    android:orientation="horizontal"
    android:foreground="?android:attr/selectableItemBackground"
    android:padding="16dp">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/ic_copy_grey_24dp"
        />
    <TextView
        android:id="@+id/copyLink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="16dp"
        android:text="Copy link"/>
</LinearLayout>

Bottomsheet Java code
    View bottomSheetView = View.inflate(mContext, R.layout.bottom_sheet_dialog_for_sharedposts, null);

            mDialog = new BottomSheetDialog(mContext);
            mDialog.setContentView(bottomSheetView);
            mDialog.show();

followBtnLayout = bottomSheetView.findViewById(R.id.bottom_sheet_follow);
followTView = bottomSheetView.findViewById(R.id.followTView);

followBtnLayout .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    followTView.setText("Unfollow");
}
});

But, the Follow Textview (I mean followTView) is not changing to Unfollow.
Please tell me where I have gone wrong...
Thanks in advance...

A: You can do it with boolean i have done it with my imageview.
Might help you
 //Initialize boolean as true by default
   public boolean showingFirst = true;

  holder.ivFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showingFirst){
                    Toast.makeText(mActivity, "Item added to favorite", Toast.LENGTH_SHORT).show();
                    holder.ivFavorite.setImageResource(R.drawable.filled_heart);
                    showingFirst = false;
                }else {
                    holder.ivFavorite.setImageResource(R.drawable.ic_favorite);
                    Toast.makeText(mActivity, "Item removed from favorite", Toast.LENGTH_SHORT).show();
                    showingFirst = true;
                }

            }
        });

A: Just a guess. Did you try to re-arrange the code? maybe the the click listener should load first before calling "mDialog.show()".
 View bottomSheetView = View.inflate(mContext, R.layout.bottom_sheet_dialog_for_sharedposts, null);

        followBtnLayout = bottomSheetView.findViewById(R.id.bottom_sheet_follow);
        followTView = bottomSheetView.findViewById(R.id.followTView);

        followBtnLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followTView.setText("Unfollow");
            }
        });

        mDialog = new BottomSheetDialog(mContext);
        mDialog.setContentView(bottomSheetView);
        mDialog.show();


text:
Q: Subtraction of perpendicular vectors Okay, so I'm reading a proof which shows that the dot product of two perpendicular vectors is 0.
I am kinda confused by the beginning of the proof, the part where it says that for two perpendicular vectors v and w, the hypotenuse is v-w. Why is this so? Am I drawing the sketches for addition and subtraction incorrectly?
The Figure 1.7 shows that the hypotenuse is the addition of the two vectors, but the proof says that it's the subtraction.
Of course, if the hypotenuse is represented as v+b the proof wouldn't stand
What am I doing wrong?

A: Your sketch shows perfectly that the hypotenuse is what the author claims it is. The problem is that you are on a vector space, so every vector is pinned to the origin (otherwise you would be working on an affine space). This may be the confusion point. When the author says that the third side is $v-w$, he or she means that this side corresponds to the vector $v-w$ (which is necessarily pinned at the origin) translated to some position in the affine plane.
The hypotenuse of the right triangle defined by $v$ and $w$ has in any case the same direction as $v-w$ (and not the same direction as $v+w$). Note that $w-v$ would also work, which is something you should expect (since the roles of $v$ and $w$ are symmetric).


text:
Q: apache2 is not running on 14.04 I install LAMP in my Ubuntu 14.04 But when I use (sudo apache2ctl status | grep version) command it returns:
/usr/sbin/apache2ctl: 101: /usr/sbin/apache2ctl: www-browser: not found
'www-browser -dump localhost:80/server-status"' failed.
Maybe you need to install a package providing www-browser or you
need to adjust the APACHE_LYNX variable in /etc/apache2/envvars

What can I do?

A: Here is a link to an answer that helped me. I am running 14.04 and had to install the command-line browser links to get rid of this error:
sudo apt-get install links


text:
Q: CSS Animation Timing Function with steps() to try to blink colors, but colors are blending I've been trying to blink two colors, using the following CSS rules but the colors just ends up blending.
Here is the jsfiddle: http://jsfiddle.net/1kyba3rd/
Here are the CSS rules:
<style>
    .block {
        width: 100px;
        height: 100px;
        border: 1px solid black;

        /* Chrome, Safari, Opera */
        -webkit-animation-name: flash-colors;
        -webkit-animation-duration: 1s;
        -webkit-animation-timing-function: steps(2, start);
        -webkit-animation-iteration-count: infinite;
        /* Standard Syntax */
        animation-name: flash-colors;
        animation-duration: 1s;
        animation-timing-function: steps(2, start);
        animation-iteration-count: infinite;
    }
    /* Chrome, Safari, Opera */
    @-webkit-keyframes flash-colors {
        0% {
            background-color: white;
        }
        100% {
            background-color: yellow;
        }
    }
    /* Standard syntax */
    @keyframes flash-colors {
        0% {
            background-color: white;
        }
        100% {
            background-color: yellow;
        }
    }
</style>

A: the blinking is not working properly because you have set background-color:yellow at the end of the animation (100%) and the background-color:white at the beginning, set first one at 50% so that the animation works as expected - demo


text:
Q: Ignore "This Workbook Contains Links to Other data Sources" I am opening a file in VBA and want to ignore the above message after my file opens through the code. That is I don't want to update the file and want to continue running the code . How can I do it? I am opening multiple file and I need to wait for every file to display that, instead I thought I can do it through code.
filter = "Text files (*.xls*),*.xls*"
Caption = "Please Select the a file"
Ret = Application.GetOpenFilename(filter, , Caption)
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)

Application.displayAlerts=False does not work for this. Is there anyway to manage it? Thanks.

A: Try This:
Private Sub Workbook_Activate()
   Application.AskToUpdateLinks = False

End Sub

source


text:
Q: HTTP server and version within Python using socket library import socket

I'm wondering how to get the web servers name and version for the Server response header for an HTTP server using the socket library:
Server: Apache/2.2.3 (Red Hat)

A: You probably want to grab the banner which is presented on the interesting ports of a server. For a lot of cases all you need is something like the following:
import sys
import socket

ip = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket()

s.connect((ip, port))
print s.recv(1024)

Since you mention Apache (httpd), I assume you would be interested in port 80 for HTTP and port 443 for HTTPS, but honestly httpd could listen to any port. Since these are speaking HTTP(S) (a protocol which sits atop TCP) they will want a request to serve before responding to you, in this case you would need to send a valid HTTP request. The bare minimum is GET / HTTP/1.0\r\n\r\n so in that case you would need something like this:
import sys
import socket

ip = sys.argv[1]
port = int(sys.argv[2])

s = socket.socket()

s.connect((ip, port))
s.send("GET / HTTP/1.0\r\n\r\n")
print s.recv(1024)

Notice the send before the recv.
You would run that script like so:
$ python grab_banner.py <IP_ADDRESS> <PORT>
HTTP/1.1 200 OK
Date: Sat, 24 Oct 2015 03:12:31 GMT
Server: Apache/2.4.16 (Fedora)
Last-Modified: Sat, 24 Oct 2015 03:06:19 GMT
ETag: "17-522d1031eac3e"
Accept-Ranges: bytes
Content-Length: 23
Connection: close
Content-Type: text/html; charset=UTF-8

Hello, World!

All of that being said if this isn't just an exercise in Python and socket programming you may wish to check out nmap as it does a wonderful job of everything you seem to be doing, it's  fast and has many options (some are pretty advanced, but google can help here).
$ sudo yum install nmap
...
$ nmap -sV google.com

Starting Nmap 6.47 ( http://nmap.org ) at 2015-10-23 22:45 EDT
Nmap scan report for google.com (204.186.215.24)
Host is up (0.013s latency).
Other addresses for google.com (not scanned): 204.186.215.38 204.186.215.39 204.186.215.46 204.186.215.45 204.186.215.32 204.186.215.59 204.186.215.31 204.186.215.18 204.186.215.25 204.186.215.53 204.186.215.52
rDNS record for 204.186.215.24: cache.google.com
Not shown: 998 filtered ports
PORT    STATE SERVICE  VERSION
80/tcp  open  http     Google httpd 2.0 (GFE)
443/tcp open  ssl/http Google httpd 2.0 (GFE)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 23.02 seconds

Note the -sV enables server and version checking. Also note that you may not want to hit google with this too many times as they might get very curious.


text:
Q: How do you do an IN or CONTAINS in LINQ using LAMBDA expressions? I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling.
SELECT * FROM Project
WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155')

Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible.
Thanks in advance!

A: GFrizzle beat me to it. But here is a C# version
var projectsMemberWorkedOn = from p in Projects
                    join projectMember in ProjectMembers on
                        p.ProjectId equals projectMember.ProjectId
                    where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155"
                    select p;

And as a bonus a purely LINQ method chain version as well:
var projectsMemberWorkedOn =
            Projects.Join( ProjectMembers, p => p.ProjectId, projectMember => projectMember.ProjectId,
                ( p, projectMember ) => new { p, projectMember } )
                .Where( @t => @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" )
                .Select(@t => @t.p );

A: In this context, you can just use .Contains(), something like this:
var projects =
from p in db.Projects
where db.ProjectMembers.Where(m => m.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155").Select(pp => pp.ProjectID).Contains(p.ProjectID)
select p;

A: No need for a lambda, you've just got a simple LINQ join here:
From p in db.Projects _
Join m in db.ProjectMember On p.ProjectId Equals m.ProjectId _
Where m.MemberId = "a45bd16d-9be0-421b-b5bf-143d334c8155" _
Select p

A: You probably want the Any() operator:
var q = db.Projects
          .Where(p => db.ProjectMembers
                        .Where(pm => pm.MemberId == memberId)
                        .Any  (pm => p.ProjectId == pm.ProjectId));

Since the result set of db.ProjectMembers.Where(...) will always be the same, you can split it up so that it's executed only once:
var projectMembers = db.ProjectMembers.Where(pm => pm.MemberId == memberId);
var q              = db.Projects
                       .Where(p  => projectMembers
                                    .Any(pm => p.ProjectId == pm.ProjectId));


text:
Q: What is best practice for retrieving a single object from database? So I have my database on MongoDB and it is stored in state via Redux, for when I want to view a single item or load a single item for updating what is the best practice for retrieving it?
currently I have it set up with hash location in the URL and adding item ID in the URL and then retrieving the ID and checking to make sure it is found before loading data/error
const recipeId = window.location.hash.substr(1);
  const recipe = useSelector((state) =>
    state.recipes.find((r) => r._id === recipeId)
  );

my reducer
const reducer = (recipes = [], action) => {
  switch (action.type) {
    case "FETCH_ALL_RECIPES":
      return action.payload;
    case "CREATE_RECIPE":
      return [...recipes, action.payload];
    default:
      return recipes;
  }
};

export default reducer;


text:
Q: How to get return value in my html file calling async javascript function in another file? I have my index.html file with a simple form
Update
<form onSubmit=" App.estraiVincitore().then(value => { alert (value)}); return false;">
    <input type="submit" value="Get Winner">
    <input type="text" name="winner">
 </form>

I have a App.js file with an async function that works properly getting an event transaction.
estraiVincitore: async() => {
  await App.vincitoreDelContest.estrazioneVincitore().then(function (value) {
      console.log(value.logs[0].args.username);
      return value.logs[0].args.username;   //returned value to show in my index.html

  });

How can I get the returned valued from my JavaScript function and shows it in my index.html?
Properly I would like to show it in my text area.
Thanks a lot.

A:
How can I get the returned valued from my JavaScript function and shows it in my index.html?

By using the promise that estraiVincitore returns in JavaScript code in the index.html file. An async function returns a promise; later, that promise is settled (fulfilled with a value, or rejected with a "reason" [error]).
So for instance:
App.estraiVincitore()
.then(value => {
    document.querySelector("selector-for-your-text-area").value = value;
})
.catch(error => {
    // ...handle/report the error...
});

Re Felix's point, the purpose of async/await is to make it possible to use promises with simple logical flow constructs rather than callbacks. So:
estraiVincitore: async() => {
  const value = await App.vincitoreDelContest.estrazioneVincitore();
  console.log(value.logs[0].args.username);
  return value.logs[0].args.username;
}

Which is (basically) equivalent to this non-async function:
estraiVincitore: () => {
  return App.vincitoreDelContest.estrazioneVincitore().then(value => {
      console.log(value.logs[0].args.username);
      return value.logs[0].args.username;
  });
}


text:
Q: Converting strings to char arrays using cstring I have a small assignment which partly requires me to take inputs from a file in the form of strings and place them into char arrays so I can check if the string contains any '*' character at the end of it.
I have been able to extract the strings from the files successfully, however i have failed to find a way in which to place them in char arrays so i can process them.
I would be very grateful if someone would let me know how to place a string into char arrays using cstring library. Please keep in mind that the strings are taken from a file and not as user input.
some of the ways i tried is the following:
//Try 1
char CstringArray[] = LineFromFile;

//Try 2
char CstringArray[100] = LineFromFile;

//Try 3
ifstream Test("Test.txt");
Test>>CstringArray;

//Try 4
ifstream Test("Test.txt");
Test>>CstringArray[0];

Thank you very much

A: Since this is an assignment, your professor will probably not be happy with you using all of C++'s functionality, particularly if you don't understand it, but since it's a one liner I figured I'd tell you how I'd print all strings ending in an asterisks. Given that you have successfully opened the file to ifstream Test you can do:
copy_if(istream_iterator<string>(Test), istream_iterator<string>(), ostream_iterator<string>(cout, " "), [](const auto& i) { return !empty(i) && i.back() == '*'; })

EDIT:

*

*I'm using an istream_iterator to read in each string in Test and istream_iterator, I'm operating on these values immediately, but if you needed to start by saving all the strings to a vector<string> you could also do this: vector<string> CstringArray{ istream_iterator<string>(Test), istream_iterator<string>() }

*I'm using an ostream_iterator to directly stream out my selected strings rather than storing them

*I'm using copy_if to iterate over all the strings that are streamed in, selecting only those that meet a given criteria

*I'm using the lambda: [](const auto& i) { return !empty(i) && i.back() == '*'; } to conditionally select non-empty strings which end with an asterisks character


text:
Q: How to log fully detailed XMPP message sent and received by Prosody IM I try to analyze a problem related to XMPP. I have two server components joined the same MUC room on Prosody IM (it's hard to make my application to print those XMPPs they received/sent , i'm using jitsi jicofo and jitsi jigasi).
So, I was wondering if it is possible to print detailed XMPP messages sent/received in MUC.
My prosody logging configuration is as below:
log = {
        { levels = {min = "debug"} , to = "console"};
}

Above configuration gave me log output as follows:
c2s55b17ab56330                                         debug   Received[c2s]: <presence type='unavailable' id='AwXwU-149' to='123456789@conference.example.com/448ddea4'>
conference.example.com:muc                              debug   session qvagnu083x5-bl78@example.com/tYARglho is leaving occupant 123456789@conference.example.com/448ddea4
c2s55b17b2a8300                                         debug   Sending[c2s]: <presence from='123456789@conference.example.com/448ddea4' id='AwXwU-149' type='unavailable' to='tiqmjoyi7d3rr69-@example.com/9W3u-kLN'>
c2s55b17ae40d40                                         debug   Sending[c2s]: <presence from='123456789@conference.example.com/448ddea4' id='AwXwU-149' to='focus@auth.example.com/focus32210095996901258' type='unavailable' xmlns='jabber:client'>
c2s55b17ab56330                                         debug   Sending[c2s]: <presence from='123456789@conference.example.com/448ddea4' id='AwXwU-149' type='unavailable' to='qvagnu083x5-bl78@example.com/tYARglho'>
c2s55b17ae40d40                                         debug   Received[c2s]: <iq type='set' id='1hORO-3097' to='123456789@conference.example.com/448ddea4'>
c2s55b17ae40d40                                         debug   Sending[c2s]: <iq from='123456789@conference.example.com/448ddea4' type='error' id='1hORO-3097' to='focus@auth.example.com/focus32210095996901258'>

Let's take line #3 above for example.
Prosody IM printed Sending[c2s]: <presence from='123456789@conference.example.com/448ddea4' id='AwXwU-149' type='unavailable' to='tiqmjoyi7d3rr69-@example.com/9W3u-kLN'> .
However, the full XMPP message is:
<presence from='123456789@conference.example.com/448ddea4' id='AwXwU-149' to='tiqmjoyi7d3rr69-@example.com/9W3u-kLN' type='unavailable'
    xmlns='jabber:client'>
    <x
        xmlns='http://jabber.org/protocol/muc#user'>
        <item role='none' jid='qvagnu083x5-bl78@example.com/tYARglho' affiliation='none'/>
    </x>
</presence>

My problem is how can I optimize the logging configuration for Prosody IM to get fully detailed XMPP message as above.
And I have checked their documents:

*

*Advanced logging configuration

*Logging
Found nothing on this topic.
Thanks in advance.

A: Well, I finally figured out how to log fully detailed XMPP message in Prosody IM.
You will need mod_stanza_debug to achieve this.
From Prosody IM website:
This module logs full stanzas to the debug log for the purposes of debugging.

It has been bundled in Prosody Installation. Just enable it by editing modules_enabled entry in Prosody global configuration file:
modules_enabled = {

        -- debug stanza
        "stanza_debug";

};

And finally , I can get the fully detailed XMPP message:
2021-09-01 12:10:51 c2s5577181821d0  debug    Sending[c2s]: <presence xmlns='jabber:client' from='123456789@conference.example.com/01f9f60c' to='jw5c6zuqagigmxyc@example.com/P2Z4rvii' id='Y81Xr-178'>
2021-09-01 12:10:51 c2s5577181821d0  debug    SEND: <presence xmlns='jabber:client' from='123456789@conference.example.com/01f9f60c' to='jw5c6zuqagigmxyc@example.com/P2Z4rvii' id='Y81Xr-178'><info os='l' v='13204'/><role role='participant'/><transcription-status status='OFF'/><nick xmlns='http://jabber.org/protocol/nick'>Transcriber</nick><stat name='version' value='Jigasi 1.1.SNAPSHOT'/><features xmlns='http://jabber.org/protocol/disco#info'><feature var='http://jitsi.org/protocol/jigasi'/><feature var='urn:xmpp:jingle:dtmf:0'/></features><c hash='sha-1' xmlns='http://jabber.org/protocol/caps' node='http://jitsi.org' ver='qo0cQuyj88ya15Au4O5PVYxqmqA='/><x xmlns='http://jabber.org/protocol/muc#user'><item affiliation='none' role='participant' jid='tfccagysjks6zjon@example.com/7XCp5aWX'/></x></presence>
2021-09-01 12:10:51 c2s557717e02950  debug    Sending[c2s]: <presence xmlns='jabber:client' from='123456789@conference.example.com/01f9f60c' to='focus@auth.example.com/focus32236264938572098' id='Y81Xr-178'>
2021-09-01 12:10:51 c2s557717e02950  debug    SEND: <presence xmlns='jabber:client' from='123456789@conference.example.com/01f9f60c' to='focus@auth.example.com/focus32236264938572098' id='Y81Xr-178'><info os='l' v='13204'/><role role='participant'/><transcription-status status='OFF'/><nick xmlns='http://jabber.org/protocol/nick'>Transcriber</nick><stat name='version' value='Jigasi 1.1.SNAPSHOT'/><features xmlns='http://jabber.org/protocol/disco#info'><feature var='http://jitsi.org/protocol/jigasi'/><feature var='urn:xmpp:jingle:dtmf:0'/></features><c hash='sha-1' xmlns='http://jabber.org/protocol/caps' node='http://jitsi.org' ver='qo0cQuyj88ya15Au4O5PVYxqmqA='/><x xmlns='http://jabber.org/protocol/muc#user'><item affiliation='none' role='participant' jid='tfccagysjks6zjon@example.com/7XCp5aWX'/></x></presence>


text:
Q: Getting "object variable or with block variable not set in excel vba" Sheets("Translator 2 Weeks").Select
today = Date - 15
Dim MyRange As Range, cl As Range
Set MyRange = Range("a2").CurrentRegion
lRow = Cells(Rows.Count, 1).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
lCol = lCol + 1

For Each cl In MyRange

 If ActiveCell.Column <= lCol Then
 If ActiveCell.Row <= lRow Then

Cells.Find(What:="*", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
    , SearchFormat:=True).Activate

    If cl.Value <> Empty And IsDate(cl.Value) Then
    N = N + 1
    End If

End If

End If
Next cl

Getting error at line "Cells.Find()" Please help...
I am trying to find out the N number of cells used and only cells populated with date.


text:
Q: Wired Network Does not Connect on first Boot I am having a problem with one of my desktop computers not connecting to the wired network when I first turn it on in the morning.  After a restart, the wired network works fine. Any suggestions I could try to get this working?
Thanks!

A: I don't know if this will be of any help. Just a thought...
Do you switch on your Internet connection just before switching on your computer? Sometimes, it can take a cable/broadband modem/router as much as two-three minutes to start completely. If this is the case, then switch on your Internet connection and wait for some time before starting your computer.


text:
Q: Installing .msi remotely without powershell? We have a multi server system that we need to install at a client site. I would like to put together a script that can:

*

*Turn off services on remote machines

*Uninstall software on several remote machines

*Install .msi files several remote machines

I've struggled with psexec and wmic to do points #2 and #3.
It seems like there has to be an easier way without having to resort to PowerShell.

A: First, see this thread for WSH Remoting: Remote Install on Windows Server 2012 R2.
Then, you can perhaps you can try to use a VBScript library such as that available in VbsEdit (I don't like to make software recommendations, but I assume it is allowed since I am not affiliated and want to suggest it to solve the problem):
Here is a script to install software remotely:
' Install Software on a Remote Computer
Const wbemImpersonationLevelDelegate = 4

Set objWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objConnection = objwbemLocator.ConnectServer _
    ("WebServer", "root\cimv2", "fabrikam\administrator", _
         "password", , "kerberos:WebServer")
objConnection.Security_.ImpersonationLevel = wbemImpersonationLevelDelegate

Set objSoftware = objConnection.Get("Win32_Product")
errReturn = objSoftware.Install("\\atl-dc-02\scripts\1561_lab.msi",,True)

Here is a script to stop services:
' Stop Services Running Under a Specific Account
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colServices = objWMIService.ExecQuery _
    ("Select * from Win32_Service Where StartName = '.\netsvc'")

For Each objService in colServices
    errReturnCode = objService.StopService()
Next

Here is a screen shot from VbsEdit's script library:


text:
Q: I want to write javascript code to get a addition countdown so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));

while (num > 0){

    first = num;

    second = num-=1;

    document.write(first +  " +" + second + " +");

    value = first + num;

    document.write(value)
    num--;
}

but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!

A: You could change the algorithm a bit, because for the first value, you need no plus sign for the output.

var num = Number(prompt("Enter a Number Greater than zero")),
    value = 0;

document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
    document.body.appendChild(document.createTextNode(' + ' + num));
    value += num;
    num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

A: You can keep total in one variable outside of while loop.

var num = Number(prompt("Enter a Number Greater than zero"));

var total = 0;
while (num > 0) {
  total += num;
  document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
  num--;
}


text:
Q: How to parse dynamic object in mvc? I am working on ASP.NET MVC4.0.
My string is posting like this from view :-
[{"name":"AddressNumber","value":"1"},{"name":"OrganizationProd","value":""},{"name":"ClientId","value":""},{"name":"ProductId","value":""},{"name":"TaxId1","value":""},{"name":"TaxId2","value":""},{"name":"LaborID","value":"0"}]

And below is my controller's action method for that,which is receiving the input :-
[AllowAnonymous]
[HttpPost]
public ActionResult UpdateProducts(string ModelString){
}

And below is the string which i am getting in action(in ModelString variable):-
[{"name":"AddressNumber","value":"1"},{"name":"OrganizationProd","value":""},{"name":"ClientId","value":""},{"name":"ProductId","value":""},{"name":"TaxId1","value":""},{"name":"TaxId2","value":""},{"name":"LaborID","value":"0"}]

And after that i am deserializing the string like that :-
var sear = new JavaScriptSerializer();
var dictDynamic = sear.Deserialize<dynamic>(ModelString);

And i am getting the dynamic array in dictDynamic variable.And now i want to get the properties by its name not by indexing from dictDynamic object.
Currently i am getting the properties by indexing like this :-
dictDynamic[0]["value"]
dictDynamic[1]["value"]

But i want to parse it by properties name like this :-
dictDynamic["Name"]["value"]
dictDynamic["Description"]["value"]

Can anyone help me out on this ?

A: You could use ViewModel on server side, not sending model string.
You create ViewModel like this:
class ProductViewModel {

   public int AddressNumber { get; set; }
   public int ProductId { get; set; }
     ...
}

Then change your controller method:
[AllowAnonymous]
[HttpPost]
public ActionResult UpdateProducts(ProductViewModel vm){
  ...
}

And from your View you'll send json object like this:
{
   "AddressNumber":"10",
   "OrganizationProd":"1",
   "ClientId":"1",
   "ProductId":"1",
   "TaxId1":"23",
   "TaxId2":"23",
   "LaborID":"10"
}

This will automaticaly bind your values from View to ViewModel on controller, and you can than use ViewModel object in your code, and you then have strongly typed entity.
Instead of this:
dictDynamic["AddressNumber"]
dictDynamic["OrganizationProd"]

now you can write this:
vm.AddressNumber
vm.OrganizationProd

A: You need to pass a JavaScript object to your function instead of an array. Array is not the correct data structure to use in this case. Objects have keys and values. The keys will be AddressNumber, OrganizationProd, ClientId, ProductId, TaxId1 etc. Their values will be 1, "", "0" etc.
For instance, for your example, this will be your object:
{
   "AddressNumber":1,
   "OrganizationProd":"",
   "ClientId":"",
   "ProductId":"",
   "TaxId1":"",
   "TaxId2":"",
   "LaborID":0
}

You deserialize it like you do now:
var s = "{\"AddressNumber\":1, \"OrganizationProd\":\"\", \"ClientId\":\"\", \"ProductId\":\"\", \"TaxId1\":\"\", \"TaxId2\":\"\", \"LaborID\":0}";
var sear = new JavaScriptSerializer();
var dictDynamic = sear.Deserialize<dynamic>(s);

Once you deserialize, you will be able to reference the values like this:
dictDynamic["AddressNumber"]
dictDynamic["OrganizationProd"]


text:
Q: Opening shell files via Terminal (default application) Currently in Ubuntu 16.04 and can't open Shell files with terminal (as the default program). I can make them run normally with sh after directing to the directory; however always used to be able to "Execute in terminal".
Any helps would be appreciated. Thanks!

A: Most probably, there are a few things to check :
Make sure you are running your shell file on a way that lets understand to your terminal that it is a file that is stored in the current folder. For instance, if the filename of your script is myscript.sh, do not type myscript.sh but ./myscript.sh. If you don't, the terminal would think that the script is in an other place, such as
/bin/
/usr/bin
/usr/sbin
/sbin

the most of the time, concerning installed or system commands. The dot refers to current folder, whereas two dots (..) refer to parent folder.
The other point you can check, is that you have the permission to execute the file. If you are running Ubuntu, right click on your file -> properties -> permissions -> check "Allow execution as a programm".
I'm not sure, but you may also need to begin you script with following line : #!/bin/sh, altough I've already used script without such a header line.