text:
Q: Wait until first BackgroundWorker is finished before running the second Worker I want to make a "Checklist" of my Installation:
1st Create Table
2nd Add PrimaryKey
3rd Set AutoIncrement
4th InsertData

So I made 4 BackgroundWorkers because of using an Loading Animation for each step:
[X] Create Table (Finished)
[...] Add Primary Key (In process)
[ ] Set AutoIncrement (Didn't loaded yet)
[ ] InsertData (didn't loaded yet)

The thing is, that the Code will not wait until the First BackgroundWorker is finished before running the second one.
This is the Code I have for now:
if (result == MessageBoxResult.Yes)
{
    DialogHostLoading.IsOpen = true;
    if (worker.IsBusy)
        {
            worker.CancelAsync();
            worker.RunWorkerAsync();
            MessageBox.Show("IsBusy");
        }
        else
        {
            if(!isError)
            {
                #region CreateTable
                tableIcon.Visibility = Visibility.Collapsed;
                tableIconLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("CreateTable");
                #endregion

                #region SetPrimaryKey
                setPrimaryKeyIcon.Visibility = Visibility.Collapsed;
                setPrimaryKeyLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("SetPrimaryKey");
                #endregion

                #region SetAutoIncrement
                setAutoIncrementIcon.Visibility = Visibility.Collapsed;
                setAutoIncrementLoading.Visibility = Visibility.Visible;
                worker.RunWorkerAsync("SetAutoIncrement");
                #endregion

                // Close Dialog if finished without Errors
                DialogHostLoading.IsOpen = false;
                MessageBox.Show("Import erfolgreich.");
            }
            else
            {
                if(!string.IsNullOrEmpty(ErrorMessageString))
                {
                    MessageBox.Show(ErrorMessageString);
                    DialogHostLoading.IsOpen = false;
                    ErrorMessageString = string.Empty;
                }
                else
                {
                    Debug.WriteLine("isError = true BUT ErrorMessageString is null or empty");
                }

            }
        }

The DoWork are SQL Querys and now the RunWorkerCompleted Event:
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Result.GetType() == typeof(string))
    {
        Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
        Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");
        switch (e.Result)
        {
            case "CreateTable":
                if(string.IsNullOrEmpty(ErrorMessageString))
                {
                    tableIcon.Foreground = new SolidColorBrush(redColor);
                    tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle;
                    tableIconLoading.Visibility = Visibility.Collapsed;
                    tableIcon.Visibility = Visibility.Visible;
                    isError = true;
                }
                else
                {
                    tableIcon.Foreground = new SolidColorBrush(greenColor);
                    tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                    tableIconLoading.Visibility = Visibility.Collapsed;
                    tableIcon.Visibility = Visibility.Visible;
                }
                break;
            case "SetPrimaryKey":
                if(string.IsNullOrEmpty(ErrorMessageString))
                {
                    setPrimaryKeyIcon.Foreground = new SolidColorBrush(redColor);
                    setPrimaryKeyIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CloseCircle;
                    setPrimaryKeyLoading.Visibility = Visibility.Collapsed;
                    setPrimaryKeyIcon.Visibility = Visibility.Visible;
                    isError = true;
                }
                else
                {
                    setPrimaryKeyIcon.Foreground = new SolidColorBrush(greenColor);
                    setPrimaryKeyIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
                    setPrimaryKeyLoading.Visibility = Visibility.Collapsed;
                    setPrimaryKeyIcon.Visibility = Visibility.Visible;
                }
                break;
        }
    }
}

What I tried is using async Tasks from another solution which doesn't worked for me:
private readonly Task _CreateTable;
public MainWindow()
{
    InitializeComponent();
    _CreateTable = PerformCreateTableAsync();
}
private async Task PerformCreateTableAsync()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(TimeSpan.FromSeconds(5));
        });
    }

    private async void CreateTable()
    {
        Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
        Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");

        tableIcon.Visibility = Visibility.Collapsed;
        tableIconLoading.Visibility = Visibility.Visible;

        await _CreateTable;

        tableIcon.Foreground = new SolidColorBrush(greenColor);
        tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
        tableIconLoading.Visibility = Visibility.Collapsed;
        tableIcon.Visibility = Visibility.Visible;
    }

and where I now calling the RunWorkerAsync I called the Task via:
#region CreateTable
CreateTable();
#endregion

A: BackgroundWorker is obsolete. All its functionality and much more is available through tasks, async/await and the IProgress< T> interface. In fact, composability is one of BGW's greatest weaknesses.
Using async/await is actually a lot easier than using BGW. If you wanted to execute an operation in response to eg a button click you could write this:
private async Task CreateTableAsync(string tableName)
{
    //Execute SQL code that creates a table
    using(var connection=new SqlConnection(_connString)
    using(var cmd=new SqlCommand(connection,sql))
    {
        ....
        await cmd.ExecuteNonQueryAsync();
    }
}

private async void MyButton_Click(object sender, EventArgs args)
{
    Color redColor = (Color)ColorConverter.ConvertFromString("#DDC31616");
    Color greenColor = (Color)ColorConverter.ConvertFromString("#DD15992D");

    tableIcon.Visibility = Visibility.Collapsed;
    tableIconLoading.Visibility = Visibility.Visible;

    try
    {
        await CreateTableAsync("SomeTableName");

        tableIcon.Foreground = new SolidColorBrush(greenColor);
        tableIcon.Kind = MaterialDesignThemes.Wpf.PackIconKind.CheckCircle;
        tableIconLoading.Visibility = Visibility.Collapsed;
        tableIcon.Visibility = Visibility.Visible;
    }
    catch(Exception exc)
    {
        MessageBox.Show(exc.ToString(),"Ouch!");
    }
}

Note that async void should only be used for event handlers. All other methods should return async Task or async Task<T>. async void methods can't be awaited. They are essentially fire-and-forget methods.
If you want to combine multiple async call, the only thing you need to do is add them one after the other :
private async void MyButton_Click(object sender, EventArgs args)
{
    SetWorkingModeUI();
    try
    {
        await CreateTableAsync("SomeTableName");
        await CreateTableAsync("OtherTableName");
        await CreateTableAsync("ThirdTableName");

        SetIdleModeUI();
    }
    catch(Exception exc)
    {
        SomeProperErrorHandlerAndLogger(exc);
    }
}

You can even run multiple operations in parallel and await all of them to complete :
private async void MyButton_Click(object sender, EventArgs args)
{
    SetWorkingModeUI();
    try
    {
        var tasks = new[] {
                   AsyncCall1(),
                   AsyncCall2(),
                   AsyncCall3()
        };
        await Task.WhenAll(tasks);

        SetIdleModeUI();
    }
    catch(Exception exc)
    {
        SomeProperErrorHandlerAndLogger(exc);
    }
}


text:
Q: i18n - Internationalization & Password Complexity Rules I'm currently working on the internationalization of a product and an issue has come up. The issue revolves around password complexity requirements for countries with non-Latin languages and complex character sets.
The application uses aspnet membership for user and password management, although this might be a whole other issue. Currently our application has settings and code in place to accommodate A-Z, 0-9 and special characters that make up passwords, but these will more than likely require extension to cope with other cultures.
I've been searching for guidance and best practice on this and so far not had much joy. The last post on this SO question touches on the issue but doesn't really provide any guidance.

A: Much depends on how secure the access needs to be. For high security a password approach isn't really practical, and some kind of biometric (fingerprint?) or two-factor (SKey?) approach may be better, especially if combined with a numeric PIN.
This is because it's not really practical to perform dictionary or complexity analysis on non-Western language passwords. Specifically:

*

*Many languages do not distinguish between upper-case and lower-case

*Some languages encode characters in two, three or four bytes

*There is no reason to introduce numeric or punctuation characters in passwords for cultures with a large number of ideograms (such as Simplified Chinese)

*Maintaining dictionaries for a large number of languages can be impractical

For simple Web sites it may be advisable to perform stronger checks on the password if you are delivering a non-Western language version of your site to the browser.

A: Depends on what you want to enforce. Dictionary checks and pattern recognition should work in any encoding and language. If you want to enforce the popular but arbitrary rules "mix of uppercase, lowercase and numerics", then, yes, you probably need to find A) a library or API that can determine case and numerics for any language or B) create a stupidly large database to map that information yourself.
That kind of complexity rules is a hack, though. Stupid people WILL create stupid passwords, no matter what kind of complexity rules you arbitrarily enforce. Best practices for password security is making sure the user has to pick a password that isn't quite as guessable as it could be, so dictionary checks (don't forget to add all words on the password creation page and all words related to password entry, the application or its environment, plus all available user-specific info, e.g. birthdate and maiden name) and pattern matching (abc123) should do.
I've actually seen a lot of cases where "abc123.-" or something similar were used as root passwords because nobody could be arsed coming up with a real password that would meet the complexity criteria.

A: After contacting technical staff in a branch of our company abroad in China, we've found that for the bulk of the systems they use, which require logins, they tend to stick to the standard ASCII characterset for usernames and passwords for these reasons.
Chinese keyboards generally have the QWERTY set up alongside chinese characters and users are able to switch between chinese and ASCII input methods easily to login to systems. For now, we will be leaving our system as it is and monitor additional cultures as they are added, handling any special cases that may arise.
More information on Chinese input methods can be seen on Wikipedia - Chinese input methods for computers

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does the hazard ratio change when the exposure is doubled? I am a medical student who somehow ended up having to do a meta-analysis. I have no knowledge about statistics.
For example, if the cardiovascular mortality hazard ratio associated with a 5μg/m3 change in PM2.5 is 1.5, what would be the hazard ratio for a 10μg/m3 change in PM2.5??
Thanks a lot!!

A: If the hazard ratio associated with a given change in circumstances is $1.5$, then this change multiplies the original hazard rate by $1.5$
Assuming this hazard ratio stays constant in different circumstances (this is a strong assumption) then making the same change a second time would multiply the new hazard rate by a further $1.5$,
so double the original change in circumstances would multiply the original hazard rate by $1.5^2$ i.e. by $2.25$, and this is the hazard ratio for the double change


text:
Q: Windows xcopy does not copy file back to directory i have this script which i try to copy the file directory up using : "../"
del /f foo.zip
cd foo_directory
zip -r foo.zip *
xcopy foo.zip ../
cd ..

but i keep getting this error :
Does ../ specify a file name
or directory name on the target
(F = file, D = directory)? d
File creation error - Cannot create a file when that file already exists.

Unable to create directory - C:\test\foo_paraent_dir\
0 File(s) copied

i just want to copy the zip to the directory above .


text:
Q: How to GET all the ALL DATA from WTForm? **How To get All Data in a wtf form with a single command in a dictionary or list without needing to write this much lines of code, specifing every single element in the form and geting data seperately
**
@app.route('/add', methods=['POST', 'GET'])
def add_cafe():
    form = CafeForm()
    if form.validate_on_submit():
        print("True")
        cafe_name = form.cafe_name.data
        cafe_location = form.cafe_location.data
        opening_time = form.opening_time.data
        closing_time = form.closing_time.data
        coffee_rating = form.coffee_rating.data
        wifi_strength_rating = form.wifi_strength_rating.data
        power_socket_availability = form.power_socket_availability.data
    return render_template('add.html', form=form)

A: The wtforms documentation says that that's Form.data:

A dict containing the data for each field.

In other words,
@app.route('/add', methods=['POST', 'GET'])
def add_cafe():
    form = CafeForm()
    if form.validate_on_submit():
        data = form.data
        print("True", data)
        # ...
    return render_template('add.html', form=form)


text:
Q: React router gives "redirect to the same route" error I have got routes like below and I want to redirect users to admin/users page if someone clicks ADMIN button (this button routes to /admin) on the home page but I get this error:

You tried to redirect to the same route you're currently on:
  /admin/users

<Switch location={this.props.location}>
     <Route path="/" exact component={Home} />
     <Route path="/orders" component={Orders} />
     <Route path="/account" component={Account} />

     <Route path="/admin/users" component={Users} />
     <Route path="/admin/auth" component={Auth} />

     <Redirect from="/admin" to="/admin/users" />

     <Redirect from="*" to="/" />
</Switch>

*

*I added location attribute into Switch because I use animations while routing. You can find an example at this link: https://reacttraining.com/react-router/web/example/animated-transitions

*If I remove location attribute everything is fine but with this attribute I get errors.

*I searched lots of sites and tried several things but I could not achieve. I need location attribute, I cannot remove it.

If you help I will be appreciated.
Thanks

A: I can only achieve if I write the below code:
<Route exact strict path="/admin" render={({location}) => {
    if (location.pathname === window.location.pathname) {
         return <Redirect to="/admin/users" />;
    }
    return null;
}} />

But why does Switch not prevent to run the below redirect route again and again? Because when the redirect happens,
/admin/users route works but also /admin route works too. Why does Switch not prevent? Does anybody have an answer for this?

A: Not a solution, but will remove the error.
<Switch location={this.props.location}>
 <Route path="/" exact component={Home} />
 <Route path="/orders" component={Orders} />
 <Route path="/account" component={Account} />

 <Route path="/admin/users" component={Users} />
 <Route path="/admin/auth" component={Auth} />

 {allowedToRedirect
  ?(
    <Redirect from="/admin" to="/admin/users" />

    <Redirect from="*" to="/" />
   )
  : null}
</Switch>

Where const allowedToRedirect = location.pathname === window.location.pathname;
https://codesandbox.io/s/pjk4ykr4kq


text:
Q: Android Studio: ExpandableListView and EditText I have an ExpandableListView with an EditText in it. It works well, but when I put a number in one row, the number is visible in another row as well. I found already some questions regarding this problem (with an holder as solution) but I am not able to use it in my case. Can anybody help me?
Here is the code:
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {
    View view = convertView;
    if(view == null){
        LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.child_lm, parent, false);
    }
    final String childName = (String)getChild(groupPosition, childPosition);
    final TextView childItem = (TextView)view.findViewById(R.id.child_layout);
    childItem.setText(childName);

        einheit1 = data2[childPosition];
        einheit2 = data3[childPosition];
        einheit3 = data4[childPosition];
        einheit4 = data5[childPosition];
        mengenbeschreibung = data6[childPosition];

    final EditText mz= (EditText) view.findViewById(R.id.etMz);
    final String menge=mz.getText().toString();

    Drawable drawable = mz.getBackground();
    drawable.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
    if(Build.VERSION.SDK_INT > 16) {
        mz.setBackground(drawable);
    }else{
        mz.setBackgroundDrawable(drawable);
    }

    TextView eh1=(TextView)view.findViewById(R.id.tv1);
    eh1.setText(einheit1);
    TextView eh2=(TextView)view.findViewById(R.id.tv2);
    eh2.setText(einheit2);
    TextView eh3=(TextView)view.findViewById(R.id.tv3);
    eh3.setText(einheit3);
    TextView eh4=(TextView)view.findViewById(R.id.tv4);
    eh4.setText(einheit4);
    TextView mengenangabe=(TextView)view.findViewById(R.id.tvMengenbeschreibung);
    mengenangabe.setText(mengenbeschreibung);

    final View finalView1 = view;
    mz.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(
                Editable arg0) {
        }
        public void beforeTextChanged(
                CharSequence s, int start,
                int count, int after) {
        }
        public void onTextChanged(
                CharSequence s, int start,
                int before, int count) {
            TextView eh1=(TextView) finalView1.findViewById(R.id.tv1);
            TextView eh2=(TextView)finalView1.findViewById(R.id.tv2);
            TextView eh3=(TextView)finalView1.findViewById(R.id.tv3);
            TextView eh4=(TextView)finalView1.findViewById(R.id.tv4); if(mz.getText().toString().equals(null)||mz.getText().toString().equals("")) {
                }else{
                    double test10= (Math.round(Float.parseFloat(mz.getText().toString().replace(",","."))*Float.parseFloat(data2[childPosition])/100*2));
                    float test1 = (float) (test10/2);
                    eh1.setText(String.valueOf(test1));

                    double test20= (Math.round(Float.parseFloat(mz.getText().toString().replace(",","."))*Float.parseFloat(data3[childPosition])/100*2));
                    float test2 = (float) (test20/2);
                    eh2.setText(String.valueOf(test2));

                    double test30= (Math.round(Float.parseFloat(mz.getText().toString().replace(",","."))*Float.parseFloat(data4[childPosition])/100*2));
                    float test3 = (float) (test30/2);
                    eh3.setText(String.valueOf(test3));

                    double test40= (Math.round(Float.parseFloat(mz.getText().toString().replace(",","."))*Float.parseFloat(data5[childPosition])/100*2));
                    float test4 = (float) (test40/2);
                    eh4.setText(String.valueOf(test4));
                }
    });

    return view;
}

A: mz.addTextChangedListener should be in your MainActivity OnCreate().
At least that's what I guess, did not check your code.


text:
Q: How to show missing messages in an Outlook Outbox folder Sometimes the Outlook count for the Outbox folder shows it contains a message ("Outbox [1]"), but even with all filtering off, no the list of items in the folder is empty. It looks like a message that failed to send. This happens with an account backed by a .ost file. How do I recover the missing message?

A: Copy the location of the .ost file from the account Data File Properties. Then close Outlook and run scanpst.exe (located in "C:\Program Files\Microsoft Office 15\root\office15" for x64 Office 2013).


text:
Q: Returning Arrays/Pointers from a function I am trying to create a new integer array which is derived from a string of characters. For example :
char x[] = "12334 23845 32084";

int y[] = { 12334, 23845, 32084 };

I am having trouble understanding how to return an array ( which I understand isn't possible ) from a function.
I originally tried :
/* Convert string of integers into int array. */
int * splitString( char string[], int n )
{
    int newArray[n];

    // CODE

    return ( newArray );
}

int main( void )
{
    int x[n] = splitString( string, n );

    return ( 0 );
}

I later learned that you can not do this.
How do pointers work in regards to functions?
Thank you.

A: int * splitString( char string[], int n )
{
    int newArray[n];
    return ( newArray );
}

This is very bad! The array newArray local to the function gets destroyed when the function returns. You'd be left out with a dangling pointer and using it would invoke undefined behaviour.
You can't return an array from a function. The best you can do is
int * splitString( char string[], int n )
{
    int *newArray = malloc(n*sizeof(int)); // the array gets allocated on the heap rather than on the stack(1)
    // Code
    return ( newArray );
}

Don't forget to free the allocated memory.
(1) Note that the standard doesn't use/define the term stack or heap as such.

A: Rather than returning an array with return (newArray), you return a pointer to the first element of newArray.
The problem is that you're allocating the array the wrong way. If you instantiate it with int newArray[n], memory gets allocated on the current stack frame. That memory will be freed as soon as your function returns, and whatever was in the array will be garbage. Instead, do the following:
int *newArray = malloc(n * sizeof(int));
// etc.
return newArray

By using malloc, you allocate memory on the heap, where it will survive past the end of the current stack frame. Just remember to free(newArray) somewhere in your program when you're done.

A: Typically, you require the caller to pass in the result array.
void splitString( const char string[], int result[], int n) {
    //....
}

This is advantageous because the caller can allocate that memory wherever they want.

A: You can wrap an array in a structure and then return an instance of the structure.
I'm mentioning this for completeness, it's not really something you'd want to do as it's ugly and there are better alternatives.
#include <stdio.h>

struct retval
{
    int a[10];
};

struct retval test()
{
    struct retval v = {{1, 5, 6}};
    return v;
}

int main()
{
    struct retval data = test();
    printf("%d %d\n", data.a[1], data.a[2]);
}

A: The main issue i see is trying to return memory which you allocated on the stack, which becomes invalid once the function it was allocated in reutrns (in this case your splitString). What you can do is allocate the memory in the caller, and pass a pointer to the beginning of the array into the function
/* Convert string of integers into int array. */
void splitString(char string[], int *out_arr, int n )
{

    // code that fills each cell of out_arr

}

int main( void )
{
    int x[n];
    splitString( string,(int *)x, n );

    return ( 0 );
}

A: The problem is you're returning a pointer to something on the stack. You need to create your array on the heap, then free it when you're done:
int * splitString( char string[], int n )
{
    int *newArray = malloc(sizeof(int) * n);

    // CODE

    return ( newArray );
}

int main( void )
{
    int *x = splitString( string, n );

    // use it

    free(x);

    return ( 0 );
}

A: Of course it's possible.
This is the way I prefer:
int func(int** results)
Function returns number of elements in results. results is a pointer to an int array.


text:
Q: Smooth $S^1$-bundle over complex projective line What are all the smooth $S^1$-bundles over $\mathbb{C}\mathbb{P}^1$? i.e. What are all smooth manifolds so that $S^1\to X \to \mathbb
{C}\mathbb{P}^1$ is a smooth fiber bundle?
Any suggestions will be helpful.
Thanks in advance!


text:
Q: Expire a Collection in Mongo using Casbah EnsureIndex I am attempting to expire a collection in Mongo using Casbah's ensureIndex API.
Based on this document
     http://docs.mongodb.org/manual/tutorial/expire-data/
I am using casbah's proposed ensureIndex API
 collection.ensureIndex(DBObject("status" -> 1, "expireAfterSeconds" -> 120))

to expire the collection in 2 minutes ...
The collection is not being evicted or expired.
Am I missing anything else here?
Thanks

A: There are a couple things to check:

*

*Were you just following the docs to a T and tried to create an index on a status field which doesn't actually exist in your documents? (had to atleast ask...)

*Does the status field contain JUST dates? It can theoretically be mixed, but only documents with a date type would be considered for expiration.

*Have you checked your collection indexes to make sure the index was properly created?

To check for the index from the console run: db.collection.getIndexes().  If the index was created successfully, then double check you have the corresponding status fields in your documents and that they are proper dates.
Adding the index alone, doesn't create the date field for you - you would need to add it to the documents or use an existing date field that is not part of any other index.
Also note, from the docs:

TTL indexes expire data by removing documents in a background task
  that runs every 60 seconds

So, if you have a 120 second expiration, bear in mind, that its possible the documents could remain for 120 seconds up to 179 seconds, give or take, depending on when the document expired and the background task last ran.
edit: As noted in the comments - a collection  itself cannot be removed based on a TTL index, the index only expires the documents in the collection.

A: I think, you are passing the Options in the wrong way.
It should be-
collection.ensureIndex(DBObject("status" -> 1), DBObject("expireAfterSeconds" -> 120))

Instead of-
collection.ensureIndex(DBObject("status" -> 1, "expireAfterSeconds" -> 120))


text:
Q: Regex: Replacing single quotes but taking care of apostrophes (I am certain that this question has already been asked, but I cannot find it.)
I need to replace anything between single quotes with \enquote{}, the capture to be put inside the curly brackets. With double quotes I can get away with:

*

*FIND: "(.*?)"

*REPLACE: \\enquote{$1}
But with single quotes there is the obvious problem of apostrophes. Is there way to solve that problem.
Example:
He said, 'it's always sunny here.'

A: One multi-step approach:

*

*Use Search and Replace, "replace all" to replace space+' with
something appropriate (e.g. space+")

*repeat .1 for '+space.

*you might also have '. to handle...
(i.e. ' at the end of a sentence, and also at the end of a line -
and how about at the very beginning of a line?)

*Now use Search and Replace to replace ' into " for
the remaining instances and select to replace or not, manually (Yes/No).

To get this to work with an automated process?
That is a bit harder to say the least, I'm all ears regarding that...
If you can find a way to express the Search-items above with regex'es (i.e. $ man re_format) then you might be at least part of the way to automation.
This https://www.regular-expressions.info/wordboundaries.html might be of some help there though, but I take it that \b isn't available in all regex-implementations.

A: As you didn't give the language/tool you are using, I give a solution that uses Notepad++.

*

*Ctrl+H

*Find what: \w'\w(*SKIP)(*FAIL)|'(.+?)'(?!\w)

*Replace with: \\enquote{$1}

*CHECK Wrap around

*CHECK Regular expression

*CHECK . matches newline*

*Replace all
Explanation:
  \w            # 1 word character
  '             # single quote (in fact an apostrophe)
  \w            # 1 word character
  (*SKIP)       # skip this match
  (*FAIL)       # abort this match (don't considere the apostrophe)
|               # OR
  '             # single quote
  (.+?)         # group 1, 1 or more any character, not greedy
  '             # single quote
  (?!\w)        # only if not followed by a word character

Screen capture (before):

Screen capture (after):


text:
Q: A question about partial Euler products Let $K/{\mathbb Q}$ be an extension of degree $d$. Let $S$ be the set of primes $p$ which split completely in $K$. What can one say about the analytic properties of
$$
\zeta_{K, S}(s) : = \prod_{p \in S} \frac{1}{1-p^{-s}}.
$$
More generally, one can define a similar partial Euler product for any splitting type, and ask the same question about the analytic properties of the resulting function. Any advice would be greatly appreciated.

A: This question turned out to be not too difficult. Please see
http://www.math.uic.edu/~rtakloo/euler-product.pdf
for a (casual) writeup of an answer.
Thanks for your comments and hints.

A: I hope this could be relevant to your nice question. There is a paper by K. Williams where a Mertens' type theorem for arithmetic progressions was proved,
K. Williams, Mertens' Theorem for Arithmetic Progressions, J. Number Theory 6 (1974) 353--359.
In this paper, the relation
$$
\sum_{\chi \bmod q}\chi(p)\bar{\chi}(a) = \begin{cases}
  \varphi(q),  & p \equiv a \bmod q, \\
  & \\
  0, & \mbox{otherwise.}
  \end{cases}
$$
for Dirichlet characters is used to derive an expression for
$$
\prod_{\substack{p \leq x\\p \equiv a \bmod q}}\left(1-\frac{1}{p}\right).
$$
Letting $G$ be the Galois group of $K/\mathbb{Q}$, $C_G(g)$ be the centralizer of $g$ in $G$, $\mathcal{C}(g)$ the set of conjugates of $g$ in $G$, $\sigma_p$ the Frobenius element of $p$, the Schur orthogonality relations
$$
\sum_{\chi}\chi(\sigma_p)\overline{\chi(g)} = \begin{cases}
 \left| C_G(\sigma_p)\right| = \frac{|G|}{|\mathcal{C}(\sigma_p)|},  & \sigma_p, g \mbox{ are conjugate}, \\
  & \\
  0, & \mbox{otherwise}
  \end{cases}
$$
where the sum is over all irreducible characters $\chi$ of $G$, can be used in a similar way to derive a formula for the partial Euler product in your nice question by writing, for some fixed $g\in G$,
$$
\prod_{\substack{p\\\sigma_p \in \mathcal{C}(g)}}(1-p^{-s})^{-C_G(g)} = \prod_{\chi}\left(\prod_{p}\left(1-p^{-s}\right)^{-\chi(p)}\right)^{\overline{\chi(g)}}
$$
where the $\chi$ are irreducible characters of $G$. In the mentioned paper, where the $\chi$ are Dirichlet characters, Williams wrote
$$
\prod_{p \leq x}\left(1-\frac{1}{p}\right)^{\chi(p)} = \left(\frac{1}{L(1,\chi)}+O(1/\log x)\right)\left(K(1,\chi)+O(1/x)\right)
$$
where $K(1,\chi)$ had some properties that could be stated in the paper. Hence in the case of the product in your nice question, maybe something can be worked out along such lines too. I guess it's more complicated as there are now Artin L-functions.

A: I do not know if you are willing to restrict to abelian $K/\mathbb{Q}$: if not, please throw away my whole answer. But let me assume that your base field is any number field $F$, as it does not change anything: and, accordingly, that $K/F$ is abelian.
Suppose first that $K/F$ is a ray class field for some conductor $\mathfrak{f}$ (for $F=\mathbb{Q}$ it means $K$ is either $\mathbb{Q}(\zeta_f)$ or $\mathbb{Q}(\zeta_f)^+$ for some $f$). Then you are simply considering the partial zeta function $\zeta({\bf{1}},s)$ where $\bf{1}$ is the trivial class in the ray class group modulo $\mathfrak{f}$. Those are well-studied and can be interpreted as suitable Mellin transform, pretty much as the usual Dedekind zeta function and admits the usual analytic continuation (see J. Neukirch Algebraic Number Theory, Chapter VII, Section 5, theorem 5.5 for the Mellin transform statement, Theorem 5.9 for analytic continuation caveat: I only have the German version and I ignore if numbering has been changed in the translation). This settles also the case in which you consider some different splitting behaviour which would be controlled by class field theory pretty much the same way – i. e. your Euler product would be that of $\zeta({\bf{c}},s)$ for the class $\bf{c}$ in the ray class field containing precisely the integral ideals whose splitting time is your favorite one.
If now your abelian extension is only contained in a ray class field, you need to follow more closely Tate's thesis (see the last chapter of Cassels and Fröhlich's Algebraic Number Theory) and chose the right measure to put on the unit ball inside $\mathbb{Q}_p$ for the primes you want to throw away – I imagine that you should chose the measure giving volume $1$ to some suitable subgroup depending on your local extension, but I am not checking. I guess that this would not affect anything at all, because Tate's strategy is somehow ''formal'' in the sense that it just depends on some very nice property of adelic Fourier transform. As for a reference, I suggest D. Ramakrishan and R. Valenza Fourier Analysis on Number Fields.
Let me also observe that what you are asking for is ''natural'' in the sense that when looking at zeta functions as being suitable measures on Galois group, your Euler product
at negative integers $k$ gives the special values of the measure agains the function $\chi_S|\cdot|^k$ where $\chi_S$ is the characteristic function of the set of primes $S$ seen as elements of the Galois group via class field theory – this is discussed very well in the introduction to Deligne and Ribet's paper about special values of $L$-functions at negative integers.
If your extension is not abelian, I think the situation is much more involved because it is not enough to play the same game simply on adeles group: and, as said before, you'd rather forget everything I have written...


text:
Q: Mix was not set up correctly. Please ensure you import or require laravel-mix in your mix config / Laravel Mix v6.0.39 On a Laravel application, while trying to run:
npm run dev

I get the following message:

npm run dev
dev
npm run development
development
mix
Mix was not set up correctly. Please ensure you import or require laravel-mix in your mix config.
99% done plugins BuildOutputPlugin

node version: v14.18.2
npm version: 8.2.0
No js and css output to public/js and public/css is being produced and I get no other error.
I removed and readded node-modules folder several times..
Any ideas how can I solve this issue pls?

A: For me, the solution for this error is to insert this line at the top of the webapck.mix.js file:
let mix = require('laravel-mix');


text:
Q: Why is it bad practice to use links with the javascript: "protocol"? In the 1990s, there was a fashion to put Javascript code directly into  href attributes, like this:
Press me!

And then suddenly I stopped to see it. They were all replaced by things like:
Press me!

For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?

A: I open lots of links in new tabs - only to see javascript:void(0).  So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents.  Why?  Well,

*

*Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically.  Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.

*Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel.  These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery).  They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people.  So it makes sense to keep them in
separate documents as well.

A: The execution context is different, to see this, try these links instead:
Press me!
Press me!

javascript: is executed in the global context, not as a method of the element, which is usually want you want.  In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all.  Check out any framework for handling these things in a much cleaner way.  Example in jQuery:
$('a').click(function() { alert(this.tagName); });

A: Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element  is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the  element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.

A: Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.

A: The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"

href = "#dostuff"

For the page:
onLoad = if(hash="dostuff") doStuff();

A: Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an
, an , or a
 would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.

A: I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work".  And then I setup my anchor tags like this...

This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible.  This will degrade gracefully.  Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.

A: Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup

*

*http://www.alistapart.com/articles/behavioralseparation

*http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.

A: Couple of reasons:

*

*Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.

*SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.

*Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.

*You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.

A: I think it has to do with what the user sees in the status bar.  Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).


text:
Q: How can I output a new line with `FORMATMESSAGE` in transact sql? The following code stats that, how many users that has created at least one post on a specific SE site.
DECLARE @RowCount INT
SET @RowCount = (SELECT COUNT(DISTINCT OwnerUserId)
FROM Posts where OwnerUserId is not null)
PRINT FORMATMESSAGE('%s has \r\n %d users', DB_NAME(), @RowCount+1)

which basically works though, the FORMATMESSAGE part does not work as expected.
Usually, \n (in lots of systems and languages) and \r\n (mainly in MS systems) represent new line. I tried both, and even /r/n, none of them worked.
How can I output a new line with FORMATMESSAGE in transact sql?

A: The problem is the interpretation of \r\n as carrriage return and line feed. SQL Server does interpret \r\n like this in some places, but the FORMATMESSAGE function is not one of them, so instead you need to use CHAR(13) and CHAR(10) which represents the the ASCII codes for Carriage Return (13) and Line Feed (10):
DECLARE @RowCount INT
SET @RowCount = (SELECT 10)
PRINT FORMATMESSAGE('%s has ' + CHAR(13) + CHAR(10) + ' %d users', DB_NAME(), @RowCount+1)

Or use a variable:
DECLARE @RowCount INT,
    @NewLine CHAR(2) = CHAR(13) + CHAR(10)
SET @RowCount = (SELECT 10)
PRINT FORMATMESSAGE('%s has ' + @NewLine + ' %d users', DB_NAME(), @RowCount+1)
-- or
DECLARE @RowCount INT,
    @NewLine CHAR(2) = CHAR(13) + CHAR(10)
SET @RowCount = (SELECT 10)
PRINT FORMATMESSAGE('%s has %s %d users', DB_NAME(), @NewLine, @RowCount+1)


text:
Q: Django form error customizing I'd like to add custom data to django form errors.
For instance, if user input exceeds available stock quantity, I'd like to add the available stock quantity to the error data.
Upon inspecting form.errors, one can look at the error code,(InsufficientStock) then it can look for the remaining quantity in the error data.
especially when we are working in ajax.
Edit
I'm trying to set the quantity to the available max in the client side using javascript.

A: class StockForm(forms.ModelForm):
    quantity = forms.IntegerField()

    def __init__(self):
        self.available_quantity = AVAILABLE_QUANTITY

    def clean_quantity(self):
        if self.cleaned_data['quantity']>self.available_quantity:
            raise forms.ValidationError('Sorry, you only have %d stocks left' % self.available_quantity)


text:
Q: jquery find span with special text I am trying to select a span with specific text in jquery. Jquery "contains" is not very strict, so if I use it and search for "tab", it would also select "table", which I dont want.
$(".spanbox:contains('Tab')").css('background-color', 'Green')

The example-spans:
Tab
Table

Is there a way to exclusively select on of the classes members with a certain text?

A: You can do it using .filter() with a function parameter, like so:
$(".spanbox").filter(function() {
   return $(this).text() == 'Tab';
}).css('background-color', 'Green');

A: try this way :
$.fn.textEquals = function (text) {
    var match = false;
    $(this).each(function () {
        if ($(this).text().match("^" + escapeRegex(text) + "$")) {
            match = true;
            return false;
        }
    });
    return match;
};

$(".spanbox").textEquals('Tab').css('background-color', 'Green');
$(".spanbox").textEquals('Table').css('background-color', 'Red');


text:
Q: Standard solutions to keep LAN connection up Do you use some "standard" solution to manage your server connectivity? In particular, how do you ensure that, week after week of uptime, your LAN remains connected, even if the router should reboot or other temporary problem should occur?
Since some years, I've arranged this using a custom script (loaded by init) which periodically pings the router, and in case it doesn't reply, a reconnection is attempted.
But I wonder if the norm is to write a custom script like this by yourself, or if there is some standard solution ready to go.

A: In short: there is no such thing as a "standard solution" to this problem solely because of the fact that it is not a "standard" problem.
With a modern OS and sane network equipment, there is no need to do anything to ensure the network connection stays up, nor should any "custom script" be required to bring things up after a power outage or other unexpected disconnection.
If you are finding that connections are not being re-established after an unexpected disconnection, then you need to do further troubleshooting to determine the source of the issue.
As an aside, you ought to have some sort of external monitoring in place to detect and alert on events like this.


text:
Q: How do I customize pagination view of ag grid I am working on ag-grid and one thing I want is to change pagination view completely and make it appear something like below image. How can I achieve this?

A: I found out one solution. We can create this pagination view separately and then trigger pagination on click like api.paginationProxy.goToPage(47), this also works as expected when we are working on server side pagination.


text:
Q: T-SQL if exists I am summer intern new to T-SQL and I have to run an sql select statement on various databases.   What I would like to do is use 'if exists' to keep an error from occuring because some of the databases on the list to have this statement executed on no longer exist.   However, I cannot figure out how to apply it to my statement.   Any help would be greatly appreciated.  Below is the statment me and another intern wrote:
select distinct mg.MatterName, mg.ClientNumber, mg.MatterNumber,grp.groupName as SecurityGroup
from (select distinct mat.matterName, mat.clientNumber, mat.matterNumber, usr.GroupID
    from <db_name>.dbo.matter mat
    inner join <db_name>.dbo.usrAccount usr
    on usr.NTlogin=mat.matterCreateBy) as mg
          inner join <db_name>.dbo.usrGroup grp
          on mg.groupID=grp.groupID
order by matterName

the < db_name> is where the passed in parameter that is the name of the database, would go.

A: You could use sp_MSforeachdb to enumerate all of the databases on the instance.
This would be similar to:
exec sp_MSforeachdb 'select distinct mg.MatterName, mg.ClientNumber, mg.MatterNumber,grp.groupName as SecurityGroup from (select distinct mat.matterName, mat.clientNumber, mat.matterNumber, usr.GroupID     from ?.dbo.matter mat     inner join ?.dbo.usrAccount usr     on usr.NTlogin=mat.matterCreateBy) as mg           inner join ?.dbo.usrGroup grp           on mg.groupID=grp.groupID order by matterName'

Alternatively, you could use dynamic sql to manufacture a script:
select 'use ' + name + ';' + char(13) + 'select distinct mg.MatterName, mg.ClientNumber, mg.MatterNumber,grp.groupName as SecurityGroup' +CHAR(13) + 'from (select distinct mat.matterName, mat.clientNumber, mat.matterNumber, usr.GroupID' + char(13) + 'from dbo.matter mat' + char(13) + 'inner join dbo.usrAccount usr on usr.NTlogin=mat.matterCreateBy) as mg' + char(13) + 'inner join dbo.usrGroup grp on mg.groupID=grp.groupID' + CHAR(13) + 'order by matterName;'
from master.sys.databases where database_id>4

If you redirect your output to "Results to Text" in SSMS then run the script, you will see a script written that you can then put into a query editor to execute.

A: I got it to work.  I think this is a bit hackey but what I did was catch the exception thrown and just change a label on the page to reflect that the database doesnt exist.
 DataAccess dal = new DataAccess();
 dal.SelectedConnectionString = "WebServer08";

 String exNetName = Request.QueryString["name"];
 if (exNetName != null && !exNetName.Equals(""))
 {
     try
     {
        gvMatters.DataSource = dal.GetMatters(exNetName);
        gvMatters.DataBind();
      }
      catch (Exception ex)
      {
         noDB.Text = "This database doesn't exist.";
         gvMatters.Visible = false;
      }
 }

And i just left the SQL statement the way it was rather than try to screw around with it


text:
Q: How can I configure the Lubuntu Update Notifier to pop up less often? Ever since I installed Lubuntu 20, the Update Notifier keeps popping up around every other day.

If I don't update, it keeps annyoing me multiple times per day. This is way too often, especially since I don't know if an update will require a subsequent restart. So:

*

*How can I schedule the Update Notifier, for example to something like "check every month (only), and if I don't update right away, ask back no earlier than 6 hours later"?

*When the Update Notifier informs me about new updates, how can I know if starting the installation would require a subsequent restart?

I was not able to find this information on Google or in the Lubuntu manual.

A: If you want to change the time after which you will receive a update notification, then you need to open the /usr/lib/lubuntu-update-notifier/lubuntu_upg_notifer.sh file and change the sleep 3600 line. This line indicates that the script will sleep 3600 after the first update notification after startup. If you do not want any update notifications to come at all, then you need to completely remove (or comment) the content of the script just delete /etc/xdg/autostart/upg-notifier-autostart.desktop autostart file.
Commented update notifer script


text:
Q: Javascript can't detect collision axis between two Divs Am detecting if 2 divs overlap, and if they do, I am checking the distance between rectangle 1's right side and rectangle 2's left side, rectangle 1's top and rectangle 2's bottom, ect, ect.
    if (rect1.right > rect2.left &&
        rect1.left < rect2.right &&
        rect1.top < rect2.bottom &&
        rect1.bottom > rect2.top) {

        //collision detected.

        var dtop = Math.abs(rect1.top - rect2.bottom);
        var dbot = Math.abs(rect1.bottom - rect2.top);
        var dright =Math.abs(rect1.right - rect2.left);
        var dleft = Math.abs(rect1.left - rect2.right);
        var closestSide = Math.min(dtop,dbot,dright,dleft);

        if (closestSide == dleft || dright) {
            collisionAxis = "x";
        }

        if (closestSide == dtop || dbot) {
            collisionAxis = "y";
        }

        alert("collisionAxis: " + collisionAxis);

        return collisionAxis;

    }

For some reason, collisionAxis is always being set to "y", even when closestSide == dleft || dright, which should set collisionAxis to "x"...
Here is a JSFiddle example.  The variable collisionAxis in my DetectCollision function should be set to "x" when the white rectangle collides with the black rectangle, since closestSide = dright, yet somehow it is being set to "y".
Can anyone please tell me why?

A: It should be,
    if (closestSide == dleft || closestSide == dright) {
        collisionAxis = "x";
    }

    if (closestSide == dtop || closestSide == dtopdbot) {
        collisionAxis = "y";
    }


text:
Q: Using Firebug dev tools I am using Firebug and I keep getting the spaces with arrows and don't know how to get rid of them. I believe it is coming form the line spacing from the Visual Studio but not sure.
Does anyone know how to get rid of them?

A: The arrow actually indicates a tab. To turn off their display open the HTML panel's options menu and uncheck the option Show Whitespace.

To automatically remove the trailing whitespace in Visual Studio there is an extension called CodeMaid, which takes care of that as you can read in an answer to another thread.


text:
Q: Reg Exp - insert a special character (~) between the first and the third character and only when an exact match is present My table has a column MSG_INFO with sample data:
Party is carrying gold in a car which is made of ,gold,
Party is carrying whitegold in a car which made of gold

I need a SQL expression that searches for gold and if there is an exact match then I append ~ after the first character of the exact match gold and no action to be performed when there is no exact match.
gold can only be surrounded by space or comma on either side.
Expected output:
Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old

Note - After inserting ~ space before and after gold should still be preserved.
This is what I've started with:
SELECT REGEXP_REPLACE (msg_info, '(^|\s|\W)(gold)($|\s|\W)', '\1~\2\3', 1,0,'i')
FROM   table;

Party is carrying ~gold in a car which is made of ,~gold,
Party is carrying whitegold in a car which made of ~gold

It correctly identifies the correct instances of gold but it puts the ~ before the word rather than after the first character.

A: Split (gold) into two patterns: (g)(old) in the search string, e.g.:
select regexp_replace('Party is carrying gold in a car which is made of ,gold,',
        '(^|\s|\W)(g)(old)($|\s|\W)', '\1\2~\3\4', 1,0,'i') from dual
union all
select regexp_replace('Party is carrying whitegold in a car which made of gold',
        '(^|\s|\W)(g)(old)($|\s|\W)', '\1\2~\3\4', 1,0,'i') from dual;

Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old

A: Try this out, it should work.
REGEX_REPLACE(msg_info,'([\s,](g)(o)(l)(d)[\s,])','\2

A: This regex is a little different in that it uses nested groups.  Don't forget "Gold" at the start of the line.
SQL> with tbl(msg_info) as (
      select 'Party is carrying gold in a car which is made of ,gold,' from dual union all
      select 'Party is carrying whitegold in a car which made of gold' from dual union all
      select 'Gold Party gold is carrying whitegold gold goldstar gold' from dual
    )
    select regexp_replace(msg_info, '(( |,|^)g)(old( |,|$))', '\1~\3', 1, 0, 'i') after
    from tbl;

AFTER
--------------------------------------------------------------------------------

Party is carrying g~old in a car which is made of ,g~old,
Party is carrying whitegold in a car which made of g~old
G~old Party g~old is carrying whitegold g~old goldstar g~old

SQL>


text:
Q: Prove or disprove uniform convergence $g_n(y)=\sum_{k=1}^{n} \frac{\sin ky}{k},x \in [0,\pi]$. So i try to find the pointwise limit function first, following this approach in this post Proving that the sequence $F_{n}(x)=\sum\limits_{k=1}^{n} \frac{\sin{kx}}{k}$ is boundedly convergent on $\mathbb{R}$. I find it to be $\lim\limits_{n\to\infty}\ \sum\limits_{k=1}^{n}\frac{\sin kx}{k}=\frac{\pi-x}{2}=g(x) ,\, x\in(0,2\pi).$
I tried to prove it by Dirichlet test:
take $h_n(x)=\frac{1}{n}\quad \text{and} \quad u_n(x)=\sin(nx) ,
\text{then}  |\sum_{k=1}^n\sin(kx)| \leq \frac{1}{\sin(\frac{x}{2})} \leq \frac{1}{\sin(\frac{\delta}{2})}$.
I want to prove or disprove that $(g_n)$ converge uniformly on $[0,\pi]$.

A: You have shown correctly with the Dirichlet test that $(g_n)$ converges uniformly on the interval $[\delta, \pi]$ for any $\delta > 0$.  This relies on the fact that $\left|\sum_{k=1}^n \sin kx \right| \leqslant 1 / \sin (\delta/2)$ is   uniformly bounded for all $n \in \mathbb{N}$ and $x \in [\delta,\pi]$.
However, if $\delta = 0$ the partial sums are not bounded and the Dirichlet test is not applicable. This is a clue that convergence is not uniform on $[0,\pi]$.
If the convergence were uniform, then by the Cauchy criterion for any $\epsilon > 0$ there exists $N \in \mathbb{N}$ such that for all $m > n \geqslant N$ and all $x \in [0,\pi]$ we would have
$$\tag{1}\left|\sum_{k=n+1}^{m}\frac{\sin kx }{k} \right| < \epsilon$$
We can show that this criterion is violated and the convergence is not uniform. Take $\epsilon = 1/(4\sqrt{2})$ and, for any integer $N$, no matter how large, choose $n = N$, $m = 2n$ and $x_n = \pi/(4n) \in [0,\pi]$. For any $k > n$, we have $kx_n > \pi/4$ and $\sin kx_n > \sin (\pi/4) = 1/\sqrt{2}$.
Hence,
$$\tag{2}\left|\sum_{k=n+1}^{2n}\frac{\sin kx_n }{k} \right| > \frac{1}{\sqrt{2}}\sum_{k=n+1}^{2n}\frac{1 }{k} > \frac{1}{\sqrt{2}}\cdot n \cdot \frac{1}{2n} = \frac{1}{2\sqrt{2}} > \epsilon,$$
and we have a contradiction to condition (1).

A: $\sum_{n \geq 1} \frac{\sin nx}{n}$ is exactly the Fourier series of $f(x)=\frac{\pi-x}{2}$ ($x \in [0, 2\pi)$) extended $2\pi$ periodically to $\mathbb{R}$. Were the convergence of the Fourier series uniform, then the Fourier series would in fact converge pointwise to $f$ (see this) but notice that at $x=0$ $f$ fails to coincide with its Fourier series. Hence we deduce that convergence is not uniform.


text:
Q: Prove that if a collection of subsets of {1,..,n} that each pair of subsets has at least one element in common, there are at most $2^{n-1}$ subsets Full question: Prove that if a collection of subsets of {1,2,...,n} has the property that each pair of subsets has at least one element in common, then there are at most $2^{n-1}$ subsets in the collection.
I have tried to do an inductive proof as follows:
Base case: When $n = 1$, there is only the set {1}, so $2^{1-1} = 2^0 = 1$ subset in the collection
Inductive step: Let $P(n)$ denote the number of subsets of {1,2,...n} that have at least one element in common, which we will call $A$, is smaller or equal to $2^{n-1}$
Assume $P(n)$ is true. Now we take a look at $P(n+1)$. We can divide subsets of {1,2,...,n+1} into two kind, those containing $n+1$, and those that don't. We know there are $A$ subsets that don't contain $n+1$. For subsets containing $n+1$, we can have $2^n$ subsets. In total, $A + 2^n \geq 2^{n+1-1} = 2^n$, which is obviously incorrect.
I'm not sure if it's possible to do it with an inductive proof, so any kind of proof is welcome. However, it would be great if someone could explain how to do it with the method above, and perhaps point out my mistakes.

A: An inductive proof is not the way to go.

HINT: Let $[n]=\{1,\ldots,n\}$. If $A\subseteq[n]$, can such a collection contain both $A$ and $[n]\setminus A$?

What I think you're missing in your attempt to prove the result by induction is that there are many such collections of subsets of $[n]$. For instance, if $n=3$ one such collection is
$$\big\{\{1\},\{1,2\},\{1,2,3\},\{1,2,3,4\}\big\}\;,$$
and another is
$$\big\{\{1,2\},\{1,3\},\{2,3\},\{1,2,3\}\big\}\;.$$
Thus, the induction step of a proof by induction would have to start by letting $\mathscr{A}$ be a collection of subsets of $[n+1]$ such that every pair of members of $\mathscr{A}$ have an element in common; the idea would be to use the induction hypothesis to show that $|\mathscr{A}|\le 2^n$.

A: Note that there are exactly $2^n$ subsets in total to choose from. It is easy to see how to pick $2^{n-1}$ pairwise intersecting sets because we can just take all subsets of $[n-1]$ and then add $n$ to them.
To see that we cannot have more than $2^{n-1}$ pairwise intersecting sets, begin with a set of $2^{n-1}$ pairwise intersecting sets. For each of those sets, we cannot add its complement, because a set and its complement can never intersect. This gives one "illegal" set for each "legal" one. So we have $2^{n-1}$ legal sets, and $2^{n-1}$ illegal ones. But we only have $2^n$ sets to choose from...

A: Show the contrapositive: If we have more tan $2^{n-1}$ subsets, then we find two among them that are disjoint.
This can be done by the pigeon-hole principle: There are exactly $2^{n-1}$ subsets $A$ with $n\notin A$. If declare $A$ and $\{1,2,,\ldots,n\}\setminus A$ as a "hole", then we have $2^{n-1}$ holes. Henec if we have more than $2^{n-1}$ subsets - or "pigeons" - then at least one hole must house at least two pigeons.

A: Let $m$ be the maximum number of subsets in the collection of $\{1,2,...,n\}$.
Prove $m\ge n$: We can select all subsets of $\{1,2,...,n-1\}$ and plus $\{n\}$ to each of them. Then we have $2^{n-1}$ subsets.
Prove $m\le n$: For each subset selected, we can't have its complement selected, we can't have more than $2^{n-1}$ subsets.
So we prove $m=2^{n-1}$. There are at most $2^{n−1}$ subsets in the collection.


text:
Q: Eclipse shows error after installing color theme After installing color theme in Eclipse the program no longer starts.
Does anyone know how to fix this?
Thank in advance,
Cheers.
!SESSION 2019-01-11 19:11:20.156 -----------------------------------------------
eclipse.buildId=4.5.2.M20160212-1500
java.version=1.8.0_05
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.epp.package.cpp.product -pluginCustomization C:/intelfpga_lite/18.1/nios2eds/bin/eclipse_nios2/plugin_customization.ini
Command-line arguments:  -data file:/C:/Users/kosti/sbt4e-18.1-workspace/ -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.cpp.product -pluginCustomization C:/intelfpga_lite/18.1/nios2eds/bin/eclipse_nios2/plugin_customization.ini

!ENTRY org.eclipse.osgi 4 0 2019-01-11 19:11:34.429
!MESSAGE Application error
!STACK 1
java.lang.RuntimeException: Application "org.eclipse.ui.ide.workbench" could not be found in the registry. The applications available are: org.eclipse.cdt.codan.core.application, org.eclipse.cdt.core.GeneratePDOM, org.eclipse.cdt.managedbuilder.core.headlessbuild, org.eclipse.e4.ui.workbench.swt.E4Application, org.eclipse.e4.ui.workbench.swt.GenTopic, org.eclipse.equinox.app.error, org.eclipse.help.base.infocenterApplication, org.eclipse.help.base.helpApplication, org.eclipse.help.base.indexTool.
    at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:248)
    at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1488)

A: It seems that you forgot to set ENV variable because its showing "org.eclipse.ui.ide.workbench" could not be found in the registry. Try this :
Control Panel → View advanced system settings → Advanced tab → Environment Variables
Now you have to do 2 things:
Create a new variable (click the New button):
Variable name: JAVA_HOME
Variable value:C:\Program Files\Java\[your Java Version]
Edit the Path variable and add this to the end of that:
;%JAVA_HOME%\bin


text:
Q: How to insert a character inside a string $string=apple
$add=£
$new=app£le

I am facing problem with inserting character in a string.

A: If I were you, I would split the string into two at the desired point, and then concatenate it back together with the new character added in.
I would give more detail, but I don't know what your intended splitting rules are.

A: $string='apple';
$add='£';
$new=substr_replace($string,$add,3,0);
echo $new;


text:
Q: How can I get the dependencies of an MVC controller I'm calling from an angular module? I need to be able to call a controller endpoint from an angular module. At the moment, I've got the controller endpoint being hit, but it falls over because locationRepository is null.
[HttpGet, Route("{locationId}")]
    public async Task<string> GetSimulcastUrl(int locationId)
    {
        var location = await _locationRepository.GetLocationById(locationId, false, "en-GB");

        //return result of the above
    }

angular.module('app.services').service('locationService',
[
  '$http', function ($http) {

    this.simulcastUrl = (locationId) => {
      const request = {
        method: 'GET',
        url: `${apiUrl}/Simulcast/GetSimulcastUrl`,
        params: {
            locationId: locationId
        }
      };

      return $http(request);
    };
  }
]);


text:
Q: mysql select unique values from multiple tables I have data that looks like this:
table:master
topic| subtopic |  task
recreation | skiiing  | use poles
recreation | skiiing  | wax skiis
events  | block party | run electricity
events  | skiing | purchase banner

I moved the data into a relational mysql database so it looks like this
table: topics
id | name
1 | recreation
2 | events
----------------------
table : subtopics
id | name | topic
1 | skiing | 1
2 | block party | 2
3 | skiing | 2

I'm having a hard time grabbing tasks without repeating them in the tasks table.
My current statement looks like this:
INSERT INTO TASKS
SELECT
 master.task,
 subtopics.id
FROM master,subtopics
WHERE master.subtopic = subtopic.name
AND master.topic = topic.name

When I run it, the result gives me 2 instances of 'use poles', one pointing to subtopic 1, the other to subtopic 3 - which is incorrect.
How can I run the SELECT statement to only pull the task that is unique to the topic/subtopic combination?

A: You need to join all three tables (topic doesn't appear in the FROM clause of your query but does in the WHERE clause).
INSERT INTO TASKS
SELECT master.task, subtopics.id
FROM master
JOIN topic ON master.topic = topic.name
JOIN subtopics ON master.subtopic = subtopics.name AND subtopics.topic = topic.id


text:
Q: Adding object data to html form fields Below is my simple form html where I want to add the object data to my form fields. I went through Google search and StackOverflow but all of them were talking about jquery implementation, so here is my simple form html where I want to add the object data to my form fields. Since I'm not aware of Jquery, I want to use the Java Script approach.
Below, I have a user form where I want to bind the details object to my above form fields, so for that I'm using the below java script approach. I don't know where I'm going wrong. My object data is not getting bound with my form.
So kindly help me with it.
Thank you.
<!DOCTYPE html>

            <form>
                Name&nbsp<input id="name" type="text" name="name">

                Place&nbsp<input id="place" type="text" name="place">

                Age&nbsp<input id="age" type="text" name="age">
            </form>

A: As mentioned in the comment by @Jaromanda X, there is no innerHTML for an input field. Instead, you should try setting the value attribute.

This should do the trick.


text:
Q: How to deploy wso2 esb version 4.7.0 on apache tomcat 7.0.37? I want to deploy wso2 esb version 4.7.0 on apache tomcat 7.0.37. I have used the following listed articles to do this, But didn't succeeded. All articles are about older versions. Is there any other option to do this.Please help.....

*

*Deploy wso2 esb in apache tomcat

*How to deploy wso2 esb 3x on apache

A: WSO2 Products are no longer recommended to run in other containers such as Tomcat. That's why you can see articles only for older versions. I'm afraid, there is no other option for this.


text:
Q: pandas dataframe calculate rolling mean using cutomized window size I'm trying to calculate the rolling mean/std for a column in dataframe. The pandas or numpy_ext rolling methods seem to need a fixed window size. The dataframe has a column "dates", I want to decide the window size based on the "dates", for example, when calculating mean/std, for rows at day 10, including rows from day 2 to day 6, for rows at day 11, including rows from day 3 to day 7, for rows at day 12, including rows from day 4 to day 8, etc.
I want to know if there are methods to do it except the brute force coding. Sample data, "quantity" is the target field to calculate mean and std.

dates
material
location
quantity

1
C
A
870

2
D
A
920

3
C
A
120

4
D
A
120

6
C
A
120

8
D
A
1200

8
c
A
720

10
D
A
480

11
D
A
600

12
C
A
720

13
D
A
80

13
D
A
600

14
D
A
1200

18
E
B
150

For example, for each row, I want to get the rolling mean for "quantity" of the previous 3-8 days (if any), the expected output will be:
| dates | material | location | quantity | Mean                    |
|-------|--------- |----------|----------|-------------------------|
| 1     | C        | A        | 870      | Nan                     |
| 2     | D        | A        | 920      | Nan                     |
| 3     | C        | A        | 120      | Nan                     |
| 4     | D        | A        | 120      | Nan                     |
| 6     | C        | A        | 120      |(870+920)/2 = 895        |
| 8     | D        | A        | 1200     |(870+920+120+120)/4=507.5|
| 8     | c        | A        | 720      |(870+920+120+120)/4=507.5|
| 10    | D        | A        | 480      |(920+120+120+120)/4=320  |
| 11    | D        | A        | 600      |(120+120+120)/3=120      |
| 12    | C        | A        | 720      |(120+120+1200+720)/4=540 |
| 13    | D        | A        | 80       |(120+1200+720)/3=680     |
| 13    | D        | A        | 600      |(120+1200+720)/3=680     |
| 14    | D        | A        | 1200     |(120+1200+720+480)/4=630 |
| 18    | E        | B       | 150|(480+600+720+80+600+1200)/6=613|

A follow-up question:
Is there a way to further filter the window by other columns? For example, when calculating the rolling mean for "quantity" of the previous 3-8 days, the rows in the rolling window must have the same "material" as the corresponding row. So the new expected output would be:
| dates | material | location | quantity | Mean                  |
|-------|--------- |----------|----------|-----------------------|
| 1     | C        | A        | 870      | Nan                   |
| 2     | D        | A        | 920      | Nan                   |
| 3     | C        | A        | 120      | Nan                   |
| 4     | D        | A        | 120      | Nan                   |
| 6     | C        | A        | 120      |(870)/1 = 870          |
| 8     | D        | A        | 1200     |(920+120)/2=520        |
| 8     | c        | A        | 720      |(870+120)/2=495        |
| 10    | D        | A        | 480      |(920+120)/2=520        |
| 11    | D        | A        | 600      |(120)/1 = 120          |
| 12    | C        | A        | 720      |(120+720)/2=420        |
| 13    | D        | A        | 80       |(1200)/1=1200          |
| 13    | D        | A        | 600      |(1200)/1=1200          |
| 14    | D        | A        | 1200     |(1200+480)/2=840       |
| 18    | E        | B        | 150      |Nan                    |

A: You can perform your operation with a rolling, you however have to pre- and post-process the DataFrame a bit to generate the shift:
A = 3
B = 8
s = (df
  # de-duplicate by getting the sum/count per identical date
 .groupby('dates')['quantity']
 .agg(['sum', 'count'])
  # reindex to fill missing dates
 .reindex(range(df['dates'].min(),
                df['dates'].max()+1),
         fill_value=0)
  # compute classical rolling
 .rolling(B-A, min_periods=1).sum()
 # compute mean
 .assign(mean=lambda d: d['sum']/d['count'])
 ['mean'].shift(A+1)
 )

df['Mean'] = df['dates'].map(s)

output:
    dates material location  quantity        Mean
0       1        C        A       870         NaN
1       2        C        A       920         NaN
2       3        C        A       120         NaN
3       4        C        A       120         NaN
4       6        C        A       120  895.000000
5       8        D        A      1200  507.500000
6       8        D        A       720  507.500000
7      10        D        A       480  320.000000
8      11        D        A       600  120.000000
9      12        D        A       720  540.000000
10     13        D        A        80  680.000000
11     13        D        A       600  680.000000
12     14        D        A      1200  630.000000
13     18        E        B       150  613.333333

A: Another possible solution:
def f(x):
  return np.arange(np.amax([0, x-8]), np.amax([0, x-3]))

df['Mean'] = df.dates.map(lambda x:  df.quantity[df.dates.isin(f(x))].mean())

Output:
    dates material location  quantity        Mean
0       1        C        A       870         NaN
1       2        C        A       920         NaN
2       3        C        A       120         NaN
3       4        C        A       120         NaN
4       6        C        A       120  895.000000
5       8        D        A      1200  507.500000
6       8        D        A       720  507.500000
7      10        D        A       480  320.000000
8      11        D        A       600  120.000000
9      12        D        A       720  540.000000
10     13        D        A        80  680.000000
11     13        D        A       600  680.000000
12     14        D        A      1200  630.000000
13     18        E        B       150  613.333333
14     19        E        B      1416  640.000000
15     20        F        B      1164  650.000000
16     21        G        B     11520  626.666667

A: Inspired by @PaulS's answer, here is a simple way to select based on conditions from multiple columns:
def get_selection(row):
    dates_mask = (df['dates'] < row['dates'] - 3) & (df['dates'] >= row['dates'] - 8)
    material_mask = df['material'] == row['material']
    return df[dates_mask & material_mask]

df['Mean'] = df.apply(lambda row: get_selection(row)['quantity'].mean(),
                      axis=1)
df['Std'] = df.apply(lambda row: get_selection(row)['quantity'].std(),
                     axis=1)

    dates material location  quantity    Mean         Std
0       1        C        A       870     NaN         NaN
1       2        D        A       920     NaN         NaN
2       3        C        A       120     NaN         NaN
3       4        D        A       120     NaN         NaN
4       6        C        A       120   870.0         NaN
5       8        D        A      1200   520.0  565.685425
6       8        C        A       720   495.0  530.330086
7      10        D        A       480   520.0  565.685425
8      11        D        A       600   120.0         NaN
9      12        C        A       720   420.0  424.264069
10     13        D        A        80  1200.0         NaN
11     13        D        A       600  1200.0         NaN
12     14        D        A      1200   840.0  509.116882
13     18        E        B       150     NaN         NaN

A: The DataFrame constructor for anyone else to try:
d = {'dates': [1, 2, 3, 4, 6, 8, 8, 10, 11, 12, 13, 13, 14, 18],
     'material': ['C','C','C','C','C','D','D','D','D','D','D','D','D','E'],
     'location':['A','A','A','A','A','A','A','A','A','A','A','A','A','B'],
     'quantity': [870, 920, 120, 120, 120, 1200, 720, 480, 600, 720, 80, 600, 1200, 150]}
df = pd.DataFrame(d)

df.rolling does accept "a time period of each window. Each window will be a variable sized based on the observations included in the time-period. This is only valid for datetimelike indexes."
So we would have to convert your days to datetimelike (e.g., a pd.Timestamp, or a pd.Timedelta), and set it as index.
But this method won't have the ability perform the shift that you want (e.g., for day 14 you want not up to day 14 but up to day 10: 4 days before it).

So there is another option, which df.rolling also accepts:
Use a BaseIndexer subclass
There is very little documentation on it and I'm not an expert, but I was able to hack my solution into it. Surely, there must be a better (proper) way to use all its attributes correctly, and hopefully someone will show it in their answer here.
How I did it:
Inside our BaseIndexer subclass, we have to define the get_window_bounds method that returns a tuple of ndarrays: index positions of the starts of all windows, and those of the ends of all windows respectively (index positions like the ones that can be used in iloc - not with loc).
To to find them, I used the most efficient method from this answer: np.searchsorted.
Your 'dates' must be sorted for this.
Any keyword arguments that we pass to the BaseIndexer subclass constructor will be set as its attributes. I will set day_from, day_to and days:
from pandas.api.indexers import BaseIndexer

class CustomWindow(BaseIndexer):
    """
    Indexer that selects the dates.

    It uses the arguments:
    ----------------------
    day_from : int
    day_to : int
    days : np.ndarray
    """
    def get_window_bounds(self,
                          num_values: int,
                          min_periods: int | None,
                          center: bool | None,
                          closed: str | None) -> tuple[np.ndarray, np.ndarray]:
        """
        I'm not using these arguments, but they must be present (not sure why):
            `num_values` is the length of the df,
            `center`: False, `closed`: None.
        """
        days = self.days
        # With `side` I'm making both ends inclusive:
        window_starts = np.searchsorted(days, days + self.day_from, side='left')
        window_ends =  np.searchsorted(days, days + self.day_to, side='right')
        return (window_starts, window_ends)

# In my implementation both ends are inclusive:
day_from = -8
day_to = -4
days = df['dates'].to_numpy()

my_indexer = CustomWindow(day_from=day_from, day_to=day_to, days=days)
df[['mean', 'std']] = (df['quantity']
                       .rolling(my_indexer, min_periods=0)
                       .agg(['mean', 'std']))

Result:
    dates material location  quantity        mean         std
0       1        C        A       870         NaN         NaN
1       2        C        A       920         NaN         NaN
2       3        C        A       120         NaN         NaN
3       4        C        A       120         NaN         NaN
4       6        C        A       120  895.000000   35.355339
5       8        D        A      1200  507.500000  447.911822
6       8        D        A       720  507.500000  447.911822
7      10        D        A       480  320.000000  400.000000
8      11        D        A       600  120.000000    0.000011
9      12        D        A       720  540.000000  523.067873
10     13        D        A        80  680.000000  541.109970
11     13        D        A       600  680.000000  541.109970
12     14        D        A      1200  630.000000  452.990066
13     18        E        B       150  613.333333  362.803896


text:
Q: Showing tables from specific database with Pyspark and Hive Having some databases and tables in them in Hive instance. I'd like to show tables for some specific database (let's say 3_db).
+------------------+--+
|  database_name   |
+------------------+--+
| 1_db             |
| 2_db             |
| 3_db             |
+------------------+--+

If I enter beeline from bash-nothing complex there, I just do the following:
show databases;
show tables from 3_db;

When I'm using pyspark via ipython notebeook- my cheap tricks are not working there and give me error on the second line (show tables from 3_db) instead:
sqlContext.sql('show databases').show()
sqlContext.sql('show tables from 3_db').show()

What seems to be wrong and why's the same code works in one place and don't work in another?

A: There are two possible ways to achieve this, but they differ a lot in terms of efficiency.

Using SQL
This is the most efficient approach:
spark_session = SparkSession.builder.getOrCreate()
spark_session.sql("show tables in db_name").show()

Using catalog.listTables()
The following is more inefficient compared to the previous approach, as it also loads tables' metadata:
spark_session = SparkSession.builder.getOrCreate()
spark_session.catalog.listTables("db_name")

A: sqlContext.sql("show tables in 3_db").show()

A: Another possibility is to use the Catalog methods:
spark = SparkSession.builder.getOrCreate()
spark.catalog.listTables("3_db")

Just be aware that in PySpark this method returns a list and in Scala, it returns a DataFrame.


text:
Q: $scope não atualiza visualmente os dados que preencho com JavaScript Estou preenchendo o meu $scope via JavaScript usando o seguinte código:
    myApp.controller('gruposController', ['$scope', '$http', '$window', 'usuariosFactory', '$timeout', function ($scope, $http, $window, membrosFactory, $timeout) {
    // Cria um namespace para os dados do formulário
    $scope.formData = {
        /* Inicializa os participantes / aprovadores para que não seja preciso
         * validar no controller principal
         */
        participantes: [],
        aprovadores: []
    };

    // [...]
    function atualizarGrupo(id) {
    // Promisse para processar a requisição
    var grupoPromise = $scope.getGrupo(id);
    grupoPromise.then(
        // Função para executar caso tudo ocorra normalmente
        function(response) {
            // Mostra a tela
            $('.fancy-inline-group[href="#add-group"]').click();

            var grupo = angular.fromJson(response.data);

            $scope.formData.grupo = grupo.grupo;
            $scope.formData.descricao = grupo.descricao;

            // Reseta os participantes e aprovadores
            $scope.formData.aprovadores = [];
            $scope.formData.participantes = [];
            var usuarios = grupo.usuarios;

            // Lógica para preencher os aprovadores e participantes
            if (usuarios.length > 0) {
                angular.forEach(usuarios, function(usuario, key) {
                    var usuarioID = usuario.id;
                    $scope.formData.participantes.push(usuarioID);
                    if (usuario.pivot.aprovador == 1) {
                        $scope.formData.aprovadores.push(usuarioID);
                    }
                });
            }

            // Aplica as mudanças ao objeto $scope
            $timeout(function() {
                console.log($scope.formData);
                $scope.$apply();
            });
        },
        function(response) {
            console.log('Error: ' + response.statusText);
        }
    );
}

Abaixo, como está o HTML:

Adicionar Grupo

    <form action="" class="form-horizontal">
        <input type="hidden" name="id" value="" ng-model="formData.id" />

            Nome do grupo*

                <input type="text" name="grupo" ng-model="formData.grupo" class="form-control" value="" required="required" placeholder="">

[...]

O binding ao digitar um valor nos inputs ocorre corretamente, assim como quando eu executo um console.log($scope) ele mostra os dados corretos, porém os inputs não atualizam no formulário. Vi que ao executar o $scope.$apply() no $timeout teoricamente atualizaria meu $scope visualmente, porém isso não aconteceu.


text:
Q: Python/numpy: Get array locations of a list of values Say I have an array of values nameArr = ['josh','is','a','person'] and I want a function like arrayLocation(nameArr,['a','is']) to return [2 1].
Does that function already exist, if not how can I implement it efficiently?

A: use numpy.where
In [17]: nameArr = np.array(['josh','is','a','person'])

In [18]: [np.where(nameArr==i) for i in ['a','is']]
Out[18]: [(array([2]),), (array([1]),)]

A: Lists have a index method that you can use.
>>> nameArr = ['josh','is','a','person']
>>> # Using map
>>> map(nameArr.index, ['a', 'is'])
[2, 1]
>>> # Using list comprehensions
>>> [nameArr.index(x) for x in ['a', 'is']]
[2, 1]

BTW, index raises ValueError if the element is not in the list. So if you want to supply elements that are not in the list to the index method, you may need to handle the error appropriately.

A: If the array is large, and do many times of location, you can create a dict that map the value to it's index first:
d = dict(zip(nameArr, range(len(nameArr))))
items = ['a','is']
print [d.get(x, None) for x in items]

A: Something like:
>>> f_idxs = np.ravel([np.where(master_data==i)[0] for i in search_list])


text:
Q: Angular Material Expanding Tables I have an application which requires the use of an expanding table, in order to show a greater detail than that within the columns. I have the table already working and have been following the example here https://stackblitz.com/angular/gdbrmljnogk?file=src%2Fapp%2Ftable-expandable-rows-example.html.
Now, I can get the expanded row to show and hide on subsequent clicks, however, my problem is that the expanded row is appearing on top of the table row, as opposed to being underneath and pushing the other rows down. I can see the CSS elements being added with the trigger being fired and removed when its fired again or on another row, but still something within my CSS isn't showing the expanded row correctly.
I would put everything up on stackblitz, but it is very integrated with the application and difficult to get working in the same way as a standalone item. The problem I'm getting is shown below.

Here is the HTML for the section in question.

    <mat-card>
        <mat-card-header>
            <mat-card-title>
                Incomplete Change Requests.
            </mat-card-title>
            <mat-card-subtitle>
                These are change requests which have been authorised and need to be marked as completed.
            </mat-card-subtitle>
        </mat-card-header>
        <mat-card-content>

                    <mat-spinner *ngIf="isLoadingResults"></mat-spinner>

                    <mat-table [dataSource]="data" matSort class="table" #Table #TableSort="matSort" multiTemplateDataRows>

                        <ng-container matColumnDef="jobNumber" sticky>
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Job #</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete" (click)="changeDetails($event, row)">
                                {{ incomplete.jobNum}}
                            </mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="createdAt">
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Created Date Time</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete">{{ incomplete.createdDateTime}}</mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="createdBy">
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Created By</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete">{{ incomplete.createdByEmail}}</mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="changes">
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Changes</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete">{{ incomplete.changes}}</mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="authorisedAt">
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Authorised Date Time</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete">{{ incomplete.authorisedDateTime}}</mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="authorisedBy">
                            <mat-header-cell *matHeaderCellDef mat-sort-header>Authorised By</mat-header-cell>
                            <mat-cell *matCellDef="let incomplete">{{ incomplete.authorisedByEmail}}</mat-cell>
                        </ng-container>

                        <ng-container matColumnDef="expandedDetail">
                            <mat-cell *matCellDef="let element" [attr.colspan]="6">

                                        This is a test

                            </mat-cell>
                        </ng-container>

                        <mat-row *matRowDef="let element; columns: displayedColumns;"
                                 class="element-row"
                                 [class.expanded-row]="expandedElement === element"
                                 (click)="expandedElement = (expandedElement === element) ? null : element">
                        </mat-row>

                        <mat-row *matRowDef="let element; columns: ['expandedDetail']" class="detail-row"></mat-row>

                        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

                    </mat-table>

        </mat-card-content>
    </mat-card>

And the CSS being applied (in addition to the material elements).
.detail-row {
    height: 0px;
    min-height: 0px;
}

.element-row {
    border-bottom-width: 0;
}

.element-detail {
    overflow: hidden;
    display: flex;
    height: 30px;
}

md-row:nth-child(even) {
      background-color:#EDF1F5;
}

mat-row:nth-child(odd) {
      background-color:#FDFDFB;
}

.loading-shade {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 56px;
    right: 0;
    background: rgba(0, 0, 0, 0.15);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
}

/*
.container {
    position: relative;
    min-height: 200px;
}

.table-container {
    min-height: 100px;
    position: relative;
    overflow: auto;
}
*/

.table {
      width: 100%;
}

mat-header-cell {
    display:flex;
    justify-content: center;
}

.mat-cell {
    display:flex;
    justify-content: center;
}

.mat-column-jobNumber {
    flex: 0 0 80px !important;
}

.mat-column-authorisedBy, .mat-column-createdBy, .mat-column-completedBy {
    word-wrap: break-word !important;
    white-space: unset !important;
    overflow-wrap: break-word;
    word-wrap: break-word;
    word-break: break-word;
    -ms-hyphens: auto;
    -moz-hyphens: auto;
    -webkit-hyphens: auto;
    hyphens: auto;
}

It is running on Angular 6 as this moment in time.
Any help or pointers on this matter would be greatly appreciated.

A: Having followed the example given in the link https://stackblitz.com/angular/gdbrmljnogk?file=src%2Fapp%2Ftable-expandable-rows-example.css, I had to remove the "height: 0;" from the detail-row class in order to get it working as intended.
Not sure why that is there and working in the example but not in my application, but hey ho. Having slept on the problem, I found it within minutes of restarting today, always the case though.
I'll leave the question and solution in here in case it is useful to someone else in the future.


text:
Q: Background Video NOT working on Sharepoint
*

*I am trying to put a background video on my SharePoint but instead of setting it as a background video it starts playing it and does not work. It works perfectly out of SharePoint (in browser) Need Help Please

Evidently there isn't something fundamentally wrong with my html since it renders in the browser. Are there any sharepoint html5 wizards out there who can help?
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Oryx Technologies</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">

       <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/normalize.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/bootstrap.min.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/font-awesome.min.css">
        <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,500,700' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/owl.carousel.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/owl.theme.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/animate.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/slicknav.min.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/responsive.css">
        <link rel="stylesheet" href="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/main.css">

    <video poster="" id="bgvid"  autoplay muted loop>

<source src="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/Jon%20Hopkins%20-%20Immunity%20(Rowbyte%20Plexus).mp4.webm" type="video/webm">
<source src="https://oryxtech.sharepoint.com/sites/newsite/Shared%20Documents/Jon%20Hopkins%20-%20Immunity%20(Rowbyte%20Plexus).mp4" type="video/mp4">
</video>

                                <im src="images/logo.png" alt="" title=""  height="40px" style="float: left;"/>

Home

Facebook

Twitter

LinkedIn

Website

Contact

Welcome to Oryx Technologies Intranet Portal

Explore Your Posibilities | Run With Oryx

Collabrative | Intelligent | Secure

Human Resources

Finance

Sales

Technology

Operations

Marketing

Projects

Investors

Business Partners

Technology Partners

Employee Self Services

Submit a Leave Application

Click Me

Claim an Expense

Click Me

Follow a Request

Click Me

Submit a Petty Cash Request

Click Me

Case Studies


text:
Q: Weird dependencies between array and a variable that is assigned by an element from that array When changing a variable that is assigned from an element of an array, that specific element in the array changes with the variable. However no where in the code is the array meant to change.
In the code the array is an array of objects, the variable is declared and assigned within the function randomCentroid (centroid), that function is called in initializeCentroid.
The code is used for generating random centroid regarding k-means clustering, Hereby the code:
//Return random centroid points with coloring
let randomCentroid = (fill) => {
  let r = Math.floor(Math.random()*points.length);
  let centroid = points[r];

  //points.splice(r, 1);
  centroid.fill = fill;
  return centroid;
}

//Gives distinct coloring to all centroid points
let initializeCentroids = (num) => {
  let allCentroids = [];
  for (let i = 0; i < num; i++) {
    let color = colors(i);
    let centroid = randomCentroid(color);
    centroid.id = 'centroid' + '-' + i;
    allCentroids.push(centroid);
  }
  return allCentroids;
}

//same for const.
let points = [{}, {}, {}, {}, {}],
  colors = d3.scaleOrdinal(d3.schemeCategory10);

initializeCentroids(3);

console.log(points);

console:
index.js:29
(5) [{…}, {…}, {…}, {…}, {…}]
0: {fill: "#2ca02c", id: "centroid-2"}
1: {}
2: {fill: "#ff7f0e", id: "centroid-1"}
3: {fill: "#1f77b4", id: "centroid-0"}
4: {}
length: 5
proto: Array(0)
How do I remove the dependency between the variable consisting out of the object that is assigned by the array and the array?

A: This part:
let centroid = points[r]
is grabbing a reference to an object in your points array
when changing centriod you change the object in the array as well.