text:
Q: removing table border I cannot get rid of this table border.
The initial HTML/CSS is from the ASP.NET MVC default.
I removed a lot of code and added a table on top.
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

                        @Html.Partial("_LogOnPartial")

            @RenderBody()

I've tried commenting out ALL the CSS, but I can't get rid of it.
My only guess is that one of the cryptic .js files is interferring with it. Or one of these exotic HTML containers is doing it.
Any guesses? I've googled around, but to no avail. I suppose it's something small I'm overlooking.

A: To remove from all tables, (add this to the head or external style sheet)

A: This will do it with border-collapse
table{
    border-collapse:collapse;
}

A: From your case, you need to set the border to none on
 and  tags.

                    @Html.Partial("_LogOnPartial")

A: Use Firebug to inspect the table in question, and see where does it inherit the border from. (check the right column). Try setting on-the-fly inline style border:none; to see if you get rid of it.
Could also be the browsers default stylesheets. In this case, use a CSS reset. http://developer.yahoo.com/yui/reset/

A: Try giving your table an ID and then using !important to set border to none in CSS. If JavaScript is tampering with your table then that should get around it.
<table id="mytable"
...

table#mytable,
table#mytable td
{
    border: none !important;
}

A: Please try to add this into inside the table tag.
border="0" cellspacing="0" cellpadding="0"

...

A: Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.
The solution is to get rid of those spaces.
Inside the table tag write:
cellspacing="0"

A: Use table style Border-collapse at the table level

A: border-spacing: 0; should work as well

A: .yourClass>tbody>tr>td{border: 1px solid #ffffff !important;}


text:
Q: enter data into a search field while web scraping in R I would like to find the elevations of multiple data points using this website: http://mygeoposition.com/.  It has one search field where latitude and longitude can be entered; you then press enter and the altitude pops up on the map.
I have a data set with about 2000 coordinates, and my question was how to use R to automate this task.  I can do basic webscraping, such as downloading tables using the XML package.  I'm just not sure how to writes a program that enters the coordinates into the field and then submits the query.
Thanks for any help!

A: Did you try the Google elevation API?
I maintain a package called rgbif for the GBIF API http://www.gbif.org/developer/summary
In there I have a function elevation(). It's somewhat flexible in the inputs it takes. Some examples are in a gist at :
https://gist.github.com/sckott/2d3ae5f0cecca3deb436

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I prevent an assignment statement to CheckBox.Checked from raising the CheckChanged event? Given
    Dim cb As CheckBox = New CheckBox
    AddHandler cb, AddressOf cb_CheckChanged
    cb.Checked = True

...aside from disabling the control, how can I prevent the assignment to Checked from raising the  CheckChanged event?  I grew up in MFC and events only got raised when the U S E R changed the control's state.  What was Softy was thinking?  Is it really impossible to distinguish between an event from the user and an event from my own assignment statement?  Yikes!

A: it is perfectly valid to raise the event regardless of the thing causing the event because the CheckChanged event just tells you when the Checked property has changed.
If you are trying to avoid the infinite loop you must be experiencing try adding a conditional:
If Not cb.Checked Then
  cb.Checked = True
End If


text:
Q: How does publish-subscribe design pattern establish loose coupling between components? C# If was going through a C# exam book and I read:

A popular design pattern (a reusable solution for a recurring problem)
  in application development is that of publish-subscribe. You can
  subscribe to an event and then you are notified when the publisher of
  the event raises a new event. This is used to establish loose coupling
  between components in an application.

It got me wondering that what does this have to do with loose coupling? Is it only because the components are now not interacting directly or do we have more reasons?

A: There are 2 important points in this .
1)  user don't need to wait for the result or fire a event like click or refresh to get the changes this decouples the event source form front end to back end
2) I am not sure you will do this but event sourcing is broadly used in publish subscriptions mechanism and this will allow you decople domain entity alot
Ex .
Employ salary credited will also trigger an event for creating a pay slip which will add the pdf on pay slip page of employee and send mail without  employees salary
This will decouple employee from pay slip generate service,  and mailing also . And also update the UI for end user


text:
Q: Difference between "stir up" and "provoke" Just I want to know the difference between the "stir up" and "provoke", where it should be placed exactly.

A: Interesting.
Well, to stir up means to instigate, or initiate or to set in motion. So a sample sentence could be

Che stirred up a revolution against oppression.

To provoke is to stimulate or give rise to a strong emotion or a reaction, which is typically an unwelcome one. A sample sentence could be

Che provoked the masses to set all the houses on fire.

Does that clear your doubts?

A: In this sense provoke is about creating a reaction

He provoked the crowd by telling them what their enemies would do

while stir up is used to mean excite

He stirred up the crowd by telling them how strong they were

Stir up is in common English usage because of a phrase in the old Anglican collect for the last Sunday before Advent

Stir up, we beseech thee, O Lord, the wills of thy faithful people

where it was a translation of the Latin excita. It was taken as an indicator that it was  time to make (i.e. stir up) Christmas puddings.

A: Provoke means "stimulate or give rise to a reaction or emotion (typically a strong or unwelcome one) in someone," while stir up means "arouse strong feeling in (someone); move or excite.

The decision provoked a storm of protest from civil rights organizations.
  She stirred up the sweating crowd.

The difference is that provoke is also used for an unwelcome reaction or emotion, while stir up is used for a strong feeling.


text:
Q: Error:Execution failed for task ':app:processDebugResources'. Error: more than one library with package name 'android.support.graphics.drawable' My android studio is failing to build right now due to the execution failed for task and it says I have more than one library with package name android.support.graphics.drawable. Here is my build.gradle (Project: DemoApp)
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
         }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle for (Module: app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.0"
    defaultConfig {
        applicationId "com.example.rishavsharma.demoapp"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:28.+'
    testCompile 'junit:junit:4.12'
}


text:
Q: java.lang.Long cannot be cast to java.lang.Double what am I missing? I am attempting to pull session data (numbers) from Firestore and I get a java.lang.Long cannot be cast to java.lang.Double error.
I've read similar articles about converting between long and double although no implementations have worked for me yet, perhaps I have implemented them incorrectly. Can anyone please advise where I am going wrong.
I have tried this but also resulted in error:
Long x = (Long) session.get("rep_set1");
s.setRepsSet1((double) x);

This is the full method:
public class BenchSessionModel extends  Session {
    public BenchSessionModel() {
        type = ExerciseType.BENCH;
    }

    public static BenchSessionModel fromJson(Map<String, Object> session) {
        BenchSessionModel s = new BenchSessionModel();

        s.setRepsSet1((double) session.get("rep_set1"));
        s.setRepsSet2((double) session.get("rep_set2"));
        s.setRepsSet3((double) session.get("rep_set3"));
        s.setGoalReps((double) session.get("goal_reps"));
        s.setGoalWeight((double) session.get("goal_weight"));
        s.setRpe((double) session.get("rpe"));
        s.setWeight((double) session.get("weight"));
        s.setStallCount((int) session.get("stall_count"));

        String exp= (String) session.get("level");
        if(exp.equalsIgnoreCase("beginner")){
            s.setXpLevel("BEGINNER");
        }else{
            s.setXpLevel("ADVANCED");
        }
        s.setType(ExerciseType.BENCH);
        return s;
    }
}

A: Long x = (Long) session.get("rep_set1");
if(x != null){
    s.setRepsSet1(x. doubleValue());
}

Long object has a doubleValue() method, you can use it.


text:
Q: super simple cipher function in python. comparing a list to keys in a dictionary I am working on ways to get me thinking in python. I have a simple idea that will take a number and give the corresponding "value" from a dictionary.
So basically I would like to have a number or numbers given, and then turn those numbers into a word.
The overall all view is to have a dictionary with keys ranging for 1 to 26 with values going from a to z. So 1 would equal "a" and 26 would equal "z".
I have a variable d = 1, and need to get the output of 'a'. Then increase size of this function for a list like (1,2,3,4) which output would be a, b, c, d.
Here is what I have so far.
d = 1

def code_scram(x):

    c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

    scram = ""

    for i in d:
        if i in c:
            scram += c[i]
    return scram

print code_scram(d)

However, its not working out as planned.

A: Your for loop should iterate through x, not d.
def code_scram(x):
    c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
    scram = ""
    for i in x:
        if i in c:
            scram += c[i]
    return scram

print code_scram([1,2,3,4])

Result:
abcd

The function only works for lists, so passing in the integer d won't work. Pass in a list instead.
d = [1]
print code_scram(d)

If you want the function to work for lists and lone integers, you can perform a type check, and convert as necessary.
def code_scram(x):
    if isinstance(x, int):
        x = [x]
    c = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
    scram = ""
    for i in x:
        if i in c:
            scram += c[i]
    return scram

d = 1
print code_scram(d)

Result:
a


text:
Q: Proof of Generalized Bézout theorem using Veronese Embedding map I was wondering if it is possible to prove a sort of Bézout theorem from the Veronese Embedding Map:
Let $f_1, \ldots, f_m \in \mathbb{C}[x_0, x_1, \ldots, x_n]$ be $m$ homogeneous polynomials all of the same degree $d$.
Considering the Veronese map of degree $d$ from the projective space $\mathbb{P}^n$, $V_{d, n} : \mathbb{P}^n \rightarrow \mathbb{P}^N$, we have that the locus $Z(f_i) = V_{d,n}^{-1}(Z(H_i))$ where $H_i$ is a hyperplane in $\mathbb{P}^N$.
Then we have $Z(f_1, \ldots, f_m) = \cap_{i} Z(f_i) = V_{d,n}^{-1}(\cap_{i} Z(H_i))$. Then we can say something about the dimension of $Z(f_1, \ldots, f_m)$ based on the dimension of the intersection of hyperplanes (easy to deal with) and the inverse image of the Veronese map (or the intersection with the Veronese variety).

I am asking if there is some source where I can look up the following questions (or if someone is willing to explain them here):

*

*Is there something known about the (hopefully nice) intersection of linear subspaces with the veronese variety?

*Is there any method to bypass the restriction on the degree of the polynomials to be the same, except the following one (which has the downside of requiring too many polynomials to substitute just one)?
Let $f$ be a polynomial of degree $k < d$. One can substitute it with $f \cdot x_0^{d-k}, f \cdot x_1^{d-k}, \ldots, f \cdot x_n^{d-k}$. (If they all vanish in a point $p$ and $f(p) \neq 0$, then we get a contradiction since $x_0 = x_1 = \ldots = x_n = 0$)

*I am hoping in particular that the following is true: Let $K$ be a linear subspace of codimension $r$ (in $\mathbb{P}^N$). Then $V_{d,n}^{-1} (K)$ has codimension $r$ (in $\mathbb{P}^n$). [Answered Negatively by Mohan]

*More specifically, if we have $m = n = 3$ and we add the hyphothesis that the associated hyperplanes to $Z(f_1), Z(f_2), Z(f_3)$ are the zero loci of linearly independent equations, is it possible to prove by this argument that the intersection $Z(f_1, f_2, f_3)$ consist of a finite number of points?

A: For ease of notation, take $d=2$ and consider the Veronese map with $y_0,\ldots, y_N$ the co-ordinates of $\mathbb{P}^N$ and the Veronese map has $y_0=x_0x_1, y_1=x_0x_2$. Then let $K=\{y_0=y_1=0\}$. $K$ has codimension 2, but $V_{2,n}^{-1}(K)$ has codimension one, since it contains $x_0=0$. This answers your 3.
4 is unclear, are you assuming something about $n$? If $n$ is arbitrary, why should the common zeroes of 3 polynomials be a finite set of points even with any assumption on them?


text:
Q: Python Pandas : Return column header/name where values equal the other in the dataframe I am trying to get the column header location(s) where the value in the last column equals a value in any of the other columns. This should be appended as a new column. Assuming I have the dataframe:
       category    color          size    max_value
a      [2, 1]     [1,1,1]      [1,1,1]      [1,1,1]
b       [2,1]   [1,1,1,1]    [1,1,1,1]        [2,1]
c         [1]         [3]      [1,1,1]          [3]

While this has been answered in some form here: Return the column name(s) for a specific value in a pandas dataframe, I have lists as opposed to numbers in my case and keeps throwing an error
I would expect the results to be:
    category         color     size       max_value       matchedcols
a      [2, 1]     [1,1,1]      [1,1,1]      [1,1,1]       color,size
b       [2,1]   [1,1,1,1]    [1,1,1,1]        [2,1]         category
c         [1]         [3]     [1,1,1]           [3]            color

Thanks!

A: You can do the comparison after dropping down to numpy
m = df.iloc[:, :-1].to_numpy() == df.max_value.to_numpy()[:, None]
#array([[False,  True,  True],
#       [ True, False, False],
#       [False,  True, False]])

df['matched_cols'] = [', '.join(df.columns[:-1][x]) for x in m]
#  category         color          size  max_value matched_cols
#0   [2, 1]     [1, 1, 1]     [1, 1, 1]  [1, 1, 1]  color, size
#1   [2, 1]  [1, 1, 1, 1]  [1, 1, 1, 1]     [2, 1]     category
#2      [1]           [3]     [1, 1, 1]        [3]        color

A: Doesn't look like a problem for pandas library, but anyway.
df = df.applymap(tuple)
cols = df.drop('max_value', 1).columns

df['matchedcols'] = (df.drop('max_value', 1)
                       .eq(df['max_value'], axis=0)
                       .apply(lambda s: ', '.join(cols[s]), 1))

  category         color          size  max_value  matchedcols
a   (2, 1)     (1, 1, 1)     (1, 1, 1)  (1, 1, 1)  color, size
b   (2, 1)  (1, 1, 1, 1)  (1, 1, 1, 1)     (2, 1)     category
c     (1,)          (3,)     (1, 1, 1)       (3,)        color

Of course if you need the lists, just do all operations in a copied df, keep the original and just add back at the df['matchedcols'] = (...) part.

A: As you said last column, so I use iloc and dot here
df1 = df.iloc[:,:-1].eq(df.iloc[:,-1], axis=0)
df['matchedcols'] = df1.dot(df1.columns+',').str.strip(',')

Out[971]:
  category         color          size  max_value matchedcols
a  [2, 1]   [1, 1, 1]     [1, 1, 1]     [1, 1, 1]  color,size
b  [2, 1]   [1, 1, 1, 1]  [1, 1, 1, 1]  [2, 1]     category
c  [1]      [3]           [1, 1, 1]     [3]        color


text:
Q: Updating Apple g++/gcc What is the difference between Apple gcc and GNU gcc? Is Apple gcc a superset of the standard one?
The g++ version information in my OSX shows:
$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)

Some of the latest features of C++11 are in gcc 4.3/4.4 as per this. Is there any newer version of Apple gcc I can upgrade to. if so, how can i do it? I have Xcode 4.1

A: Well, for the first part, Apple in this case is using the LLVM backend for g++ as the default g++. Apple also installs the wonderfully named clang and clang++ front-ends for LLVM. However, there is absolutely nothing stopping you from installing newer branches of GCC; MacPorts has packages for everything up to 4.6. If you look for "APPLE ONLY" in the gcc man page, you can see what won't be available outside of Apple branches.

A: Beside the already mentioned llvm-gcc and clang, there is also an Apple-supplied gcc-4.2 (without LLVM backend) at /usr/bin/gcc-4.2 in Xcode 4.1.  But do not overwrite the Apple-supplied versions in /usr/bin.  All three support a superset of features include multi-arch support and multi-abi support not found in the vanilla GNU distributions and many third-party packages depend on these features in OS X.  If you install something via MacPorts or from source, it will be installed to a different path, like /opt/local/bin or /usr/local/bin.  Use PATHs or environment variables to manage which compiler you use.

A: You can use macport to install newer versions. You can download it here. Once you have installed gcc with macport, you can use it with xcode by adding an user-defined setting to your build :
- Go to the build setting of your project
- Click on the add build setting button
- Choose user-defined setting
- Name it CC
- In the value field, put the path of the gcc version installed by macport.

A: One thing that definitely is present in the Apple GCC branch but not in GNU GCC is blocks.


text:
Q: new line inside an alias command without newline character I want to setup an alias that would show useful git commands to make it easier to find what I'm looking for, and echoing each to a new line
alias git_help='echo "Delete local branch: git branch -d <branch_name>" \n; echo "Delete remote branch: git push origin --delete <branch_name>" \n'

but each time I run it, while the output does break into a newline, the 'n' character is still there:
Delete local branch: git branch -d <branch_name> n
Delete remote branch: git push origin --delete <branch_name> n

Is there a way to do this without printing the 'n' character at the end of each line?

A: echo already adds a newline, so just remove the \n entirely.
[user@host]$ alias git_help='echo "Delete local branch: git branch -d <branch_name>" ; echo "Delete remote branch: git push origin --delete <branch_name>"'
[user@host]$ git_help
Delete local branch: git branch -d <branch_name>
Delete remote branch: git push origin --delete <branch_name>
[user@host]$

Using a function over an alias may make this easier to understand.
git_help() {
  echo "Delete local branch: git branch -d <branch_name>"
  echo "Delete remote branch: git push origin --delete <branch_name>"
}


text:
Q: Storing a reference to a java class in a database I have some kind of job control with persistence via a database.
There is a interface for actions:
public interface IAction {
    Object perform(Work work, Map<String, String> parameter) throws Exception;
}

There are multiple implementations:
public class SingleFileConvertAction implements IAction {
    public InputStream perform(Work work, Map<String, String> parameter) throws Exception {
        // ...
    }
}

public class CacheDeleteAction implements IAction {
    public Object perform(Work work, Map<String, String> parameter) throws Exception {
        // ...
    }
}
// ...

There is a job control class:
@Entity
public class ActionControl {

    @Id
    @GeneratedValue
    private Integer id;

    @ElementCollection
    private Map<String, String> parameter = new HashMap<String, String>();

    @ManyToOne
    @JoinColumn(name = "work_id", referencedColumnName = "id", nullable = false)
    private Work work;

    private IAction action;

    private Date requestTime;
    private Date startTime;
    private Date endTime;

    // ...

    private ActionControl() {}

    public ActionControl(Work work, String action, Map<String, String> parameter) {
        this.parameter = parameter;
        this.work = work;
        // ...
    }
}

Now I want to save the action control to the database. I only need to know, which action class to use. Everything else is saved in work and parameter.
I thought about saving a string and do a switch() to choose it like "CacheDeleteAction" -> CacheDeleteAction but I assume there is a better way to do it. Is it possible to save "CacheDeleteAction.class" in a database field? (I saw it in Spring annotations)
How to save a reference to a java class in a database?

A: as @XtremeBaumer said depends on your usage, if you need to create an instance later on then what XtremeBaumer has suggested would be preferred way, else with enum it would go something like this,
   public enum IActionEnum {
        CACHE_DELETE_ACTION("Cache delete action"),
        SINGLE_FILE_CONVERT_ACTION("Single file convert action"),

        private String actionDescription;

        IActionEnum(String description) {
            actionDescription= description;
        }

        @Override
        public String toString() {
            return actionDescription;
        }
    }

And whenever you would like to save it to DB you can use it like,
IAction actionControl = new IAction();
// set all other parameters
actionControl.setIAction(IActionEnum.CACHE_DELETE_ACTION)

actionControlRepository.save(actionControl);


text:
Q: Powershell RegEx - capturing "too much" (not honoring non-Greedy indicators?) The code below is returning:
partner=<Partner>
 more stuff <Name>Test</Name>
 other things </Partner>  <Partner>
 more stuff <Name>CompanyX</Name>
 other things </Partner>

but I want it to return:
partner=<Partner>
 more stuff <Name>CompanyX</Name>
 other things </Partner>

Sample Code:
$partyName = "CompanyX"

#$bindings = [IO.File]::ReadAllText($inputFileName)

$bindings = "starting stuff <Partner>`r`n more stuff <Name>Test</Name>`n other things </Partner>  <Partner>`r`n more stuff <Name>CompanyX</Name>`n other things </Partner> ending stuff"

$found = $bindings -match "(?s)(<Partner>.*?<Name>$partyName</Name>.*?</Partner>)"

if ($found)
{
    Write-Host "matched"
    $partner = $matches[1]
}

Write-Host "partner=$partner "

A: As TheIncorrigible1 says: Use an xml parser instead of Regex.
However.. Since the reason for doing it with regex for you might simply be te see IF and HOW it can be done using Regular Expression you can use:
$found = $bindings -match "(?sx)(<Partner>(?:((?!</Partner>).)+<Name>$([Regex]::Escape($partyName))</Name>)(?:((?!</Partner>).))*</Partner>)"

A: The non-greedy duplication symbols (.*?) are being honored, but they're not enough in this case:
<Partner>.*?<Name>$partyName</Name> matches between <Partner> and the next instance of the <Name> element, but that doesn't guarantee that there won't be another <Partner> tag in between.
In other words: Your regex will invariably match between the first <Partner> tag and the <Name> element of interest.
To prevent that, you need a negative look-ahead assertion ((?!...)) that rules out intervening <Partner> tags:
# Sample input, defined as a here-string.
$bindings = @'
starting stuff <Partner>
more stuff <Name>Test</Name>
 other things </Partner> <Partner>
 stuff of interest before <Name>CompanyX</Name>
 stuff of interest after </Partner> even more </Partner> ending stuff
'@

# Escape the name to ensure it is treated as a literal inside the regex.
# Note: Not strictly necessary for sample value 'CompanyX'
$partyName = [regex]::Escape('CompanyX')

# Use a negative look-ahead assertion - (?!...) - to rule out intervening
# <Partner> tags before the <Name> element of interest.
if ($bindings -match "(?s)<Partner>((?!<Partner>).)*<Name>$partyName</Name>.*?</Partner>") {
  # Output the match.
  $matches[0]
} else {
  Write-Warning 'No match.'
}

The above yields:
<Partner>
 stuff of interest before <Name>CompanyX</Name>
 stuff of interest after </Partner>

*

*(?!<Partner>). matches a single character (.) not preceded by string <Partner>.

*This subexpression must itself be matched against each character (if any) between the opening <Partner> and the <Name> element of interest, hence it is wrapped in (...)*

*

*I presume this makes for an inefficient matching algorithm, but it does work.
As mentioned, using proper XML parsing with an XPath query is worth considering as an alternative.

*You could make this matching more efficient by using (?:...)* as the wrapper, which tells the regex engine not to capture (the latest) match of the subexpression. ((...) are capture groups, meaning that what the subexpression matches is reported as part of what automatic variable $Matches returns, which is not needed here, so ?: suppresses that).


text:
Q: Multipliers in trace spaces I need a reference for the following fact. Let $\Omega \subset \mathbb R^n$ be an open domain with $C^{1,1}$ boundary (maybe, less regularity is needed). Let $H^{1/2}(\Gamma)$ be the trace space of $H^1(\Omega)$. Then, the multiplication with a function $\theta \in C^{0,1}(\Gamma)$ is a bounded, linear operator in $H^{1/2}(\Gamma)$.
I think it can be easily proved by using extensions of the functions from $\Gamma$ to $\Omega$, but I think, there should be a nice reference somewhere.


text:
Q: Best practice for hiding virtual console while rendering video to framebuffer I'm currently rendering video in Linux directly to the framebuffer using GStreamer.
I was wondering how I would go about hiding the virtual console while rendering. I can stop the cursor from blinking, but that only works when no text changes on the console.
X seems to create a new screen accessible with Ctrl(+Alt)+F7 – is it possible to do something like that myself? Somehow be able to switch between a console & the rendering screen with Ctrl+Alt+F1 and Ctrl+Alt+F2.

A: X does not create a new screen.
To use the same display and input event devices that the kernel's built-in terminal emulator is using (to present its virtual terminals) a program must arrange to share them.  The kernel's terminal emulator provides an API through which such a program can negotiate when it has responsibility for input and output, and when the kernel's built-in terminal emulator has.
This API is through ioctl() calls on a file descriptor that is open to a kernel virtual terminal character device.  There are 64 of these devices in Linux, 16 in FreeBSD/PC-BSD.  X does not create these.  It opens an existing one — by convention one which no TUI programs are simultaneously trying to use as a kernel virtual terminal.  In other words: By convention there's no TUI login session run on the kernel virtual terminal device that X opens and uses.
A program that shares with the kernel terminal emulator must …

*

*… tell the kernel terminal emulator to stop writing into the framebuffer to display output, or the cursor.  This is done with the KDSETMODE ioctl() to set the nowadays quite misnamed KD_GRAPHICS mode.  When in KD_TEXT mode the kernel terminal emulator doesn't nowadays usually have anything to do with display hardware being in an actual text mode.  So-called framebuffer consoles have the display hardware in graphics mode.  The distinction between KD_TEXT and KD_GRAPHICS modes is that in the former mode the kernel's terminal emulator will draw character glyphs onto the framebuffer as the terminal line discipline delivers output to it, and will also draw a cursor; whereas in the latter mode it will not do any drawing at all.  These would actually be better thought of as "draw graphics" and "don't draw graphics" modes nowadays, were the wrong one not named "graphics".  ☺

*… negotiate virtual terminal switching, if applicable.  This is done with the VT_SETMODE ioctl(), with which the program can arrange to receive signals when the virtual terminal that it is using for the ioctl() calls is switched to or away from.

*… negotiate the handling of input with the kernel terminal emulator.

*

*On Linux one might be reading from the input event subsystem directly, in which case the program tells the kernel's terminal emulator to stop reading those same input events, which it receives copies of, to stop translating them into characters, and to stop sending them off to the line discipline as input.  How this is done varies:

*

*The original way to do this was with the KDSKBMODE ioctl(), switching the virtual terminal into K_RAW mode.  In this mode, the kernel terminal emulator still receives input events from the kernel's input event subsystem, but it performs no processing of them whatsoever, passing them to the line discipline as character input.  However, this mechanism (which had its roots in the way that X worked before there was an input event subsystem) was broken, in that input was still being sent to the line discipline and still had to be drained.  And it required that the termios input state for the terminal also be in raw mode, otherwise the raw scancodes would be misinterpreted as special characters such as the STOP or INTR characters by the line discipline.

*A way, once considered to be better, to do this was with the  KDSKBMODE ioctl(), switching the virtual terminal into K_OFF mode.  In this mode, the kernel terminal emulator not only wouldn't process the input events, it wouldn't send them along to the line discipline.  However, this mechanism was broken, because it was part of an K_OFF/K_RAW/K_CODE/K_XLATE mode switch.  systemd and other similar systems would manage virtual terminal modes, and end up switching virtual terminals out of K_OFF mode.

*The better way nowadays is to use the KDSKBMUTE flag.  This turns off all input event processing without affecting, or being affected by, the K_RAW/K_CODE/K_XLATE mode switch.

*On FreeBSD/PC-BSD, there's no separate input event character device in the first place.  One reads keyboard input through the kernel virtual terminal anyway, so whilst one might want to switch it into scancode (K_RAW) or keycode (K_CODE) modes, one does not want to switch it off.

There are some interactions, here.  An X server, for example, switches the virtual terminal into keycode mode, reads the keycodes and turns them into X keysyms, passing them through the X keyboard handling mechanisms.  This means that the kernel's built-in terminal emulator never gets to perform the special processing for the Alt+Fn keyboard sequences.  It is the X server that has to itself recognize Ctrl+Alt+Fn.
Further reading

*

*Arthur Taylor (2013-02-02).  systemd should not call KDSKBMODE on a VT with X.  systemd-devel.

*Adam Jackson (2012-11-16).  [PATCH] vt: Drop K_OFF for VC_MUTE.  Linux kernel mailing list.

*Adam Jackson (2012-11-16).  [PATCH] linux: Prefer ioctl(KDSKBMUTE, 1) over ioctl(KDSKBMODE, K_OFF).  xorg-devel.

*Michael K. Johnson (1994-06-01). Linux Programming Hints.  Linux Journal.


text:
Q: MongoDB aggregate elements of nested arrays We've got a MongoDB (v2.4) collection that contains time-series snapshots:
{"foo": "bar",
 "timeseries": [{"a": 1, "b": 2},
                {"a": 2, "b": 3},
                ...]}
{"foo": "baz",
 "timeseries": [{"a": 0, "b": 1},
                {"a": 2, "b": 3},
                ...]}

I need to group all the entries by the foo key, and then sum the the a values of the last entry in each of the timeseries values of each document (timeseries[-1].a, as it were), per key. I want to believe there's some combination of $group, $project, and $unwind that can do what I want without having to resort to mapReduce.

A: Are you looking for something along the lines of:
> db.collection.aggregate([
  {$unwind: "$timeseries"},
  {$group: {_id: "$_id", foo: {$last: "$foo"},
                         last_value: {$last: "$timeseries.a"}}},
  {$group: { _id: "$foo", total: { $sum: "$last_value" }}}
])
{ "_id" : "baz", "total" : 2 }
{ "_id" : "bar", "total" : 2 }

*

*the $unwind stage will produce one document per-item in the timeserie

*after that, documents are grouped back again, keeping only the $last value

*finally, a second group clause will group (and sum values) by the foo field.

As a final note, I don't think this will be time efficient for very long time series as basically MongoDB will have to iterate over all items just in order to reach the last one.


text:
Q: Need to find quartile ranges for my dataframe and the creating a pivot table with it in Python Pandas I have collected data from Google API for Traffic and cleaned them to make the first table. This includes data from every 15 mins for each hour as a separate row. different road junctions were made that were subtracted from the previous one. e.g., Junct1_reach was taken by subtracting 1916 - 0,  Junct2_cross was taken by subtracting  1784 - 1916. the data is for 2 months Jab - Feb

Now I want to make a new dataframe That looks as follow:
with min, max, quartile ranges & mean for each day with day and time being the index. I want output like this (mean isn't showing up in the table)

dayofWeek
Time
Junct1_reach
Junct1_reach
Junct1_reach
Junct1_reach
Junct1_reach

min
max
q1
q2
q3

Monday
0000

Monday
0100

:
:

Friday
row

I did the following code and I was able to generate values for min & max:
# Create a pivot table
pivot_table3 = df1.pivot_table(values=['1916', '3913', 'Junc1_cross'], index=['dayOfWeek', 'time'],
                             aggfunc={'1916': [min, max],
                                      '3913': [min, max],
                                      'Junc1_cross': [min, max]})

# Print the pivot table
df_pivot3 = pivot_table3.reset_index()
df_pivot3

and this was the output:

How can I modify this to generate quartile ranges?


text:
Q: Wordpress search result to match exact word I am trying to get the Wordpress search results to match the exact search key to a word in post.
I have tried the solution from the link below but the search results still returns posts with titles that has words that matches part of the search key:
https://wordpress.stackexchange.com/questions/177183/make-a-wp-query-search-match-exactly-the-search-term/17786
For example, the search key is thank, I would like the result to be something like Thank you so much and not include Thanking is important.

A: You can try this bellow code.
That code search your word inside post content only. after use that code the search oparation dose not perform on post title.
//searh contenet only
function _search_by_content_only( $search, $wp_query )
{
    global $wpdb;
    if(empty($search)) {
        return $search; // skip processing - no search term in query
    }
    $q = $wp_query->query_vars;
    $search =
    $searchand = '';
    foreach ((array)$q['search_terms'] as $term) {
        $term = esc_sql($wpdb->esc_like($term));
        $search .= "{$searchand}($wpdb->posts.post_content regexp '[[:<:]]".$term."[[:>:]]')";
        $searchand = ' AND ';
    }
    if (!empty($search)) {
        $search = " AND ({$search}) ";
        if (!is_user_logged_in())
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }
    return $search;
}
add_filter('posts_search', '_search_by_content_only', 500, 2);

Try the above code and let me know the result.


text:
Q: cc: error: this_example.o: No such file or directory I've a SDK with some examples, but when I want to compile any of these examples, I receive this error:
cc -g -I -o this_example.o -c this_example.c
cc: error: this_example.o: No such file or directory
make: *** [Makefile:15: this_example.o] Error 1

Here is the makefile:
CC ?= gcc
INC_PATH ?= $(realpath ../inc)
LIB_PATH ?= $(realpath ../lib)
LIBS ?= $(wildcard $(LIB_PATH)/*.a) -pthread -lrt -lm
LDFLAGS :=-g -L$(LIB_PATH)
CFLAGS +=-g -I$(INC_PATH)

EXAMPLES=sdk_this_example_folder

.PHONY: all

all: $(EXAMPLES)

%.o: %.c
    $(CC) $(CFLAGS) -o $@ -c $<

this_example: this_example.o  frozen.o
    $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS) -Wl,-rpath,'$$ORIGIN/../../lib'

clean:
    rm -f *~ *.o $(EXAMPLES)

In this_example_folder, I've four files: Makefile, this_example.c and frozen.c and frozen.h. Where is the problem? Thank you everybody for your help!

A: The realpath function returns the empty string if the path you are expanding doesn't exist.
You have:
INC_PATH ?= $(realpath ../inc)

then:
CFLAGS +=-g -I$(INC_PATH)

and your command output is:
cc -g -I -o this_example.o -c this_example.c

Clearly, the value of INC_PATH is empty (since there's nothing after the -I in the command line) which  means the directory ../inc does not exist.
As for why you get that failure: the -I option expects a filename afterwards.  Since you don't have one, it uses -o (the next word in the command line) as the filename.  That means that this_example.o is treated as a file to compile, rather than the output file, and of course it doesn't exist.


text:
Q: Query error for query containing a column named "order" For the life of me i can seem to figure it out
INSERT INTO category SET CategoryName = 'Hardware_1',
Category = 'HARDWARE', Status = '1', Order = '1'

 You have an error in your SQL syntax; check the manual that
 corresponds to your MySQL server version for the right syntax
 to use near 'Order = '1'' at line 1

CREATE TABLE `category` (
  `CategoryID` int(11) NOT NULL AUTO_INCREMENT,
  `CategoryName` varchar(255) NOT NULL,
  `Category` varchar(255) NOT NULL,
  `Status` tinyint(4) NOT NULL,
  `Order` int(11) NOT NULL,
  PRIMARY KEY (`CategoryID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

A: Order is a reserved word.  Enclose Order in backticks if you intend to use it.
INSERT INTO category SET CategoryName = 'Hardware_1',
Category = 'HARDWARE', Status = '1', `Order` = '1'

A: As Cfreak pointed out in the comments, your syntax is valid. It's your use of the unescaped Order keyword that is the issue.
Insert Into category (CategoryName, Category, Status, `Order`)
Values ('Hardware_1', 'HARDWARE', '1', '1')

A: INSERT
INTO    category (CategoryName, Category, Status, `Order`)
VALUES  ('Hardware_1', 'HARDWARE', 1, 1)

A: order is a reserved word in sql, you proably need to escape that column name:
INSERT INTO category SET CategoryName = 'Hardware_1', Category = 'HARDWARE', Status = '1', [Order] = '1'


text:
Q: Flutter How to insert nested JSON array into different SQLite tables I hope I could explain clearly my need, What I have is an API that I connect to and recive a JSON from it.
The Json is nested into a list and an object that have a 2ed tier list.
What i want is to insert this Josn into my local DB (Using SQLite for Flutter).
The point I reached is the inserting of the 1st tier of the json data, but could not insert the data that exist as a list in the 2ed tier. Although I serilize it but the list after when i try to insert, have no mappnig from a list form to the database table fields.
Its like I have [Class User] and [Class Company] A user have many companies rolled in.
When serilaizing the data from the JSON I have the data come to the User Class then nesting to the Companies Class and do the serilaizng for the 2ed tier of the json object then return.
The next step is to insert the data into DB but the data I have in my last object is something like this:
"username" : userName
"company"  : CompanyList  --- This is a list and cant be inserted into the DB directly in a nested way. As the companylist have multyble fields. and more than one records ex: two companies.
I belive there would be A map to do this in reverse so i could insert it to the DB (I have it in my Company Class) but i cant call it from the place where i try to insert the data into DB due of the differnce in the Classes instances
The instance in my hand is a User Type instance [The main Class between the two], while the companyList if wanted to map it needs a Company insance type.
I can provide code or explain more, any help or idea about the approach may help. Thanks a lot!
#EDIT
This where i try to insert the data into DB
The first inserting is fine but the 2ed one is not.
  Future<int> createUserPermissions(UserPermissions userPermissions, ComListPermissions comListPermissions) async {
    final db = await dbProvider.database;
    var result = db.insert(userPermissionsDBTable, userPermissions.mapToDB());

    db.insert(userCompaniesTableDB, comListPermissions.toJson());
    return result;
  }

User Class
class UserPermissions {
  final String userName;
  final  List<ComListPermissions> comLists;
  final bool active;

  final String groupName;
  final int companyId;
  final String permissions;
  final ComListPermissions company;

  UserPermissions({this.company, this.groupName, this.companyId, this.permissions, this.userName, this.active, this.comLists});

  factory UserPermissions.mapFromJsonToDB(Map<String, dynamic> data) {
    if (data['comLists'] != null) {
      var companyObjJson = data['comLists'] as List;

      List<ComListPermissions> _companies = companyObjJson
          .map((companyJson) => ComListPermissions.fromJson(companyJson))
          .toList();

      return UserPermissions(
        userName: data['userName'],
        active: data['active'],
        comLists: _companies,
      );
    } else {
      return UserPermissions(
        userName: data['userName'],
        active: data['active'],
      );
    }
  }

  Map<String, dynamic> mapToDB() => {
        "userName": userName,
       // "comLists": comLists,
        "active": active,
      };

}

Comapny Class
class ComListPermissions {
  ComListPermissions({
    this.groupName,
    this.companyId,
    this.permissions,
  });

  String groupName;
  int companyId;
  String permissions;
  //List<String> permissions;

  factory ComListPermissions.fromJson(Map<String, dynamic> json) {
    if (json['permissions'] != null) {
      var permissionsObjJson = json['permissions'] as List;
      String s = permissionsObjJson.toString();

      return ComListPermissions(
        groupName: json["groupName"],
        companyId: json["companyID"],
        permissions: s,
      );
    } else {
      return ComListPermissions(
        groupName: json["groupName"],
        companyId: json["companyID"],
      );
    }
  }

  Map<String, dynamic> toJson() => {
        "groupName": groupName,
        "companyID": companyId,
        "permissions": permissions,

    //"permissions": List<dynamic>.from(permissions.map((x) => x)),
      };
}

A: I Just added a for loop and sent index every time i needed to insert a new recırd into my DB
  Future<int> createUserPermissions(UserPermissions userPermissions) async {
    final db = await dbProvider.database;
    var result = db.insert(userPermissionsDBTable, userPermissions.mapToDB());
    int index = userPermissions.comLists.length;
    for (int i = 0; i < index; i++) {
      db.insert(userCompaniesTableDB, userPermissions.toDatabaseForCompany(i));
    }
    return result;
  }

  Map<String, dynamic> toDatabaseForCompany(int index) => {
    "companyID": comLists[index].companyId,
    "groupName": comLists[index].groupName,
    "permissions": comLists[index].permissions,
  };


text:
Q: Adding to featureGroup asynchronously I've run into this problem with Leaflet Map. I am trying to loop over some addresses, make a call for each loop to get the lat-long, plot on mymap, and group the markers to bound them using fitBounds
createRequest(projectUrl, getAddresses, handleErrors, projectInit)
    .then( (jsonAddresses) =>{
        // jsonAddresses = [{building_num: 100, street_name: 'main', ... }, {}, ...]

        let state_province = ''
        let markers        = []
        let projectsGroup  = L.featureGroup().addTo(mymap)   // Creating an empty group to add markers to later on

        for (let address of jsonAddresses )
        {

            let theAddress  = address.building_num + ' ' +
                              address.street_direction + ' ' +
                              address.street_name + ' ' +
                              address.street_type + ' ' +
                              address.civic_address_city + ' '+
                              address.state_province + ' ' +
                              address.country

            addressInit = {'address': theAddress ,
                           'buidlingNum': address.building_num,
                           'streetName': address.street_name,
                           'city': address.civic_address_city
                          }

            // Using geoApify API to get lat-long for each address
            geoCodingUrl = `${geoapifyURL}${theAddress}&apiKey=${GEOAPIFY_API_KEY}`

            // createRequest makes asynchronous call and returns a json response
            createRequest(geoCodingUrl, getLatLongGeoApify, handleErrors, addressInit )
            .then( (response) => {
                latLongAddress = response
                latLongAddress.address = address  // address comes from the for-loop

                latLongs.push(latLongAddress)   // latLongAddress is a list of objects [{<lat>,<lon>}, {},...] returned by createRequest
                return latLongs
            })
            .then( (result)=> {
                let marker = L.marker( [latitude,longitude] ).addTo(mymap)
                marker.addTo(projectsGroup)

                markers.push(marker)

                for (let project of result)  // project represents the lat-long of the project, e.g. project = [<lat>,<lon>]
                {
                    marker.setLatLng( [project.lat, project.lon] ).bindPopup("Try!") // Setting the marker coordinates
                    marker.addTo(projectsGroup)   // Adding the marker to the projectGroup
                }
                mymap.setZoom(12)

            })

        }

        // test_marker is to create another marker that cannot fit in the
        // default view, which necessitates fitBounds to work properly
        const test_marker = L.marker( [48.354495, -122.0905781] ).addTo(mymap)
        test_marker.addTo(projectsGroup)

        mymap.fitBounds(projectsGroup.getBounds() )

        return latLongs

    })

});

When I look at my markers in the console, it looks like an empty list, but when I open it, there are 4 markers in it.  I know this must have to do with asynchronous nature of the call and the fact that the console is live, so initially it does not have any data and then it receives the data.  But, I cannot figure out how I can add markers to the featureGroup in the async-proper way so I can bound them

A: If I have understood this right:

*

*You pull a list of addresses from somewhere called projectUrl

*For each of those addresses you perform a call to a Geocoding API (geoapify in your specific case)

*

*Each of those geocoding calls is asynchronous

*You want to have a L.Marker for the result of each of those geocoding calls (i.e. one L.Marker per address)

*

*(Your current code seems to suggest that you want a marker for every geocoding result for every address, and I'm gonna think that's not desired)

*You want to do something (i.e. fitBounds) once all the markers are ready (i.e. when all the geocoding requests have been performed and handled)

*You are using Promises (even if you're not aware) since .then(callback) is several times in your code.

For this scenario, the trick is to leverage Promise.all to trigger a function call when all geocoding requests are done.
I see two main approaches here, depending on what each promise shall resolve to: a lat-lng or a marker.
So we can do something like:
createRequest(projectUrl, /* stuff */).then((jsonAddresses) => {
    let projectsGroup = L.featureGroup().addTo(mymap); // Creating an empty group to add markers to later on
    let requests = [];

    for (let address of jsonAddresses) {
        let geocodingAddress = address.street + address.city; /* Real code is a bit more complex */
        geoCodingUrl = `${geoapifyURL}${theAddress}&apiKey=${GEOAPIFY_API_KEY}`;

        let request = createRequest(geoCodingUrl, /* stuff */)
            .then((geojson) => {
                // geoapify seems to return a GeoJSON FeatureCollection of Points, so fetch the first
                if (geojson.features.length === 0) {
                    // Sanity check: no geocoding results means no marker, and resolving to 'undefined'.
                    return;
                }
                let marker = L.marker( L.GeoJSON.coordsToLatLng(geojson.features[0].coordinates) );
                marker.addTo(projectsGroup);

                // Returning the marker means that the Promise stored in this 'request' variable will resolve to a marker.
                return marker;
            });

        requests.push(request);
    }

    Promise.all(requests).then(fulfilledStuff=>{
        console.log(fulfilledStuff);    // Shall be an array of L.Marker, since each Promise resolved to a Marker
        mymap.fitBounds(projectsGroup.getBounds());
    });
});

Or
createRequest(projectUrl, /* stuff */).then((jsonAddresses) => {
    let projectsGroup = L.featureGroup().addTo(mymap); // Creating an empty group to add markers to later on
    let requests = [];

    for (let address of jsonAddresses) {
        let geocodingAddress = address.street + address.city; /* Real code is a bit more complex */
        geoCodingUrl = `${geoapifyURL}${theAddress}&apiKey=${GEOAPIFY_API_KEY}`;

        let request = createRequest(geoCodingUrl, /* stuff */)
            .then((geojson) => {
                if (geojson.features.length === 0) { return; }
                return L.GeoJSON.coordsToLatLng(geojson.features[0].coordinates);
            });

        requests.push(request);
    }

    Promise.all(requests).then(fulfilledStuff=>{
        console.log(fulfilledStuff);    // Shall be an array of L.LatLngs, since each Promise resolved to a L.LatLngs
        fulfilledStuff
            .filter((item)=>!!item) // Filter out 'undefined' geocoding results
            .forEach((latLng) => {
                (L.marker(latLng)).addTo(projectsGroup);
            });
        mymap.fitBounds(projectsGroup.getBounds());
    });
});

Or we can get even fancier and do something like
createRequest(projectUrl, /* stuff */).then((jsonAddresses) => {
    let projectsGroup = L.featureGroup().addTo(mymap); // Creating an empty group to add markers to later on

    // jsonAddresses is an Array, right? Applying Array.prototype.map we can convert that into an Array of Promises.
    var promises = jsonAddresses.map((address)=>{
        let geocodingAddress = address.street + address.city; /* Real code is a bit more complex */
        geoCodingUrl = `${geoapifyURL}${theAddress}&apiKey=${GEOAPIFY_API_KEY}`;
        return createRequest(geoCodingUrl, /* stuff */)
            .then((geojson) => {
                if (geojson.features.length === 0) { return; }
                return (L.marker(L.GeoJSON.coordsToLatLng(geojson.features[0].coordinates))).addTo(projectsGroup);
            });
    })

    Promise.all(promises).then(fulfilledStuff=>{
        console.log(fulfilledStuff);    // Shall be an array of L.Markers
        mymap.fitBounds(projectsGroup.getBounds());
    });
});

Note that this sample code is missing code paths for handling most geocoding errors (what if the network is down for one of the geocoding operations?).
In any case, please do read the documentation about Promises, be aware if what you have is a Promise, an Array of Promises, an Object, an Array of Objects or whatever, and be aware of what your Promises resolve to (which is the return value of the callback passed to the last chained .then()).


text:
Q: Establishing a proper conditional statement for strings in 2.7 I'm scraping through various webpages and extracting a collection of numbers in a string named Numbers. For some of the webpages, the string Numbers comes out empty since none of what I'm looking for is within the webpage. The string Numbers can be of any length from empty to over 10000+.
My code reads an excel sheet where I specify the position of the number I am looking for within the string Numbers. This position is given by the variable Position. I would like to write a condition that would tell me if there is a number in the string Numbers at the position Position and if so, move on to other commands. My problem arises from the fact that the webpages I'm scraping are updated frequently. Therefore, the string Numbers changes length and what I was looking for at the position Position is no longer there. The string Numbers could be shorter it would result in an error using the following code:
if Numbers[Position]:
    move on with the code
else:
    print 'no number found'

I get
IndexError: list index out of range

in the event that

*

*The string Numbers is empty

*There is no number at the position Position within the string Numbers
I would like to know what condition, adapted to the various scenario (empty string, shorter string), to have something like:
if there is a number at the position Position within Numbers, move on.  It would prevent my code from crashing.

A: You can use a few checks here.
if numbers:
   # string is not empty
   try:
       print('Number at position {} is {}'.format(position, numbers[position]))
   except IndexError:
       # position doesn't exist
       print('{} does not exist in string'.format(position))
else:
   # string is empty
   print('String is empty')

If you don't want to be that specific, since slices are always less than the length of the string, you can just do:
if len(numbers) > position:
    print('Number at position {} is {}'.format(position, numbers[position]))
else:
    print('{} does not exist'.format(position))

A: Test the length:
if len(Number) > Position:
    # Number[Position] will work

or you could just catch the excepton:
try:
    result = Number[Position]
    # get here and it worked
except IndexError:
    # nope, no such position


text:
Q: Makefile in Linux error: *** No rule to make target `all'. Stop I'm installing Apache on my Linux server RedHat 6.4.
I follow the following guide: http://squirrelmail.org/docs/admin/admin-3.html
When executing the make file, i got the following error:
Making all in srclib
make[1]: Entering directory `/usr/local/src/httpd-2.4.20/srclib'
make[1]: *** No rule to make target `all'.  Stop.
make[1]: Leaving directory `/usr/local/src/httpd-2.4.20/srclib'
make: *** [all-recursive] Error 1

Can you please suggest how I can proceed further?

A: SquirrelMail is in the epel.repo https://fedoraproject.org/wiki/EPEL
yum install epel-release-6-8.noarch.rpm

https://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install squirrelmail

A: Im facing this recently and manage to solved it.. below is the solution i made.
go to srclib folder in httpd
create new file as "Makefile.in"
the content will be like this
BUILD_SUBDIRS = $(AP_BUILD_SRCLIB_DIRS)
CLEAN_SUBDIRS = $(AP_CLEAN_SRCLIB_DIRS)

include $(top_builddir)/build/rules.mk

and save it.
Now you can run make command in httpd folder


text:
Q: I am new to Angular. How do I have to do login page a theme and all other pages with a different theme Login page with a theme1*emphasized text*
all other pages with theme2

A: Html in layout
<app-header></app-header>
  <app-menu></app-menu>
    <router-outlet></router-outlet>

Router should like below
    routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      { path: '', redirectTo: 'Dashboard', pathMatch: 'full' },
      { path: 'Dashboard', component: DashboardComponent},
      { path: 'Users', component: UsersComponent}
    ]}
  },
  {
    path: 'Login',
    component: LoginComponent
  }
];


text:
Q: DIfference between Navision DB and SQL Server DB I am new to Navision application.Can you please explain the difference between Navision DB and Sql Server DB?

A: That completely depends on how you have Navision installed. See the entry on Wikipedia to see what I mean. It can be installed with SQL Server, or their native database server (referred to as 'Classic'). A google search for Classic Navision Database should get you well along in your research.

A: If you want to be able to use sql syntax for database queries, then you need to install the sql server database. The native database does not support sql.

A: Navision uses MySQL standard database, not just SQL. You should be able to see it depending on the tier composition you have on your NAV installation.


text:
Q: best practice with memcache/php - multi memcache nodes So I am working on a web app - that has to be built for scalability. It stores frequent MySQL querys into the cache. I have pretty much everything built and ready to go - but I am concerned on best practices on handling where to cache the data. I've talked to a few people and one of them suggested to split each key/value across all the memcache nodes.
Meaning if i store the example: 'somekey','this is the value'
it will be split across lets say 3 memcache servers.
Is that a better way? or is memcache more built on a 1 to 1 relationship?. For example.
store value on server A till it faults out - go to server B and store there.
that is my current understanding from the research I have done and past experience working with memcache.
Could someone please point me in the right direction in this and let me know which way is best or if I completely have this mixxed up.
Thanks

A: I would use consistent hashing in php
See http://php.net/manual/en/memcached.constants.php
This way if a memcache server goes down, your keys won't be redistributed :)
In my experience memcache servers have been REALLY reliable, and are usually restarted due to OS upgrades and such.
If you don't use consistant hashing, then if a server goes out and comes back, then you may have an old piece of data cached on that server.
IE Memcache servers A, B
A: set key = 1234, value = 'abc', expires = 1 day
B:
after a time
A: vanishes
B: get key = 1234
   returns nothing
B: set key = 1234, value = 'def', exipres = 1 day
after more time
A: comes back!

get_key(1234) returns 'abc', because A is now available.!
-daniel


text:
Q: Retaining some starting elements of an array and set others to zero in R Suppose in an array of order (k*1*N) where k=a+b, we want to retain first a elements of that array and replace remaining b elements equal to zero, thus forming another array of same order (k*1*N). How can we achieve this goal in R?
Example
set.seed(51214)
library(mvtnorm)
library(Matrix)
library(abind)
library(arrayhelpers)
library(reshape2)
##########################################################
N=1000
n=200
##########################################################
p1=2
p2=3
p=p1+p2
##########################################################
B1=c(1.5,2.5)
B2=rep(0,p2)
B=as.matrix(c(B1,B2),nrow=n)
##########################################################
avg=rep(0,p)
sig=diag(p)
##########################################################
X=array(data=NA,dim=c(n,p,N))
BB=array(data=NA,dim=c(p,1,N))
XB=array(data=NA,dim=c(n,1,N))
Zi=array(data=NA,dim=c(n,1,N))
Yi=array(data=NA,dim=c(n,1,N))
Dat=array(data=NA,dim=c(n,p+1,N))
UE=array(data=NA,dim=c(p,1,N))
DD=array(data=NA,dim=c(p,1,N))
RE=array(data=NA,dim=c(p,1,N))
##########################################################
for(i in 1:N){
            X[,,i]=rmvnorm(n,mean=avg,sigma=sig)
            BB[,,i]=B
            XB[,,i]=X[,,i]%*%BB[,,i]
            Zi[,,i]=1/(1+exp(-XB[,,i]))
            Yi[,,i]=rbinom(n,1,Zi[,,i])
            Dat[,,i]=abind(Yi[,,i],X[,,i])
            df=melt(Dat[,,i])
            df1=subset(df,select=c(value))
            DT=as.data.frame(matrix(df1$value,ncol=p+1))
            colnames(DT)=c("y","x1","x2","x3","x4","x5")
            fit=glm(y~x1+x2+x3+x4+x5+0,data=DT,family=binomial(link="logit"))
            UE[,,i]=as.matrix(fit$coefficients,ncol=5)
            RE[,,i]=
         }

Now we want a new array, say RE in such a way that starting (p1*1*1000) elements of UE are still there in RE but remaining (p2*1*1000) are zero.

A: To fill RE vector the way you want, you can do, inside the loop:
RE[1:p1, , i] <- UE[1:p1, , i] # fill the first p1 entries of first dimension with the same value as UE
RE[(p1+1):(p1+p2), , i] <- 0 # fill the rest of the entries of first dimension with 0


text:
Q: Suggested approach for building dynamic sql queries with haskell I would like to use postgresql-simple for my database access layer in my application and i was wondering what the best method would be for dynamically building my sql queries. A simple example of what i would want to accomplish would be the following:
A user has a series of filters than can apply to the things they are searching:

*

*Number of pets

*Name of pet

*When pet was created

*etc

How should i handle composing the filters such that i dont make myself susceptible to attacks. My frst instinct would be that i would need to only worry about String/Text data since i can check that the number that comes in is actually a number and the date supplied is actually a date. Using the following format:
makeNumberOfPetsFragment :: String -> Either String String
makeNumberOfPetsFragment candidate =
  case createStatement of
   Left _ -> Left "Error creating number of pets filter"
   Right x -> Right ("WHERE number_of_pets = " ++ (show x))
  where createStatement = readEither candidate :: Either String Int

I'm not sure if this is just a bad approach or if it would be better to just use existing libraries or if there is a better approach in pre made statements that i just am not thinking about.


text:
Q: How do I implement one to many relationship in django? So I have a case where I have to use one to many relationship in django, I don't know how to use it. I want to implement one to many relationship in order(one)  to product(s) which could be many. My code is like:
class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.IntegerField()
    image = models.ImageField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
    created_at = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.name

class Order(models.Model):
    order_id = models.CharField(max_length=20)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

A: In your case you have M:N relation between User and Product, because one Product can be member of multiple Orders, and Order can contain multiple Products. It's modeled as two 1:N relations as visualized below.
    ┌─────────┐
    │ Product │
    │ - name  │◄──┐
    │ - price │   │        ┌───────────────┐
    └─────────┘   └────────┤ Order         │
                           │- <FK> User    │
    ┌─────────┐   ┌────────┤- <FK> Product │
    │ User    │   │        └───────────────┘
    │ - name  │◄──┘
    └─────────┘

https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/
class Order(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True)
    ...


text:
Q: Can tfdbg be run with Cloud ML Engine training job? I cannot find any examples of the tfdbg tool being run with a cloud ML engine. This post shows how to wrap a tensorflow session with the debugger, but I have not encountered any way to run an ML engine package in debug mode. Has anybody found a way to do this?

A: CloudML Engine does not support the interactive CLI debugger.
However, you should be able to use the offline debugger. How you get it to work in your case will depend on how your code is structured.
Suppose your code is written to accept a --job-dir command-line argument. When you submit your job you will have something like this:
export JOB_NAME=my_job
export JOB_DIR=gs://my_bucket/$JOB_NAME
gcloud ml-engine jobs training submit ... --job-dir=$JOB_DIR ...

# Start with this code.
from tensorflow.python import debug as tfdbg

# job_dir is on GCS and is passed on the command-line if you specify
# it when submitting your training job.
dump_dir = os.path.join(job_dir, 'tfdbg_dumps')

For more info on watch_fn, see docs.
Core TensorFlow (User-created Session)
If you're using "core" TensorFlow, i.e., creating your own session, then will replace the construction of any tf.Session objects like so:
sess = tfdbg.DumpingDebugWrapperSession(sess, dump_dir)
sess.run(fetches=my_fetches, feed_dict=my_feed_dict)

See DumpingDebugWrapperSession docs for more info.
Estimator API
If you are using learn_runner or Experiment, you can use DumpingDebugHook:
experiment = Experiment(
  ...,
  train_monitors =[tfdbg.DumpingDebugHook(dump_dir)],
  ...
)
learn_runner.run(experiment)

Unfortunately, I cannot see a way to use filters such as tfdbg.has_inf_or_nan except with LocalCLIDebugHook, so you'll just have to analyze the tensors offline.
Offline analysis
Once the data is available in GCS, you can examine the dumps using the provided offline_analyzer executable module. You'll have to choose one of the run sub directories:
python -m tensorflow.python.debug.cli.offline_analyzer \
    --dump_dir=$JOB_DIR/tfdbg_dumps/run_XXXXXXX


text:
Q: \nameref breaks for star versions of section/paragraph when titlesec is loaded \nameref breaks for the star versions of section, paragraph when titlesec is loaded. I have a document that numbers paragraphs by default, but I have a few I do not want to number but would like to refer to. These are marked with \paragraph*, however, if the titlesec package is loaded at the same time, it causes nameref to display an empty string (the link box of hyperref is still visible).
MWE:
\documentclass[12pt]{article}
\usepackage[sf]{titlesec} %comment this out and it works fine.
\usepackage{hyperref}
\begin{document}
\section{Sections}
\label{sec}
This is \nameref{sec}
\paragraph{A named Paragraph}
\label{par}
This is \nameref{par}
\paragraph*{A starred named Paragraph}
\label{par:star}
This is \nameref{par:star}
\end{document}

I suspect titlesec causes this defect for ALL star variants of sectioning commands but have not tested this. For me only paragraph* is relevant however a fix for all variants would be the best.
I have a hunch it might be related to this: https://tex.stackexchange.com/a/6658/19326 however this happens to go way beyond my latex knowledge and is just "magic" for me.

A: Add the following to your preamble:
\makeatletter
\def\ttl@useclass#1#2{%
  \@ifstar
    {\ttl@labeltrue\@dblarg{#1{#2}}}% {\ttl@labelfalse#1{#2}[]}%
    {\ttl@labeltrue\@dblarg{#1{#2}}}}
\makeatother

This allows for processing of the regular arguments \<section>[<ToC>]{<regular>} with the sectional unit \<section>. Additionally, setting \ttl@labeltrue inserts the appropriate hyperref anchor.

\documentclass[12pt]{article}
\usepackage[sf]{titlesec} %comment this out and it works fine.
\usepackage{hyperref}
\makeatletter
\def\ttl@useclass#1#2{%
  \@ifstar
    {\ttl@labelfalse\@dblarg{#1{#2}}}% {\ttl@labelfalse#1{#2}[]}%
    {\ttl@labeltrue\@dblarg{#1{#2}}}}
\makeatother
\begin{document}
\section{Sections}
\label{sec}
This is \nameref{sec}
\paragraph{A named Paragraph}
\label{par}
This is \nameref{par}
\paragraph*{A starred named Paragraph}
\label{par:star}
This is \nameref{par:star}
\end{document}

Not extensively tested.


text:
Q: How to enable Windows Authentication in AspNetCore SignalR Alpha How do I configure SignalR to Authenticate/Authorize to a server that is must be protected by Windows Authentication.  There appears to be no way to make the JavaScript Client send Credentials with the request.

A: Windows authentication should be handled by the browser and you should not have to do anything special. The problem is that Chrome does not seem to handle Windows Authentication correctly. There is a thread on github that contains more details.
Also, SignalR MVC 5 Websocket no valid Credentials seems still to apply as the issue is browser related (i.e. external to SignalR).


text:
Q: Material-UI Autocomplete/Popper - How to prevent x-scroll I am currently working on implementing the Material-UI Autocomplete component, and I want each option label to display an icon and some text. However, I only want the popper to be the full width of the text input, and then add an ellipsis to any text that would normally overflow on the Popper width.
In my renderOption method, if I return <Typography noWrap>"Text"</Typography> it succesfully forces the text to have an ellipsis, but if I put it in a Grid or Flex box in order to also include the icon, then the Popper component will be able to scroll horizontally. Is there a way to fix the Popper viewport to the width of Autocomplete, so that way the text in the renderOption method will wrap?
import React from 'react';
import InputAdornment from '@material-ui/core/InputAdornment';
import TextField from '@material-ui/core/TextField';
import SearchIcon from '@material-ui/icons/Search';
import PersonIcon from '@material-ui/icons/Person';
import GraphicEqIcon from '@material-ui/icons/GraphicEq';
import { Grid } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
import Typography from '@material-ui/core/Typography';

function SearchBarDisplay({ options = [], onChange, onSelectValue, value = '' }) {
    function getOptionLabel(option) {
        if (option.name) {
            return option.name;
        } else if (option.username) {
            return option.username;
        } else if (option.type === 'advanced') {
            return option.value;
        } else {
            return null;
        }
    }

    function renderOption(name, username, type) {
        if (name) {
            return (
                <Grid container alignItems="center" spacing={1} wrap={'nowrap'}>
                    <GraphicEqIcon />
                    <Grid item>
                        <Typography noWrap>{name}</Typography>
                    </Grid>
                </Grid>
            );
        } else if (username) {
            return (
                <Grid container alignItems="center" spacing={1} wrap={'nowrap'}>
                    <PersonIcon />
                    <Grid item>
                        <Typography noWrap>{username}</Typography>
                    </Grid>
                </Grid>
            );
        } else if (type === 'advanced') {
            return (
                <Grid container alignItems="center" spacing={1}>
                    <SearchIcon />
                    <Grid item>
                        <Typography
                            noWrap={true}
                            color="textSecondary">{`See more results for "${value}"`}</Typography>
                    </Grid>
                </Grid>
            );
        } else {
            return null;
        }
    }

    return (
        <Autocomplete
            id="autocomplete"
            options={options}
            getOptionSelected={(option, value) => option._id === value._id}
            getOptionLabel={(option) => getOptionLabel(option)}
            onChange={(event, value) => {
                onSelectValue(value);
            }}
            onInputChange={(event, value) => onChange(value)}
            renderOption={({ name, username, type }) => renderOption(name, username, type)}
            renderInput={(params) => (
                <TextField
                    {...params}
                    placeholder="Search for podcasts or users"
                    margin="normal"
                    variant="outlined"
                    InputProps={{
                        ...params.InputProps,
                        startAdornment: (
                            <>
                                <InputAdornment position="start">
                                    <SearchIcon />
                                </InputAdornment>
                            </>
                        )
                    }}
                />
            )}
        />
    );
}

export default SearchBarDisplay;

A: To change each option label to have just one line with ellipsis (... - tree dots) instead two or more lines, do you need to change your renderOption property to the follow code:
<Autocomplete
...
getOptionLabel={(option: any) => `${option.label} (${option.code})`}
renderOption={(option) => (
        <React.Fragment>
          <div style={{ textOverflow: 'ellipsis', overflow: "hidden", whiteSpace: "nowrap" }}>
            {option.label} ({option.code})
          </div>
        </React.Fragment>
      )}
...
/>

See an example with the countries list at CodeSandbox that I did: https://codesandbox.io/s/autocomplete-with-ellipsis-i8hnw


text:
Q: Issue with drawing polylines on iOS11 beta 4? I'm having trouble drawing polylines, and I think I've deduced it to being an issue with iOS 11 beta 4. It was working yesterday with the same code, and now I've updated to beta 4 and it doesn't draw polylines.
Just confirmed this by trying it in Xcode 8 on iOS 10.3 simulator, and in Xcode 9b4 on the iOS 11b4 simulator.
Code:
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

    let mapView = MKMapView()

    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.frame = CGRect(x: 10, y: 10, width: 300, height: 300)
        mapView.delegate = self
        mapView.region = MKCoordinateRegionMake(CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.015253), MKCoordinateSpanMake(0.005, 0.005))
        mapView.delegate = self

        let coordinate1 = CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.015253)
        let coordinate2 = CLLocationCoordinate2D(latitude: 51.482736, longitude: -0.016253)

        let polyline = MKPolyline(coordinates: [coordinate1, coordinate2], count: 2)

        mapView.add(polyline, level: .aboveLabels)

        view.addSubview(mapView)
    }

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)

        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 4.0

        return renderer
    }
}

iOS 10:

iOS 11:

Annotations are added to the map without issue.

A: Fixed in beta 5. We just had to wait.


text:
Q: Continuous Looping Video in TVOS? I'm just getting started with TVOS and was wondering if anyone has addressed looping in TVOS / TVJS / TVML.  I'm using this tutorial to create a simple interface for playing videos. My wrinkle is that I want these videos to play in a continuous seamless loop - basically a moving screensaver type effect - see example videos at art.chrisbaily.com.
Is there a simple way to do this, or do I need to build some kind of event listener to do the looping manually?  I'd like the videos to be fairly hi res, and the videos would be somewhere between 1 and 3 minutes.

A: I was looking for an answer for this question as well. And found that the only way this would be possible is to create an event listener and adding a duplicate media item to the playlist. But honestly it is not that hard, given if you followed the tutorial that you listed in your post.
So the code would be something like
player.playlist = playlist;
player.playlist.push(mediaItem);
//Again push the same type of media item in playlist so now you have two of the same.
player.playlist.push(mediaItem);
player.present();

This will make sure that once your first video ends the second one starts playing which is essentially a loop. Then for the third one and on you implement an event listener using "mediaItemWillChange" property. This will make sure that once a video ends a new copy of the same video is added to the playlist.
player.addEventListener("mediaItemWillChange", function(e) {
   player.playlist.push(mediaItem);
});

Just put the event listener before you start the player using
player.present();

Note this question and idea of this sort was already asked/provided on Apple's discussion board. I merely took the idea and had implemented it in my own project and now knowing that it works I am posting the solution. I found that if I pop the first video out of the playlist and add then push a new on the playlist as mentioned in the linked thread below, my videos were not looping. Below is the link to the original post.
How to repeat video with TVJS Player?

A: You could also set repeatMode on the playlist object
player.playlist.repeatMode = 1;

*

*0 = no repeat

*1 = repeat all items in playlist

*2 = repeat current item

A: There's really no need to push a second media item onto the.  Simply listen for the media to reach its end, then set the seek time back to zero.  Here's the code.
Play the media.
    private func playVideo(name: String) {

    guard name != "" else {
        return
    }

    let bundle = NSBundle(forClass:object_getClass(self))
    let path = bundle.pathForResource(name, ofType:"mp4")
    let url = NSURL.fileURLWithPath(path!)
    self.avPlayer = AVPlayer(URL: url)

    if (self.avPlayerLayer == nil) {
        self.avPlayerLayer = AVPlayerLayer(player: self.avPlayer)
        self.avPlayerLayer.frame = previewViews[1].frame
        previewViews[1].layer.addSublayer(self.avPlayerLayer)

        avPlayer.actionAtItemEnd = .None

        //Listen for AVPlayerItemDidPlayToEndTimeNotification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.avPlayer.currentItem)
    }

    avPlayer.play()

}

Play Again
    func playerItemDidReachEnd(notification: NSNotification) {
        let item = notification.object as? AVPlayerItem
        item?.seekToTime(kCMTimeZero)
    }


text:
Q: how this recursion is reaching the cout statement ? I have this function to solve the Tower of Hanoi problem and fortunately It's working good but can anybody explain to me if the function is calling it self before the cout statement in case m!=0 then how does it ever reach the cout statement or even the other call of itself ??
#include <iostream>

using namespace std;

void Hanoi(int m, char a, char b, char c){
if(m == 1){
    cout << "Move disc " << m << " from " << a << " to " << c << endl;
 }else{
      Hanoi(m-1, a,c,b);
      cout << "Move disc " << m << " from " << a << " to " << c << endl;
      Hanoi(m-1,b,a,c);
  }
}

int main(){

int discs;
cout << "Enter the number of discs: " << endl;
cin >> discs;
Hanoi(discs, 'A', 'B', 'C');

 return 0;
}

A: Calling Hanoi(m), where m > 1: First it executes Hanoi(m-1) and all resulting calls. Then it executes cout. Then it executes Hanoi(m-1) and all resulting calls a second time.
Consider m == 3:
Hanoi(3)
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout
    cout
    Hanoi(2)
        Hanoi(1)
            cout
        cout
        Hanoi(1)
            cout


text:
Q: Update these dates in SQL Server to consecutive timestamps for each id? I have a table of IDs and dates. I need to turn the dates into datetimes, but each timestamp has to be unique within that ID. For example, if this is my table:

ID
Date

0001
2020-03-21

0001
2020-03-21

0001
2020-03-21

0002
2020-03-21

0002
2020-03-21

then I need my output to look like:

ID
Datetime

0001
2020-03-21 00:00:01

0001
2020-03-21 00:00:02

0001
2020-03-21 00:00:03

0002
2020-03-21 00:00:01

0002
2020-03-21 00:00:02

I'm pretty sure we can safely assume that no ID will have 86,400 entries on one day, so I shouldn't have to worry about the date rolling over by accident.
I'm thinking a cursor may be the answer, but I'm new to SQL and haven't had much luck figuring out how I'd use one for this. Here's what I tried so far, which didn't get me quite where I need to be:
SELECT TOP 1000 ROW_NUMBER() OVER(ORDER BY [CID] ASC,[XDATE] ASC) AS RN
,[CID]
,[XDATE]
,dateadd(second, ((ROW_NUMBER() OVER(ORDER BY [CID] ASC,[XDATE] ASC))%86400),cast([XDATE] as datetime)) AS NEW_DATE -- 86400 sec in a day so need to mod ROW_NUMBER to prevent changing the date
FROM entryTable

This query applies the datetime addition consecutively, meaning it will occasionally happen that the time rolls over at midnight on the same day and ID as the last entry. This causes the entries to be out of order in our final database, as it sorts the data based on the timestamp, and anything showing up as post-midnight will then come before everything else that actually came first in our current database.

A: While you may not have a single ID with more 86,400 entries per day, it sounds like you have enough IDs with enough entries to go over 86,400 total. In order to reset the row numbers like you show in the question, you need to apply a PARTITION to the window function:
SELECT TOP (1000) OverallRN = ROW_NUMBER() OVER (ORDER BY CID, XDATE)
,ROW_NUMBER() OVER
  (PARTITION BY CID ORDER BY [XDATE]) AS RN
,[CID]
,[XDATE]
,dateadd(second, ROW_NUMBER() OVER
  (PARTITION BY CID ORDER BY [XDATE]),cast([XDATE] as datetime)) AS NEW_DATE
FROM dbo.entryTable;

*

*Example db<>fiddle
If you still go over 86,400 entries for any given ID / day combination, you need to define what to do with 86,401+ because it certainly won't be mod (%) if you want to maintain the original sequence. Perhaps you need to go more granular than a second, like adding ROW_NUMBER() * 100 milliseconds. Although if those are the only two columns in the table, I don't know how you would know that anything is out of sequence.

A: use this
SELECT ID ,Date,
       concat(Date,' ',DATEADD(second,
    CAST(43200000 * (CAST(CRYPT_GEN_RANDOM(4) as int) / 4294967295.0 + 0.5) as int),
    CAST('00:00:00' AS Time))) AS datetime
from entrytable

or better fit to your query
SELECT TOP 1000 ROW_NUMBER() OVER(ORDER BY [CID] ASC,[XDATE] ASC) AS RN
,[CID]
,[XDATE]
, concat(Date,' ',DATEADD(second,
    CAST(43200000 * (CAST(CRYPT_GEN_RANDOM(4) as int) / 4294967295.0 + 0.5) as int),
    CAST('00:00:00' AS Time))) AS datetime
FROM entryTable


text:
Q: Scaled a path without losing its center position path p ;
p = (1u,1u) -- (1u,3u) -- (3u,3u) -- (3u,1u) -- cycle ;
draw p ;
draw p scaled 2 withcolor red ;

The center of the red square is moved from (2,2) to (4,4) but I want it to stay at (2,2).

Of course in this example everything is simple, due to the integer factor, and I can just use shifted -center p.

However, life is not as simple as that and with decimal factor this simple trick is not working properly.
path p ;
p = (1u,1u) -- (1u,3u) -- (3u,3u) -- (3u,1u) -- cycle ;
draw p ;
draw p scaled 1.5 shifted -center p withcolor red ;

So, is it possible to keep the center position of a path when scaling it?

A: Yes, it's possible. There may be better ways, but here is one.  The scaling that occurs is about the origin so you can shift to the origin, do your scaling, then shift back.  Your initial attempt worked due to a lucky(?) choice of position and scale factor for the square.
\documentclass{article}
\usepackage{luamplib}
\begin{document}
\begin{mplibcode}
beginfig(0);
path p ;
u:=1cm;
p = (1u,1u) -- (1u,3u) -- (3u,3u) -- (3u,1u) -- cycle ;
draw p ;
draw p scaled 1.5 shifted -center p withcolor red ;
draw p shifted -center p scaled 1.5 shifted center p withcolor blue;
endfig;
\end{mplibcode}
\end{document}


text:
Q: Using parent field in subquery I've got the following query on a Prestashop 1.4 DB and I can't figure out how to use parent id_order field in the subquery.
Error message is "#1054 - 'o.id_order' field unknown in where clause".
I tried using a left join but getting same error.
Both tables order and order_detail have an id_order field. There can be many order_detail rows for one order.
SELECT
    o.invoice_date,
    o.invoice_number,
    (
    SELECT ROUND(SUM(price),2) FROM
        (
            SELECT (od.product_price * od.tax_rate / 100) as `price`
                FROM order_detail od
                WHERE od.id_order = o.id_order
        ) as `tmp`
    ) as `tax`
FROM `order` o
WHERE o.invoice_number != 0 ...

Is it because I try to use it in a where clause?
On the following query (can't use it on this case), o.id_order is well known...
(
    SELECT ROUND(SUM(total_amount),2)
    FROM order_detail_tax ot
    WHERE ot.id_tax = 2 AND ot.id_order_detail
    IN (
        SELECT od.id_order_detail
            FROM order_detail od
            WHERE od.id_order = o.id_order
    )
) as `Tax`,

A: Try using only one subquery:
SELECT
  o.invoice_date,
  o.invoice_number,
  (
    SELECT ROUND(SUM(od.product_price * od.tax_rate / 100), 2)
      FROM order_detail od
     WHERE od.id_order = o.id_order
  ) as `tax`
FROM `order` o
WHERE o.invoice_number != 0

Because, if you nest two subquerys the most inner one will not be able to reference to the outer one.


text:
Q: Weird Behaviour of CHROME Javascript CONSOLE Here I have a simple button with class .change in my HTML.
Now when I click on the button and then observe the Chrome console I get the output as mouse event and the text written on button ("Click Me!"), which is excepted.
To my surprise when I navigate the mouse event in the google console then I see e.target.innerText was set to "HELLO". How is it possible I have first console log the event then changed the innerText to "HELLO" in last line.
Also when I use debugger breakpoint the output was expected. Without using debugger the innerText attribute in the mouseevent (console log in 1st line of eventhandler) is showing "HELLO".
let btn = document.querySelector('.change');
btn.addEventListener ("click", (e) => {
   console.log(e);
   const text = e.target.innerText;
   console.log(text);
   e.target.innerText = "HELLO";
});

HTML :-
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>A button</title>
</head>
<body>
    <button type="button" class="change">Click me!</button>
    <script src="/practice/prac.js"></script>
</body>
</html>


text:
Q: Obtener una imagen por default en dashboard PHP Ajax Buen día colegas, quiero obtener una imagen por default en una tabla del dashboard, estoy metiendo un if para que me traiga la de default en caso de que no haya imagen dentro de mi ajax.
$.ajax({
     type: "POST",
     async: false,
     url: "<?php echo constant('URL'); ?>alumno/readByIdEscuela",
     dataType: 'json',
     success: function(data) {

        $.each(data, function(ind, elem) {
           if (ind <= 4) {
              var img = new Image();
              if (elem.foto_alumno == null || elem.foto_alumno == '') {
              }else{
                    var img = '<?php echo constant('URL'); ?>public/img/default.jpg'
                 }

              var htmlTags = '
' +
                 '<img class="rounded-circle img-fluid" style="max-width: 60px; max-height: 60px" src="<?php echo constant('URL') ?>public/alumno/'
                 + elem.appaterno_alumno + '_' + elem.apmaterno_alumno + '_'
                 + elem.nombre_alumno + '/' + elem.foto_alumno + '"' +
                 '' + elem.nombre_alumno + '' +
                 '' + elem.email_alumno + '' +
                 '
';
              $('#tableAlumnos').append(htmlTags);

Esta parte sería del sistema donde quiero que se muestre la de default.

A: Pensando en que elem.foto_alumno trae un dato como nombreunicoimagen.jpg o null, se pudiera hacer algo como:
const BASE_URL = <?php echo constant('URL'); ?>;
$.ajax({
     type: "POST",
     async: false,
     url: BASE_URL + "alumno/readByIdEscuela",
     dataType: 'json',
     success: function(data) {

        $.each(data, function(ind, elem) {
           if (ind <= 4) {
              let src_foto_alumno = (elem.foto_alumno !== null)? BASE_URL + 'public/img/default.jpg':BASE_URL + 'public/alumno/'+elem.foto_alumno;

              var htmlTags = '
' +
                 '<img class="rounded-circle img-fluid" style="max-width: 60px; max-height: 60px" src="'+src_foto_alumno+'"'
                 + elem.appaterno_alumno + '_' + elem.apmaterno_alumno + '_'
                 + elem.nombre_alumno + '/' + elem.foto_alumno + '"' +
                 '' + elem.nombre_alumno + '' +
                 '' + elem.email_alumno + '' +
                 '
';
              $('#tableAlumnos').append(htmlTags);


text:
Q: cakephp database table defining three dependent relationships I have three tables (blocks, roles, users) where the following is true in the schema:
blocks have many users
users have many blocks
users have many roles, but the roles are specific to the block (and the user)
blocks have many roles, but the roles are specific to the user (and the block)

For example:
user => john
belongs to block => 'metro' with role => 'builder'
belongs to block => 'rural' with role => 'investor'

user => dan
belongs to block => 'metro' with role => 'resident'
belongs to block => 'rural' with role => 'investor'

I have a join table named block_role_user with the following columns:
id   block_id   role_id   user_id   created   modified

I guess this would be a hasandbelongstomany relationship amongst all three tables. I thought about laying this out with a hasandbelongstomany table between blocks and users and another hasandbelongstomany table between roles and users but this will not fully define the unique relationship between a block, role and user.
I'm looking for advice on the best way to approach this and appreciate any advice.
I've looked into binding the model, but this doesn't seem to apply for the unique three part relationship I have here.
I thought about creating a model called blockroleuser and setting up the relationships using standard cakephp convention. If this is an acceptable way, can you give some guidance on naming the model and controller files?
Thanks again...

A: If I got you right, then you are looking for a relation less loose than HABTM, which will define a specific connection between a User, a Block and a Role.
Personally I would probably use a model that defines these relations using belongs to, where a User can have many of those, something like:
User hasMany Whatever

Whatever belongsTo User
         belongsTo Block
         belongsTo Role

This is probably more or less what you ment when you were talking about a BlockRoleUser model, the proper naming might depend on what exactly blocks are. Of course a generic name like for example Involvement or even UserBlockRole might be fine too, I don't think you should bother too much about this.
Anyways, this looks pretty straightforward and strict to me, and if necessary for your application, then additional HABTM relations could be set up too utilizing the same table. These HABTM relations would most probably only be used for selects only, for example when there's need for querying all the Blocks a User is related to, or when testing whether a User is related to a specific Block, etc...


text:
Q: Should I run an ANOVA between groups on each question from a questionnaire? I have asked one group of participants their views on 2 different forms of recruitment. They answer 19 identical Likert scale questions for each form, of the 19 questions there are 5 themes.
My idea was to an ANOVA for each question to determine whether there is a difference in opinions between the two forms of recruitment. Does this seem right?
Additionally, I am also looking at different demographics (i.e., gender, age etc) how do I go about testing whether these have an impact on the scores between the two?


text:
Q: Python constraint adding variable with fixed value I have this code:
variables = range(0, 16)
domain = range(1, 5)

problem.addVariable(variables[15],[4])
problem.addVariables(variables[:15], domain)
problem = Problem()

The 15th varible value is 4 but i want to make the fixed value of the 12th variable to be 1. How do add all variables expect the 12th and the 15th?
Something like this:
problem.addVariable(variables[15],[4])
problem.addVariable(variables[12], [1])
problem.addVariables(variables[0:12,13:15], domain)

A: You can do something like this :
problem.addVariable(variables[15],[4])
problem.addVariable(variables[12], [1])
new_variables = variables[11:] + variables[13:14] + variables[:16]
problem.addVariables(new_variables,domain)


text:
Q: Apply JS to dynamically created divs? I have multiple div's on my page, that can be added to the page dynamically, and can also be removed.
On page load, the dynamically created div's are loaded from localStorage with uniqiue id's and a common class depending on the div, and I call a function along with that, content().
The function content() looks like this:
function content(){
    alert("test");
    $(".two button").click(function(){
        var id = $(this).parent().attr("id");
        alert(id);
    });
}

Pretty simple, all it does is alert "test" when the function is called, and if you click .two <button>, it will alert .two <textarea> .val().
This works fine once the div's have been loaded, but I run into the problem when I clone the div's
When I clone the div's, it gives them a unique id and a common class like above. At the end of cloneDiv(), I call content(), so that clicking on the elements inside will produce the same results as above.
The problem is, the function will get called as many times as there are div's on the screen, but also means that clicking on the <button> in div .two will alert .two <textarea> .val() three times.
TLDR; Clicking on the button in .two get's called as many times as there are div's on the screen, as the function is called once the dynamic div is created, but should only be called once.
There's a lot of code to do all this, but I think I explained what happens pretty clearly. I will however whip up a demo if that would help more.

A: You want to use the .on function:
$('body').on('click', '.two button', function(){
    var id = $(this).parent().attr("id");
    alert(id);
});

I would change the 'body' part of that to the real container of these buttons.  So say the buttons are always inside a content div with id my-div, you'd do:
$('#my-div').on('click', '.two button', function(){
    var id = $(this).parent().attr("id");
    alert(id);
});

You also only need this code to run once, so no need to put it in a function that gets called multiple times.  Just put it in your $(document).ready(....).
A fiddle: http://jsfiddle.net/gromer/dxbqz/

A: This is what "event delegation" is for.  You set up a handler on the document and it will handle events from its descendants, even if they are created after the handler is attached:
$(document).on("click", ".two button", function(){
// put a click hander on the document to process clicks
// from buttons that are descendants of elements with class=two

A: The problem is this: "At the end of cloneDiv(), I call content(), so that clicking on the elements inside will produce the same results as above." What happens is that you are compounding the events on to the existing elements so that is why you get so many callbacks. You should instead use the .on function, and use it only once. If you call .on multiple times it will produce the same results because multiple events will be registered.
$(".two button").on("click",function(){
    var id = $(this).parent().attr("id");
    alert(id);
});

Do this once, every button matching (".two button") will respond to it, even if appended later.
Another approach would be to pass in the element to the content() call and then mark it up from there if you are always calling this function when creating the elements anyway.
function content(element){
 $(element).click(function(){
    var id = $(this).parent().attr("id");
    alert(id);
 });
}

As a side note, using alerts to debug can be problematic as they interrupt program execution. I would highly recommend using console.log(id) instead and then looking in the console for your testing variables. console.trace() is also a good one to keep in mind if you are using a third party script and need to see what went wrong where.


text:
Q: Sending Notification with Amazon SNS and Firebase FCM to Android app are not received when app is closed I'm sending notifications via amazon sns and google Firebase fcm.
Everything is working fine if the app is in the foreground or background.
But if the app is killed then notifications stop.
I get the following in the debug console
W/GCM/DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE pkg=... (has extras) }
I've look around for answers but found nothing?