text:
Q: Is it possible to use OSGi Enterprise 4.x & JPA 2.1 Entity Listener injected via blueprint? We are in the OSGi world.

*

*JPA 2.1 supports injectable EntityListner.

*And EclipseLink supports JPA 2.1.

*But the OSGi Enterprise Spec 4.x only supports JPA 2.0.

So it seems that injectable EntityListener doesn't work in OSGi, even when EclipseLink supports them.
Is it currently possible to define EntityListener in blueprint.xml and use them for injection? This would allow to inject OSGi Services into an Entity Listener. (Currently we need an explicit lookup using FrameworkUtil to do the lookup.)
Has anybody done so successfully and can share some hints, especially in regard to the used bundle (versions)?

A: Have you tried using the following maven dependency with org.eclipse.persistence.jpa.PersistenceProvider in the provider-Element of the persistence.xml? In the case of a JEE application server, the classloader would prefer libraries packaged with the deployed application by the ones bundled with the server itself.
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>


text:
Q: Switch high voltage with triggered spark gap I want to switch a high current/voltage pulse (up to few 10kV, <1kA) from a capacitor as supply. It needs to be cheap and I don't care about efficiency too much yet.
I took a look at using thyristors in series but I think it'll cost too much and could possibly be dangerous as without the correct balancing the thyristors break. I found old Thyratron tubes that I think would work, however I couldn't find them to buy (let alone buying newly made ones that are made for power electronics).
From the search of the vacuum tubes and getting to know all available tech I decided it would be cheapest to use a triggered spark gap.
Do gas discharge tubes (i.e. https://www.littelfuse.com/products/gas-discharge-tubes/high-voltage-gdt/cg3.aspx) work like a spark gap? My idea is to have a high voltage GDT in series with a smaller voltage triggered spark gap (i.e. https://uk.rs-online.com/web/p/gas-discharge-tubes/7606807/ / or homemade). I would then balance the voltage with resistors in parallel. I imagined to have it like this:

(I used a thyristor symbol as I couldn't find any triggered spark gap symbol.)
My thought is that by this arrangement the voltage supplied would divide to ~9 parts over the spark gap and ~1 part to the switch (when it is off). When the switch opens the resistance drops and the voltage over the spark gap rises creating an arc (when the voltage is sufficient). I know the resistance values are too low for above specs but this circuit is only for reference.
Would such approach work for switching an energy pulse of above specs?
(I didn't calculate the duration of the pulse yet, but I'd be surprised if the cap held for long as the spark gap would no longer arc at some point.)
If not please point out why and maybe guide me in a direction how I could realize this with cheap parts.

A: Gas discharge tubes work like a spark gap, the difference is they have a gas encapsulated in glass. This lets you determine the breakdown voltage, whereas the breakdown of a spark gap in air would be different depending on conditions such as pressure, humidity, ect.

Source: http://g3ynh.info/disch_tube/intro.html
The circuit above may work, but you'd have to get a GDT that would trigger below the 10kV and above the voltage of the resistor divider.
Another option might be a triggered spark gap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use svn log to find the last checkins? I was trying use svn to find a checkin using "svn log", but it seems like svn log is limited somehow. I started at the root of our source tree, and I did "svn log -l 10" and it gives me revision information for revisions 958 - 949. However, if I do "svn log -r HEAD:900 -l 10", I get revision information for revisions 998 - 989. Why is that? It seems backwards to me - "svn log -l 10" should give the 10 latest, right? Why do I need all the other parameters to make this work? If I do "svn log -r HEAD" I get just one log entry. I want to be able to get all log entries, then I could grep the results. There must be an easier way?

A: I've experienced this same thing.  I solved it by doing an 'svn up' before an 'svn log'.  My understanding from this is that svn will only list what it knows about the server, and it doesn't know about your commits (it only pushed them, it didn't cache them).

A: ~$ svn help log
log: Show the log messages for a set of revision(s) and/or file(s).
usage: 1. log [PATH]
       2. log URL[@REV] [PATH...]

  1. Print the log messages for a local PATH (default: '.').
     The default revision range is BASE:1.

So, by design, it starts at BASE. not HEAD if you use a path.
  2. Print the log messages for the PATHs (default: '.') under URL.
     If specified, REV determines in which revision the URL is first
     looked up, and the default revision range is REV:1; otherwise,
     the URL is looked up in HEAD, and the default revision range is
     HEAD:1.

If I do "svn log -r HEAD" I get just one log entry. I want to be able to get all log entries, then I could grep the results.

By all means, don't limit then:
 svn log HEAD:1


text:
Q: Python function doesn't work I'm learning Python, and I am up to the chapter on functions, and I wrote code for one:
import random

def roll(sides, dice):
    result = 0
    for rolls in range(0,dice):
        result += random.randint(1, sides)
    return result

but, when I try to enter the function, this comes up
Traceback (most recent call last):

File "<pyshell#16>", line 1, in <module>
    roll ()
TypeError: roll() takes exactly 2 positional arguments (0 given)

A: Your function expects two arguments.  You need to pass a value for sides and another one for dice.
Thus, an example of a proper call to your function would look like this:
roll(1,3)

Of course, sometimes you want your function to have default arguments.  In other words, you want to be able to call your function without any explicit arguments.  To do this, you add the default value for the argument in your function definition.  Let's suppose you want the function to act like a normal die by default.  All you need to do is this:
def roll(sides = 6, dice = 1)

With this function, a call such as roll(), will assume you're passing 6 and 1 as arguments.  Of course, you can always call your function with arguments and it'll override the defaults.
TL;DR:  Either pass arguments, define default arguments, or both.

A: The function expects two arguments, as in
twoDice = roll(6, 2)

or
nineCoinFlips = roll(2, 9)

A: >>> import random
>>> def roll(sides, dice):
...     result = 0
...     for rolls in range(0,dice):
...         result += random.randint(1, sides)
...     return result
...
>>> roll(6, 8)
23

you could also set defaults:
>>> import random
>>> def roll(sides = 6, dice = 2):
...     result = 0
...     for rolls in range(0,dice):
...         result += random.randint(1, sides)
...     return result
...
>>> roll()
10

A: You need to put in numbers between the (). Like roll(3, 1)


text:
Q: when is dangeraous using dereference to 0 pointer? consider following example:
   // someLibrary.h  which is exported.
    struct HandlePrivate;
    typedef HandlePrivate&  Handle;

    Handle getHandle(int code);
    void closeHandle(Handle handle);

   // someLibrary.cpp
   #include "someLibrary.h"
   struct HandlePrivate{};//definition of HandlePrivate;
   Handle getHandle(int code)
   {
        static HandlePrivate instance;
        return  code >= 0
                ? instance
                :  ( *(HandlePrivate*)0); // Hack, I know it's UB.
   }

Now, other programmer uses this library:
    // userSource.cpp
    #include "someLibrary.h"

    void foo(int code)
    {

        Handle h = getHandle(code);
        // some user code

       closeHandle(h);
    }

Question:  When is may break user code (crash or something bad), if "SomeLibrary" author uses that hack (UB) ?
if user uses only Windows and Visual Studio 2010, answer is changed ?
Because, following example is not crashed !!! :
#include <functional>
#include <type_traits>
#include "someLibrary.h"

void foo(int code)
{
     typedef std::reference_wrapper< std::remove_reference<Handle>::type> reference;

     reference h = getHandle(code);

     closeHandle(h); // is not crash, if code = -1     !!!!!!!!!!

//  However, std::reference_wrapper::operator &() - uses dereference to pointer of 0.
    }

A: When a pointer is set to zero, it is pointing to something at address zero.  The address could be physical address 0 or logical (relative to your user space) address.
The only time dereferencing a pointer to zero, is when there is memory at address zero, and address zero is accessible by the application (some OSes don't allow access to various address).
For example, in some embedded systems, address zero is a vector that contains the address of the starting program.  To read the value of the address vector, one has to assign a pointer with the value zero and dereference it.
Using a null pointer to access an objects methods is undefined behavior.  You may be lucky if the method doesn't use any data members.  If the method uses data members, the method expects those data members to be around address 0.
If you want to access object methods without creating an instance of the object, then declare the methods as static.


text:
Q: Higher Dijkgraaf Witten Theory I am trying to understand higher form symmetries in TQFT. In particular the higher form version of Dijkgraaf Witten Theory.
It is know that for a 0-form symmetry we can specify the principal G-bundle through homotopy classes of the classyfing map
$$ M \rightarrow BG = K(G,1). $$
This is known from Homotopy Theory and Eilenberg-MacLan spaces. Indeed the homotopy classes of this maps are in bijection with the first cohomology group $H^1(M,G)$ that for a finite group is isomorphic to $Hom(\pi_1(M),G)$ and fit the usual gauge theory:
$$ [M,K(G,1)] \simeq H^1(M,G) \simeq Hom(\pi_1(M),G) $$
I cannot find any reference about higher version of this. Should I expect a naive generalization? This is motivated from the fact that for a 1-form symmetry $H^2(M,G)$ works as a straightforward generalization to the previous case. But does homotpy theory tell me something about classification of gerbes via classyfing maps?
Moreover the 2-Group approach works in a similar way, we introduce $K(G,2)$ and stuff.
But how should I formulate this for a single 1-form symmetry? I hope I was clear, any help is appreciated.


text:
Q: Unable to append to a linked list in python I'm trying to learn how to create linked lists. This is my first time doing this and the reason of code failure may be something basic I'm missing.
That being said, I am unable to figure out even after using vs code's debugger. It simply stops at the end of the append method when it is called the second time.
I am using recursion to traverse to the tail. Could that be a the problem?
class Node:

    def __init__(self, data, next_node=None):
        self.data = data
        self.next = next_node

class LinkedList:

    def __init__(self):
        self.head = None

    def __repr__(self):

        if not self.head:
            return 'Linked list is empty'

        linked_list = self.head.data

        if self.head.next == None:
            return linked_list

        current = self.head

        while current.next != None:
            linked_list += '\n|\nV' + current.data

        return linked_list

    def append(self, value):

        if not self.head:
            self.head = Node(data=value)
            return

        tail = self.tail()

        tail.next = Node(data=value)

    def tail(self):

        tail = self._traverse_to_tail(self.head)

        while tail.next != None:
            tail = self._traverse_to_tail(tail)

        return tail

    def _traverse_to_tail(self, current_node, recursion_count=0):
        print(current_node.data)
        if recursion_count > 997:
            return current_node

        if current_node.next == None:
            return current_node

        current_node = current_node.next
        recursion_count += 1

        return self._traverse_to_tail(current_node, recursion_count)

if __name__ == '__main__':
    ll = LinkedList()

    ll.append('foo')
    ll.append('baz')

    print(ll)

A: The problem is you have an infinite loop in the __repr__() function, because you never increment current.
    def __repr__(self):

        if not self.head:
            return 'Linked list is empty'

        linked_list = self.head.data

        if self.head.next == None:
            return linked_list

        current = self.head

        while current.next != None:
            current = current.next
            linked_list += '\n|\nV' + current.data

        return linked_list


text:
Q: How to search in multiple columns on yii using $criteria->compare() or $criteria->addCondition() How to search in multiple columns on yii using $criteria->compare() or $criteria->addCondition()
I have a table named product and inside this table I have multiple columns for example: "productId, name, description..."
I need my user to be able to search in multiple columns like
$criteria->compare('name' AND 'id' And '','' ,$search,true); but this never works! only one column works like:
$criteria->addCondition("name LIKE '%$search%'");
or  $criteria->compare('productId',$search,true);
My search form:

<div class="search-bar col-md-9 col-lg-9 no-hor-padding">
 <form role="form" onSubmit="return dosearch();" class="navbar-form- navbar-left- search-form" style="padding-left: 0;"
  action="<?php echo Yii::app()->createAbsoluteUrl('/'); ?>" method="get">
  <input type="text" maxlength="30" placeholder="<?php echo Yii::t('app','Search products'); ?>" class="search-icon form-control input-search <?php echo !empty(Yii::app()->user->id) ? "" : "sign" ?>" name="search"></input>
 </form>
</div>

And my function or controller:
if(!empty($search)) {
    //$criteria->addCondition("name LIKE '%$search%'");
    $criteria->compare('name',$search,true);

    $searchCriteria = clone $criteria;
    $searchproducts = Products::model()->find($searchCriteria);
    if(empty($searchproducts)){
        $catrest = 1;
        $location = 1;
    }
}

Products::model() refer to product table
Here is the search function form model class for table "hts_products".:

public function search()
 {
  // @todo Please modify the following code to remove attributes that should not be searched.

  $criteria=new CDbCriteria;

  $criteria->compare('productId',$this->productId);
  $criteria->compare('userId',$this->userId);
  $criteria->compare('name',$this->name,true);
  $criteria->compare('price',$this->price);
  $criteria->compare('quantity',$this->quantity);
  $criteria->compare('sizeOptions',$this->sizeOptions,true);
  $criteria->compare('productCondition',$this->productCondition,true);
  $criteria->compare("from_unixtime(`createdDate`, '%d-%m-%Y')",$this->createdDate,true);
  //if(!empty($this->createdDate))
  //$criteria->condition = "from_unixtime(`createdDate`, '%d-%m-%Y') = '$this->createdDate'";
  //else
  //$criteria->compare('createdDate',$this->createdDate);
  /* $criteria->compare('likeCount',$this->likeCount);
  $criteria->compare('commentCount',$this->commentCount); */
  $criteria->compare('chatAndBuy',$this->chatAndBuy);
  $criteria->compare('exchangeToBuy',$this->exchangeToBuy);
  $criteria->compare('instantBuy',$this->instantBuy);
  $criteria->compare('paypalid',$this->paypalid,true);
  // $criteria->order = 'productId DESC';
  return new CActiveDataProvider($this, array(
  'criteria'=>$criteria,
  'pagination'=>array(
              'pageSize'=>10,
  ),
  'sort'=>array(
               'defaultOrder'=>'productId DESC',
  )

  ));
 }

Thanks.

A: For search in multiple columns, with variables and user inputs, compare() could be the best option. Taken from official Yii 1.1.x docs:

compare() method appends to the condition property with a new comparison
  expression. The comparison is done by comparing a column with the
  given value using some comparison operator.
  Note that any surrounding white spaces will be removed from the value
  before comparison. When the value is empty, no comparison expression
  will be added to the search condition.

Example. In a model Invoices, before submit, with empty values in your search form:
public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('invoice_number', $this->invoice_number);
        $criteria->compare('city_id', $this->city_id);
        $criteria->compare('state', $this->state);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
}

It will output something similar to:
SELECT * FROM `invoices`

After your submit, with all the values filled in your search form:
SELECT * FROM `invoices`
WHERE ( invoice_number = :ycp1 AND city_id = :ycp2 AND state = :ycp3)

Only with invoice_number filled and submitted from your form. city_id and state are empty:
SELECT * FROM `invoices`
WHERE ( invoice_number = :ycp1 )

You can look all compare() method documentation to custom it as you want.
I suggest you to use compare() to match exact values like numbers.
For search in multiple columns with LIKE or not exact/approximated values, I suggest you to use addSearchCondition().
Example:
public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('invoice_number', $this->invoice_number);
        $criteria->compare('city_id', $this->city_id);
        $criteria->compare('state', $this->state);
        $criteria->addSearchCondition('customer_name', $this->customer_name);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
}

It will output something similar to:
SELECT * FROM `invoices`
WHERE ( invoice_number = :ycp1 AND city_id = :ycp2 AND state = :ycp3 AND customer_name LIKE :ycp4 )

If you need more code examples with compare() and other methods from CDbCriteria you can see this nice article.


text:
Q: Keyboard combination ctrl+shift+ ( f9 - f12 ) not working I have been using Ubuntu 18.04 for a while and everything went well. But now I noticed something weird. The shortcut for hiding all tools windows in IDEA stopped working. I checked my keyboard shortcuts to see if I have any collisions, but I didn't find any.
Then I used "Show keyboard layout" to visualize my keyboard and I noticed, that the combination ctrl+shift+f12, is not registered. I see that that ctrl and shift are pressed, but not f12. The same thing happens for f9, f10 and f11. But it works fine with f1-f8 (I see all three of them being pressed in "show keyboard layout") and any other keyboard combinations.
I use the shortcut ctrl+shift+f12 quite extensively and I would prefer not changing the shortcut combination if possible.

A: I've had the same issue on my Ubuntu 20.04. I have toggled off all GNOME Shell Extensions and it works fine now, so some extension might be the cause for you too.
You might want to test each extension to find which one is overriding your keys. In my case, the Clipboard Indicator holds the Ctrl+F9 to Ctrl+F12.
Other places to look at are /org/gnome/desktop/wm/keybindings/ in dconf Editor and Keyboard shortcuts in Settings.


text:
Q: multiline view for lists I have a list that currently looks like this (Excel mockup):

I want it to look like this:

I tried to be really sneaky and insert

 in the XSL but SharePoint just strips it out when I save it. (Actually, I used <xsl:text disable-output-escaping="yes"><![CDATA[

]]></xsl:text> because otherwise the HTML/XML validator complains about mismatched tags.)
I tried searching for multiline views in Google, etc., but multiline is too noisy and I couldn't find anything useful.
Any suggestions on how to make this work?

A: You need you XSL to look something like this:

 <xsl:value-of select="@Client" />
 <xsl:value-of select="@Date1" />
 <xsl:value-of select="@Date2" />
 <xsl:value-of select="@Date3" />

 <xsl:value-of select="@Rep" />
 <xsl:value-of select="@Elapsed1-2" />
 <xsl:value-of select="@Elapsed3-4" />


text:
Q: Basic application of Ito's formula during a proof On pg 61 of Diffusions, Markov Processes and Martingales Volume 2 by Rogers and Williams, a proof of Ito's formula for continuous semimartingales involves demonstrating that the space of functions for which it applies is a multiplicative algebra. This derivation appears:

The integration by parts formula tells us that [for $X_t = X_0+M+A$ a continuous semimartingale with its canonical decomposition and $f,g$ two $C^2(\mathbb{R})$ functions for which Ito's formula holds (with $F_t := f(X_t),\ G_t := g(X_t)$),]
\begin{align}
F_tG_t-F_0G_0 &= \int_0^tF_sdG_s+\int_0^tG_sdF_s + \int_0^t f'g'(X_s)d[M]_s \\
&= \int_0^t \{ F_sg'(X_s) + f'(X_s)G_s\} dX_s + \\
&\qquad \frac{1}{2}\int_0^t\{F_sg''(X_s) + 2f'g'(X_s)+f''(X_s)G_s\}d[M]_s.
\end{align}

The first inequality is a direct application of the integration-by-parts formula, plus a recently shown identity for the third term.
The second equality applies Ito's formula to terms $\int_0^tF_sdG_s$ and $\int_0^t G_sdF_s$. But then I expect the last equality to include a $4f'g'$ term instead, since I believe
\begin{align}
  \int_0^t F_s dG_s &\color{red}{=}  \left[\int_0^tF_s dG_s\right]_{t=0} + \int_0^tF_sg'(X_s)d(M_s+A_s) + \frac{1}{2}\int_0^t (f'g'+fg'')(X_s)d[M_s] \\
&\color{red}{=} 0+\int_0^tF_sg'(X_s)dX_s + \frac{1}{2}\int_0^t f'g'(X_s)+F_sg''(X_s)d[M_s]. \end{align}
whence an $f'g'$ comes from each of $\int F_s dG_s$ and $\int G_s dF_s$, and another $2f'g'$ comes from the third summand.
Where am I going wrong?

A: The first red $\color{red}{=}$ is incorrect. The chain rule application there is what would be expected from classical calculus and is meaningless in this context.
The correct manipulation is more explicit with dots:
\begin{align}
\int_0^t F_s dG_s = F\cdot G \ |_t &= F\cdot g(X) \quad|_{t} \\
&\overset{(2)}= F\cdot (g(X_0)+g'(X)\cdot (M+A)+\frac{1}{2} g''(X)\cdot [M]) \quad|_{t} \\
&\overset{(3)}= F\cdot (g'(X)\cdot  (M+A)) + F\cdot\left(\frac{1}{2}g''(X)\cdot [M]\right)  \quad|_t \\
&\overset{(4)} = (Fg'(X))\cdot (M+A) + \frac{1}{2}F g''(X)\cdot [M] \quad|_t
\end{align}
The first line uses definitions. (2) uses what is assumed of $g$. (3) uses distributivity of Ito integrals. (4) uses associativity of Ito integrals on both terms.


text:
Q: Is it possible to trigger Informatica workflow using a data in database table? I am a newbie in ETL and will be using Informatica soon for one of the requirements we have.
The requirement is that Informatica needs to monitor a table in Oracle for certain "trigger data" and as soon as that data is available in that table, Informatica should start executing steps in its workflow.
Is it possible to do this? If yes, could someone please point me to a link/document where this is explained.
Many thanks.

A: No, it is not possible (checked in PowerCenter 9.5.1).
The Event-Wait task supports only two types of events:

*

*predefined events (the task instructs the Integration Service to wait for the specified indicator file to appear before continuing),

*user-defined events (the event is triggered by an Event-Raise task somewhere in the workflow).

A: Yes it is possible and you will be needing a script that can be created with following steps.
--create a shell script that checks if data is present in table on not you can use this just by taking count of the table
--if count is grater than create an empty file say DUMMY.txt (by using touch command) at a specified path.

--in you Informatica scheduling either by scheduler or by script check every 5 mins if file is present.

--if file is present call you Informatica workflow and delete the DUMMY file.

--once workflow is completed start the process again.


text:
Q: HTML/CSS - Using Custom Fonts I am trying to use a custom font from: https://www.google.com/fonts/#QuickUsePlace:quickUse/Family:Underdog
I find the font is displaying correctly when I use a Nexus One Emulator in Eclipse but on my Samsung Galaxy S2 it doesn't work...
My code is as follows:
CSS:
@font-face
{
font-family: 'Underdog', cursive;
}

#categories
{
font-family: 'Underdog';
}

#subCategories
{
font-family: 'Underdog';
}

body
{
background-color:#272714;
}

HTML:
The drop down boxes are created dynamically with JQuery. The "loadingDiv" are shown and then hidden after an AJAX call is completed.
<!DOCTYPE html>

    <title>Coupon Finder</title>
    <link rel="stylesheet" href="css/main.css" type="text/css" media="all"/>
    <link href='http://fonts.googleapis.com/css?family=Underdog' rel='stylesheet' type='text/css'>

Coupon Categories

            Please wait...

    <button class = "buttons" onclick="categorySubmit()">Search!</button>

            Please wait...

Here is a screenshot of the output on the emulator (Sorry for the dark background... need to change that):

Any ideas why it isn't working on my Galaxy S2?
Thanks for your help!

A: A good start would be to do some remote debugging.
Check this out:
How to do remote debugging on android
From there, you can use the console to see what happens in your code.
You might even find that your S2 throws an error to the console.


text:
Q: Dynamically Assign Routes in ngModule of app.routing.module.ts I have a couple of routes I need to remove based on a flag from a service file. I am not able to set the routes dynamically...Here is what I have tried so far.
My app.routing.module.ts
const productionRoutes = [
    {
        path: 'a',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.A),
        canLoad: [LoginGuard]
    }
] as Routes;

const developmentRoutes = [
    {
        path: 'a',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.A),
        canLoad: [LoginGuard]
    },
    {
        path: 'b',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.B),
        canLoad: [LoginGuard]
    },
    {
        path: 'c',
        loadChildren: () =>
            import('module').then(
                (r) => r.C
            )
    }
] as Routes;

export const routes = AppRoutingModule['getRoutes'] // **((("CHANGE HERE")))**;

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            paramsInheritanceStrategy: 'always'
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {
    constructor(private featureToggleService: FeatureToggleService) {}

    getRoutes(): Routes {
        return this.featureToggleService.productionRoutes()
            ? productionRoutes
            : developmentRoutes;
    }
}

As seen above, based on if the boolean returned by productionRoutes(),,I want to dynamically load the routes. Any help here is much appreciated...

A: Found it, we need to use resetConfig() to reassign the routes in app.component.ts
import { developmentRoutes, productionRoutes } from './app.routing.module';

constructor(
    private router: Router
) {}

ngOnInit(): void {
        this.hideRoutes =
            this.featureToggleService.productionRoutes();
        this.router.resetConfig(
            this.hideRoutes ? productionRoutes : developmentRoutes
        );
    }

app.routing.module.ts
export const productionRoutes = [
    {
        path: 'a',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.A),
        canLoad: [LoginGuard]
    }
] as Routes;

export const developmentRoutes = [
    {
        path: 'a',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.A),
        canLoad: [LoginGuard]
    },
    {
        path: 'b',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.B),
        canLoad: [LoginGuard]
    },
    {
        path: 'c',
        loadChildren: () =>
            import(
                'module'
            ).then((r) => r.C),
        canLoad: [LoginGuard]
    }
] as Routes;

export const routes = productionRoutes;

@NgModule({
    imports: [
        RouterModule.forRoot(routes, {
            paramsInheritanceStrategy: 'always'
        })
    ],
    exports: [RouterModule]
})
export class AppRoutingModule {}


text:
Q: XSL evaluate dynamic XPATH from another document I have two sample documents defined below. In module_meta.xml only the effect nodes on xpath /mdata/effectivity are relevant. As seen below, they contain a path attribute and a effrg attribute. The goal is now to evaluate the xpath (which is defined in the module_meta.xml as the path attribute) on the module.xml and append the effrg to it. See desired_output.xml for the desired result. The xsl transformation is applied on module.xml. I know that I have to use the document() function to "include" module_meta.xml, but so far I am at a loss.
module.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE proc>

<procbody>
 <info>
  <action lid="a">
  </action>
  <action lid="b">
  </action>
  <action lid="c">
  </action>
 </info>
</procbody>

module_meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mdata>
<mdata>
  <metadata>
    <metadata-item name="n1" value="v1" />
    <metadata-item name="n2" value="v2" />
    <metadata-item name="n3" value="v3" />
  </metadata>
  <effectivity>
    <effect path="//*[@lid='a']" effrg="0074 0080 0087" />
    <effect path="//*[@lid='b']" effrg="0136 0146 0174" />
  </effectivity>
</mdata>

desired_output.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE proc>

<procbody>
 <info>
  <action lid="a" effrg="0074 0080 0087">
  </action>
  <action lid="b" effrg="0136 0146 0174">
  </action>
  <action lid="c">
  </action>
 </info>
</procbody>

A: In XSLT 3 with xsl:evaluate support:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  xmlns:mf="http://example.com/mf"
  expand-text="yes">

  <xsl:function name="mf:evaluate" as="element(action)?">
    <xsl:param name="effect" as="element(effect)"/>
    <xsl:evaluate xpath="$effect/@path" context-item="$main-doc"/>
  </xsl:function>

  <xsl:variable name="main-doc" select="/"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="info/action">
    <xsl:copy>
      <xsl:apply-templates select="@*, $meta//effect[current() is mf:evaluate(.)]/@effrg"/>
    </xsl:copy>
  </xsl:template>

  <xsl:param name="meta">
<mdata>
  <metadata>
    <metadata-item name="n1" value="v1" />
    <metadata-item name="n2" value="v2" />
    <metadata-item name="n3" value="v3" />
  </metadata>
  <effectivity>
    <effect path="//*[@lid='a']" effrg="0074 0080 0087" />
    <effect path="//*[@lid='b']" effrg="0136 0146 0174" />
  </effectivity>
</mdata>
  </xsl:param>

</xsl:stylesheet>

For self-containedness of the example the second document is inline as a parameter but you can of course use <xsl:param name="meta" select="doc('module_meta.xml')"/> instead.
It might be much more efficient to use the xsl:evaluate only once for each effect element, for instance, by declaring a key doing that, and store the generated-id if there is one:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  xmlns:mf="http://example.com/mf"
  expand-text="yes">

  <xsl:key name="ref" match="mdata/effectivity/effect">
    <xsl:variable name="referenced-node" as="node()?">
      <xsl:evaluate xpath="@path" context-item="$main-doc" as="node()?"/>
    </xsl:variable>
    <xsl:sequence select="generate-id($referenced-node)"/>
  </xsl:key>

  <xsl:variable name="main-doc" select="/"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="info/action">
    <xsl:copy>
      <xsl:apply-templates select="@*, key('ref', generate-id(), $meta)/@effrg"/>
    </xsl:copy>
  </xsl:template>

  <xsl:param name="meta">
<mdata>
  <metadata>
    <metadata-item name="n1" value="v1" />
    <metadata-item name="n2" value="v2" />
    <metadata-item name="n3" value="v3" />
  </metadata>
  <effectivity>
    <effect path="//*[@lid='a']" effrg="0074 0080 0087" />
    <effect path="//*[@lid='b']" effrg="0136 0146 0174" />
  </effectivity>
</mdata>
  </xsl:param>

</xsl:stylesheet>

If you want to match any element referenced in the other document and copy any attribute but the path one you could change the template having match="info/action" to
  <xsl:template match="*[key('ref', generate-id(), $meta)]">
    <xsl:copy>
      <xsl:apply-templates select="@*, key('ref', generate-id(), $meta)/(@* except @path), node()"/>
    </xsl:copy>
  </xsl:template>


text:
Q: Should I add database queries to Codeigniter Routes.php? All of the pages and resources that php will give through readfile() exist in a database table entities.  The entities table includes the uri alias for the object, what type of object it is so it can properly route it.  Should I just include it in application/config/routes.php, should I write some helper functions and include them in the application/config/routes.php?
Should I put this elsewhere?
example:
URI:
  index.php/about-us

SQL:
  SELECT *
  FROM entities
  WHERE alias LIKE ?

RESULT:
  array(
    [id]=>5
    [alias]=>'about-us'
    [type]=>'page'

ROUTE:
  "page/get_page/$1"

A: What I would recommend is that you subclass CodeIgniter's router (discussed here: CodeIgniter System Subclassing), and make your calls in there. This way you keep your routes in your routes config, and your routes logic in the router class.
This way you'll be able to put whatever routing related functions that are necessary in the same class, as well.

A: Any data access you do should be done through models. If I'm not mistaken, I believe you can call your models directly from Routes.php (meaning the CI object should be instantiated), but you may want to test this first.


text:
Q: Firefox Extension SQLite - Update/Delete query In my firefox extension I'm trying to make an Update statement, but I've getting back this error
Error: Component returned failure code: 0x80630001 (NS_ERROR_STORAGE_BUSY)   [mozIStorageConnection.executeSimpleSQL]
Insert/Select statements works fine, but Update and Delete are not working.
Code:
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
...
this.dbFile = FileUtils.getFile("ProfD", [Source.globalValue.DB_NAME+".sqlite"]);
this.db = Services.storage.openDatabase(this.dbFile);
...
/* #1 */
var statement = this.db.createStatement('UPDATE articles SET isRead="true" WHERE id= :row_id');
statement.params.row_id = 6643098;
statement.executeAsync(); //no errors. Nothing happening - only CPU 100% Load
//statement.execute();  //getting that  error

/* #2 */
this.db.executeSimpleSQL('UPDATE articles SET isRead="true" WHERE id=6643098'); //getting that  error
...

A: Ok, i figured it out. After reboot it started working like it has to.


text:
Q: Verifying Stokes' theorem with a line integral I have the following question:

I've managed to do the surface integral part of stokes theorem (and got an answer of 0) however I'm having a lot of trouble doing the line integral part in order to verify the theorem.
As I understand it, I should be doing a line integral around the part of the plane $z = 2-2x-y$ that's in the $x,y,z > 0$ quadrant of the $x$ $y$ and $z$ axes but I don't know how to parametrize that particular part seeing as it's in 3D. All the examples I've done so far have been solely in the $xy$ plane.
Should I treat each side of the path I'm going to traverse as a separate line and then just do all four and add their answers up? Or am I missing something really simple?

A: Since your boundary is where that plane intersects the coordinate planes, then you can just think in 2D by doing each part separately. You have the part in the xy-plane which is $2-2x-y=0$ by setting $z=0$. The part in the xz-plane by setting $y=0$ and getting the line $z=2-2x$. And lastly the part in the yz-plane by setting $x=0$ to get the line $z=2-y$.
Parametrize those separately and do the integral. The last thing to be careful of is that when you add the integrals you may get a sign wrong if you don't parametrize according to the orientation. I'd maybe sketch it, so that the orientation is clear, and then just make sure the parametrization starts and ends in the right place.


text: Q: How to add an Image element for the new PageBuilder content-type in Magento2? So I have created a new content-type PageBuilderQuote for PageBuilder following the documentation here https://devdocs.magento.com/page-builder/docs/create-custom-content-type/overview.html , however all the elements added are textarea, input and select it doesn't show you how to add an image element, I would like to add for example for this PageBuilderQuote module, an image element to show the quote_author_image, but I can't find how to do it in the documentation, can someone help please?


text:
Q: Django template: Why block in included template can't be overwritten by child template? To illustrate my question more clearly, let's suppose I have a include.html template with content:
{% block test_block %}This is include{% endblock %}

I have another template called parent.html with content like this:
This is parent

{% include "include.html" %}

Now I create a templated called child.html that extends parent.html:
{% extends "parent.html" %}
{% block test_block %}This is child{% endblock %}

My idea is that when rendering child.html, the test_block in child.html can overwrite the one in include.html. As per my understanding, when a template is included, it is included as it is. So in my case, I think parent.html equals to:
This is parent

{% block test_block %}This is include{% endblock %}

So child.html should be able to overwrite test_block. But looks like it can't. Why? Is there a workaround?

A: When you include a template, it renders the template, then includes the rendered content.
From the django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

A workaround would be to have the child template extend the included template instead of the including template.  Then, include the child template.


text:
Q: How can I store the Claims by Azure Authentication in Session in .net Core? MY application - .Net Core MVC 3.1 is using Microsoft.Identity.Web and Microsoft.Identity.Web.UI for Microsoft Authentication and I receive claims. I have policy based authorization which on every hit to controller checks the users roles from DB and provides the permission to land. But I want to achieve following cases-
1> If I can redirect user from Microsoft Authentication page to a particular Controller for once where i can read the claims and add extra claims and can store it into session which can be used throughout the application and can save the unnecessary db hit on every authorization.
But after authentication currently my application is redirecting to the url which user was trying to access i.e. redirectUrl.
2> If above step is not possible, Can we store the claims after AUthentication using custom middleware into some session which can be access by anywhere.
But problem is that custom middleware will be called everytime and everytime it will check db to store the session. Secondly, HTTPConetext Session is getting cleared on every new request. How can I have session of my own which should not get cleared?

A: You can explore using ASP .NET core Distributed Cache here: https://dzone.com/articles/aspnet-core-session-storage-strategies


text:
Q: App slowdown when passing Core Data objects around views? UPDATE:
After spending a ton of time in Instruments it appears that I was saving out to Core Data a bunch of times by accident when I switch the views. To fix this, I'll have to rearrange a ton of how I load/save the data to/from the data entry fields in the subviews.
However, I did find that the major slow down caused when the number of Events increases is that for each Core Data save, something related to Core Data is doing a bunch of redrawing.
It appears that this is the original tableView doing an [UITableView _updateWithItems:updateSupport] and all the UIKit animation that goes with it. For the record, this is a stock UITableViewController with a segue to my editViewController using the prepareForSeque code below.
Is this what fetchedResultsControllers do? Keep the datasource for the tableView updated and the tableView is redrawing itself every time as the data changes, even though it's no longer visible?
(I've also pasted in the rest of the code that for the fetchedResultsController at the bottom of this post so you can see how I update the table...again, this is pretty boiler plate stuff except for  a small modification I made for when new items are added to the table.)

ORIGINAL POST:
In my iOS app that uses Core Data, I have a UITableViewController that correctly queries Core Data and displays the "Event" objects that exist in the database (uses a fetchedResultsController).
When I segue from the tableView to an edit view, I pass the selected data object like so:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"EditEventSegue"]) {
        // start a progress HUD
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack];
        // pass the selected Event object to EditViewController during segue
        NSIndexPath *indexPath = [[self eventListTable] indexPathForSelectedRow];
        Event *theEvent = [_fetchedResultsController objectAtIndexPath:indexPath];
        EditViewController *editController = segue.destinationViewController;
        editController.theEvent = theEvent;
        // set EventListViewController as the delegate for the EditViewController
        editController.delegate = self;
    }
}

The editController view has a property defined to hold the Event object as so:
@property (strong, nonatomic) Event *theEvent;

Everything works throughout the app by passing around this object between views (there are multiple views that get created/destroyed from the editController and they also have the same theEvent property defined).
When I want to save the data, I've built a protocol to send a "save" message up the view chain using delegation (maybe this isn't the best way) and the original tableViewController does the save (since it has the original managed object context).
The major problem in all this though, is that I'm finding that when I have lots of Event objects in the database, switching views slows right down!  The more objects, the slower it gets!  I'm not sure why since I'm just passing around a pointer to the one Event object selected in the original tableView.
Could it be because I've defined theEvent as "strong" in the detail view controller(s)?  Should each view controller only have a weak reference?
Further, I've read about passing around the managed object context instead but even so, I'm not sure how to pass around a reference to the correct object other than how I'm doing it already.  How would the various edit view controllers (or even the single editController you see in the code above) know which object is being edited?
Any ideas or suggestions would be helpful.  Thanks!
EDIT:
This is code from the controller that contains the starting tableView:
   - (NSFetchedResultsController *)fetchedResultsController {
            if (_fetchedResultsController != nil) {
                return _fetchedResultsController;
            }

            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:_managedObjectContext];
            [fetchRequest setEntity:entity];

            NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
            [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

            [fetchRequest setFetchBatchSize:20];

            NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
            self.fetchedResultsController = theFetchedResultsController;
            _fetchedResultsController.delegate = self;

            return _fetchedResultsController;
        }

    - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
        // The fetch controller is about to start sending change notifications, so prepare the table view for updates.
        [self.eventListTable beginUpdates];
    }

    - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
        UITableView *tableView = self.eventListTable;
        switch(type) {
            case NSFetchedResultsChangeInsert:
                [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                break;
            case NSFetchedResultsChangeDelete:
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                break;
            case NSFetchedResultsChangeUpdate:
                [self configureCell:(EventCell *)[_eventListTable cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
                break;
            case NSFetchedResultsChangeMove:
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                break;
        }
    }

    - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
        switch(type) {
            case NSFetchedResultsChangeInsert:
                [self.eventListTable insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
                break;
            case NSFetchedResultsChangeDelete:
                [self.eventListTable deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
                break;
        }
    }

        - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
            // The fetch controller has sent all current change notifications, so tell the table view to process all updates.
            [self.eventListTable endUpdates];

            // if a new event has just been added by the addEvent method then select it and segue to the Edit Details view
            if (_justAddedNewEvent == YES) {
                NSIndexPath *indexPath = [controller indexPathForObject:_newlyAddedEvent];
                _justAddedNewEvent = NO;
                // now open details view of newly added object
                [self.eventListTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
                [self performSegueWithIdentifier:@"EditEventSegue" sender:self];
            }
        }


text:
Q: Y axis ticks display format in Google line chart I need Y axis ticks format in multiples of 500's
What I have is
http://i60.tinypic.com/104500w.jpg
What I need is
http://i58.tinypic.com/bfhod5.jpg

A: Solved.
I added the below property to the graph:
vAxis:{ticks: [0, 500, 1000, 1500, 2000, 2500, 3000, 3500]}


text: Q: Where does brew get all its binaries from? Is there some centralized place were people just put their binaries and brew just queries that? Or do people submit their binaries to Brew? If so how do I go about submitting my binaries to brew?


text:
Q: Why do all of these methods of accessing an array work? It seems to me that some of these should fail, but they all output what they are supposed to:
$, = "\n";
%test = (
    "one" => ["one_0", "one_1"],
    "two" => ["two_0", "two_1"]
);

print @{$test{"one"}}[0],
      @{$test{"one"}}->[0],
      $test{"two"}->[0],
      $test{"one"}[1];

Why is this?

A: Your first example is different than the others. It is an array slice -- but in disguise since you are only asking for one item.
@{$test{"one"}}[0];

@{$test{"one"}}[1, 0];  # Another slice example.

Your other examples are alternative ways of de-referencing items within a multi-level data structure. However, the use of an array for de-referencing is deprecated (see perldiag).
@{$test{"one"}}->[0]; # Deprecated. Turn on 'use warnings'.
$test{"two"}->[0];    # Valid.
$test{"one"}[1];      # Valid but easier to type.

Regarding the last example, two subscripts sitting next to each other have an implied -> between them. See, for example, the discussion of the Arrow Rule in perlreftut.


text:
Q: Set decimal(16, 3) for a column in Code First Approach in EF4.3 How can I do this :
private decimal _SnachCount;
[Required]
[DataType("decimal(16 ,3)")]
public decimal SnachCount
{
    get { return _SnachCount; }
    set { _SnachCount = value; }
}

private decimal _MinimumStock;
[Required]
[DataType("decimal(16 ,3)")]
public decimal MinimumStock
{
    get { return _MinimumStock; }
    set { _MinimumStock = value; }
}

private decimal _MaximumStock;
[Required]
[DataType("decimal(16 ,3)")]
public decimal MaximumStock
{
    get { return _MaximumStock; }
    set { _MaximumStock = value; }
}

After generating the database by this part of my model , these three columns type are decimal(18,2),why?
what is this code error? how can i do that ?

A: The DataType Attribute is a Validation Attribute. You need to do that using the ModelBuilder.
public class MyContext : DbContext
{
    public DbSet<MyClass> MyClass;
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyClass>().Property(x => x.SnachCount).HasPrecision(16, 3);
        modelBuilder.Entity<MyClass>().Property(x => x.MinimumStock).HasPrecision(16, 3);
        modelBuilder.Entity<MyClass>().Property(x => x.MaximumStock).HasPrecision(16, 3);
    }
}

A: You can modify all decimal propreties in database. In your DBContext in method OnModelCreating add line:
modelBuilder.Properties<decimal>().Configure(c => c.HasPrecision(18, 3));

A: This is copied from the answer I posted to the same question over here; https://stackoverflow.com/a/15386883/1186032.

I had a nice time creating an Custom Attribute for this:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
    public DecimalPrecisionAttribute(byte precision, byte scale)
    {
        Precision = precision;
        Scale = scale;

    }

    public byte Precision { get; set; }
    public byte Scale { get; set; }

}

using it like this
[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }

and the magic happens at model creation with some reflection
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                   where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
                                   select t)
     {
         foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
                p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
         {

             var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
             ParameterExpression param = ParameterExpression.Parameter(classType, "c");
             Expression property = Expression.Property(param, propAttr.prop.Name);
             LambdaExpression lambdaExpression = Expression.Lambda(property, true,
                                                                      new ParameterExpression[]
                                                                          {param});
             DecimalPropertyConfiguration decimalConfig;
             if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }
             else
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }

             decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
        }
    }
}

the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)
the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data
after that i have to call
modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECITION,SCALE);

so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable
then i build the "c => c.PROPERTY_NAME" lambda expression
After that, if the decimal is nullable i call the
Property(Expression<Func<TStructuralType, decimal?>> propertyExpression)

method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)
and if it's not nullable i call the
Property(Expression<Func<TStructuralType, decimal>> propertyExpression)

method.
Having the DecimalPropertyConfiguration i call the HasPrecision method.

A: You can also set the precision of decimals using the code-first model mapping approach like this:
public class MyEntityMapping : EntityTypeConfiguration<MyEntity>
{
    public MyEntityMapping()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).IsRequired();
        // .HasPrecision(precision, scale)
        // 'precision' = total number of digits stored,
        // regardless of where the decimal point falls
        // 'scale' = number of decimal places stored
        Property(x => x.DecimalItem).IsRequired().HasPrecision(16, 6);
    }
}

A: So, what I got working for me is this:
public class RestaurantItemEntity : BaseEntity
{
    [Column(TypeName = "VARCHAR(128)")]
    [StringLength(128)]
    [Required]
    public string Name { get; set; }

    [Column(TypeName = "VARCHAR(1024)")]
    [StringLength(1024)]
    public string Description { get; set; }

    [Column(TypeName = "decimal(16,2)")]
    [Required]
    public decimal Price { get; set; }

    [Required]
    public RestaurantEntity Restaurant { get; set; }
}

This is EF Code first for .NET core.


text:
Q: String to Date error In PowerShell, I am trying to convert a string that I selected from a text file to a date so I can add or substract days, hours and so on from it. The problem is that when I try to convert the resulted string from the text file, I receive the following error:
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

At line:15 char:5

+     [datetime]::ParseExact($SC4,'HH:mm:ss', $null)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

The Code:
Get-Content results2.txt | ForEach-Object{
$splitUp = $_ -split " "
$SC=$splitUp[0] -split " "
$SC2=$splitUp[1] -split " "
$SC3=$SC + $SC2
Write-Host -NoNewline $SC3 | Write-Output $SC4
Write-Host $SC4
$r=[datetime]::ParseExact($SC4,'dd/MM/yyyy HH:mm:ss', $null)
echo $r

}
The file result2.txt, from which I read, contains the following:
09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:55:51,312 [342]
09/07/2017 16:35:56 - 2017-09-07 14:56:54,918 [305]
09/07/2017 16:35:56 - 2017-09-07 14:58:36,133 [113]

A: The problem is because $SC4 is an empty variable. Your attempt to populate it via a pipe of output from Write-Host doesn't work (because Write-Host writes to the console and not to the pipeline).
That whole part over complicates things and can just be removed. This works fine in my testing:
Get-Content result2.txt | ForEach-Object {
    $splitUp = $_ -split " "
    $SC=$splitUp[0] -split " "
    $SC2=$splitUp[1] -split " "
    $SC3 = $SC + $SC2
    $r=[datetime]::ParseExact($SC3,'dd/MM/yyyy HH:mm:ss', $null)
    echo $r
}

Here's a shorter solution that uses regex to match the first date in the file:
Get-Content result2.txt | ForEach-Object {
    $Check = $_ -Match '^\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}(?= .*$)'
    If ($Check) { $R=[datetime]::ParseExact($Matches[0],'dd/MM/yyyy HH:mm:ss', $null) }
    Echo $R
}

A: Other method:
Get-Content "c:\temp\test.txt" | ForEach-Object {
    [datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)
}

#short version
gc "c:\temp\test.txt" |%{[datetime]::ParseExact(($_ -split " - ")[0],'dd/MM/yyyy HH:mm:ss', $null)}


text:
Q: OpenCV C++ Mat object dealloaction error The code runs but reports an error when returning from main().  I assume it has to do with the Mat object deallocation which is supposed to be automatic.  While working with openCV IplImage* I never had this problem.
Here is full code:
int main(){
Mat img_1 = imread("D:/cigare.jpg", CV_LOAD_IMAGE_GRAYSCALE);
Mat img_2 = imread("D:/cigare1.jpg", CV_LOAD_IMAGE_GRAYSCALE);

if (!img_1.data || !img_2.data)
{
    printf(" --(!) Error reading images \n"); return -1;
}

//-- Step 1: Detect the keypoints using SURF Detector
int minHessian = 400;

SurfFeatureDetector detector(minHessian);

std::vector<KeyPoint> keypoints_1, keypoints_2;

detector.detect(img_1, keypoints_1);
detector.detect(img_2, keypoints_2);

//-- Step 2: Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;

Mat descriptors_1, descriptors_2;

extractor.compute(img_1, keypoints_1, descriptors_1);
extractor.compute(img_2, keypoints_2, descriptors_2);

//-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_1, descriptors_2, matches);

double max_dist = 0; double min_dist = 100;

//-- Quick calculation of max and min distances between keypoints
for (int i = 0; i < descriptors_1.rows; i++)
{
    double dist = matches[i].distance;
    if (dist < min_dist) min_dist = dist;
    if (dist > max_dist) max_dist = dist;
}

printf("-- Max dist : %f \n", max_dist);
printf("-- Min dist : %f \n", min_dist);

//-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist,
//-- or a small arbitary value ( 0.02 ) in the event that min_dist is very
//-- small)
//-- PS.- radiusMatch can also be used here.
std::vector< DMatch > good_matches;

for (int i = 0; i < descriptors_1.rows; i++)
{
    if (matches[i].distance <= max(2 * min_dist, 0.02))
    {
        good_matches.push_back(matches[i]);
    }
}

//-- Draw only "good" matches
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
    good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
    vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);

//-- Show detected matches
cv::namedWindow("Good Matches",0);
imshow("Good Matches", img_matches);

for (int i = 0; i < (int)good_matches.size(); i++)
{
    printf("-- Good Match [%d] Keypoint 1: %d  -- Keypoint 2: %d  \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx);
}
waitKey(0);
return 0;
}

This is the error http://prntscr.com/c9cup8
Can somebody tell me what I'm doing wrong?


text:
Q: Batch insert PostgreSQL/Go I need to save multiple tags in the single query:
valueStrings := make([]string, 0, len(tags))
valueArgs := make([]interface{}, 0, len(tags) * 3)
for _, tag := range tags {
    valueStrings = append(valueStrings, "(?, ?, ?)")
    valueArgs = append(valueArgs, tag)
    valueArgs = append(valueArgs, "NOW()")
    valueArgs = append(valueArgs, "NOW()")
}
stmt := fmt.Sprintf("INSERT INTO tags (name, created_at, updated_at) VALUES %s ON CONFLICT DO NOTHING;", strings.Join(valueStrings, ", "))
c.DB.Exec(stmt, valueArgs...)

Checking PostgreSQL logs:
ERROR:  syntax error at or near "," at character 58
STATEMENT:  INSERT INTO tags (name, created_at, updated_at) VALUES (?, ?, ?), (?, ?, ?) ON CONFLICT DO NOTHING;

I believe that Exec does not replace question marks with corresponding values.

Golang how do I batch sql statements with package database.sql


text:
Q: What are benefit to use library module in Android Studio? I have read some sample codes, I find that many project use library module structure, you can see Image A.
Could you tell me the benefit to use library module in Android Studio ?
What code do I need to place it in library ?
And More, both app and lib module use the same namesapce in the sample code, I don't know if it's suitable, could you tell me ?
Image A

A: Library module gives you two options to create library Android and Java.

*

*Android library module->  Android library compiles into an Android Archive (AAR) file that you can use as a dependency for an Android app module . It allows you to add android specific components like resources and manifest file, which allows you to bundle in shared resources like layouts and drawables in addition to Java classes and methods.

*Java Library -> It builds a JAR file. JAR file is useful for many projects especially when you want to share code with other platforms. But it does not allow you to include Android resources or manifest files, which is very useful for code reuse in Android projects. So when you do not need any android specific resources in library you should create a java library.
Library modules are beneficial for projects :-

*

*When you're building multiple apps that use some of the same components, such as activities, services, or UI layouts.

*When you're building an app that exists in multiple APK variations, such as a free and paid version and you need the same core components in both.

Quoted from developer.android.com
Other than that same namespace is not problematic unless you have same package name inside App and libraries . You should use a different namespace for libraries.
PS-> If you are familiar with Clean Architecture, The idea behind most of the software design pattern is  Separation of concern . In Clean architecture a project is divided into multiple modules. When you implement clean architecture in android you'll see that some of the module you can create as Java library like domain module. Creating module is really useful to follow re-usability and SOLID principles and Inversion of control.

A: Firstly, don't look into the package name declared in the java directory. Look into the manifest file. You can see that these modules have different package name. It means that all modules in a project must have different package name.

Regarding to your question, what are the benefit of naming library module as lib?
There's no benefit at all. Some people are comfort with lib name, so they can differentiate the demo and library module easily. However, using lib as library's module name requires you to add additional configuration in the lib/build.gradle, i.e. archiveBaseName. This Gradle attribute will rename the JAR/AAR from lib.aar to work-runtime.aar, so people can use it like this:
implementation "androidx.work:work-runtime:$work_version"

If archiveBaseName is not set, people will use it like this:
implementation "androidx.work:lib:$work_version"

In real case, let's take my open source library as the example, MaterialPreference. I used to use lib name on this project, but now I think lib is not a good module name. Using materialpreference as module name will remove additional configuration archiveBaseName. So I feel it is more simple.


text:
Q: Issue dropping rows in AWS Glue with null values Currently having an issue with an AWS Glue Job reading an S3 collection and writing it to AWS Redshift where we have a column with null values.
The job should be fairly simple and most of the code is auto-generated by the Glue interface but as we have not null columns in Redshift that are sometimes null in our data set we are unable to get the job to complete.
A condensed version of the code is shown below, code is in Python and environment is PySpark.
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "db_1", table_name = "table_1", transformation_ctx = "datasource0")

resolvedDDF = datasource0.resolveChoice(specs = [
  ('price_current','cast:double'),
  ('price_discount','cast:double'),
])

applymapping = ApplyMapping.apply(frame = resolvedDDF, mappings = [
  ("id", "string", "id", "string"),
  ("status", "string", "status", "string"),
  ("price_current", "double", "price_current", "double"),
  ("price_discount", "double", "price_discount", "double"),
  ("created_at", "string", "created_at", "string"),
  ("updated_at", "string", "updated_at", "string"),
], transformation_ctx = "applymapping")

droppedDF = applymapping.toDF().dropna(subset=('created_at', 'price_current'))

newDynamicDF = DynamicFrame.fromDF(droppedDF, glueContext, "newframe")

dropnullfields = DropNullFields.apply(frame = newDynamicDF, transformation_ctx = "dropnullfields")

datasink = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dropnullfields, catalog_connection = "RedshiftDataStaging", connection_options = {"dbtable": "dbtable_1", "database": "database_1"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink")

We have a not null constraint on the price_current and created_at table in Redshift and due to some early errors in our system some records have reached the S3 bucket without the required data. We want to just drop these rows as they make up a very small percentage of the overall data to process.
Despite the dropna code we still get the following error from Redshift.
Error (code 1213) while loading data into Redshift: "Missing data for not-null field"
Table name: "PUBLIC".table_1
Column name: created_at
Column type: timestampt(0)
Raw field value: @NULL@

A: You can pass default values if you don't wish to remove them
df= dropnullfields.toDF()

df = df.na.fill({'price_current': 0.0, 'created_at': ' '})

dyf = DynamicFrame.fromDF(df,'glue_context_1')

datasink = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dyf, catalog_connection = "RedshiftDataStaging", connection_options = {"dbtable": "dbtable_1", "database": "database_1"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink")

If you wish to remove , use following code in place of df.na.fill
df = df.na.drop(subset=["price_current", "created_at"])


text:
Q: Using Namespaces in Other Projects As the screenshot demonstrates, I have a project SampleApp that uses the namespaces EDAM and Thrift.  I want to replicate the functionalities of SampleApp to another project.
Do I have to include the two projects (EDAM and Thrift) in my other project?  Can I just copy the folders instead of including the actual project files?  Can I just convert them to some sort of DLL or something?

A: You definitely should add references to the EDAM and Thrift projects from the SampleApp project.
To do so, follow these steps:

*

*Right click the 'References' folder in the SampleApp project.

*Select 'Add Reference...'

*On the popup, go to the 'Solution' tab.

*Select the EDAM and Thrift projects.
Under no circumstances should you just copy the files.

A: Don't copy the folders, just add references to the projects. Even if the projects are class libraries you don't want to copy the DLLs, instead you should add references, just in case your DLLs are updated:
How to: Add or Remove References in Visual Studio

A: If the "other" project is in the same Solution, you should be able to reference EDAM, Thrift and even SampleApp from that project much in the same way you set the references up for SampleApp.
If this "other" project will be in a new solution...I'd have to do a little research and testing.

A: Visual Studio project references are equivalent to referencing an assembly directly, but it has a great advantage: when you build a project, Visual Studio take cares of building its dependent projects too.
In addition, Visual Studio will prevent circular references.
There're many other pros, but it's a good summary.
Copy-pasting the code files isn't importing a namespace: this is duplicating code! And referencing the assemblies directly is a waste of time and features!


text:
Q: Custom DescribeFeatureType response in Geoserver? I'm using Geoserver in my web application. I need custom DescribeFeatureType response. What this mean?
layer_a is a layer in Geoserver. It have Feature Type Details as follow:

DiscribeFeatureType request for this layer, return a response as follow:
<?xml version="1.0" encoding="UTF-8"?>
  <xsd:schema xmlns:gml="http://www.opengis.net/gml"
              xmlns:opengeo="http://opengeo.org"
              xmlns:xsd="http://www.w3.org/2001/XMLSchema"
              elementFormDefault="qualified"
              targetNamespace="http://opengeo.org">
  <xsd:import namespace="http://www.opengis.net/gml"
              schemaLocation="http://localhost:8080/geoserver/schemas/gml/3.1.1/base/gml.xsd"/>

  <xsd:complexType name="WorldCountriesType">
    <xsd:complexContent>
      <xsd:extension base="gml:AbstractFeatureType">
        <xsd:sequence>
          <xsd:element maxOccurs="1" minOccurs="0" name="the_geom" nillable="true" type="gml:MultiSurfacePropertyType"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="ObjectID" nillable="true" type="xsd:int"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="FIPS_CNTRY" nillable="true" type="xsd:string"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="SQKM" nillable="true" type="xsd:double"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="SQMI" nillable="true" type="xsd:double"/>
          <xsd:element maxOccurs="1" minOccurs="0" name="COLORMAP" nillable="true" type="xsd:int"/>
        </xsd:sequence>
      </xsd:extension>
    </xsd:complexContent>
  </xsd:complexType>
  <xsd:element name="WorldCountries" substitutionGroup="gml:_Feature" type="opengeo:WorldCountriesType"/>
</xsd:schema>

I want to get more description for some fields. For example, for SQKM row, I want to get some extra description such as: minValue, maxValue and etc.
Is it possible? If yes, HOW?
A suggestion: We can put our data in column comment of table and then define a db datastore in geoserver. So we can response comment of table with describeFeatureType?

A: There is a limited possibility to adjust the schema by using the schema mapping as described in http://docs.geoserver.org/2.7.1/user/services/wfs/schemamapping.html. However, the following edit did not change anything in DescribeFeatureType and maxLength does not appear in the schema of of the topp:states layer even the edited schema.xsd was accepted and I verified by removing some attributes from the schema that the file was really used.
<xsd:element maxOccurs="1" minOccurs="0" name="STATE_NAME" nillable="true" type="xsd:string" maxLength="30"/>

There is also this open issue which suggests that what you want to do is not doable at the moment https://osgeo-org.atlassian.net/browse/GEOS-5336.
However, the application schema extension is flexible and it might work for you but it is complex http://docs.geoserver.org/stable/en/user/data/app-schema/index.html.


text:
Q: How to convert single zip name using perl? For example folder contains 10 XML File. Convert the folder to Single Zip file with that folder name
use strict;
use warnings;

use IO::Compress::Zip qw(zip $ZipError) ;

my $file = $ENV{"HOME"}."C:/zip";

my $s = zip [ $file, $file2 ] => $ENV{"HOME"}."C:/zip/new_.zip" , zip64 => 1
    or die "zip failed: $ZipError \n";

Update: Suggested code:
use strict;
use warnings;

use IO::Compress::Zip qw(zip $ZipError) ;

my $files="C:/zip";

my @file = "<$files/*.xml>";
zip \@file => 'output.zip'
  or die "zip failed: $ZipError\n";

Update: Suggested code:
use strict;
use warnings;

use IO::Compress::Zip qw(zip $ZipError) ;
my $dir="C:/zip";

my @files = <$dir/*.xml>;

print @files;

zip \@files => 'output.zip'
    or die "zip failed: $ZipError\n";

A: The documentation for the module that you are using seems to have some examples which are very close to what you are trying to do.
my @files = <*.txt>;
zip \@files => 'output.zip'
    or die "zip failed: $ZipError\n";

Or
zip [ <*.txt> ] => 'output.zip'
    or die "zip failed: $ZipError\n";

You just need to edit that to include the directory name in a couple of places.


text:
Q: Making sure a checkbox stays checked when a text input is not empty? I'm trying to keep a checkbox checked whenever a given text input is not empty.
At the moment, the text input box isn't responding to the event I added to it through jquery, and I'm wondering if there's something off in my code. (still quite new to jquery)
Here is my text input and checkbox:
<input type="text" id="textInput"/>

<input type="checkbox" id="checkBox" checked="checked" />

And here is my jquery code:
$('#textInput').on('click', function(){
    //if text input is not empty
    if($('#textInput').val() !== ''){
        //if checkbox not checked, check it
        if($('checkBox').checked !== 'checked'){
            $('checkBox').checked = 'checked';
        }
    }
})

A: You can affect the checkbox checked state via .prop() - and in this case we can just set it to the truthy $('#textInput').val() !== ''.

$('#textInput').on('blur', function() {
  $('#checkBox').prop('checked', $('#textInput').val().trim() !== '');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="textInput" />
<input type="checkbox" id="checkBox" checked="checked" />

A: You should call function to check on page load(ready), and every text field change. I didn't test my solution, but it should be fine
const textInput = $('#textInput');
const checkbox = $('#checkBox');

function setCheckboxState() {
  const text = textInput.val();
  if (text) {
    checkbox.prop('checked', true);
  }
}

setCheckboxState();
textInput.on('focus change keyup', setCheckboxState);


text:
Q: Use Values- and Range-Attribute in NUnit TestFixture constructor I have multiple test methods which should test all possible combinations of multiple parameters. I can use the NUnit ValueAttribute or RangeAttribute on methods like this:
[TestFixture]
public class MyExampleTests
{
    [Test]
    public void TestedEntity_GivenParemeter_Passes(
        [Values(1, 2)] int inputA,
        [Range(1, 4)] int inputB)
    {
        if (inputA > 0 && inputB > 0)
            Assert.Pass();
    }
}

However, in my real-world case there are 4 parameters, a dozen methods and more values, so it becomes tedious to write out all the values for every method and if I want to make a change, I might make a mistake somewhere.
How can I move the test generation for all value combinations away from the individual methods and into the TestFixture body? The following doesn't work, but it would be what I want:
[TestFixture]
public class MyExampleTests2
{
    readonly int inputA;
    readonly int inputB;

    public MyExampleTests2(
        [Values(1, 2)] int inputA,
        [Range(1, 4)] int inputB)
    {
        this.inputA = inputA;
        this.inputB = inputB;
    }

    [Test]
    public void TestedEntity_GivenParemeter_Passes()
    {
        if (this.inputA > 0 && this.inputB > 0)
            Assert.Pass();
    }
}

I already know that the TestFixtureAttribute can take parameters, but they don't work the way I want. I can only give each parameter a hardcoded value. Instead I want to use ranges and also let NUnit create a test for every combination. Also, I would like the solution to work in NUnit 2.6.4.

A: You can use ValuesSource:
[Test]
public void TestedEntity_GivenParemeter_Passes(
    [ValueSource(nameof(FirstSource))] int inputA,
    [ValueSource(nameof(SecondSource))] int inputB)
{
    if (inputA > 0 && inputB > 0)
        Assert.Pass();
}

private static readonly int[] FirstSource = { 1, 2 };
private static readonly IEnumerable<int> SecondSource = Enumerable.Range(1, 4);

If you want to avoid the repetition of parameter declarations, you could create a single type containing properties for InputA and InputB, and a source which returned a sequence of that type.


text:
Q: Unable to play .m3u8 streaming link using cast sdk I have implemented Google Cast SDK successfully and the main problem that I am facing is .m3u8 streaming link is not playing on Chromecast. CORS is also enabled on the server side as well.
I have tried test streams of .mp4 as http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4 and it's working fine and for .m3u8 i am using the test streaming link as https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/hls/DesigningForGoogleCast.m3u8 but this does not work.
Below is how I am building MediaInfo:
MediaMetadata movieMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
        movieMetadata.putString(MediaMetadata.KEY_TITLE, mBinding.getItem().getName());
        movieMetadata.putString(MediaMetadata.KEY_SUBTITLE, mBinding.getItem().getStreamingLink());
        movieMetadata.addImage(new WebImage(Uri.parse(mBinding.getItem().getImage())));

        return new MediaInfo.Builder(streamUrl)
                .setStreamType(MediaInfo.STREAM_TYPE_LIVE)
                .setContentType("videos/mp4")
                .setMetadata(movieMetadata)
                .build();

What might be wrong here?


text:
Q: Having trouble executing a stored procedure When the following VBA code executes it passes the following string to SQL with the world "default" instead of the integer that is needed.  As you can see in the code below, I've even made sure that what is being passed through is an integer by declaring it as such.
When I run profiler here is what is coming across:
exec dbo.Dispensing_Days '9999',default

VBA code:
Sub ADO_DispensingDays()
    Dim DayValue As Integer
    DayValue = Forms("PatientRecordTabbedF").DaysDispensed.Value

    Call Module4.ADO      ' Opens the oConn SQL connection
    Dim cmdObjCmd As New ADODB.Command
        With cmdObjCmd
            .ActiveConnection = oConn
            .CommandType = adCmdStoredProc
            .CommandTimeout = 15
            .CommandText = "dbo.Dispensing_Days"
            .Parameters.Append .CreateParameter("@PatientID", adVarChar, adParamInput, 16, Forms("PatientRecordTabbedF").PatientID.Value)
            .Parameters.Append .CreateParameter("@Days", adInteger, , DayValue)
            .Execute
        End With
        Set cmdObjCmd = Nothing
    Call Module4.ADO_Close    ' Closes the oConn SQL connection
End Sub

A: In this line of code...
.Parameters.Append .CreateParameter("@Days", adInteger, , DayValue)
I missed the adParamInput value.  The code should look like this...
.Parameters.Append .CreateParameter("@Days", adInteger, adParamInput, , DayValue)
I spent way to many hours trying to figure this out.


text:
Q: Send JSON data with jquery ajax request and receive response from Controller in Spring I need some help, I want to make a jquery ajax request to obtain some data and then to save them in controller. I obtain the fields correctly but when I push the button nothing happens.
    Failed to load resource: the server responded with a status of 405 ()
add:1 Uncaught SyntaxError: Unexpected end of JSON input
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.error (add:190)
    at i (jquery.min.js:2)
    at Object.fireWith [as rejectWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

    <!DOCTYPE html>

Adauga masini :

                        <legend>
                            Model <input type="text"
                                                                                class="form-control"
                                                                                id="model"
                                                                                placeholder="Model"
                                                                                required>
                        </legend>

                        <legend>
                            An fabricatie :
                        </legend>
                        <select name="year" id="year">
                        </select>

                        <legend>
                            Combustibil :

                        </legend>
                        <input type="radio" name="fuel" value="benzina +  gpl"
                               required> benzina+gpl

                        <input type="radio" name="fuel" value="motorina + gpl"
                               required> motorina+gpl

                        <input type="radio" name="fuel" value="motorina"
                               required> motorina

                        <input type="radio" name="fuel" value="benzina"
                               required> benzina

                        <legend>
                            Numar locuri :
                        </legend>
                        <select name="seats" id="seats">
                            <option value="two">2</option>
                            <option value="four">4</option>
                            <option value="six">6</option>
                            <option value="eight">8</option>
                        </select>

                        <legend>
                            Culoare : <input type="text"
                                                                                class="form-control"
                                                                                id="color"
                                                                                placeholder="Color"
                                                                                required>

                        </legend>

                        <legend>
                            Cutie viteze :

                        </legend>
                        <input type="radio" name="gear"
                               value="automat" required> automata

                        <input type="radio" name="gear"
                               value="manual" required> manuala

                        <legend>
                            Pret :</legend>
                        <input type="text"
                               class="form-control"
                               id="price"
                               placeholder="Price"
                               required>

                        <select id="coin">
                            <option value="EUR">EUR</option>
                            <option value="USD">USD</option>
                            <option value="LEI">LEI</option>
                        </select>

                    <button onclick ="addCar()" class="btn btn-primary" >Add car</button>

                    Back

The controller:
@PostMapping(value = "/cars/add")
public @ResponseBody String addCars(Cars car,
                                    @RequestParam("model") String model,
                                    @RequestParam("year") int year,
                                    @RequestParam("fuel") String fuel,
                                    @RequestParam("seats") int seats,
                                    @RequestParam("color") String color,
                                    @RequestParam("gear") String gear,
                                    @RequestParam("price") int price,
                                    @RequestParam("coin") String coin) {
    System.out.println(model);
    System.out.println(year);
    car.setModel(model);
    car.setYear(year);
    car.setFuel(fuel);
    car.setSeats(seats);
    car.setColor(color);
    car.setGearBox(gear);
    car.setPrice(price);
    car.setCoin(coin);

    return "redirect:/cars/list";
}``

I want to save those car details in database and to redirect to a page where I have a list with those cars


text:
Q: Error after upload the file I have two files, upload.php:
<?php

$validExt=array("txt","xml");
$ext=end(explode(".", $_FILES['file']['name']));
if(($_FILES['file']['type']=='text/plain') ||($_FILES['file']['type']=='text/xml')&&($_FILES['file']['size']<1000)&& in_array($ext,$validExt)){
    if($_FILES['file']['error']>0){
        echo "ERROR!";
    }else{
        echo "Name: ".$_FILES['file']['name']."
";
        echo "Type: ".$_FILES['file']['type']."
";
        echo "Size: ".$_FILES['file']['size']."
";
        echo "Tmp name: ".$_FILES['file']['tmp_name']."
";
    }
}else{
    echo "wrong file!";

}

?>

And the second one index.html:
<!DOCTYPE html>

    <title></title>
    <meta charset="utf-8" />

    <form enctype="multipart/form-data" action="upload.php" method="post">
        <input name="file" type="file"/>
        <input type="submit" value="Wyslij" />
    </form>

When i try to upload the file i get an error and good answer.
Error:
Strict standards: Only variables should be passed by reference in D:\wamp\www\php_z\upload\upload.php on line 4
I'm a beginner in php but can someone explain me what to do to solve this problem wth errror?

A: The function end() takes an array that can be passed by reference since it modifies the internal pointer of the array. What you've passed it is the return of explode(). Since the return of explode isn't necessarily a variable, it can't be passed by reference. What you should do is set a variable containing the return of explode(...) and then pass that to end().
$validExt = array("txt", "xml");
$ext = explode(".", $_FILES['file']['name']);
$ext = end($ext);


text:
Q: How to limited copy file using Powershell? I want to check .jpg file in the 2nd folder. 2nd folder has some subfolder. if .jpg exist in the subfolder of 2nd folder, I will copy a file from 1st folder to subfolder of 2nd folder based on the base name. I can do this part refer to this answer
How to copy file based on matching file name using PowerShell?
But I want to do limitation while I copy a file from 1st folder. I will NOT copy the file, if I already copy the same file from 1st folder to 2nd folder 3 times.
This is the code from the reference.
$Job_Path = "D:\Initial"
$JobError = "D:\Process"

Get-ChildItem -Path "$OpJob_Path\*\*.jpg" | ForEach-Object {
    $basename = $_.BaseName.Substring(15)
    $job = "$Job_Path\${basename}.png"
    if (Test-Path $job) {
        $timestamp = Get-Date -Format 'yyyyMMddhhmmss'
        $dst = Join-Path $_.DirectoryName "${timestamp}_${basename}.gif"
        Copy-Item $job $dst -Force
    }

Anyone can help me to solve this problem please. Thank you.
Updated
$Job_Path = "D:\Initial"
$JobError = "D:\Process"

Get-ChildItem -Path "$OpJob_Path\*\*.jpg" | ForEach-Object {
    $basename = $_.BaseName.Substring(15)
    $job = "$Job_Path\${basename}.png"
    if (Test-Path $job) {
        $timestamp = Get-Date -Format 'yyyyMMddhhmmss'
        $dst = Join-Path $_.DirectoryName "${timestamp}_${basename}.gif"
        $Get = (Get-ChildItem -Name "$OpJob_Path\*\*$basename.jpg*" | Measure-Object).Count
        $Get
        if ($Get -eq "3") {
            Write-Host "Continue Other Process"
            NEXT_PROCESS
        } else {
            Write-Host "Less than 3"
        }
        Copy-Item $job $dst -Force
    }

A: $Get is not a hashtable, and it's also not keeping track of what's been copied already. You need to define the hashtable outside the loop
$copy_count = @{}
Get-ChildItem -Path "$OpJob_Path\*\*.jpg" | ForEach-Object {
    ...
}

and then update it whenever you copy a file
if ($copy_count[$_.Name] -le 3) {
    Copy-Item ...
    $copy_count[$_.Name]++
} else {
    ...
}


text:
Q: Powershell: Passing parameters to function So I'm doing a bit of 'House Keepying' on my script and I've found one area than can be reduced/tidied.
Take this GUI I've created:

Both menu bar add_click events to Restart HostnameA and HostnameB call seperate functions even though the code in both of the functions is pratically the same, the only difference is this variable for the hostname (see below).
Code for button events.
$Restart_current_machine.Add_Click(
{
restart_current_machines
})

$Restart_target_machine.Add_Click(
{
restart_target_machines
})

# Function Blocks

function restart_target_machines
{
restart-computer -computer $combobox1.text -force
}

function restart_current_machines
{
restart-computer -computer $combobox2.text -force
}

My question is this:
is there a way I can use Param() (or something like that) to get rid of function restart_current_machinesthereby only having one function to restart either of the machines?
Something like?
$Restart_current_machine.Add_Click(
{
param($input = combobox1.text)
$input | restart_current_machines
})

$Restart_target_machine.Add_Click(
{
param($input = combobox2.text)
$input | restart_current_machines
})

# Only needing one function

function restart_target_machines
{
restart-computer -computer $input -force
}

I know that is in all probability wrong, but just to give you a better idea of what I'm trying to do.

A: Create a generic function that defines a ComputerName parameter and pass that parameter to the underlying cmdlet:
function restart-machine ([string[]]$ComputerName)
{
    Restart-Computer -ComputerName $ComputerName -Force
}

The Rastart-Compter cmdlet ComputerName parameter accepts a collection of names so the parameter is defained as a string array.
Now, from anywhere in your code just call  restart-machine and pass the computer names to restart to the ComputerName parameter. To restart multiple machines, delimit each name with a comma (i.e  restart-machine -computerName $combobox1.text,$combobox2.text)
$Restart_target_machine.Add_Click(
{
   restart-machine -computerName $combobox1.text
})


text:
Q: How do astronomers describe location and navigation on Mars? In The Martian, the astronauts describe the incoming storm's movement in terms of bearings but surely the use of bearings would require a 'north'? I understand that Mars does not have a magnetic north and so I wonder how location and navigation are described?

A: "North" or "true North" on Earth usually refers to the direction of the point where the vector about which the Earth rotates emerges from the surface (the North Pole). If you look at a globe, it's where the sphere is attached to the stand on the top, and about which it spins.
Magnetic North moves around, and so isn't a good point of reference.  For navigating, when you use a compass to find magnetic, you than have to adjust based on your location to where "true North" is relative to magnetic North.
Mars also rotates about a fixed axis, so we just use the same system.  The weak magnetic field doesn't change things, though it would make a compass pretty useless.  But Matt Damon could presumably figure out North by just observing where the Sun rose.
ETA: Just dug up my copy of the book of "The Martian", and that's indeed the solution the author came up with for his protagonist.  He keeps track of where the moon (Phobos) rises and sets.


text:
Q: Total rows and divide by columns of all tables in a list object? I have a list object that contains several tables that contains a year column and then frequencies of particular words. Each table might be slightly different dimensions depending on range of years and words used.

Year
word1
word2
word3

2009
1
5
4

2010
2
3
5

I would like to create a table that sums every row (not including the year) and then divides the column value by the row sum so that it produces a table like this:

Year
word1
word2
word3

2009
0.1
0.5
0.4

2010
0.2
0.3
0.5

Is there a way to do this to a list object? TIA

A: Does this work:
cbind(df[1], t(apply(df[-1], 1, function(x) x/sum(x))))
  Year word1 word2 word3
1 2009   0.1   0.5   0.4
2 2010   0.2   0.3   0.5

If you have a list of such dataframes :
mylist <- list(df, df)
mylist
[[1]]
  Year word1 word2 word3
1 2009     1     5     4
2 2010     2     3     5

[[2]]
  Year word1 word2 word3
1 2009     1     5     4
2 2010     2     3     5

lapply(mylist, function(y) cbind(y[1], t(apply(y[-1], 1, function(x) x/sum(x)))))
[[1]]
  Year word1 word2 word3
1 2009   0.1   0.5   0.4
2 2010   0.2   0.3   0.5

[[2]]
  Year word1 word2 word3
1 2009   0.1   0.5   0.4
2 2010   0.2   0.3   0.5

Data used:
df
  Year word1 word2 word3
1 2009     1     5     4
2 2010     2     3     5

A: For a single data.frame, you can use the following function:
doit <- function(df) {
  cbind(df[1],sweep(df[-1],1,rowSums(df[-1]),"/"))
}

e.g.
df <- data.frame(Year = 1:3, Word1 = c(1,2,3), Word2 = c(3,2,1), Word3 = c(6,6,6))
doit(df)
#  Year Word1 Word2 Word3
#1    1   0.1   0.3   0.6
#2    2   0.2   0.2   0.6
#3    3   0.3   0.1   0.6

If you have multiple data.frames in a list, just wrap everything with lapply, like lapply(dfList,doit).


text:
Q: Docker aspnet 4.8 with active directory I have a challenge in my customer. he use legade apps in .Net framework 4, and suggest the idea of containerize the app. this is okay but the app need add to domain controller (AD). I try the use this command in powershell  but not work with this image mcr.microsoft.com/dotnet/framework/aspnet:4.8
and the conteiner is crash.
Do You have a experience in similar use case?


text:
Q: Swipe UIView off screen I'd like to be able to have a UIView (or, if necessary, UIViewController), which can be 'dragged'/flicked/swiped off screen - but locked to the vertical axis (so the view would go up or down off the screen to show the view below). This is sort of like the Facebook app's web views.
Could this perhaps be achieved with UIGravityBehavior?
Any ideas would be fantastic.

A: I have made something similar a while ago by using a UIPanGestureRecognizer. Here is how this would work:
float slidingMenuOffsetSum;

    - (void)handleSlidingMenuPan:(UIPanGestureRecognizer *)gestureRecognizer {
        CGPoint translation = [gestureRecognizer translationInView:_slidingMenuView];

        slidingMenuOffsetSum += translation.y;
        CGPoint newSlidingMenuCenter = CGPointMake(_slidingMenuView.center.x, _slidingMenuView.center.y + translation.y);

        if (_slidingMenuView.frame.origin.y <= 512 && _slidingMenuView.frame.origin.y >= 0) {
            _slidingMenuView.center = newSlidingMenuCenter;
        }

        [gestureRecognizer setTranslation:CGPointZero inView:_slidingMenuView];

        if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
            [UIView animateWithDuration:0.3
                animations:^{
                    [_slidingMenuView setUserInteractionEnabled:false];
                    if (slidingMenuOffsetSum > 0) {
                        if (slidingMenuOffsetSum > _slidingMenuView.frame.size.height / 4) {
                            [self setSlidingMenuHidden:false];
                        } else {
                            [self returnSlidingMenuToPosition];
                        }
                    } else {
                        if (slidingMenuOffsetSum < -_slidingMenuView.frame.size.height / 4) {
                            [self setSlidingMenuHidden:true];
                        } else {
                            [self returnSlidingMenuToPosition];
                        }
                    }
                }
                completion:^(BOOL finished) {
                    slidingMenuOffsetSum = 0;
                    [_slidingMenuView setUserInteractionEnabled:true];
                }];
        }
    }

You can adjust the values at which the sliding menu can move, and the thresholds for detecting if the view should go back to its original position, or eg. go off the screen.


text:
Q: SVG & XLink: Rendering of Circle is inconsistent? I have inline SVG showing a simple circle, which works as expected:
<svg width="200" height="200" viewBox="-25 -25 50 50" >
    <circle cx="0" cy="0" r="15" />
</svg>

This same code renders differently if I include the circle via XLink:
<svg width="200" height="200" viewBox="-25 -25 50 50">
    <use xlink:href="#circle"/>
</svg>

Here is an example: Fiddle
Why would these two examples render differently?
Thanks.

A: Simply add overflow="visible" to your symbol
refined answer based on Robert Longson's Comment:
Even better is to move your circle inside the symbol to a position so that it's inside the viewport.

<svg style="display:none;">
  <symbol id="circle">
    <circle cx="25" cy="25" r="15" />
  </symbol>
</svg>

<svg width="200" height="200" viewBox="-25 -25 50 50">
  <use x="-25" y="-25" xlink:href="#circle" />
</svg>

<svg width="200" height="200" viewBox="-25 -25 50 50">
  <circle cx="0" cy="0" r="15" />
</svg>