text:
Q: Android build .jar from command line fails I would like to generate some .jar for tools to include in an Android project.
So I use command tool "javac" which works great.
But when I try to use Android SDK, it fails:
C:\Dev\Tools.java:123: package android.util does not exist
    android.util.Log.d("MYTAG", "hello !");

To compile, I use this command:
"C:\Program Files (x86)\Java\jdk1.6.0_23\bin\javac.exe" -g -d C:\Gen C:\Dev\Tools.java

Any help?

A: *

*"javac" is the Java compiler, not the tool used to create JAR files, so just compiling a class does not generate a jar file

*To be able to compile a class, you must also tell the compiler where it can find the required libraries. This is automatically done for system libraries, but you'll have to pass the path to the Android libraries. This can be done by specifying the folders/jar files using the -classpath parameter on the command line, or by adding it to the respective CLASSPATH environment variable.


text:
Q: protected inherientence with virtual function I write a virtual function with protected inherientence
#include<iostream>
using namespace std;
class D{
private:
    int a;
protected:
    int b;
public:
    D(){a=b=c=0;}
    virtual void f(){
    a=2;
    cout <<"D::f"<<a<<endl;
    }
    void g(){cout<<"D::g"<<a<<endl;}
    int c;
};
class E:protected D{
    private:
        int a,b,c;
    public:
        E(){a=b=c;}
        void f(){
            a=3;
            cout<<"E::f"<<a<<endl;
        }
        void g(){cout<<"E::g"<<a<<endl;}
};
int main(){
    D *d = new E;
    d->f();
    d->g();
    return 0;
}

but if I use it, it turn out inaccessible base.
If I change it to public inherience , it can run.
I wonder that why I cannot use  D *d = new E; with private and protected inherience?
Thx in advance.

A: private or protected base means the base is inaccessible to the world. So when you write an expression which requires conversion from the derived to the inaccessible base, that is forbidden due to accessibility rules because the conversion needs to take place at the call-site which is a part of the world.
In object-oriented terminology, private or protected base  doesn't define is-a relationship. It is actually an implemented-in-terms-of relationship, which is composition in simpler term.

A: because non-public inheritance does not define a "is-a" relationship, compiler generally will not allow implicit up-cast
The following would have worked, but it's a bad idea/design
D*d = (D*)(new E);

redpajama_set_name: RedPajamaStackExchange


text:
Q: correct syntax to add a relationship constraint to Access 2007 DB Looking for the correct syntax for this query...
"ALTER TABLE [Test_St] ADD CONSTRAINT [FKTestNameStIDTestStID] FOREIGN KEY ([ID]) REFERENCES [Test_Name] ([St_ID])"

with the addition of NO INDEX
My understanding is that...
To prevent the automatic creation of indexes for foreign keys, the modifier NO INDEX can be used. (per MS)

A: Figured it out...
ALTER TABLE [Test_St] ADD CONSTRAINT [FKTestNameStIDTestStID] FOREIGN KEY NO INDEX ([ID]) REFERENCES [Test_Name] ([St_ID])"


text:
Q: SSRS Default parameters not showing up when the report is loaded Overview: I have 4 report parameter: Start Date, End Date, Phone Number and Skill.  Phone number has a default 7 rows as default values and skill has 147 rows as default values.
Issue: When I preview my report I can see that the Phone number is auto-populated by the default value that I set, but the Skill parameter is blank even though i set it up to have a default value based on a sql query. so now i am having issues setting up a data driven subscription.
Please advise.
Thanks.


text:
Q: Limit of a sum as n approaches infinity. I have a sum
$$T_n(x)= 1 + 2x + 3x^2 + \dots +n  x^{n−1}.$$
and I am supposed to find the limit of $T_n(1/44)$ as $n$ approaches infinity.
I would appreciate any suggestions on how to proceed.

A: Hint:
$$(1-x)T_n(x) = 1+x+x^2+x^3+\cdots+x^{n-1}-x^n$$
For $x \in (0, 1)$, this gives
$$\lim_{n \to \infty} T_n(x) = \frac{1}{(1-x)^2}$$

A: The question is to find the sum of the series $\sum\limits_{n=1}^{\infty}na^{n-1}$, where $a=1/44$. We know that $$\sum\limits_{n=1}^{\infty}a^n=\frac{a}{1-a}.$$ From Abel formula for summation with $A_n=\sum\limits_{k=1}^n1=n$ we have $$\sum\limits_{n=1}^{\infty}a^n=\sum\limits_{n=1}^{\infty}A_n(a^n-a^{n+1})+\lim\limits_{n\to \infty}A_na^n$$ $$\sum\limits_{n=1}^{\infty}a^n=(1-a)\sum\limits_{n=1}^{\infty}na^{n}=\frac{a}{1-a}\,\,\, (*)$$
From (*) it follows that $$\lim\limits_{n\to \infty}T_n(1/44)=\sum\limits_{n=1}^{\infty}na^{n-1}=\frac{1}{(1-a)^2}=\frac{1936}{1849}.$$

A: Note that the expression you evaluate is the derivative of $1+ x + x^2 + \dots$.
Find a closed form expression for this, and continue from there.

A: HINT: Note that $T_n(x)=(F_n(x))'=(1+x+.......+x^n)'$ $n\to\infty$ $F_n(x) \to \frac{1}{1-x} $ if
$x<1$.


text:
Q: Hibernate: HQL delete from embedded map I want to delete entries from an embedded map. If the object CategoryTag is deleted, I want to execute a HQL query in an interceptor, which deletes the entries from a map:
'Product' model:
@NotNull
@ElementCollection
@CollectionTable(name = "producttag", joinColumns=@JoinColumn(name="id"))
protected Map<CategoryTag, String> tags = new HashMap<CategoryTag, String>();

I am kinda blank how i can write the HQL query. It starts with the problem, that I do not know how to reference the map in a delete query. delete Product.tags t where t.key = :tag fails with an Product.tags is not mapped exception.
Can somebody help me on this?

A: Tags is not entity.
A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.

This is why you are getting the error. The correct way is to load Entity, update its collection and then save this object.
Product p = session.load(Product.class, id);
p.removeTags(tag);
session.flush();


text:
Q: About category theory and direct sum What is the explicit meaning of the statement that * is compatible with direct sums ; what are these maps ; I guess they are projection and injection map but could somebody explain how duality works in this kind of maps intutively? Also how Hom(M,N) is isomorphic to Hom(M**,N**)?

A: Well as is said $*$ is a functor, let's say $Mod_R \to Mod_R$ for some commutative ring $R$. The compatibility with direct sums can be rephrased categorically as does this duality functor preserve finite coproducts (which are the same as finite products in an additive category). The projection and injection map are the maps defined for the product/coproduct respectively. For your final question, if we know that $**$ is naturally isomorphic to the identity functor, then in particular it is full and faithful, which means that we get an isomorphism of Hom sets.

A: $*$ is a contravariant functor $\mathscr{M\to M}$.
So if you have a canonical projection map $\pi_i : M_1\oplus ...\oplus M_n \to M_i$, you get $\pi_i^* : M_i^*\to (M_1\oplus ...\oplus M_n)^*$. The requirement is that this is the "injection" of $M_i^*$ into a direct sum of the $M_i^*$'s.
Dually, if you have a canonical injection $\rho_i : M_i \to M_1\oplus ...\oplus M_n$, the requirement is that $\rho_i^*$ be the canonical projection map (note that the author says "direct sum" whereas after they only mention finite direct sums; this is something that should be clarified)
For your last question, there's a requirement that $(-)^{**}$ be naturally isomorphic to $id_\mathscr{M}$, but classically if $F\simeq G$, then $\hom (F(x),F(y))\cong \hom (G(x), G(y))$. It's just the same argument as saying that if $A\simeq B, C\simeq D$, then $\hom (A,C) \simeq \hom (B, D)$, only that since the initial isomorphism are natural, so are the induced ones.
Note that this doesn't follow from the other assumptions, it is another assumption


text:
Q: pound(#) sign in directory name: in Java How to read it The ClassLoader doesn't find me the file. It throws a:

javax.xml.transform.TransformerConfigurationException:
  javax.xml.transform.TransformerException: java.io.FileNotFoundException:

I was trying to do the follwoing:
TransformerFactory.newInstance().newTransformer(new StreamSource("C:\\dev\\workspace\\test1\\a#b\\Browser-Email.xslt"))

A: That is because the StreamSource(string) constructor takes an URI, not a file name and # has special meaning in URIs:

StreamSource
public StreamSource(String systemId)

Construct a StreamSource from a URL.
Parameters:
systemId - Must be a String that conforms to the URI syntax.

You can use
new StreamSource(new File("C:\\dev\\workspace\\test1\\a#b\\Browser-Email.xslt"))

instead.

A: Here is workaround for above problem
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4294586


text:
Q: Android: startActivity() from AlertDialog I am trying to use a Button in an AlertDialog to view a webpage.
The problem is that this AlertDialog is located inside a class that extends ItemizedOverlay and doesn't extend Activity, so Eclipse underlines it and gives the following error:

The method startActivity() is undefined for the type new DialogInterface.OnClickListener(){}

I would like to launch activities from the PositiveButton, NeutralButton and NegativeButton, but I am not able to.
In case you need more context, the main Activity is a MapView with some ItemizedOverlay, and I would like to launch a webpage with directions or another activity that does that.

A: Construct a constructor in the class which contains your alert with Context object as a parameter. Assign it to a Context variable.
Use this context variable for creating the intent.
Intent intent = new Intent(mContext, "Your next activity to be shown");//mContext is the Context variable over here.
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intent);

A: Actually the answer is provided by you in your question. i.e startActivity is undefined in ClickListener functions. so in oncreate function, initialize a Global variable like
Activity myActivity = this;

then in onclicklistener, start another activity from this.
myActivity.startActivity(xxxxxxxx);

This could be one answer.

A: Take a look at this
In these you write your desired code inside the Positive Button,You can start an Activity by using Intent..
startActivity(new Intent (YouPage.this,NewPage.class));

A: If you have the context say context.startActivity();
if you dont have context try to get it from getContext(); or getApplicationContext(); or getBaseContext();

A: Pass context of the activity in constructor of that class and create a field of type activity
and store context in that activity and then
say
Activity activityClass;

and initialize it from your constructor
and start activity from that  activiytClass
activityClass.startActivity();


text:
Q: Passing import context variables to decorators Say you have a configuration class (like Django's settings.py style settings) that gets set up when an application is started. You load it like so.
from myapp import config

CONF = config.CONF

You want to use some variable from this configuration as a decorator argument, like so.
@decorators.mydecorator(run_timeout=CONF.timeout)
def run_stuff_once():
    # blah, blah, blah...

@decorators.mydecorator(interval=CONF.interval)
def run_stuff_periodically():
    # blah, blah, blah...

If you run this, the configuration variables are loaded at runtime and never change. We can see this happening even without the use of decorators.
>>> class Config(object):
...     x = 5
...
>>> config = Config()
>>>
>>> def func(param=config.x):
...     print(param)
...
>>> func()
5
>>> config.x = 9
>>> func()
5

This causes two issues:

*

*If the configuration for that configuration variable is loaded after the file where this function is contained, the function uses the original value of the variable.

*Regardless of import order, it is not possible to change configuration dynamically once the file has been loaded.

Can this be resolved? Were I talking about "normal functions", I would adopt a solution similar to resolving PyLint's W0102 warning, i.e.
>>> def func2(param=None):
...     if param is None:
...         param = config.x
...     print(param)
...
>>> func2()
9
>>> config.x = 5
>>> func2()
5

However, it is not possible to do this for the decorator as, as seen above, the value passed to the decorator can change. I'm stumped as to a resolution for this case.

A: This should provide a dynamic decorator that is evaluated at runtime instead of at definition time
class Config(object):
     x = 5
     y = 6

config = Config()
config2 = Config()

# takes object and atribute as arguments
def dynamic_dec(reference,atrib,kw=None):

    # gets function pointer to wraped function
    def dynamic_dec_functor(functor):

        # creates lamda function to revalueate config value
        def func_wrapper(ref_wrapper=(lambda ref=reference: getattr(ref,atrib))):

            #call original function with result of lambda
            if(kw):
                #store lambda result to keyword arg
                functor(**{kw:ref_wrapper()})
            else:
                #pass lambda result to positional arg
                functor(ref_wrapper())

        return func_wrapper

    return dynamic_dec_functor

@dynamic_dec(config,'x','param')
def func(param="default"):
    print(param)

@dynamic_dec(config2,'y')
def func2(param):
    print(param)

#time to test

print("\n call func and func2 with original config \n")

func()
func2()

print("\n update original config \n")

config.x = 9
config.y = 10

print("\n call func and func2 after config change \n")

func()
func2()

print("\n func2 did not change as it used a different config object \n")


text:
Q: What is that Teradata? syntax for a subquery aliased with a parameter (can't find a name of ref for this) it goes like this:
SELECT LOOKUP.LOOKUP_ID
FROM (
    SELECT INNER_ID FROM
        (
         SELECT max(INNER_ID) INNER_ID
         FROM INNER_TABLE
        ) INNER_QUERY
      ) LOOKUP (LOOKUP_ID)

It's a legacy code - I inherited - in Teradata, still runs in TD 16.20, but this is the only instance I have run into something so strange. And why would you key it like this - is another question.

A: Well these are subqueries in the FROM clause. Such subqueries are also known as "derived tables".
The innermost subquery is
(
  SELECT MAX(inner_id) inner_id
  FROM inner_table
) inner_query

Here we select the maximum inner_id and call this value inner_id again. We reference this one-row query result by the alias inner_query.
The next subquery is
(
  SELECT inner_id
  FROM ( <above subquery> ) inner_query
) lookup (lookup_id)

We select the aforementioned maximum inner_id that is still called inner_id and call the one-row result set now lookup and the value lookup_id.
At last we select that value
SELECT lookup.lookup_id FROM ( ... ) lookup (lookup_id);

We would get the same result with a mere
SELECT MAX(inner_id) AS lookup_id
FROM inner_table;

of course.
Maybe you are just unfamiliar with the alias name syntax for tables and columns:
FROM mytable table_alias

or
FROM mytable table_alias (col1_alias, col2_alias, ...)


text:
Q: cellRendererParams component doesn't receive props after a second component mount I have a basic grid that renders a custom component in one of the cells and I also pass some props to this component inside renderer cell. It all works on the initial page load but if I go to another route and come back to the old route that has ag-grid, the application will crash because my cell renderer component no longer receive the props. What is causing this weird behaviour? Why is it working on initial page load but not the other component life cycles?
class UsersRoles extends Component {
  constructor(props) {
    super(props)
    this.state = {
      columnDefs: [
        {
          headerName: 'Phone',
          field: 'phone'
        },
        {
          headerName: 'Role',
          field: 'role'
        },
        {
          headerName: 'Edit',
          field: 'id',
          checkboxSelection: false,
          cellRenderer: 'EditIcon',
          cellRendererParams: (params) => {
            return {
              users: params.colDef.cellRendererParams.users,
              currentLoggedInUser: params.colDef.cellRendererParams.currentLoggedInUser,
              clickHandler: this.handleEditClick.bind(this)
            }
          },
        }
      ],
      frameworkComponents: {
        EditIcon
      }
    }

    this.handleEditClick = this.handleEditClick.bind(this)
  }

  componentDidMount() {
    this.props.fetchAllUsers()
  }

  handleEditClick(clickedUserId) {
    this.props.currentlyEditingUser(clickedUserId)
    this.props.openEditUserDetailsModal()
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps !== this.props) {
      const array = this.state.columnDefs
      array[4].cellRendererParams.currentLoggedInUser = this.props.currentLoggedInUser // update with loops instead of hardcode index selection
      array[4].cellRendererParams.users = this.props.users
      this.setState({ columnDefs: array })
    }
  }

  render() {
    return (
      <div style={styles.container}>
        <main style={styles.mainSection}>
          <CardSettings headline="Team members" size={{ flex: 3 }}>
            <div
              style={[styles.gridContainer, { width: '100%', height: '100%' }]}
              className="ag-theme-material custom-ag-theme ag-theme-material"
            >
              <AgGridReact
                columnDefs={this.state.columnDefs}
                rowData={this.props.users}
                frameworkComponents={this.state.frameworkComponents}
                suppressCellSelection
              />
            </div>
        </main>
      </div>
    )
  }
}

On initial page load params inside cellRendererParams has all the data of users but once the ag grid component unmount and mounts again, the params is empty.
      cellRendererParams: (params) => {
        return {
          users: params.colDef.cellRendererParams.users,
          currentLoggedInUser: params.colDef.cellRendererParams.currentLoggedInUser,
          clickHandler: this.handleEditClick.bind(this)
        }
      },

How can I make sure that my cell renderer component EditIcon always receive the users and currentLoggedInUser props and not only on initial page load?


text:
Q: Azure storage Services How do you create a blob or tables in using Azure storage services?.
    I have created the Azure storage account. below is the code I have written using c#.
    private CloudBlobContainer GetCloudBlobContainer()
    {
       // this is the storage account connection string created

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("<storageaccountname>_AzureStorageConnectionString"));
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
        return container;

I have created the storage account and now the connection string, so how do I proceed from here?

A: All you have to do is to call the CreateIfNotExist() method on the container to create it:
container.CreateIfNotExist();


text:
Q: Load balancer configuration in SharePoint Can you tell me the steps used to configure web application and alternative access mapping in multi tire farm with load balancer?

A: Because each load balancer implementation is different, you'll need to refer to the manufacture documentation. The basic steps are:

*

*Point the DNS A record at the virtual IP of the load balancer for the SharePoint FEs.

*Direct TCP/443 (don't use HTTP in today's world) from the VIP to the target SharePoint FEs.

*The SharePoint FEs should have the appropriate SSL certificate and FQDN configured for the Web Application AAM/IIS binding.


text:
Q: Matlab: How can I use the a center mouse button click to record/log the data shown by a datacursor? I am new to using Matlab and I have just made my first custom datacursor for a scatter graph I have plotted. This datacursor shows me the x position, y position and the location of that point within the original matrix (row). I want to be able to call the datacursormode and then have a callback within the datacursor, so that pressing the center mouse button on the point it will log the point data shown by the datatip/cursor into a matrix or array.
The idea is to be able to click on a point of interest,see the data tip info and then if the user wants they can click on the point with the middle mouse button to log the data tip information displayed, then move straight to the next point, without re-calling the datacursormode. This should then result in a cell array/matrix of all the point information selected.
I have tried disp(pos) but this displays every point clicked and I want to be able to click on the point and see the info before deciding whether to log it or not. I have tried ginput but calling it disables datacursormode. I think a callback within the custom datacursor function is needed, but I can never get them to work.
Please help.
Thanks for any help you can give.


text:
Q: Output value error in shell Script Python I have a Python program in which I have used a shell script which returns an output value.Below is my code:
#!/usr/bin/env python3
import subprocess
import os
import sys

filename=input("Enter the filename:")
val=subprocess.check_output(['bash','./grep.sh',filename])
print(val)

grep.sh code:
file=$1
grep -c "^[0-9]" $file

My Output:
Enter the filename:lg.txt
b'4\n'

As you can see it prints result as b'4\n' instead of printing only the value 4
What is wrong with my code ? How to rectify this error ?

A: Nothing is wrong in your code

*

*the b prefix is for bytes, to get the strict value from the terminal

*the \n is just because that is what returned in th terminal, this is the new line at the end

No matter the command, you'll to do this when retrieving frmo a command
val = subprocess.check_output(['bash','./grep.sh',filename])
result = val.decode('utf-8').rstrip() # decode in UTF-8 then remove newline char


text:
Q: Win10: Game controller prevents screen saver My Game controller prevents the screen saver from starting. How do I solve that?
I used to solve that through the device manager, but now, when I click the device in the device manager, the power management tab is missing.
A related question: to find that the controller was the culprit I did manual testing. Is there a better way to find that? I'm noting that powercfg -requests returns nothing.

More info:

*

*The controller is a PS5 Dualsense, and it's detected as xbox 360 controller.

*There's no power management tab for the mouse and keyboard as well.

A: My current hack until this bug is fixed:
# Toggle (disable/enable device) a game controller that prevents the screen saver from running; based on devcon.exe (from Windows Driver Kit)
# https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/devcon-examples

import colorama, time, subprocess

devcon = r'"C:\Program Files (x86)\Windows Kits\10\Tools\x64\devcon.exe"'

def print_red( st ):
    print(colorama.Fore.RED + colorama.Style.BRIGHT + st + colorama.Style.RESET_ALL)

def print_green( st ):
    print(colorama.Fore.GREEN + colorama.Style.BRIGHT + st + colorama.Style.RESET_ALL)

def main():
    # query
    cmd = "%s status *game controller" % devcon
    out = subprocess.check_output(cmd).decode("utf-8")
    print( out )

    if out.find( "1 matching device(s) found." ) != -1:
        print( 'Found' )
    else:
        print_red( 'Not found!' )
        input()
        return

    if out.find( "Driver is running." ) != -1:
        print_red( 'Disabling' )
        cmd = "%s disable *game controller" % devcon
        out = subprocess.check_output(cmd).decode("utf-8")
        print( out )
    else:
        print_green( 'Enabling' )
        cmd = "%s enable *game controller" % devcon
        out = subprocess.check_output(cmd).decode("utf-8")
        print( out )

    time.sleep(1)

if __name__ == "__main__":
    main()

EDIT
Strange, after doing disable/enable once, the screensaver works fine. Maybe the disable does something to the power management that the enable doesn't revert. So, a simple batch file (.bat) to disable/enable the driver on startup may be enough.
"C:\Program Files (x86)\Windows Kits\10\Tools\x64\devcon.exe" disable *game controller
"C:\Program Files (x86)\Windows Kits\10\Tools\x64\devcon.exe" enable *game controller


text:
Q: JavaScript null coalescing operator ?? leads to .NET JS minifier/bundler crash The following line in my code leads to a crash of the MVC built-in bundler/minifier. The problem is the ?? operator. If I comment out this line or remove the operator, everything works fine. How can I fix this?
span.textContent = typeof (info) === 'object' ? info.column.caption ?? info.column.dataField : info;

Here's the error message it throws:
[NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.]
   Microsoft.Ajax.Utilities.JSParser.ParseExpression(AstNode leftHandSide, Boolean single, Boolean bCanAssign, JSToken inToken) +820
   Microsoft.Ajax.Utilities.JSParser.ParseExpression(AstNode leftHandSide, Boolean single, Boolean bCanAssign, JSToken inToken) +654
   Microsoft.Ajax.Utilities.JSParser.ParseExpression(AstNode leftHandSide, Boolean single, Boolean bCanAssign, JSToken inToken) +654
   Microsoft.Ajax.Utilities.JSParser.ParseExpressionStatement(Boolean fSourceElement) +147
   Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean fSourceElement, Boolean skipImportantComment) +1474
   Microsoft.Ajax.Utilities.JSParser.ParseFunctionBody(Block body) +43
   Microsoft.Ajax.Utilities.JSParser.ParseFunction(FunctionType functionType, Context fncCtx) +1077
   Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean fSourceElement, Boolean skipImportantComment) +905
   Microsoft.Ajax.Utilities.JSParser.ParseFunctionBody(Block body) +43
   Microsoft.Ajax.Utilities.JSParser.ParseFunction(FunctionType functionType, Context fncCtx) +1077
   Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean isMinus) +2626
   Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean& isLeftHandSideExpr, Boolean isMinus) +1090
   Microsoft.Ajax.Utilities.JSParser.ParseExpressionList(JSToken terminator) +408
   Microsoft.Ajax.Utilities.JSParser.ParseMemberExpression(AstNode expression, List`1 newContexts) +106
   Microsoft.Ajax.Utilities.JSParser.ParseLeftHandSideExpression(Boolean isMinus) +3074
   Microsoft.Ajax.Utilities.JSParser.ParseUnaryExpression(Boolean& isLeftHandSideExpr, Boolean isMinus) +1090
   Microsoft.Ajax.Utilities.JSParser.ParseExpressionStatement(Boolean fSourceElement) +41
   Microsoft.Ajax.Utilities.JSParser.ParseStatement(Boolean fSourceElement, Boolean skipImportantComment) +1474
   Microsoft.Ajax.Utilities.JSParser.ParseStatements(Block block) +76
   Microsoft.Ajax.Utilities.JSParser.InternalParse() +830
   Microsoft.Ajax.Utilities.Minifier.MinifyJavaScript(String source, CodeSettings codeSettings) +805
   System.Web.Optimization.JsMinify.Process(BundleContext context, BundleResponse response) +115
   System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable`1 bundleFiles) +325
   System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +59
   System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +213
   System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +421
   System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +34
   ASP._Page_Views_Work_Index_cshtml.Execute() in C:\dev\DE.ZA.TrailerLoading\DE.ZA.TrailerLoadingAssistant.Web\Views\Work\Index.cshtml:152
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +252
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +148
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +86
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +378
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +91
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +795
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +795
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +81
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +43
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +651
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +220
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +134


text:
Q: Ajax call via POST not working I have a lil problem with an AJAX request.
We have a lil PHP, JavaScript application (Website). The application is running fine on all desktop browsers + on our old MDE's (some Windows CE6 MDE). Now on our new Motorola MC9200 (Windows Embedded Compact 7 formerly CE7) it's not working anymore.
The problem is some small JavaScript function. It disables the buttons/input fields, starts a Ajax.Request (prototype 1.72 but I tested jQuery 1.11.1 too), does something on the database and when everything went right it is refreshing the site via window.location. This function isn't working always on the new devices. Sometimes it does, sometimes not.
simplified code:
function loadSite(siteName) {
  disableForm();
  var parameters = {
    /* SOME PARAMETERS */
  };

  new Ajax.Request('ajax/ajax_db_execute.php', {
     method: 'post',
     parameters: parameters,
     onSuccess: callbackFunc
  });
}

function callbackFunc(transport) {
  response = transport.responseText.evalJSON(true);
  if(response.retcode === 0) {
    window.location = "start.php?id=<?php echo $id; ?>";
  } else {
    show_error_box(response.errortext);
      enableForm();
  }
}

I tried to output the response in the callbackFunc but that function wasn't even called. Next thing I tried was to put some alert at the end of the loadSite function, it was fired everytime. I already checked the parameters and they look fine too.
After that I put some simple fwrite in the php file. It looks like that file isn't even called sometimes. So the question is why?
By changing the method to 'get' I couldn't reproduce the problem and everything is working fine. Problem about that is that I don't want to use get + some parameters might be too long for get to handle.
The parameters in that example were just some simple integers and strings. Does anyone have an idea what might cause the problem and some workaround?

A: It seems that your post request response is not synchronized. So please use setTimeout function in your post callback like that
setTimeout(function(transport) {
     response = transport.responseText.evalJSON(true);
         if(response.retcode === 0) {
             window.location = "start.php?id=<?php echo $id; ?>";
         }
         else
         {
            show_error_box(response.errortext);
            enableForm();
         }
    }, 3000);


text:
Q: Type.GetType() doesn't work for non-native types? I tried getting the type of UnityEngine.Vector3 using Type.GetType() but its returning NULL. It works fine for native types.

A: You need to use the Assembly if it's not a "nativa type" or inside the calling Assembly
Read this:

If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.

typeName (the parameter of Type.GetType(string type))

Type: System.String
  The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
  The syntax is like this:

var type = Type.GetType("UnityEngine.Vector3, AssemblyName");

A: You might need to specify the assembly in which this type is located as well if the type is situated in a different assembly:
var type = Type.GetType("UnityEngine.Vector3, UnityEngine", true);


text:
Q: How to use selenium to search a webpage for a key in a dictionary, fill in the answer field with the corresponding value? (python, selenium) I want to automatically answer a security question on a webpage. The question is chosen randomly from 6 questions. I have a dictionary whose keys and values correspond to the questions and answers respectively. I want to use selenium to search the webpage for the keys and if a key is found I want to enter in the answer field. Below is my failed attempt.
secuQA = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}

# i want to loop through the keys in the secuQA and search the webpage for each of them

# i think I will have to use:
browser.find_element_by_name(keys)

# if question contains a key in the dict, fill answer field w/ corresp value
ansElem = browser.find_element_by_id("secu_answ")
ansElem.click()
ansElem.send_keys(secuQA[key])

Edit: Below is the source for the part of the webpage I thought was relevant.
<form class="form_login" id="vbsecques" name="vbsecques" method="post" encType="multipart/form-data"  action="fillquestions.aspx">
        Question 1 of 3:

In what city did you meet your spouse/significant other?

        Answer
        <input type="password" id="secu_answ" name="secu_answ" class="form-control ehd_sec_ques" placeholder="Answer" autocomplete="off" required autofocus />
        <input type="hidden" id="lid" name="lid" value="1" />
        <input type="hidden" id="aflag" name="aflag" value="submit" />

        <button class="btn btn-danger btn-block ehd_sec_ques" type="submit">Submit</button>

    </form>

A: First you must find the question element.
q_element = driver.find_element_by_id("secu_ques")
question_strings = q_element.text.split(" ")#get a list of words from the question sentence

for key in secuQA:
    if key in question_strings:
        ans = secuQA[key]
        break

Naturally the keys you're using must be unique for being able to identify correctly the corresponding answer.
Let me know if this helps.


text:
Q: How to store a .cer file in the keychain macOS (objective c) I need to store a root certificate (for the browser) in the keychain of macOS with an application built in Objective C. Is there an example of how to do this?

A: sorry, but I mean by code (objective C). This should be a MAC OS app which generates a CSR based of a private/public key.
I used this sample https://github.com/ateska/ios-csr/, but when I check the csr generated with this code, it has an invalid signature. why?

A: Simple. After downloading the .cer file you just double-click it, that should register it in the Keychain application.  If that doesn't work, then just open Keychain, to my Certificates, and drag and drop it into the list.


text:
Q: ActiveModel::ForbiddenAttributesError within Active Admin I have a model that is only ever created within active admin. I have the following controller setup:
def index
@events = Event.all
end

def new
 @event = Event.new
end

def create
@event = Event.new(event_params)

end
private

def event_params
 params.require(:event).permit(:venue, :trainer_id, :description, :training_request_id, :title, :date)
end
end

My event model is:
class Event < ActiveRecord::Base
 has_one     :trainer, inverse_of: :events
 belongs_to  :training_request, inverse_of: :event

 delegate :module, to: :training_request
end

All the fields are there but I cant see why it is throwing this error.
Here is the output from the error:
Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"H0sdhO3JsWBb8tYvFm52YvGsVvcnArigaVD+1r5HzL8=",
 "event"=>{"training_request_id"=>"3",
 "venue"=>"this is a venue",
"description"=>"this is a descripton",
"title"=>"event title",
"date(1i)"=>"2018",
"date(2i)"=>"3",
"date(3i)"=>"5",
"date(4i)"=>"05",
"date(5i)"=>"00",
"commit"=>"Create Event"}

Anyone got any ideas why this is happening?
Its worth mentioning that within rails console it saves fine.

A: I was missing
  controller do
    def permitted_params
     params.permit event: [:venue, :trainer_id, :description, :training_request_id, :title, :date]
   end
  end

inside ActiveAdmin.register Event do


text:
Q: Why isn't a disconnected and then reconnected mdadm RAID1 disk automatically re-attached and re-sync? I'm doing the following test with Debian 9 under Hyper-V: I have two (virtual) disks, each with one partition, and /dev/md0 defined as RAID1 of /dev/sda1 and /dev/sdb1. The root EXT4 file system defined on md0 works well.
Then I reboot the machine removing the sdb disk, by deleting the virtual hardware. Everything works fine, I get an email saying that the array is now clean but degraded:
md0 : active raid1 sda1[0]
      4877312 blocks super 1.2 [2/1] [U_]

Ok, as expected. I re-attach sdb, creating a new virtual disk using the same disk file and reboot the machine but the system doesn't seem to re-detect the disk. Nothing is changed, the array has still 1 drive and is in clean, degraded state. mdadm --detail /dev/md0 still reports the disk as removed.
I expected the disk to be re-detected, re-attached and re-sync automatically the next boot, since the uuid and disk name match.
I re-added the disk manually, mdadm --manage /dev/md0 --add /dev/sdb1, the system syncs it and the array goes back to clean.
Is this the way the system is supposed to work?
PS: I have a significant number of mdadm: Found some drive for an array that is already active messages at boot. mdadm: giving up.

A: If a RAID disk just vanishes suddenly (as far as the OS is concerned), causing the RAID array to become degraded, and then comes back, is it because the system administrator intentionally pulled the disk and then reinserted it? Or perhaps because there is an intermittent connection somewhere, perhaps a bad cable or a loose connection?
If the system had a way of knowing that the removal and restoration was intentional, it could automatically pick it up. But a software RAID has no such knowledge, so it assumes the worst and acts as if the disk or its connection has become unreliable for some reason, until told otherwise.
A hardware RAID controller with hot-pluggable disks may have extra circuitry to detect when a disk in a particular slot has been physically removed and replaced, and may work with an extra assumption that all the disks in slots associated with that RAID controller are always supposed to be RAID disks.
So when a disk vanishes and a hot-plug monitor circuit indicates the disk was physically removed, the controller can check any disk subsequently plugged into that same slot for its own type of RAID metadata. If there is no metadata present, it's presumably a new disk fresh from the factory, and can be freely overwritten as soon as the hot-plug monitor circuit indicates the disk is fully slotted in. Likewise, if the metadata indicates it's the same disk being re-inserted, the RAID set can be automatically recovered.
If the metadata is present and indicates that the disk used to belong to a different RAID set, the system administrator might be setting up to rescue data from a different server that uses the same type of RAID controller, and so it will be best to wait for further instructions: the administrator will decide whether to overwrite the disk or to import its RAID set as another RAID volume with its existing data.
But if a disk vanishes while the hot-plug monitor circuit indicates it's still physically present, the hardware RAID controller will have a very good case for declaring it faulty, even if it later re-appears on its own.
(An important side lesson: If you are moving hardware RAID disks from a failed server to another similar server to salvage the failed server's data, make sure the recipient server does not have any of its own RAID sets in a degraded state before plugging in the disk containing the only copy of some critical data. )


text:
Q: Gettng undefined offset:0 I get this Undefined offset: 0
$lasttrade = BaseDonnee::execQuery($bdd, "SELECT Price FROM Trade_History WHERE
Market='$ipair' ORDER BY Timestamp DESC LIMIT 1")[0]["Price"];

What is this problem? and how do I solve this? the BaseDonne::execQuery function is this
static function execQuery($bdd, $query){
try{
    $req = $bdd->prepare($query);
    $req->execute();
    $result = $req->fetchAll(PDO::FETCH_ASSOC);
    $req->closeCursor();
    return $result;
} catch( PDOEXception $e ) {
       echo $e->getMessage(); // display bdd error
       exit();
   }

}


text:
Q: Proving that if $|G| > 1$, then every irreducible $FG$-module has dimension $<|G|$ I think that the thing stopping me from solving this is that I don't fully understand the relationship between $FG$-modules and $F$-vector spaces. I believe $FG$-modules are in correspondence with representations $\psi: G \rightarrow GL_n(F)$, but to be honest I don't know how to interpret $GL_n(F)$. It's the set of $n$ by $n$ matrices over $F$, but I don't see where $n$ comes in.
Can someone give me some direction?

A: For a field $F$ and a finite group $G$, $R=F[G]$ is a quasi-Frobenius ring, and in particular, $R_R$ contains a copy of every simple right $R$ module.
(Actually, the more specific relevant condition is that it is a left and right Kasch ring.)
Since $F[G]$ is $|G|$ dimensional, the dimension of any such copy would have to be less or equal.
Now since $F[G]$ is Artinian, it has finite composition length. A composition series can start at any one of these simple submodules. Now, the only way for $\dim(S)=|G|$ for one of these simple submodules is if the compostion length is $1$: but that would mean $F[G]$ is a simple $F[G]$ module, implying that it is a field. But when $|G|>1$, the augmentation ideal of $F[G]$ is always nonzero, so it is only a field when $|G|=1$.
Thus if $|G|>1$, $F[G]$ has composition length $>1$, and therefore $S\neq F[G]$ and has strictly smaller dimension.

A: Try something like this. Let $M$ be an irreducible $FG$ module, that means $M$ an $F$ vector space equipped with a left linear action of $G$ such that it has no non trivial submodule. Let $m \in M$ be a non zero vector. Because of $M$ irreducible , the span of $gm$ for all $g \in G$ is the entire $M$...


text:
Q: Foreign Key mapping using model mapper I am getting a JSON which is deserialised into a POJO and I am trying to map a POJO to below entity class using modelmapper and trying to save these entities into the database.All the fields are getting mapped and saved as expected except the foreign key value which is coming as null. Also, the userid is auto generated.Can you please help me how can I save the user id in vehicle table using modelmapper??
My User Entity class
@Entity
@Table(name = "usr")
class User{
    @Id
    @Column(name = "user_id", updatable = false, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long userId;
        private String username;
        @OneToMany(mappedBy = "user",cascade = CascadeType.ALL)
        private List<Vehicle> vehicles= new ArrayList<>();
        //getters and setters
}

My Vehicles Entity Class:
@Entity
@Table(name = "vehicle")
class Vehicle{
    @Id
    @Column(name = "vehicle_id", updatable = false, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long vehicleId;
    private String vehicleName;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_fk" , nullable = false)
    private User user;
    //getters and setters
}

My ModelMapping class:
@Service
public class UserService {

    @Autowired
    private UserDetailsService userDetailsService;

    public void saveUserDetails(UserDetails userDetails
        User targetuser{
            UserDetails sourcePojo= userDetails
            User  targetEntity= targetuser
            ModelMapper modelMapper = new ModelMapper();
            modelMapper.map(sourcePojo, targetEntity);

            userDetailsService.save(targetEntity);
    }
}

A: You Can try with making annotation more specific this :
    @OneToMany(mappedBy = "user",
               targetEntity = Vehicle.class,
               cascade = CascadeType.ALL)
    private List<Vehicle> vehicles= new ArrayList<>();

And
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_fk" ,
                referencedColumnName = "user_id",
                nullable = false)
    private User user;

And I think you have to remove annotation for auto generation of userid
As per my understanding issue is due to Auto generation of userid is done while saving an entry to DB. But when we mapped userid to vehicle it is null as it is not generated.


text:
Q: How to fake a soap response in Python? I am trying to test a function in company product. Our software will make a SOAP request like this:
Request Header
POST /testfunction.php HTTP/1.1
Accept: application/soap+xml, application/xml, text/xml
SOAPAction: "http://www.abc.com/testfunction#test"
Host: soap.abc.com
Content-Length: 461
Connection: Keep-Alive

Request Content
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.abc.com/testfunction">
<SOAP-ENV:Body>
<ns1:test>
<productID>3</productID>
<productSubID>1</productSubID>
<version>1.0.1</version>
<serialNumber/>
<language>EN</language>
<daysLicensed>0</daysLicensed>
<daysLeft>0</daysLeft>
</ns1:test>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

And the SOAP service should respond:
Response Header
HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Mon, 02 May 2011 13:43:46 GMT
Content-Type: text/xml; charset=utf-8
Connection: keep-alive
X-Powered-By: PHP/5.3.3-1ubuntu9.3
Content-Length: 304
Content-encoding: gzip

Response Content
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.abc.com/testfunction"><SOAP-ENV:Body><ns1:testResponse><result>1000</result></ns1:testResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>

In the beginning I thought I could just make a web service in web.py and returns the same response whenever someone make a POST request on http://www.abc.com/testfunction.
import web
url = (
    '/testfunction', 'testfunction',
)

class testfunction:
    def POST(self):
        web.header('Content-Type',  'text/xml; charset=utf-8')
        return """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.abc.com/testfunction"><SOAP-ENV:Body><ns1:testResponse><result>1000</result></ns1:testResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
                """

app = web.application(url, globals())

if __name__== "__main__":
    app.run()

But it didn't work. I think that maybe something to do with the header. Then I tried with SimpleXMLRPCServer.
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
import xmlrpclib

class MyRequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/',)
    def do_POST(self):
        return SimpleXMLRPCRequestHandler.do_POST(self)

def test():
    return "hello, world"

server = SimpleXMLRPCServer(
        ("0.0.0.0", 80),
        requestHandler = MyRequestHandler,
        )
server.register_function(test, 'test')
server.serve_forever()

but problem is I don't know how to deal with SOAPAction in the header and the client is not using the test function here. Can anyone help me? Thanks a lot!!
Update:
Finally did it, using the following code:
from wsgiref.simple_server import WSGIServer, WSGIRequestHandler

def echo(environ, start_response):
    status = "200 OK"
    headers = [("Content-type", "text/xml")]
    start_response(status, headers)

    return ["""<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.abc.com/testfunction"><SOAP-ENV:Body><ns1:testResponse><result>1000</result></ns1:testResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>"""]

httpd = WSGIServer(('0.0.0.0', 80), WSGIRequestHandler)
httpd.set_app(echo)
httpd.serve_forever()

It should work the same with the web.py code, however the web.py one doesn't. From the captured package in wireshark I found some garbled code ("3bc" and "0) before and after the xml content, something to do with the encoding?

A: You could use soaplib to create a real SOAP service which implements your interface and returns dummy data. This should be a bit easier to maintain then creating handwritten static responses, and the code shouldn't be much longer than your web.py-based example.
Here's a Hello World example.


text:
Q: Copy paste from excel, difference between line break in cell and row delimiter We need to offer to our customers a way of copy pasting an excel to a table in a web application.
We split rows with line breaks, and columns with tabulation.
The problems is that in a single cell you can have line break so the split(\n) will simply understand that there is a new row.
    const rows = event.target.value.split('\n');
    for (let row of rows) {
      const values = row.split('\t');
    }

With the code above, when there are no line break in cells we can get a nice table of the copy paste, but as soon as there are linebreaks in cells, everything is move to one row and break everything.
How can I differentiate line breaks for delimiting rows and line breaks in cells ?

A: Consider the small example where I've copy-pasted the Excel data into Notepad++ and we can see that cat\nfish is quoted:

So you can treat the content being pasted to the web application as tab separated values (tsv) and parse them as such.
In the snippet below tsvStringToArray is adapated from here (see here too). Note that an extra row is being returned because of that final CR LF after dog. In real life you should probably look for a library to do this for you. You might look at D3 as something that can run in the browser.
For arrToTable, I assume you must have a better effort of arrToTable. However, you should consider if you need to recreate the newline in the HTML.

const target = document.getElementById("input");
const output = document.getElementById("output");

const tsvStringToArray = (data) => {
  const re = /(\t|\r?\n|\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^\t\r\n]*))/gi
  const result = [[]]
  let matches
  while ((matches = re.exec(data))) {
    if (matches[1].length && matches[1] !== "\t") result.push([])
    result[result.length - 1].push(
      matches[2] !== undefined ? matches[2].replace(/""/g, '"') : matches[3]
    )
  }
  //console.log(result);
  return result
}

const arrToTable = arr => {
  let tbl = document.createElement("table");
  for (row of arr) {
    let tr = document.createElement("tr");
    for (cell of row) {
      let td = document.createElement("td");
      let test = /\n/.test(cell);
      if (test) {
        let items = cell.split(/\n/);
        for ([idx, item] of items.entries()) {
          td.appendChild(document.createTextNode(item));
          if (idx < items.length) {
            td.appendChild(document.createElement("br"));
          }
        }
      } else {
        td.appendChild(document.createTextNode(cell));
      }
      tr.appendChild(td);
    }
    tbl.appendChild(tr);
  }
  return tbl;
}

target.addEventListener("paste", e => {
  const text = event.clipboardData.getData("text");
  const arr = tsvStringToArray(text).slice(0, -1);
  const el = arrToTable(arr);
  output.appendChild(el);
});
div#input {
  height: 90px;
  width: 320px;
  background-color: powderblue;
}

table, tr, td {
  border: 1px solid black;
}
Paste in blue box:


text:
Q: How to escape hash in markdown syntax? How do I escape the hash value inside a code snippet in markdown?
All tries resulted to a red display of the character (invalid)
```gradle
# My gradle comment
artifactory_user=YOUR_ARTIFACTORY_USER
artifactory_password=YOUR_ARTIFACTORY_PW
```

I tried already
\\#
\#
##
#

None of these works?!

A: That's because it is invalid. Gradle syntax is based on Groovy syntax. Single-line comments in both Gradle and Groovy use //, not #:
```gradle
// My gradle comment
```

Thanks for the OP for pointing out that gradle.properties files use # for comments. The following code block with the language set to properties works as expected:
```properties
# My gradle comment
artifactory_user=YOUR_ARTIFACTORY_USER
artifactory_password=YOUR_ARTIFACTORY_PW
```


text:
Q: Please help me with the merge trigger for Contact object, where a Contact can have case associated merge trigger for Contact object, the merge is required because of duplicate Contact records and the scenario is that a Contact can have a case, therefore there will be a need to reassign that case to the winning Contact record.
Please give me some sample code to understand as to how to do it.
Thanks,

A: One way to do this is maintain a merge table(A custom Object) with a winner and loser fields .An admin can just enter the records here .A salesforce ID in winner or loser or an external Id.
A batch class can be designed to delete all loser contact records after re-parenting cases linked to the loser records to the winner records.
Here is the logic you can adapt for this
1)Fetch all the records from merge table and have a Map of winner and loser record Ids
2)Query for  records from  contact with winner and loser Ids found in merge table .
3)For each of records (Assuming they are winner ) get the corresponding loser Id from map and collect these to fetch cases and delete them.
Hope this small logic helps .


text:
Q: Troubleshoot Cinnamon window list entries appearing temporarily Background
https://youtrack.jetbrains.com/issue/WI-39812
Something in the application is causing a window or entry to temporarily appear on the task bar (or "Window list" in my panel).
The maintainers asked if I can track the process id or anything, to narrow down what is creating the window.
The taskbar entry only appears temporarily, and usually only as long as the main application has focus. I can hover the entry for a preview image, and right-click it for maximize/minimize, but so far this has not resulted in better understanding where it is coming from.
Linux Mint 18.1 Serena
Cinnamon 64-bit
Question
Is there a log file or a monitoring tool in Cinnamon, that provides information about windows opening and closing, or windows currently active, and the originating process?
I assume there is a 1:1 relationship between windows and entries in the task bar. Please correct me if this is not the case. In this case, I am more interested in task bar entries than windows.
Resolution
This section is not part of the question! It just fits better here than in a comment!
The accepted answer by mviereck was helpful.
Here is my version of the commands:
mkdir ~/troubleshooting; cd ~/troubleshooting
sleep 10; wmctrl -lp > list1; xwininfo -root -children -tree > tree1
# Focus on phpstorm, do NOT make the strange window appear.
# Wait long enough!
sleep 10; wmctrl -lp > list2; xwininfo -root -children -tree > tree2
# Focus on phpstorm, do something to let the strange window appear.
# Wait long enough!
diff -U30 list1 list2 > list.diff
diff -U30 tree1 tree2 > tree.diff
# Open in gedit for nice colors.
gedit list.diff tree.diff & disown

These are changes in tree.diff:
 xwininfo: Window id: 0xf5 (the root window) (has no name)

   Root window id: 0xf5 (the root window) (has no name)
   Parent window id: 0x0 (none)
-     44 children:
+     46 children:
+     0x22004e9 "win13": ("sun-awt-X11-XWindowPeer" "jetbrains-phpstorm")  502x224+1209+354  +1209+354
      0x4a0000c (has no name): ()  1x1+-1+-1  +-1+-1
[..]
      0x3c00001 "mintUpdate.py": ("mintUpdate.py" "")  10x10+10+10  +10+10
+     0x22004fc "win15": ("sun-awt-X11-XWindowPeer" "jetbrains-phpstorm")  9x18+1696+355  +1696+355
      0x1a0347e (has no name): ()  1920x1053+0+0  +0+0

This means these two lines were added, but in different positions in tree.diff:
+     0x22004e9 "win13": ("sun-awt-X11-XWindowPeer" "jetbrains-phpstorm")  502x224+1209+354  +1209+354
+     0x22004fc "win15": ("sun-awt-X11-XWindowPeer" "jetbrains-phpstorm")  9x18+1696+355  +1696+355

This is the added line I found in list.diff:
+0x022004fc  0 7177   asus-mint-2017 win15

The label of the task bar entry was "win15", and the preview looked like "9x18" could be the dimensions.
The "win13" did not show up in the task bar.
I will report these findings in https://youtrack.jetbrains.com/issue/WI-39812 and see what they say.
UPDATE after the comment by mviereck:
ps -f -p 7177 shows
USERNAME  7177  7113  8 09:52 ?        00:09:31 /home/USERNAME/phpstorm/jre64/bin/java -classpath /home/USERNAME/phpstorm/lib/bootstrap.jar:...

I am not sure if any private information is in there, so I don't paste the complete thing. But it seems to be the main phpstorm process.

A: Possibilities to get some infos about the window:
Create window lists with wmctrl and xwininfo.
If that strange task bar entry appears, open a terminal and type:
wmctrl -lp > list1
xwininfo -root -children -tree > list3

Change nothing but what is needed to let that entry disappear. Than:
wmctrl -lp >list2
xwininfo -root -children -tree > list4

diff can show you differences between the lists:
diff list1 list2
diff list3 list4

Maybe that gives you some hints. wmctrl -lp also shows the process id (pid) belonging to the window. If you identified the window and it provides a pid, get some infos with ps -f -p PID.


text:
Q: How to make maven build fail with shell script? I am trying to automate mvn release:prepare through Shell Script and GitHub Action.
I want to make a condition where if my current pom version and the input version I provided don't match, then the maven build should fail.
Here is my shell script:
#!/usr/bin/env bash

set -e

if [[ -z $1 ]]; then
  echo "latest version is not set"
  exit 1
fi
TARGET_VERSION=$1
echo TARGET_VERSION="$TARGET_VERSION"

CURRENT_VERSION=$(xmlstarlet sel -N pom=http://maven.apache.org/POM/4.0.0 \
                             -t -m pom:project -v pom:version pom.xml | sed "s/-SNAPSHOT//")
echo CURRENT_VERSION="$CURRENT_VERSION"

if [ "$TARGET_VERSION" != "$CURRENT_VERSION" ]; then
  # Here I want to make maven build fail
fi

SKIP_TEST="-DskipTests -DskipITs"
SKIP_CHECKSTYLE="-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true"
SKIP_OTHERS="-Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true -Dxml.skip=true"

echo "Version bump in pom.xml (release:prepare) ..."
mvn -e --no-transfer-progress -Pgpg release:prepare -B -Darguments="$SKIP_TEST $SKIP_CHECKSTYLE \
  $SKIP_OTHERS"

Also, I had a question: While automating the release:prepare, is there any way to escape the gpg key or any other way to run the release:prepare? I am totally new to maven


text:
Q: deprecated functions, is it breaking my site? Error logs are showing several deprecated errors these are:
[19-Jan-2022 22:55:27 UTC] The is_ajax function is deprecated since version 6.1.0. Replace with wp_doing_ajax.

[19-Jan-2022 22:39:06 UTC] woocommerce_add_order_item_meta is deprecated since version 3.0.0! Use woocommerce_new_order_item instead.

We then installed Deprecated Calls plugin which displays is_ajax() used in wp-content/plugins/woocommerce/includes/wc-deprecated-functions.php on line 54.
We then checked such file which only gives us this on line 1136
if ( ! function_exists( 'is_ajax' ) ) {

    /**
     * Is_ajax - Returns true when the page is loaded via ajax.
     *
     * @deprecated 6.1.0
     * @return bool
     */
    function is_ajax() {
        wc_deprecated_function( 'is_ajax', '6.1.0', 'wp_doing_ajax' );
        return function_exists( 'wp_doing_ajax' ) ? wp_doing_ajax() : Constants::is_defined( 'DOING_AJAX' );
    }
}

Could deprecated functions break a WordPress site? Yesterday we had between 160,000 - 220,000 requests made to the site which crippled the server ultimately causing the site to go offline and display "Error establishing connetion to database". When enabling attack mode on cloudflare the site was back online however some plugins and features were not working from this point onwards.
However when checking cloudflare their only appears to be traffic coming from the site itself and all of the thousands and thousands of requests are the same (see picture below):

Today we see requests from our site itself which are being challenged by cloudflare

I understand this is a very broad question but we remain quite anxious after yesterday , can conflicting plugins cause a self inflicted DDoS? is deprecated functions possibly causing issues?


text:
Q: How to mock a SecurityContext Endpoints with Jersey.
I want to secure an endpoint with a ContainerRequestFilter
@Provider
@Secured
public class AuthorizationRequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        final SecurityContext securityContext =
                requestContext.getSecurityContext();

        //TODO: on logger here...
        System.out.printf("Filtering %s request... AuthorizationRequestFilter\n", requestContext.getMethod());
        requestContext.getHeaders().add("X-Secured-By", "Jersey >_<");
        System.out.printf("SecurityContext: %s (%s).\n", securityContext, securityContext.getAuthenticationScheme());

        if (securityContext == null || !securityContext.isUserInRole("privileged")) {
            requestContext.abortWith(new UnauthorizedResponse().getResponse());
        }
    }
}

The annotation @Secured:
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface Secured {}

So I can do this:
@Path("foobar")
public class FooResource {

    //...

    @Context
    SecurityContext securityContext;

    //...

    @GET
    @Secured
    @Path(value = "foo")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getFoo(@Context SecurityContext sc, @Context UriInfo ui, @Context HttpHeaders hh) {
        // ...
    }

    //...

And I'm doing it right (I think), because with my test I don't even pass through the getFoo endpoint but is the ContainerRequestFilter that kicks me out. In fact I receive this (the "X-Secured-By" header is hand-made):
Headers: {X-Secured-By=[Jersey >_< kicked you out!], Content-Length=[97], Date=[Wed, 03 Dec 2014 17:46:50 GMT], Content-Type=[application/json], X-Powered-By=[Jersey ^_^]}
Response: InboundJaxrsResponse{ClientResponse{method=GET, uri=http://localhost:9998/urler/test, status=401, reason=Unauthorized}}

Now it would be nice to mock the SecurityContext.
This is what I'm doing... and if I'm here, it's obviously silly and/or wrong.
public class UrlerResourceTest extends JerseyTest {
    //....

    @Override
    public TestContainerFactory getTestContainerFactory() {
        GrizzlyTestContainerFactory grizzlyTestContainerFactory = new GrizzlyTestContainerFactory();
        System.out.printf("The GrizzlyTestContainerFactory: %s ", grizzlyTestContainerFactory);
        // just for debugging...
        return grizzlyTestContainerFactory;
    }

    @Test
    public void testSecuredEndpoint() throws JSONException {

        SecurityContext securityContext = Mockito.mock(SecurityContext.class);
        Mockito.when(securityContext.isUserInRole(anyString())).thenReturn(true);
        Mockito.when(securityContext.getAuthenticationScheme()).thenReturn("Just Mocking...");
        ReflectionTestUtils.setField(resource, "securityContext", securityContext, SecurityContext.class);

        final Response response = target("foobar")
            .path("foo")
            .request(MediaType.APPLICATION_JSON)
            .get();
        System.out.println(getFormattedStringResponseInfo(response));

        JSONObject entity = new JSONObject(response.readEntity(String.class));
        assertTrue(entity.get("secured").equals(true));
        assertTrue(response.getHeaders().containsKey("X-Secured-By"));
        assertEquals(Status.OK.getStatusCode(), response.getStatus());
    }

How can I mock the SecurityContext in my tests?
Thank you so much in advance.

A: Disclaimer: I'm not really a Mockito user, but from what I understand, mocking is used for situations where you have injected class dependencies (fields), and you mock those dependencies. In which case you still need to set the field with the mocked object. For example
public class TestClass {
    TestService testService;
    public void doTest() {
        System.out.println(testService.getString());
    }
    public void setTestService(TestService testService) {
        this.testService = testService;
    }
}
public class TestService {
    public String getString() {
        return "Hello world";
    }
}
@Test
public void toTest() {
    TestService testService = Mockito.mock(TestService.class);
    Mockito.when(testService.getString()).thenReturn("Hello Squirrel");
    TestClass testClass = new TestClass();
    testClass.setTestService(testService);
    testClass.doTest();
}

You can see we are setting the the TestService in the TestClass with the mocked object. It's not greatest example, as we could simple instantiate TestService, but it shows, from my understanding, how the mocking should work.
That being said, I don't see how it is possible to do this with the AuthorizationRequestFilter, as it's handled by the test container, and we are not instantiating it for a unit test. Even if we were, it would seem intrusive (and redundant) to add a SecurityContext field.
So without a full integration test, where we are starting the server, and using the server's authentication capabilities, it will be difficult to handle the SecurityContext per this use case, as the SecurityContext is created by the container, taking information from the underlying servlet containers authentication mechanism.
One way you can achieve this though (which IMO doesn't seem very elegant - but works), without a full integration test, is to create a a filter which performs before your AuthorizationRequestFilter, and set the SecurityContext from there. Testing aside, this is actually pretty common in cases where we need to implement outr own custom authentication mechanism.
An example of how you might do this for your unit test, might be something like:
public class UrlerResourceTest extends JerseyTest {
    ...
    @Override
    public Application configure() {
        return new ResourceConfig(FooResource.class)
                .register(AuthorizationRequestFilter.class)
                .register(AuthenticationFilter.class);
    }

    @Provider
    @Priority(Priorities.AUTHENTICATION)
    public static class AuthenticationFilter implements ContainerRequestFilter {
        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            requestContext.setSecurityContext(new SecurityContext() {
                @Override
                public Principal getUserPrincipal() {
                    return new Principal() {
                        @Override
                        public String getName() {
                            return "Stackoverflow";
                        }
                    };
                }
                @Override
                public boolean isUserInRole(String string) {
                    return "privileged".equals(string);
                }
                @Override
                public boolean isSecure() { return true; }
                @Override
                public String getAuthenticationScheme() { return "BASIC"; }
            });
        }
    }
    ...
}

This filter will perform before the AuthorizationRequestFilter because of the @Priority annotation. We've set it to Priorities.AUTHENTICATION which will before before any other filter without such annotation. (See Priorities API and Priorities with Jersey. Also the SecurityContext will be passed along between filters and also be injected into your resource class.
As I said, I don't think this is very elegant to have to create another filter, but it works for this purpose. Also I am not too familiar with the Jersey Test Framework, as I'm still beginning with it, but there are many configuration options for deployment within a servlet context. I don't know if we can configure the needed authentication mechanism for this case, but it might be something worth looking into.

Edit: In the beginning I explained about setting the field for the test object, but we can also pass the mocked object to a method. For example we could mock the ContainterRequestContext in the filter method, and call filter ourselves, passing the mocked ContainerRequestContext. But this is only useful when we are actually unit testing the filter class and instantiating it ourselves, which is not the case here.


text:
Q: Javascript to set hidden form value on drop down change - options not populating from Javascript array I have some Javascript code that creates 2 arrays:  One for Product Category and one for Product.
But before the user can choose the Product Category or Product, they have to choose the type of Campaign they wish to use.  Thus, the selection (event) of the 'Campaign', triggers the hidden drop-down menu from which to choose the Product Category.  Once the Product Category is chosen, the Product drop-down populates and the user is allowed to choose from the appropriate options.
My only problem:  the Product Category does not populate correctly.  The options are invisible, but once I select one - the Product options drop-down populates accordingly.  I'm super confused....
Here's the JScript code:

Here's the code from my .php file:

<form name="selector" action="#" method="post">
Select the Campaign methodology to model:

<select id='campnum' name='dropnum' class='css_button_example' onChange="javascript: ShowMenu(document.getElementById('campnum').value, 'camp', 5);">
        <option value='0'>Select Campaign
        <option value='1'>Retention Campaign
        <option value='2'>Acquisition Campaign
        <option value='3'>Cross-Sell Campaign
        <option value='4'>Up-Sell Campaign
</select>
</form>

 <form name="myForm1">

 Product Category:
 <select name="main" size=1 onChange="updateMenus(this)">
 <option>
 <option>
 <option>
 </select>

 Product:
 <select name="title" size=1>
 <option>
 <option>
 <option>
 </select>
 </form>

Regards,
Vijay

A: "href" attribute on div doesn't make sense:
<div href="javascript:showonlyone

And onChange="javascript:..." is wrong -- the value of onchange should be just JS code, no "javascript:" prefix.
Where's ShowMenu defined?


text:
Q: simplicial approximation of an open subset I am interested in the following problem :
Let $K$ be an abstract simplicial complex, let $\vert K \vert$ be its geometrical realization, let $U\subset \vert K \vert$ be an open subspace (not a subcomplex). Is it possible to find some subdivision $K^*$ of $K$ and a subcomplex $L\subset K^*$ such that $U$ is a deformation retract of the geometric realization $\vert L \vert$?
Thanks for any hint.


text:
Q: What's the deprecation policy of previous releases of Mono? Mono 3.0 has been released in October 2012. Latest version (v3.0.12) has been released in June 2013.
In his "What is new in Mono?" presentation at MonkeySpace 2013, Miguel de Icaza states that "Mono 2.10.X is no longer supported".
Despite all my researchs, I haven't been able to find an authoritative source regarding Mono support policy and scheduled deprecation of a version.
Is there an updated web page similar to the Microsoft products lifecycle fact sheet  for Mono?
That would be handy in order to plan Mono upgrades or check if it's worth reporting a bug for a specific version.


text:
Q: Vertical alignment of TikZ within text I have a bit of TikZ in my text, namely:
\documentclass[]{standalone}
  \usepackage{tikz}
  \begin{document}
    Some text (\tikz{\node[scale=0.5,solid,draw,thick,blue,rectangle,fill=white] {A};}), and some more
  \end{document}

This produces the blue rectangle as expected, but it is not aligned with the bottom of the parentheses, which I want.
Is there a simple way to shift an object or even text within a line vertically, while keeping the rest? Or is there some workaround in TikZ that might be able to do so?

A: This is a bit like the Chain Tutorial in the pgfmanual.  It is best to specify text height and text depth for the nodes in this case.  For example as follows:

\documentclass{article}

\usepackage{tikz}

\begin{document}
\tikzset{every node/.style={anchor=base,scale=0.5,draw,thick,blue,
text height=1.7ex,text depth=0.3ex, minimum width=1em}}

Some text
(\tikz[baseline]{\node {a};}),
(\tikz[baseline]{\node {d};})

More demonstration
(\tikz[baseline]{\node {a};}\tikz[baseline]{\node {d};}%
\hbox to 0pt{\hss\tikz{\draw[very thin,red] (0,0) -- (4cm,0);}})

\end{document}

I have specified anchor=base for the nodes, so the baseline of the text in these nodes lies on the x-axis.  Then it is sufficient to just pass the plain baseline option to \tikz for the vertical alignment.
In general, you can set baseline to some vertical dimension to shift material

\documentclass{article}

\usepackage{tikz}

\begin{document}

\tikzset{every node/.style={anchor=base,draw,thick,blue,
text height=1.7ex,text depth=0.3ex, minimum width=1em,scale=0.5}}

Some text
\tikz[baseline]{\node {a};}
\tikz[baseline=0.1ex]{\node {a};}
\tikz[baseline=0.3ex]{\node {a};}
\tikz[baseline=0.7ex]{\node {a};}
\tikz[baseline=1ex]{\node {a};}
\tikz[baseline=2ex]{\node {a};}
\tikz[baseline=4ex]{\node {a};}
\tikz[baseline=-0.3ex]{\node {a};}
\tikz[baseline=-0.5ex]{\node {a};}
\tikz[baseline=-1ex]{\node {a};}
\tikz[baseline=-2.5ex]{\node {a};}
\tikz[baseline=-4ex]{\node {a};}
for a dance.

\end{document}

or use a node as in the linked question.
I have specified dimensions in terms of ex and em units which reflect the size of the font used, rather than absolute units such as cm.


text:
Q: Android App Startup Crash - customtabs.CustomTabsSession.validateRelationship I followed Googles guidelines for the recent Trusted Web Activities and my app has been working fine on my device and some select emulators.
However, on certain devices and emulators (such as Google Pixel 2) I get an immediate crash on startup.
The logcat outputs:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ocdev.yu_gi_ohdatabase, PID: 5020
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.customtabs.CustomTabsSession.validateRelationship(int, android.net.Uri, android.os.Bundle)' on a null object reference
        at android.support.customtabs.TrustedWebUtils.launchAsTrustedWebActivity(TrustedWebUtils.java:134)
        at android.support.customtabs.trusted.LauncherActivity$TwaCustomTabsServiceConnection.onCustomTabsServiceConnected(LauncherActivity.java:199)
        at android.support.customtabs.CustomTabsServiceConnection.onServiceConnected(CustomTabsServiceConnection.java:44)
        at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1634)
        at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1663)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ocdev.yu_gi_ohdatabase">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ygo_fore"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ygo_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="asset_statements"
            android:resource="@string/asset_statements" />
        <activity
            android:name="android.support.customtabs.trusted.LauncherActivity">

            <!-- Edit android:value to change the url opened by the TWA -->
            <meta-data
                android:name="android.support.customtabs.trusted.DEFAULT_URL"
                android:value="https://db.ygoprodeck.com" />

            <!-- This intent-filter adds the TWA to the Android Launcher -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!--
              This intent-filter allows the TWA to handle Intents to open
              airhorner.com.
            -->
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE"/>

                <!-- Edit android:host to handle links to the target URL-->
                <data
                    android:scheme="https"
                    android:host="db.ygoprodeck.com"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Module build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.ocdev.yu_gi_ohdatabase"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.github.GoogleChrome.custom-tabs-client:customtabs:3a71a75c9f'
    implementation 'com.android.support:support-media-compat:28.0.0'
    implementation 'com.android.support:animated-vector-drawable:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
}

Project build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.1'

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

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

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

I also tested my release apk on Android Emulators via Browserstack and I receive the exact same issue.
I also received the issue on some physical devices I test such as Samsung Galaxy S7 Edge but the strange thing is that I tested a different Galaxy S7 Edge and it worked without issues. From what I have tested so far, I'd guess it works on 50% of the devices I've tested.
I'm not an inherit Android developer so I am struggling to find the cause of this issue and why it works fine and some devices and not on others.

A: I posted this question on the Chromium forums and got redirected to a temporary fix listed here.
In short, they are aware of the issue and hope to have a permanent solution out soon so the temporary fix shouldn't be needed for long.
The answer given:

For the moment, you can change the last parameter to
  CustomTabsClient#getPackageName here to true. This parameter is
  'ignoreDefault' and as you can probably guess will make the package
  selection ignore the user's default. Ideally though this won't be
  necessary for long.

A: I have the same problem.
I noticed that if I update chrome to the last version (currently 72) the TWA works great.
What is annoying is that there is no error message for the user to make him update chrome.
IMO this makes TWA currently not usable.

A: I have this issue with my TWA too, I found that if the browser default is set to chrome or edge then it'll work but not for samsung browser and firefox

A: This issue may not happen anymore with the new versions. However, if someone still uses old versions, updating to the new version can be helped.
In the new version the validate function has been removed as explain:

Allow to send multiple trusted origins from TWA clients
  Currently, if the user is able to navigate or gets redirected to
  another trusted origin within a TWA, the only way to ensure that the
  other origin gets verified is by calling
  CustomTabsSession#verifyRelationship on the client side. Besides being
  a bit awkward api, that would delay launching Chrome, and
  consequently, showing splash screen, so this needs to change.

Please check this answer.
https://stackoverflow.com/a/58231296/4446181


text:
Q: Aggregating overlapping data I have a table called dbo.StayData. In this table there are 4 columns the GuestID, StayID, CheckIn, CheckOut. I am trying to write a report that will return 3 columns GuestID, CheckIN, CheckOut. However if a guest has stays that overlap such as CheckOuton one line being the same as CheckIn on a different line or if the CheckIn on one line falls between the CheckIn and CheckOut of a different entry I want to combine those into one entry so I can get a better understanding of when a full trip occurred. below I have a sample of the data on the left and a sample of the desired results on the right. I am open to all ideas. I have thought about trying to make temp tables but I am unsure how to get to where I want to be.

I think this question should be able to answer my question but I don't really understand the code. SQL - Consolidate Overlapping Data
I used the code from the answer in the above question and was able to make it work fine when looking at 1 guest in a temp table. However I am trying to modify that code to look at the whole dbo.StayData table which has 100k's of rows and 10k's of GuestID's. below is the what I came up with after modification.
with temp_positions as  --Select all limits as a single column along with the start / end flag (s / e)
(
    select GuestID,CheckIn as limit, 's' as pos from dbo.StayData
    union
    select GuestID,CheckOut as limit, 'e' as pos from dbo.StayData
)
, ordered_positions as --Rank all limits
(
    select GuestID,limit, pos, RANK() OVER (ORDER BY GuestID,limit) AS Rank
    from temp_positions
)
, collapsed_positions as --Collapse ranges (select the first limit, if s is preceded or followed by e, and the last limit) and rank limits again
(
    select op1.*, RANK() OVER (ORDER BY Op1.GuestID,op1.Rank) AS New_Rank
    from ordered_positions op1
    inner join ordered_positions op2
    on (op1.Rank = op2.Rank and op1.Rank = 1 and op1.pos = 's')
    or (op2.Rank = op1.Rank-1 and op2.pos = 'e' and op1.pos = 's')
    or (op2.Rank = op1.Rank+1 and op2.pos = 's' and op1.pos = 'e')
    or (op2.Rank = op1.Rank and op1.pos = 'e' and op1.Rank = (select max(Rank) from ordered_positions))
)
, final_positions as --Now each s is followed by e. So, select s limits and corresponding e limits. Rank ranges
(
    select Cp1.GuestID,cp1.limit as cp1_limit, cp2.limit as cp2_limit,  RANK() OVER (ORDER BY cp1.GuestID, cp1.limit) AS Final_Rank
    from collapsed_positions cp1
    inner join collapsed_positions cp2
    on cp1.pos = 's' and cp2.New_Rank = cp1.New_Rank+1
)
--Finally, subtract 1 from Rank to start Range #'s from 0
select fp.GuestID, fp.Final_Rank-1 seq_no, fp.cp1_limit as starty, fp.cp2_limit as endy
from final_positions fp;

A: So below is the final code I am now using which appears to work. I moved the Subquery up into a join on the collapsed Positions portion, I also added distinct to the final select.
with temp_positions as  --Select all limits as a single column along with the start / end flag (s / e)
(
    select GuestID,CheckIn as limit, 's' as pos from dbo.StayData
    union
    select GuestID,CheckOut as limit, 'e' as pos from dbo.StayData
)
, ordered_positions as --Rank all limits
(
    select GuestID,limit, pos, RANK() OVER (ORDER BY GuestID,limit) AS Rank
    from temp_positions
)
, collapsed_positions as --Collapse ranges (select the first limit, if s is preceded or followed by e, and the last limit) and rank limits again
(
    select op1.*, RANK() OVER (ORDER BY Op1.GuestID,op1.Rank) AS New_Rank
    from ordered_positions op1
    Left Join (Select GuestID, Max(Rank) as Rank from Ordered_Positions Group by GuestID) as OP
    on OP1.Rank = OP.Rank

    inner join ordered_positions op2
    on (op1.Rank = op2.Rank and op1.Rank = 1 and op1.pos = 's')
    or (op2.Rank = op1.Rank-1 and op2.pos = 'e' and op1.pos = 's')
    or (op2.Rank = op1.Rank+1 and op2.pos = 's' and op1.pos = 'e')
    or (op2.Rank = op1.Rank and op1.pos = 'e' and op1.Rank = OP.Rank)
)
, final_positions as --Now each s is followed by e. So, select s limits and corresponding e limits. Rank ranges
(
    select Cp1.GuestID,cp1.limit as cp1_limit, cp2.limit as cp2_limit,  RANK() OVER (ORDER BY cp1.GuestID, cp1.limit) AS Final_Rank
    from collapsed_positions cp1
    inner join collapsed_positions cp2
    on cp1.pos = 's' and cp2.New_Rank = cp1.New_Rank+1
)
--Finally, subtract 1 from Rank to start Range #'s from 0
select distinct fp.GuestID, fp.Final_Rank-1 seq_no, fp.cp1_limit as starty, fp.cp2_limit as endy
from final_positions fp;


text:
Q: non-ASCII character declaration I would like to store a character (in order to compare it with other characters).
If I declare the variable like this :
char c = 'é';

everything works well, but I get these warnings :
warning: multi-character character constant [-Wmultichar]
   char c = 'é';
            ^
ii.c:12:3: warning: overflow in implicit constant conversion [-Woverflow]
   char c = 'é';

I think I understand why there is these warnings, but I wonder why does it still work?
And should I define it like this : int d = 'é'; although it takes more space in memory?
Moreover, I also get the warning below with this declaration :
warning: multi-character character constant [-Wmultichar]

int d = 'é';
Do I miss something? Thanks ;)

A: Try using wchar_t rather than char.  char is a single byte, which is appropriate for ASCII but not for multi-byte character sets such as UTF-8.  Also, flag your character literal as being a wide character rather than a narrow character:
#include <wchar.h>
...
wchar_t c = L'é';

A: é has the Unicode code point 0xE9, the UTF-8 encoding is "\xc3\xa9".
I assume your source file is encoded in UTF-8, so
char c = 'é';

is (roughly) equivalent to
char c = '\xc3\xa9';

How such character constants are treated is implementation-defined. For GCC:

The compiler evaluates a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not (a slight change from versions 3.1 and earlier of GCC). If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored.
For example, 'ab' for a target with an 8-bit char would be interpreted as (int) ((unsigned char) 'a' * 256 + (unsigned char) 'b'), and '\234a' as (int) ((unsigned char) '\234' * 256 + (unsigned char) 'a').

Hence, 'é' has the value 0xC3A9, which fits into an int (at least for 32-bit int), but not into an (8-bit) char, so the conversion to char is again implementation-defined:

For conversion to a type of width N, the value is reduced modulo 2N to be within range of the type; no signal is raised.

This gives (with signed char)
#include <stdio.h>
int main(void) {
    printf("%d %d\n", 'é', (char)'é');
    if((char)'é' == (char)'©') puts("(char)'é' == (char)'©'");
}

Output:
50089 -87
(char)'é' == (char)'©'

50089 is 0xC3A9, 87 is 0xA9.
So you lose information when storing é into a char (there are characters like © which compare equal to é). You can

*

*Use wchar_t, an implementation-dependent wide character type which is 4 byte on Linux holding UTF-32: wchar_t c = L'é';. You can convert them to the locale-specific multibyte-encoding (probably UTF-8, but you'll need to set the locale before, see setlocale; note, that changing the locale may change the behaviour of functions like isalpha or printf) by wcrtomb or use them directly and also use wide strings (use the L prefix to get wide character string literals)

*Use a string and store UTF-8 in it (as in const char *c = "é"; or const char *c = "\u00e9"; or const char *c = "\xc3\xa9;", with possibly different semantics; for C11, perhaps also look for UTF-8 string literals and the u8 prefix)

Note, that file streams have an orientation (cf. fwide).
HTH


text:
Q: User is reporting that they've unable to SSH into an EC2 instance in AWS? The user's are doing the following:
$ ssh -i /Users/user1/key.pem centos@10.12.10.10

The error message received while trying to access is as follows:
$ ssh -i /Users/user1/key.pem centos@10.12.10.10
centos@10.12.10.10 : Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

A: A novel solution to this particular problem was presented by the AWS support and I felt compelled to share it here, since I hadn't seen it previously. In the past the method most of my colleagues have used revolved around stopping the instance and then mounting the EBS volume attached to it to another EC2 instance as a secondary volume and then mount it and edit it as needed.
These howtos show that traditional method:

*

*https://n2ws.com/blog/how-to-guides/connect-aws-ebs-volume-another-instance

*AWS Knowledge Center Videos: How do I recover access to my EC2 instances if I lost my SSH key pair?
Using User Data
This new method to me was to utilize #userdata to for a sequence of commands to run within the EC2 instance as it boots.

*

*Before you begin, please create a snapshot of your volume (Volume ID: vol-XXXX) that's attached to the EC2 you're unable to SSH into, just as a precaution. A snapshot is essentially a backup of your volume. You can find the steps for creating a snapshot in this documentation.

*Stop your instance.

*In the console, select your instance, go to Actions → Instance Settings → View/Change User Data

*Inside User Data, put the information below:

#cloud-config
bootcmd:
  - [ chmod, 700, /home/centos ]
  - [ chmod, 700, /home/centos/.ssh ]
  - [ chmod, 600, /home/centos/.ssh/* ]
  - [ chmod, 600, /etc/ssh/ssh_host_*_key ]
  - [ chmod, 711, /var/empty/sshd ]
  - [ chmod, 600, /home/centos/.ssh/authorized_keys ]
  - [ sh, -c, "chown -R centos:centos /home/centos" ]

*Start your instance.

Once the instance is restarted, attempt to access the instance via ssh.
Notes

*

*The above user-data script will correct any ownership and permissions issues within the instance itself.

*If you are still experiencing an issue after using the above user-data script, please let me know and I will get back to you.

*If the previous procedure worked, please repeat the  steps 1-4 and delete the content from the User-Data box to avoid the procedure repeats again every instance reboot.


text:
Q: css inheritence - quiz12 What will be the text size "Universe" with the below declaration

World is
VERY small in
Universe

*

*12px

*6px

*font size specified for BODY

*Varies from browser to browser

I encountered this question in a quiz. Option 4, tempt me to post this question here.

A: 100% of 12 * .5 is 6.

A: The answer is 6px

A: A must read in this context
Although Percentages and Ems are arguably the best method for font sizing, there are two main problems to overcome:

*

*Consistency across browsers

*Inheritance and its effect on nested items

Consistency across browsers
Browsers interpret relative font sizing in different ways, especially in relation to inheritance. One example would be setting font size in the body tag:
body { font-size: 80%; }
Most browsers will render this as being 80% of the element's default font behaviour. A standard H1 will render at 200% default font size, so with the rule above applied to the page, an H1 would become 160% (200% x 80%= 160%) of default font size.
Mac/Opera6 will not apply this rule consistently across content. Text within tables stays at default size. Mac/Netscape4 and Win/Netscape4 will apply this rule to headings as well as text within paragraph tags - making all content on the page 80% size.
Inheritance and its effect on nested items
Relative font sizing also runs into problems with inheritance and its effect on nested items. For example, a rule like the one below can cause inheritance problems:
p, ul { font-size: 85%; }
A sample showing paragraph and unordered nested list problem.
Any content within a paragraph or unordered list will be scaled to 80% of the user's default browser size. The problem occurs when there is a nested unordered list. The nested list item will inherit the relative font sizing and apply it again, making the nested list items 72.25% in size (85% x 85% = 72.25%).
This is easily fixed with another rule that will bring all nested list items back to 85% font size:
ul ul { font-size: 100%; }
More here
Relative font sizes and inheritance


text:
Q: django objects...values() select only some fields I'm optimizing the memory load (~2GB, offline accounting and analysis routine) of this line:
l2 = Photograph.objects.filter(**(movie.get_selectors())).values()

Is there a way to convince django to skip certain columns when fetching values()?
Specifically, the routine obtains all rows of the table matching certain criteria (db is optimized and performs it very quickly), but it is a bit too much for python to handle - there is a long string referenced in each row, storing the urls for thumbnails.
I only really need three fields from each row, but, if all the fields are included, it suddenly consumes about 5kB/row which sadly pushes the RAM to the limit.

A: Check out the QuerySet method, only. When you declare that you only want certain fields to be loaded immediately, the QuerySet manager will not pull in the other fields in your object, till you try to access them.
If you have to deal with ForeignKeys, that must also be pre-fetched, then also check out select_related
The two links above to the Django documentation have good examples, that should clarify their use.

Take a look at Django Debug Toolbar it comes with a debugsqlshell management command that allows you to see the SQL queries being generated, along with the time taken, as you play around with your models on a django/python shell.

A: The values(*fields) function allows you to specify which fields you want.


text:
Q: pycaret.anomaly.compare_models() not working; "no attribute 'compare_models'", "'compare_models' is not defined" I have tried using the compare_models() function for anomaly detection in PyCaret, but it always gives me the following error:
AttributeError                            Traceback (most recent call last)
<ipython-input-45-df60bd5a4f1b> in <module>()
----> 1 compared = pycaret.anomaly.compare_models()

AttributeError: module 'pycaret.anomaly' has no attribute 'compare_models'

If I try to do just compare_models():
NameError                                 Traceback (most recent call last)
<ipython-input-47-47f60ac858d1> in <module>()
----> 1 compared = compare_models()

NameError: name 'compare_models' is not defined

It does this both when run in the terminal and in Google Colab. Does anyone know why this is happening?

A: At the moment, it seems that this function is only supported in pycaret.classification and pycaret.regression modules.
More information: https://pycaret.org/compare-models/