text:
Q: How to separate provider extender for custom control with ngModel to a separate file in Angular 2 I created custom control and connected it to ngModel. And now to reuse this code in a multiple components I want to separate it in a different file. Taking the following example -
import {Component, Provider, forwardRef} from "angular2/core";
import {ControlValueAccessor, NG_VALUE_ACCESSOR, CORE_DIRECTIVES} from "angular2/common";

const noop = () => {};

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => CustomInput),
    multi: true
  });

@Component({
  selector: 'custom-input',
  template: `
      <div class="form-group">
        <label><ng-content></ng-content>
          <input class="form-control"
                 [(ngModel)]="value"
                 (blur)="onTouched()">
        </label>
      </div>
  `,
  directives: [CORE_DIRECTIVES],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInput implements ControlValueAccessor{

    //The internal data model
    private _value: any = '';

    //Placeholders for the callbacks
    private _onTouchedCallback: (_:any) => void = noop;

    private _onChangeCallback: (_:any) => void = noop;

    //get accessor
    get value(): any { return this._value; };

    //set accessor including call the onchange callback
    set value(v: any) {
      if (v !== this._value) {
        this._value = v;
        this._onChangeCallback(v);
      }
    }

    //Set touched on blur
    onTouched(){
      this._onTouchedCallback();
    }

    //From ControlValueAccessor interface
    writeValue(value: any) {
      this._value = value;
    }

    //From ControlValueAccessor interface
    registerOnChange(fn: any) {
      this._onChangeCallback = fn;
    }

    //From ControlValueAccessor interface
    registerOnTouched(fn: any) {
      this._onTouchedCallback = fn;
    }

}

Example taken from here.
Then I'm separating this code -
const noop = () => {};

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => CustomInput),
    multi: true
  });

to external-file.ts:
import { forwardRef } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from 'angular2/common';

const fr = forwardRef;

export function createExtendedProvider(customInput) {
  return new Provider(
    NG_VALUE_ACCESSOR, {
      useExisting: fr(() => { console.log(`Inside method ${customInput}`); return customInput; }),
      multi: true
    });
}

I'm calling it in the component like this -
 const MD_INPUT_CONTROL_VALUE_ACCESSOR =  providerExtender.createExtendedProvider(CustomInput);
And when I try to run the app I'm getting the following error -
browser_adapter.js:77 Error: Uncaught (in promise): Token must be defined!
    at resolvePromise (zone.js:538)
    at eval (zone.js:515)
    at ZoneDelegate.invoke (zone.js:323)
    at Object.NgZoneImpl.inner.inner.fork.onInvoke (ng_zone_impl.js:45)
    at ZoneDelegate.invoke (zone.js:322)
    at Zone.run (zone.js:216)
    at eval (zone.js:571)
    at ZoneDelegate.invokeTask (zone.js:356)
    at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (ng_zone_impl.js:36)
    at ZoneDelegate.invokeTask (zone.js:355)
    at Zone.runTask (zone.js:256)
    at drainMicroTaskQueue (zone.js:474)
    at HTMLDocument.ZoneTask.invoke (zone.js:426)BrowserDomAdapter.logError @ browser_adapter.js:77ExceptionHandler.call @ exception_handler.js:60(anonymous function) @ application_ref.js:194schedulerFn @ async.js:123SafeSubscriber.__tryOrUnsub @ Subscriber.js:166SafeSubscriber.next @ Subscriber.js:115Subscriber._next @ Subscriber.js:74Subscriber.next @ Subscriber.js:51Subject._finalNext @ Subject.js:124Subject._next @ Subject.js:116Subject.next @ Subject.js:73EventEmitter.emit @ async.js:112NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.js:120NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.js:66ZoneDelegate.handleError @ zone.js:327Zone.runGuarded @ zone.js:233_loop_1 @ zone.js:487drainMicroTaskQueue @ zone.js:494ZoneTask.invoke @ zone.js:426
zone.js:461 Unhandled Promise rejection: Token must be defined! ; Zone: angular ; Task: Promise.then ; Value: BaseException {message: "Token must be defined!", stack: "Error: Token must be defined!↵    at new BaseExcep…oke (webpack:///./~/zone.js/dist/zone.js?:426:22)"}message: "Token must be defined!"stack: "Error: Token must be defined!↵    at new BaseException (webpack:///./~/angular2/src/facade/exceptions.js?:17:23)↵    at new Key (webpack:///./~/angular2/src/core/di/key.js?:26:19)↵    at KeyRegistry.get (webpack:///./~/angular2/src/core/di/key.js?:65:22)↵    at Function.Key.get (webpack:///./~/angular2/src/core/di/key.js?:40:60)↵    at resolveFactory (webpack:///./~/angular2/src/core/di/provider.js?:365:54)↵    at resolveProvider (webpack:///./~/angular2/src/core/di/provider.js?:385:66)↵    at Array.map (native)↵    at Object.resolveProviders (webpack:///./~/angular2/src/core/di/provider.js?:393:31)↵    at Function.Injector.resolve (webpack:///./~/angular2/src/core/di/injector.js?:426:27)↵    at Function.DirectiveProvider.createFromType (webpack:///./~/angular2/src/core/linker/element.js?:100:82)↵    at ResolvedMetadataCache.getResolvedDirectiveMetadata (webpack:///./~/angular2/src/core/linker/resolved_metadata_cache.js?:27:50)↵    at Function.AppProtoElement.create (webpack:///./~/angular2/src/core/linker/element.js?:159:45)↵    at eval (viewFactory_Login:833:41)↵    at Object.evalExpression (webpack:///./~/angular2/src/facade/lang.js?:457:94)↵    at TemplateCompiler._createViewFactoryRuntime (webpack:///./~/angular2/src/compiler/template_compiler.js?:184:27)↵    at eval (webpack:///./~/angular2/src/compiler/template_compiler.js?:144:49)↵    at ZoneDelegate.invoke (webpack:///./~/zone.js/dist/zone.js?:323:29)↵    at Object.NgZoneImpl.inner.inner.fork.onInvoke (webpack:///./~/angular2/src/core/zone/ng_zone_impl.js?:45:41)↵    at ZoneDelegate.invoke (webpack:///./~/zone.js/dist/zone.js?:322:35)↵    at Zone.run (webpack:///./~/zone.js/dist/zone.js?:216:44)↵    at eval (webpack:///./~/zone.js/dist/zone.js?:571:58)↵    at ZoneDelegate.invokeTask (webpack:///./~/zone.js/dist/zone.js?:356:38)↵    at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (webpack:///./~/angular2/src/core/zone/ng_zone_impl.js?:36:41)↵    at ZoneDelegate.invokeTask (webpack:///./~/zone.js/dist/zone.js?:355:43)↵    at Zone.runTask (webpack:///./~/zone.js/dist/zone.js?:256:48)↵    at drainMicroTaskQueue (webpack:///./~/zone.js/dist/zone.js?:474:36)↵    at HTMLDocument.ZoneTask.invoke (webpack:///./~/zone.js/dist/zone.js?:426:22)"__proto__: ErrorconsoleError @ zone.js:461_loop_1 @ zone.js:490drainMicroTaskQueue @ zone.js:494ZoneTask.invoke @ zone.js:426

I noticed that when I'm calling createExtendedProvider function and passing CustomInput there, it is still undefined. So, could someone please give me a hint if it is possible to separate it to a different file and if it is - how?

A: Update
To create the provider in an external file you can use it like
@Component({
  selector: 'custom-input',
  template: `
...
  `,
  directives: [FORM_DIRECTIVES],
  providers: [providerExtender.createExtendedProvider(forwardRef(() => CustomInput))]
})
export class CustomInput implements ControlValueAccessor{

and in the other file
export function createExtendedProvider(customInput) {
  return new Provider(
    NG_VALUE_ACCESSOR, {useExisting: customInput, multi: true});
}

Plunker example
Original
This seems invalid
export function createExtendedProvider(customInput) {
  return new Provider(
    NG_VALUE_ACCESSOR, {
      useExisting: fr(() => { console.log(`Inside method ${customInput}`); return customInput; }),
      multi: true
    });
}

useExisting means that there needs to come a type that should be resolved by Angulars DI.
I guess this is what you want:
export function createExtendedProvider(customInput) {
  return new Provider(
    NG_VALUE_ACCESSOR, {
      useClass: customInput,
      multi: true
    });
}

A: Perhaps it's a silly answer but I would say that you just need to specify the CustomInput component into the components (directives attribute) where you want to use it:
import {CustomInput} from './custom.input';

@Component({
  (...)
  template: `
    <custom-input [(ngModel)]="something" ngControl="test"></custom-input>
  `,
  directives: [CustomInput]
})
export class SomeOtherComponent {
  (...)
}

In fact, the value accessor is registered within the providers of the component itself so I can see no needs to separate them into two different modules.


text:
Q: Process.Start, Read Progress From WebMethod? I am starting a console application from an ASP.NET webform via the following, called from the Click event handler of a Button control:
Process p = new Process();
p.StartInfo.FileName = @"C:\HiImAConsoleApplication.exe";

// Set UseShellExecute to false for redirection.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.Arguments = "-u " + url + " -p BLAH";
p.StartInfo.CreateNoWindow = false;

// Set our event handler to asynchronously read the sort output.
p.OutputDataReceived += OutputReceived;

// Start the process.
p.Start();

// Start the asynchronous read of the sort output stream.
p.BeginOutputReadLine();
p.WaitForExit();

This works fine, I am using the OutputDataReceived event handler to read the output from the console application without issue by adding the received messages to a globally defined string collection, and then on a timer I get the new messages from a WebMethod.
protected static void OutputReceived(object sender, DataReceivedEventArgs e)
            {
                if (e.Data != null)
                {
                        messages.Add(myData);
                }
                if (messages.Count > 20)
                {
                    messages.Clear();
                }
            }

and then to check for messages via the WebMethod:
 public static List<string> messages = new List<string>();

    [WebMethod]
    public static string[] CheckForNewMessages()
    {
        List<string> tempCollection = new List<string>();
        if (messages.ToArray().Length > 0)
        {
            foreach (string str in messages.ToArray())
            {
                    tempCollection.Add(str);
            }
        }

        return tempCollection.ToArray();
    }

the problem with this approach is if I have more than one user attempt to use the application, they obviously share messages with each other and that's not very good. I am wondering if there is a better approach that would allow me to support multiple users more accurately.
TIA experts!

A: You can use a Dictionary and connect the Cookie Of The User with the message that can read.
public static Dictionary<string, string> messages = new Dictionary<string, string>();

The key, must be the user cookie.
But this is not a bug free solution.
Bug number 1, on the recycle of the pool you lose your data.
Bug number 2, on any update/compile of your web site, your lose your data.
Bug number 3, when you have more than one pools (web garden) each pool have their static data, so the same user can be lost/never see their data.
The correct way is to use a database, either some file to write them down - and connect the messages with the user cookie / user id
Lifetime of ASP.NET Static Variable

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I create a custom map view pin with a dynamic element? I am trying to create a custom pin which has a label in the center of the pin which will change with every pin. The label will just be the pin number, so if I have 8 pins each pin will have a number in the center i.e. 1st pin will have 1, 2nd pin will have 2, etc. The issue is that the regular pin appears, not the custom pin.
override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    loadPins()
}

func loadPins() {
        let annotation = CustomPin()
        annotation.coordinate = CLLocationCoordinate2D(latitude: 30.2531419, longitude: -97.78785789999999)
        mapView.addAnnotation(annotation)
    }

class AnView: UIView {

    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var pinImage: UIImageView!

    override func draw(_ rect: CGRect) {
        //Draw function
    }

}

class CustomPin: MKPointAnnotation {
    var pin = AnView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

}

A: The annotation (your CustomPin) gets the latitude/longitude values.
The annotation view (which your code doesn't show) gets the label or image you want to show on the map.
Since the Maps and Location Programming Guide from the comments gives all of its examples in Objective-C, you might want to also look at this RayWenderlich.com tutorial for Swift help:
MapKit Tutorial: Getting Started

A: You can draw the number over the map pin image. Just create a function (or extension) to add text over the image like this:
func addTextOverImage(_ text: String, overImage image: UIImage) -> UIImage {

    //set scale and context
    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    //set font face, size and color
    let textColor = UIColor.black
    let textFont = UIFont.boldSystemFont(ofSize: 12)

    //define the text attributes
    let paragraph = NSMutableParagraphStyle()
    paragraph.alignment = .center

    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: paragraph
        ] as [String : Any]

    //set the text position (in the image rect)
    let textPoint=CGPoint.init(x: 0.0, y: image.size.height/2)
    //create the rect to draw the text
    let rect = CGRect(origin: textPoint, size: image.size)
    //draw the text over the image, in the rect just defined
    text.draw(in: rect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //return image with text
    return newImage!
}

You may need to adjust the textPoint in the function to get the text positioned where you want it to be.


text:
Q: CUPS - install once, use another printer (of the same model) without re-configuring problem For example I have "HP 1020 LaserJet" local USB printer successfully installed on a CUPS.
It uses one connection.
If I get another HP 1020 LaserJet printer it wouldn't print, I am having to
modify the printer and change it's connection. Why?
How can I avoid this?
I know that it's illogical to use the same type printer on the same computer, but that's my environment.
How to make CUPS to use the same Connection for all printers of the same type, model, manufacturer etc.?
Thank you!!!
EDIT:
I have found out that it's not possible through the configs or any other standard ways.
The only way is to find a nice workaround.

A: The fix is in the UDEV rule.
Since it is not possible through standard ways.
You just create an UDEV rule which would detect printer adding
and then run lpadmin -p PRINTERNAME -v CONNECTION?serial=
so printer would be automatically reconfigured to use another connection.
P.S: I would give 300 of points if someone gave me right direction. I hope I will get my 300 back now :D

A: I had the same problem on my raspberry pi while working on a Kiosk application.
I found a possible solution, following the possible steps (the printer I am using is CUSTOM TG2460, in this case):

*

*Run lpinfo -v which returns the list of devices attached.

network https
file cups-brf:/
direct vnc:/
network ipp
network beh
network ipps
network socket
network lpd
network http
direct hp
direct usb://CUSTOM%20SPA/TG2460-H?serial=TG2460-H_NUM:_0
direct hpfax
network dnssd://HP%20LaserJet%20200%20color%20M251n%20(E9A2D9)._ipp._tcp.local/?uuid=564e4333-4230-3339-3439-a0d3c1e9a2d9
network dnssd://XEROX%20WorkCentre%203335%20(XRX9C934E79F15F)._printer._tcp.local/
network socket://192.168.10.12
network socket://192.168.10.123
network ipp://VodafonePS.local:631/ipp/print
network ipp://NPIE9A2D9.local:631/ipp/print

*Filter for the line containing the printer you want and extract the device URI with grep and cut.

lpinfo -v | grep usb://CUSTOM | cut -d ' ' -f 2
>>> usb://CUSTOM%20SPA/TG2460-H?serial=TG2460-H_NUM:_0

*Add the URI to the existing printer, updating the CUPS entry

lpadmin -p PRINTER_NAME -v usb://CUSTOM%20SPA/TG2460-H?serial=TG2460-H_NUM:_0

All can be summarized in this one liner:
lpadmin -p PRINTER_NAME -v $(lpinfo -v | grep usb://PRINTER_MODEL | cut -d ' ' -f 2)

I then run the command at each reboot. If a new printer is attached, the user must reboot the kiosk.
I think you can easily bind this to a UDEV rule and run when something changes on the printer that you want to swap.


text:
Q: Does the set of natural numbers contain infinity? Let $N=\{1,2....\}$ be the set of naturals numbers. Is $\infty \in N$, as the list is never ending  ?

A: One property about the set $\Bbb N$ of natural numbers is that it does not have a largest element, so if you defined $\infty$ as some element which is larger than every natural number, it wouldn't be in $\Bbb N$ anyway because of this property.
Having said that, I recommend you look up the ordinal numbers and what it means for a set to be well-ordered (it means every subset has a least element).  We could add an element into the set $\{1,2,3, \dots \}$ which we define to be larger than every element in $\{1,2,3,\dots \}$.  Usually, instead of $\infty$, we call the element $\omega$.  But the set $\{1,2,3,\dots, \omega \}$ is a different set than $\Bbb N$ (it contains $\Bbb N$ as a proper subset).  $\omega$ is the largest element in this set, and you could think about $\omega$ as "infinity" in some sense.
But then we can add an element defined to be larger than every element in this set.  Let's call this element $\omega + 1$.  So $\{1, 2, 3, \dots, \omega, \omega + 1 \}$ is the set where $\omega$ is larger than every natural number, and $\omega + 1$ is larger than every natural number and larger than $\omega$.  So, it's not useful to call $\omega$ "$\infty$" because there is something larger than it.  (Although, Georg Cantor proved that, as far as set cardinalities/sizes go, there are infinitely many distinct infinites...).

A: No, if $\infty \in N$, then the list would have an end, namely $\infty$. Of course, you would still need to go infinitely far up from $1$ (or indeed any other number) to get to $\infty$.

A: Infinity is not well-defined as it has different meanings depending on the context so placing it in a set that is well-defined (the set of natural numbers $\mathbb{N}$ for instance) is clearly meaningless.


text:
Q: vCenter in a ESXI host that it manages We have 2 physical servers (A and B), each with ESXI 7.0 installed. We'd like to manage them with vCenter. Can we install vCenter on one of those servers? Is it advisable?

A:
Can we install vCenter on one of those servers?

Yes absolutely, in fact that's kind of the default scenario.

Is it advisable?

Sure, why not.
I'll give you a little more info. For larger installations - tens/hundred of hosts what you often see is a small 'management' cluster to run these central VMware tool VMs (vCenter, vROps, Log Insight, NSX controllers etc.), usually 4 hosts or so, maybe 6-8). Then you have one or more workload clusters with the rest of your hosts. All of these servers are managed by the vCenter. The reason you separate these out is that often these management VMs have slightly different use case than the general computer clusters - as an example if your vCenter crashes (and you're not running in HA mode) then you need to find which host is running the vCenter (due to DRS moves) so you can restart it and deal with any issues with it. It's easier to find it if it's a small 4-8 host cluster than a larger one. Also you don't want to run NSX on the hosts that are running the NSX controllers typically.
So for larger installation then yes, I'd have a small management cluster to run the vCenter, but if you only have two servers then you don't have that luxury, in which case then yeah, just get on with it, you'll be fine!

A: You can install vcenter on any of the two physical server you have, but it's generally not advisable to do so because during the maintenance of the host on which vcenter is installed you will loose connectivity to vcneter.


text:
Q: Force  to open gallery in mobile I want to make my input to only accept files from gallery instead of allowing the user to open the camera.
How can I achieve it?
ASP.NET
<asp:FileUpload ID="filGallery" runat="server" AllowMultiple="true" />

HTML 5
<input type="file" id="filGallery" multiple="multiple" />

The behaviour I want is similar to the one found in iOS 8 or less, where input with multiple files enabled couldn't open the camera

A: I don't think there is a way to force using gallery - current trend is more on using camera (and suggesting using front or back) rather than disabling it.
However, there is a similar question on SO (but focus on type of capture) where that answerer has pointed to some ways of input attribute you may try out:
original SO: https://stackoverflow.com/a/40512470/2564920
More detail test he has done regard to the mobile capture: https://addpipe.com/blog/correct-syntax-html-media-capture/
A test page which you can try out: https://addpipe.com/html-media-capture-demo/
specifically one setting which is
<input type="file" accept="image/*" capture="filesystem">

looks promising - but probably won't work (since this syntax is deprecated and capture attribute in newer spec is used to say you want to use camera - choosing between front or back camera source)

A: just use simple method to open gallery in mobile
  <input type="file" id="fileProfile2" name="fileProfile2"  accept="image/png,image/jpeg" capture="filesystem">


text:
Q: Srednicki LSZ reduction formula motivation once more I have seen this question asked before, but have not really found a satisfying answer, or maybe more exactly, I have not seen an answer that I can really understand.
I refer to section 5 of his book, p 39. He imposes the condition $\langle0| \varphi(0)|0 \rangle =0 $ as one of the conditions needed for the LSZ formula to be valid. His motivation is that
"This is because we would like $a^\dagger_1(\pm\infty)$, when acting on $|0 \rangle$, to create a single-particle state. We do not want  $a^\dagger_1(\pm\infty)$ to create a linear combination of a single particle state and the ground state. But this is precisely what will happen if $\langle 0|  \varphi(0)|0 \rangle$ is not zero."
I understand everything, expect the last sentence. Why would $a^\dagger_1(\pm\infty)|0 \rangle$ be such a linear combination if $\langle 0|  \varphi(0)|0 \rangle$ is not zero. I just can't work this out.

A: First, it's important to know what kind of states there are. I'll call them ground state $|0\rangle$, one-particle state $|k\rangle$ and multi-particle state $|n,k\rangle$. Here, $k$ specifies the momentum of a particle and $n$ is a collection of other quantum numbers that may arise (e.g. relative momentum between some other momenta, ...).
We want $a^\dagger|0\rangle$ to create a one-particle state. In Eq. (3.19), Srednicki defines
$$ \varphi(x) = \int \widetilde{\text{d}k} \big[ a(k)\, \text{e}^{\text{i} kx} + a^\dagger(k)\,  \text{e}^{-\text{i} kx} \big].\tag{1}\label{a} $$

Assume, that $a^\dagger$ creates both a one-particle state, as well as the ground state, like this
$$ a^\dagger |0\rangle = c_1 |k\rangle + c_2 |0\rangle, $$
with some complex numbers $c_{1,2}$.
Now we calculate the vacuum expectation value of $\varphi$ (and only consider the $a^\dagger$-part for notational simplicity):
\begin{align*}
  \lim\limits_{x\to 0}\langle 0|\varphi(x)|0\rangle &= \lim\limits_{x\to 0}\int \widetilde{\text{d}k} \langle 0| a^\dagger(k)\,  \text{e}^{-\text{i} kx} |0\rangle \\
&= \int \widetilde{\text{d}k} \langle 0| a^\dagger(k) |0\rangle  \,\text{e}^{0} \\
&= \int \widetilde{\text{d}k} \langle 0| \big[ c_1 |k\rangle + c_2 |0\rangle \big]\\
&\propto c_1 \underbrace{\langle 0|k\rangle}_{0,\text{ orthogonal!}} + c_2 \underbrace{\langle 0|0\rangle}_{1}\\
&= c_2 \neq 0
\end{align*}
This means, if we let $a^\dagger$ create both a one-particle state and the ground state, then $\langle 0|\varphi(0)|0\rangle$ does not vanish. But if we define $\langle 0|\varphi(0)|0\rangle\equiv 0$, we must set $c_2=0$, which means that $a^\dagger$ truly only creates a one-particle state in Eq. \eqref{a}.

Ad comment: (1) If we want to be precise and include the $a$ term, we should also not perform the limit so quickly. Inside the integration, there's a $\text{e}^{\text ikx}$ and a $\text{e}^{-\text ikx}$. They are linearly independent, so each should vanish. (Also note that while $x\to 0$, $k\to \infty$, so that's ill-defined within the exponential)
(2) $a$ being evaluated at $t=\pm\infty$ helps us make it non-interacting. If this doesn't answer your question, I am sorry I did not understand it. If so, please restate it.


text:
Q: Discord.py multiple missing arguments I have a simple command that requires to arguments to be passed; datatype and length, I have
@ran.error
async def ran_error(ctx, error):
    if isinstance(error, commands.CommandError):

This just gives an output if there is a general error, I'm looking for something where if no arguments are provided then do a or if only one is provided then do b.

A: Referring to this you can easily pass all arguments like this:
@bot.command()
async def ran(ctx, *args):
    # do something

To check if arguments are provided you could first get the number of all arguments and and check if it is 0, than your error handling comes into play:
@bot.command()
async def ran(ctx, *args):
    # get number of arguments provided
    number_of_arguments = len(args)
    if number_of_arguments == 0:
        # error handling
    else:
        # perform command action

Have a look at my linked website for more information.


text:
Q: AngularJS Ionic $http request to API maintain authentication data I'm writing Ionic/Cordova-based application which requires usage of external API where authentication data must be provided (via http-basic header).
The problem is that the application maintains the authorization (after providing correct credentials) and I am not able to logout (force the application to block access to the API).
HTTP authentication validation mechanism:
var validateCredentials = function(user, password, callback) {

    var req = {
        method: 'GET',
        url: 'http://server.host.com/api/check?Accept=application/json',
         headers: {
            'Authorization': 'Basic ' + btoa(user + ':' + password)
         }
    };

    $http(req).success(function(data) {
        callback(true);
    }).error(function(error) {
        callback(false);
    });
}

My use case:
1) I am providing wrong credentials to the method and recieve 401 (which is good):

2) Then I provide correct credentials and recieve 200 OK (which is also good):

3) And finally, if I provide the wrong credentials one more time the API is still working (200 instead of 401):

As a result, I cannot logout from my application and moreover - I cannot login to different user!
I've tried to clear caches, ionic history and webview cache with https://github.com/moderna/cordova-plugin-cache but still no success. The only option to clear the session/authentication data is Andoird OS Settings/Application/Clear App Data.
And finally - there are no cookies or session variables in the context of the application (at least according to Chrome Developper console running in debug mode with my device).
Any hints appreciated!


text:
Q: Jquery slideToggle() - only toggle certain items I have a page where there are questions with answers hidden underneath them. When someone clicks on a question, the answer slides down (this is a seperate function which works fine). When clicked again, it returns to its hidden state.
The problem I am having is a seperate link #expand-close a that when clicked, will open/close ALL the answers to the questions.
When an answer is already open, this function runs and opens all the closed answers but closes all the open answers.
I want it to open all and keep the open answers open, and close all and keep the closed answers closed.
$('#expand-close a').click(function () {

        $(this).toggleClass("hide");

        $('.faq-hideable').slideToggle(500);
        $('.faq-hideable').closest('li').find('h2').toggleClass('p-open');

    });

A: For the adding/removing classes, this is simple since toggleClass() has an optional switch parameter which determines if the class should be added or removed (instead of simply toggling it).
There's no such facility for .slideToggle() so we do this manually using an basic if/else clause to choose between a slideUp() or slideDown().
$('#expand-close a').click(function () {
    var tohide = $(this).toggleClass("hide").hasClass("hide");

    if (tohide) {
        $('.faq-hideable').slideUp(500);
    } else {
        $('.faq-hideable').slideDown(500);
    }
    $('.faq-hideable').closest('li').find('h2').toggleClass('p-open', !tohide);

});

If you want something more succinct (but less readable):
$('#expand-close a').click(function () {
    var tohide = $(this).toggleClass("hide").hasClass("hide");
    $('.faq-hideable')[tohide ? "slideUp" : "slideDown"](500)
        .closest('li').find('h2').toggleClass('p-open', !tohide);
});

A: try something like the following (you will need to change the selector to match your html/clases):
$('#expand-close a').click(function () {

        $(this).toggleClass("hide");

        if($(this).hasClass("hide")){
             $('.faq-hideable .answer:visible').slideToggle(500);
        }else{
             $('.faq-hideable .answer:hidden').slideToggle(500);
        }
        $('.faq-hideable').closest('li').find('h2').toggleClass('p-open');

    });

A: I have something like your open/close system I use a if close like this:
$('#expand-close a').click(function () {
        if ($('.faq-hideable').is(':hidden')) {
            $('.faq-hideable').show();
        }
        else {
        $('.faq-hideable').hide();
        }
    });

Hope it can help you


text:
Q: Is possible to get a SPListItemCollection by just a URL of its SPList? In my project, I have to get the SpListItemCollection of the splist by the url that user entered. However, I cannot get anything by just using it.
To get a SPListItemCollection:
1) get SPSite object (site collection)
2) get SPWeb object (sub site (optional))
3) get SPList object (Guid, list name...)

The URL I received:
http://aaa/bbb/ccc/ddd/eee/fff/Forms/AllItems.aspx
Do you guy have any idea to  split the URL to fill the items?

A: According to MSDN,
The URL that is passed to the SPSite constructor does not need to match a site collection URL exactly. See examples below.
The following code example returns the site collection that is located at http://Server_Name/sites/Site_Name even though the URL that is passed to the constructor does not match the site collection URL.
using (SPSite oSiteCollection = new SPSite("http://Server_Name/sites/Site_Name/Subsite_Name/default.aspx"))
{
    ...
}

So you can use as below and get site collection object....
SPSite oSiteCollection = new SPSite("http://aaa/bbb/ccc/ddd/eee/fff/Forms/AllItems.aspx");

From here you can get list items based on view/caml query etc....


text:
Q: Importing matlab data into ArcMap I'm creating regression lines using matlab from points having UTM geographic coordinates.
I would like to import those regression lines into a map of the same area in ArcMap.
What kind of data do I need to extract from Matlab to be read and imported as polylines in ArcMap?

A: As @PolyGeo points out, convert to shapefile.  Looks like you can do this in the Mapping Toolbox.

A: There looks to be a related question and answer over at StackOverflow that incorporates what looks like a solution to this question.  It suggests that shapefile may be the easiest format to use.


text:
Q: Python Script Hanging After Executing Jar File with Subprocess Can't seem to figure out what is causing the script to hang, I know for sure it is hanging as the code below the "p2" variable doesn't seem to get executed at all.
The jar file does what I need it to do which to summarize in a few words, downloads all the necessary files and folders from somewhere.
I need to kill the process before removing files related to it else there will be an error relating to it being occupied by another process which I am sure it is self explanatory.
Here is the full code with the paths changed a little for reasons:
#!/usr/bin/python3.8

import os
import shutil
import json
import time
import requests
import subprocess
import wget

from zipfile import ZipFile
from glob import glob

def post_to_slack(message):
    webhook_url = "someurlhere"

    encoded_data = json.dumps({'text': message}).encode('utf-8')
    response = requests.post(
        webhook_url,
        data=encoded_data
    )
    # print(str(response.status_code))

src = "/somepath/ATM6/"
dest = "/someotherpath/All the Mods 6/"
extension = ".zip"

files_in_dest = os.listdir(dest)
for file in files_in_dest:
    filepath = os.path.join(dest, file)
    try:
        if os.path.isfile(filepath) or os.path.islink(filepath):
            os.unlink(filepath)
        elif os.path.isdir(filepath):
            shutil.rmtree(filepath)

    except Exception as e:
        post_to_slack(f"Error occured in {os.path.basename(__file__)}!")

for item in os.listdir(src):
    abs_path = os.path.join(src, item)

    if item.endswith(extension):
        file_name = os.path.abspath(abs_path)
        zip_ref = ZipFile(file_name)
        zip_ref.extractall(src)
        zip_ref.close()

time.sleep(20)

contents_in_dir = os.listdir(src)
folder = [content for content in contents_in_dir if content.startswith("SIMPLE") and not content.endswith(extension)]

os.chdir("{}{}".format(src, folder[0]))

wget.download("https://github.com/AllTheMods/alltheservers/releases/download/2.0.1/serverstarter-2.0.1.jar")

p1 = subprocess.run(["chmod", "+x", "serverstarter-2.0.1.jar"], stdout=subprocess.DEVNULL)

p2 = subprocess.Popen(["java", "-jar", "serverstarter-2.0.1.jar", "&"], stdout=subprocess.DEVNULL)
time.sleep(180)
p2.kill()

try:
    log_files = glob(src + "**/*.log")
    for files in map(str, log_files):
        os.remove(files)

    zip_files = glob(src + "**/*.zip")
    for files in map(str, zip_files):
        os.remove(files)

    startserver_files = glob(src + "**/startserver.*")
    for files in map(str, startserver_files):
        os.remove(files)

    serverstarter_files = glob(src + "**/serverstarter*.*")
    for files in map(str, serverstarter_files):
        os.remove(files)

    files_to_move = glob(src + "**/*")
    for files in map(str, files_to_move):
        shutil.move(files, dest)

    time.sleep(20)

    forge_jar_file = glob(dest + "forge-*.jar")
    for files in map(str, forge_jar_file):
        print(files)
    os.rename(files, "{}{}".format(dest, "atm6.jar"))

except Exception as e:
        post_to_slack(f"Error occured in {os.path.basename(__file__)}! {e}")

quit()

A: This line here: p2 = subprocess.Popen(["java", "-jar", "serverstarter-2.0.1.jar", "&"], stdout=subprocess.DEVNULL) creates a Popen object but it doesn't trigger the subprocess call. So your script jumps to the next line, which is a time.sleep(180) call; have you timed your 'hang'? It's probably 180 seconds in length. After that, the rest of your code should execute.
Take a look at this answer here; you might want to wrap your Popen inside of a with statement and deal with the execution using a .wait() command.
Something like:
with subprocess.Popen(["java", "-jar", "serverstarter-2.0.1.jar", "&"] as sub:
    try:
        sub.wait(timeout=timeout)
    except:
        sub.kill()


text:
Q: Running apache in an ubuntu Docker container on a RedHat machine I am new to Docker and have been trying to configure a standard default install of Apache2 running on the ubuntu:14.04 image.
This seems to work just fine when the Docker host machine is running Ubuntu, but when I try to run this same config on a machine running RHEL 6, I get apache config errors having to do with file permissions. Specifically, the default apache page returns a 403 forbidden page.
I thought the point of Docker was that I could create a container on one environment and it should behave exactly the same on any other environment.. am I way off?

A: Not 100% sure, but it may be that you need RHEL 7.  From here you can:
docker pull rhscl/httpd-24-rhel7
See https://access.redhat.com/solutions/1378023


text:
Q: How to de-couple and do dependency injection with highcharts-ng I have two models: iposectors, and ipomarketcap, a Factory that creates an instance of the model depending on the parameter, and BindingCode that binds all together.
The models have hard-coded data for testing, but plan to retrieve data from API.
Here is the fiddle: highcharts.
Nothing shows up...
When on the debugger line - I can see that the highchart object is created, and all data is attached, but only default title appears.
What am I missing?
        var myapp = angular.module('myApp', ["highcharts-ng"]);
    myapp.controller('myctrl', BindingCode);
    myapp.factory("Factory", Factory);

    function iposectors() {
        this.charttitle = "Sector Distribution";
        this.apidata = [
            ['APP Android', 45.0],
            ['APP Ios', 26.8],
            ['Widget Web', 12.8],
            ['MTC BAckoffice', 8.5],
            ['Correo electrónico', 6.2],
            ['Facebook', 6.2],
            ['Twitter', 6.2],
            ['Teléfono', 6.2],
            ['Presencial', 6.2],
        ];
        this.chartConfig = {
            options: {
                chart: {
                    type: 'pie'
                },
                plotOptions: {
                    pie: {
                        dataLabels: {
                            enabled: false
                        }
                    }
                },
                legend: {
                    enabled: true,
                    layout: 'vertical',
                    align: 'left',
                    height: 135,
                    width: 160,
                    verticalAlign: 'middle',
                    useHTML: true,
                    labelFormatter: function () {
                        return '
' + this.name + '  ' + this.percentage.toFixed(1) + '%
';
                    },
                    itemStyle: {
                        color: '#421C40',
                        fontWeight: 'bold',
                        fontFamily: 'Century Gothic',
                        fontSize: '10px'
                    }
                },
                tooltip: {
                    pointFormat: '\u25CF Weight: {point.percentage:.1f}%'
                },
            },
            title: {
                text: this.charttitle,
                align: 'center',
                verticalAlign: 'top'
            },
            series: [{
                name: 'Weight',
                size: '75%',
                showInLegend: true,
                data: this.apidata
            }],
            loading: false
        }
    }

    function ipomarketcap() {
        this.charttitle = "Market Cap Distribution";
        this.apidata = [
            ['MC APP Android', 45.0],
            ['MC APP Ios', 26.8],
            ['MC Widget Web', 12.8],
            ['MC MTC BAckoffice', 8.5],
            ['MC Correo electrónico', 6.2],
            ['MC Facebook', 6.2],
            ['MC Twitter', 6.2],
            ['MC Teléfono', 6.2],
            ['MC Presencial', 6.2],
        ];
        this.chartConfig = {
            options: {
                chart: {
                    type: 'pie'
                },
                plotOptions: {
                    pie: {
                        dataLabels: {
                            enabled: false
                        }
                    }
                },
                legend: {
                    enabled: true,
                    layout: 'vertical',
                    align: 'left',
                    height: 135,
                    width: 160,
                    verticalAlign: 'middle',
                    useHTML: true,
                    labelFormatter: function () {
                        return '
' + this.name + '  ' + this.percentage.toFixed(1) + '%
';
                    },
                    itemStyle: {
                        color: '#421C40',
                        fontWeight: 'bold',
                        fontFamily: 'Century Gothic',
                        fontSize: '10px'
                    }
                },
                tooltip: {
                    pointFormat: '\u25CF Weight: {point.percentage:.1f}%'
                },
            },
            title: {
                text: this.charttitle,
                align: 'center',
                verticalAlign: 'top'
            },
            series: [{
                name: 'Weight',
                size: '75%',
                showInLegend: true,
                data: this.apidata
            }],
            loading: false
        }
    }

    function BindingCode($scope, Factory) {

        $scope.iposectors = Factory.CreatePieChart('iposectors');
        debugger;
    }

    function Factory() {
        return {
            CreatePieChart: function (type) {
                if (type == 'iposectors') {
                    return new iposectors();
                }
                else {
                    return new ipomarketcap();
                }
            }
        }
    }

html page

            @*<highchart id="chart1" config="highchartsNG"></highchart>*@
            <highchart id="chart1" config="chartConfig" class="span9"></highchart>

A: The problem is that your data is binded to iposectors property, while highcharts-ng expects config in $scope variable. For example you can bind this references this way:
function BindingCode($scope, Factory) {

    $scope.iposectors = Factory.CreatePieChart('iposectors');
    $scope.chartConfig = $scope.iposectors.chartConfig;

}

Live demo: http://jsfiddle.net/fjv93vvu/


text:
Q: Need to update the primary key on existing objects in GAE Java I am building a web app using GAE Java. I have a class that uses a Long ID (generated by appengine) as its primary key.
I now want to create a new class that would be the parent class to this original class (a one to many relationship) however the child needs to have a primary key of type "key", not the Long ID I have now.
What is the best way to change the primary key to be type "key" instead of long for the existing persisted entities?  Should I create a new class with primary key of type "key" and instantiate and persist new objects that copy the field values from the old ones?   Or can I somehow just update the existing class?
Thanks

A: In fact, the Key of a persisted Entity is considered to be immutable. Changing the key will, without a doubt, be equivalent to changing the used instance. What I suggest you is to link your initial object to a child of you created parent.

A: You could store the existing Long IDs in a list in the parent class: that would create the necessary one-to-many parent-child relationship.
You would have to manage consistency yourself though (which may not be too difficult if your site doesn't have very high traffic), and the parent and child classes would not be in the same entity group (implications for transactions).
Changing the key means changing the Entity itself (and also its entity group).
Ultimately, the solution that works for you will depend on the specifics of your problem. For example, is there already a lot of existing data? Is this a live application (i.e., is it already being used)?
Another solution could be to migrate your app over to a different (better suited) data model, and do so account-by-account (by locking out the account for a brief period of time). This way only a few individuals will be affected by the change (if they happen to access the app when you are migrating their account) rather than the whole app being down.


text:
Q: What is the best way to use enrich-my-library in scala? The are two different way to implement it.
One is more short
implicit def toR1(s:String) = new { def getLength = s.length)}

Second is more long
class R2(s:String){def getLength2 = s.length)}
implicit def toR2(s:String) = new R2(s)

Which one is better?

A: The first version uses a structural type. It makes it possible to write short and readable code, but a disadvantage of structural types is that reflection is used at runtime when you call the method in the structural type. Calling a method via reflection is slower than calling a method directly.
More details are in this blog post (written by me): Avoid structural types when pimping libraries


text:
Q: Showing that a sequence converges, in distribution, to a normal r.v. Let $X_1, X_2, \dots$ be independent, with
$$P(X_n=1) = P(X_n = -1) = \frac{1}{2} \left( 1 - \frac{1}{n^2} \right),$$
and
$$P(X_n = n) = P(X_n = -n) = \frac{1}{2n^2}.$$
Let $S_n = X_1 + \cdots + X_n$ and $S_n^* = S_n/\sqrt{n}$. The first part of the problem asked to show that $\text{Var}(S_n^*) \rightarrow 2$, which was a pretty straightforward calculation.
The second part asks us to show that $S_n^* \stackrel{d}{\underset{n\to\infty}{\longrightarrow}} Z$, where $Z$ is a normal random variable. I tried to do this by using characteristic functions. We have that
$$\varphi_{X_n}(t) = \cos t + \frac{1}{n^2}\left( \cos (nt) - \cos t \right).$$
However, writing the characteristic function of $S_n^*$ in terms of $\varphi_{X_n}(t)$ made it really messy and not workable much. Is there a more efficient way of approaching this problem? Would Lindeberg-Feller CLT work here?

A: The lindeberg CLT can be applied for this sequence of random variables.
Hint: figure out a convinient lower bound for the cumulative variance
$s_n^2=\sum_{i=1}^n \sigma_k^2$


text:
Q: Load new module in Kamailio I would like to ask, how can I load new module in Kamailio 4.1.2?
Actually, I have an issue, when I tried to compile my kamaiio.cfg
I've got error:
root@kamailio:/usr/local/# kamailio -c kamailio.cfg
loading modules under /usr/local/lib64/kamailio/modules/
 0(25392) ERROR: <core> [sr_module.c:587]: load_module(): ERROR: load_module: could not find module <websocket> in </usr/local/lib64/kamailio/modules/>
 0(25392) : <core> [cfg.y:3408]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 323, column 12-25: failed to load module
 0(25392) ERROR: <core> [cfg.y:3272]: yyparse(): cfg. parser: failed to find command ws_handle_handshake
 0(25392) : <core> [cfg.y:3411]: yyerror_at(): parse error in config file /usr/local/etc/kamailio/kamailio.cfg, line 1083, column 27: unknown command, missing loadmodule?

ERROR: bad config file (2 errors)

when I look physically to the /usr/local/lib64/kamailio/modules/ there is some modules, but websocket.so is missing.
So, how can I get and load module in Kamailio?
Thank you for help!

A: You haven't installed the module websocket. Edit modules.lst file in the source code directory and add websocket to include_modules variable. If you don't have modules.lst, just do:
make cfg

Alternative is to do:
make cfg include_modules="websocket"

By default, the build system for kamailio compiles and install only the modules that have the same dependencies as the core of the application. For websocket you need to install libunistring and openssl (libssl) devel packages.

A: Steps  to load new module to Kamailio server. (Try if above answer is not working for you)

*

*Check the modules is exist in the default module directly /usr/local/lib64/kamailio/modules.
If found, add loadmodule "module_name.so" in load module section in kamailio.cfg file.

*If the module is not found in default module directory, you can check for the source code of that module in the default module source code directory /usr/local/src/kamailio-4.4/kamailio/modules.

*If source code found, enter to the module directory. Then create modules' shared object file(.so) by following commands.
./configure
make
make test
make install

*Then you will get a shared object file(.so). Copy that file into the default module directory. and load this module from the kamailio.cfg file as mentioned in step 1.

*If module source code does not exist in the default source code directory, You need to download the source code from the web. And follow step 3 and 4.


text:
Q: FORALL update is updating only last record from collection and it's giving error ORA-22160: element at index [1] does not exist error message FORALL update is updating only last record from collection and it's giving error ORA-22160: element at index [1] does not exist. I have scenario were i have to update million of records. When i execute the below code the update is happening only for the 100th record remaining 99 records remains same( i tested with 100 records). after execution it's giving ORA-22160: element at index [1] does not exist. i am using oracle 9i database.need suggestion for this issue.
Declare
 CURSOR tk_iflow_cur
  IS
    SELECT DISTINCT top.rule_id,
      top.rule_item_id,
      msib.segment2
    FROM iflow_rules top,
      iflow_active_rules msib
    WHERE top.rule_id = msib.rule_item_id
    AND msib.organization_id  = 5039 and rownum<=100
    ORDER BY top.ora_inv_item_id; -- cursor fetches 100 row
  ---Variable declaration
TYPE l_iflow_id
IS
  TABLE OF VARCHAR2(200) INDEX BY BINARY_INTEGER;
TYPE l_iflow_org
IS
  TABLE OF NUMBER INDEX BY BINARY_INTEGER;
TYPE l_iflow_inv_id
IS
  TABLE OF NUMBER INDEX BY BINARY_INTEGER;
TYPE l_r12_inv_id
IS
  TABLE OF NUMBER;
TYPE l_r12_item_key
IS
  TABLE OF VARCHAR2(200) INDEX BY BINARY_INTEGER;
TYPE l_r12_iflow
IS
  TABLE OF VARCHAR2(200) INDEX BY BINARY_INTEGER;
TYPE l_omar_item_id
IS
  TABLE OF NUMBER INDEX BY BINARY_INTEGER;
TYPE l_omar_seg2
IS
  TABLE OF VARCHAR2(200) INDEX BY BINARY_INTEGER;
  tk_iflow_id l_iflow_id;
  tk_iflow_org l_iflow_org;
  tk_iflow_inv_id l_iflow_inv_id;
  t_omar_item_id l_omar_item_id;
  t_omar_seg2 l_omar_seg2;
  r12_inv_id l_r12_inv_id:=l_r12_inv_id();
  r12_item_key l_r12_item_key;
  r12_iflow l_r12_iflow;
  user_excep  EXCEPTION;
  v_err_count NUMBER;
  PRAGMA EXCEPTION_INIT (user_excep, -24381);
  r12_item_id2 VARCHAR2(200);

BEGIN --
  tk_iflow_id.DELETE;
  tk_iflow_inv_id.DELETE;
  OPEN tk_iflow_cur;
  LOOP --Cursor Loop
    tk_iflow_id.DELETE;
    tk_iflow_inv_id.DELETE;
    t_omar_seg2.DELETE;
    FETCH tk_iflow_cur BULK COLLECT INTO tk_iflow_id, tk_iflow_inv_id, t_omar_seg2; ---100 records assigned to variables
    FOR i IN 1..tk_iflow_id.COUNT -- to store the cursor value
    LOOP                         --for Loop
      BEGIN
        --Comment : passing the cursor value to derive new records from different instance for updating the records
        SELECT DISTINCT segment1,
          inventory_item_id,
          item_type
        INTO r12_iflow(i),
          r12_item_id2,
          r12_item_key(i)
        FROM iflow.ifl_active_rules@R12_db_link
        WHERE segment1           =tk_iflow_id(i)
        AND NVL(SEGMENT2,'NULL') = NVL(t_omar_seg2(i),'NULL')
        AND organization_id      =5063;
      EXCEPTION
      WHEN OTHERS THEN
        r12_inv_id(i)   := 0;
        r12_item_key(i) := 0;
      END;
      r12_inv_id :=l_r12_inv_id();
      r12_inv_id.EXTEND (i);
      r12_inv_id (i) := r12_item_id2;

    END LOOP; --end for loop
    BEGIN
      FORALL i IN r12_inv_id.FIRST..r12_inv_id.LAST SAVE EXCEPTIONS -- for all the derived records i'm updating the target table.100 records i'm  updating
      UPDATE iflow_active_rules
      SET ora_org_id      =5063,
        ora_inv_item_id   =r12_inv_id(i)
      WHERE iflow_id       =r12_iflow(i)
      AND ora_inv_item_id = tk_iflow_inv_id(i);
    EXCEPTION
    WHEN user_excep THEN
      v_err_count := SQL%BULK_EXCEPTIONS.COUNT;
      FOR i       IN 1 .. v_err_count
      LOOP
        DBMS_OUTPUT.put_line ( 'Error: ' || i || ' Array Index: ' || SQL%BULK_EXCEPTIONS (i).ERROR_INDEX || ' Message: ' || SQLERRM (SQL%BULK_EXCEPTIONS (i).ERROR_CODE) );
      END LOOP;
    END;
    BEGIN
      FORALL i IN r12_inv_id.FIRST .. r12_inv_id.LAST SAVE EXCEPTIONS
      UPDATE iflow_rules --- updating openup system iflow cost details
      SET ora_org_id      =5063,
        ora_inv_item_id   =r12_inv_id(i)
      WHERE iflow_id       =r12_iflow(i)
      AND ora_inv_item_id = tk_iflow_inv_id(i) ;
    EXCEPTION
    WHEN user_excep THEN
      v_err_count := SQL%BULK_EXCEPTIONS.COUNT;
      FOR i       IN 1 .. v_err_count
      LOOP
        DBMS_OUTPUT.put_line ( 'Error: ' || i || ' Array Index: ' || SQL%BULK_EXCEPTIONS (i).ERROR_INDEX || ' Message: ' || SQLERRM (SQL%BULK_EXCEPTIONS (i).ERROR_CODE) );
      END LOOP;
    END;
    EXIT
  WHEN tk_iflow_id.COUNT=0;
    COMMIT;
  END LOOP; --End Cursor Loop
  CLOSE tk_iflow_cur;
END;

A: This is happening because you are using r12_iflow collection in the scope of collection r12_inv_id where it not not accessible. FORALL statement is differnt the FOR LOOP. Even though they work pretty on same logic but they differs on scope of usage of variables. You can create a RECORD in your case and do the processing. See below how you can do it. PS Not tested.
DECLARE
   CURSOR tk_iflow_cur
   IS
        SELECT DISTINCT top.rule_id, top.rule_item_id, msib.segment2
          FROM iflow_rules top, iflow_active_rules msib
         WHERE     top.rule_id = msib.rule_item_id
               AND msib.organization_id = 5039
               AND ROWNUM <= 100
      ORDER BY top.ora_inv_item_id;                  -- cursor fetches 100 row

     Type var_cur is table of tk_iflow_cur%rowtype index by pls_integer;
     l_cur   var_cur;

     --Record of your variables.
     TYPE var_rec is RECORD
     (
        l_r12_iflow  VARCHAR2 (200),
        l_r12_inv_id number,
        l_r12_item_key VARCHAR2 (200)

     );

     TYPE rec is table of var_rec index by pls_integer;

     --Variable declared to hold the result of your cursor.
     l_rec   rec;

   user_excep        EXCEPTION;
   v_err_count       NUMBER;
   PRAGMA EXCEPTION_INIT (user_excep, -24381);
   r12_item_id2      VARCHAR2 (200);
BEGIN
   OPEN tk_iflow_cur;

   LOOP                                                          --Cursor Loop

      FETCH tk_iflow_cur  BULK COLLECT INTO l_cur LIMIT 100; ---100 records assigned to variables

      FOR i IN 1 .. l_cur.COUNT             -- to store the cursor value
      LOOP                                                          --for Loop
         BEGIN
            --Comment : passing the cursor value to derive new records from different instance for updating the records
            SELECT DISTINCT segment1, inventory_item_id, item_type
              INTO l_rec(i).l_r12_iflow ,l_rec(i).l_r12_inv_id ,l_rec(i).l_r12_item_key
              FROM iflow.ifl_active_rules@R12_db_link
             WHERE  segment1 = l_cur(i).rule_id
              AND NVL (SEGMENT2, 'NULL') = NVL (l_cur(i).segment2 , 'NULL')
              AND organization_id = 5063;
         EXCEPTION
            WHEN OTHERS
            THEN
               l_rec(i).l_r12_iflow := 0;
               l_rec(i).l_r12_inv_id:= 0;
               l_rec(i).l_r12_item_key := '';
         END;

      END LOOP;                                                 --end for loop

      BEGIN
         FORALL i IN 1 .. l_rec.COUNT SAVE EXCEPTIONS -- for all the derived records i'm updating the target table.100 records i'm  updating
            UPDATE iflow_active_rules
               SET ora_org_id = 5063,
                   ora_inv_item_id = l_rec(i).l_r12_inv_id
             WHERE     iflow_id = l_rec(i).l_r12_iflow
              AND ora_inv_item_id = l_rec(i).l_r12_inv_id;

      EXCEPTION
         WHEN user_excep
         THEN
            v_err_count := SQL%BULK_EXCEPTIONS.COUNT;

            FOR i IN 1 .. v_err_count
            LOOP
               DBMS_OUTPUT.put_line (
                     'Error: '
                  || i
                  || ' Array Index: '
                  || SQL%BULK_EXCEPTIONS (i).ERROR_INDEX
                  || ' Message: '
                  || SQLERRM (SQL%BULK_EXCEPTIONS (i).ERROR_CODE));
            END LOOP;
      END;

      BEGIN
         FORALL i IN 1..l_rec.COUNT SAVE EXCEPTIONS
            UPDATE iflow_rules   --- updating openup system iflow cost details
               SET ora_org_id = 5063,
                   ora_inv_item_id = l_rec(i).l_r12_inv_id
             WHERE     iflow_id = l_rec(i).l_r12_iflow
             AND ora_inv_item_id = l_rec(i).l_r12_inv_id;

      EXCEPTION
         WHEN user_excep
         THEN
            v_err_count := SQL%BULK_EXCEPTIONS.COUNT;

            FOR i IN 1 .. v_err_count
            LOOP
               DBMS_OUTPUT.put_line (
                     'Error: '
                  || i
                  || ' Array Index: '
                  || SQL%BULK_EXCEPTIONS (i).ERROR_INDEX
                  || ' Message: '
                  || SQLERRM (SQL%BULK_EXCEPTIONS (i).ERROR_CODE));
            END LOOP;
      END;

      EXIT WHEN tk_iflow_cur%NOTFOUND;
    END LOOP;                                                 --End Cursor Loop

   COMMIT;
   CLOSE tk_iflow_cur;

END;


text:
Q: Are 'per-user' daemon services a new thing? I always had the impression that daemon processes were system-wide services that are run, owned, controlled and maintained by the 'init' system. However, I have recently learned that some daemon services (such as pulseaudio, as explained by this excellent answer) are run as 'per user' services, which are owned and controlled by individual users.
When did this start? Is it a new thing? Is having explicit support for 'per user' daemons by the init system something that was introduced by systemd, or is it typical of other init systems as well?

A: The fundamental mechanism is as old as fork+wait themselves, of course.  Handy command-line tools for doing this sort of thing have been around since the 1990s.  It in no way began with systemd.
Daniel J. Bernstein famous daemontools package could be used without superuser access by users who wanted to manage their own sets of services.  A user can quite happily set up a scan directory and run svscan against it.  The only missing part, that just needed to be written by an administrator, is the infrastructure to run svscans for users automatically, which is of course just a system service that drops privileges and runs svscan as the appropriate user.
The same is true for all of the other toolsets in the daemontools family, from Laurent Bercot's s6 to Wayne Marshall's perp.
Service management toolsets that provided such infrastructure out of the box, rather than expecting the system administrator to set up such services manually from scratch, largely began with Upstart, whose init program had a "session init" mode, which wasn't quite per-user.
launch agents on MacOS are a similar idea, although launchd is strongly coupled to Mach.
systemd came afterwards.  It can run in a per-user mode, with the system-wide service manager instantiating a template service unit for each user, on demand (via a somewhat complex combination of PAM add-ins, a Desktop Bus, and a "login" dæmon), that runs another instance of the systemd program.
Other toolsets providing this include the nosh toolset.
Further reading

*

*"Session Init". upstart Cookbook. Ubuntu.

*James Hunt, Stéphane Graber, Dmitrijs Ledkovs, and Steve Langasek (2012-11-12). Ubuntu Raring upstart user sessions.    Ubuntu.

*Nathan Willis (2013-04-17). Upstart for user sessions.  LWN.

*Jonathan de Boyne Pollard (2016).  "per-user system services".  nosh Guide.  Softwares.  jdebp.eu.

*Jonathan de Boyne Pollard (2016).  "per-user user services".  nosh Guide.  Softwares.  jdebp.eu.

*Create and Manage Upstart Services without Root Access

*https://unix.stackexchange.com/a/407863/5132

A: It has always been possible.
To make init (process 1), be the parent process. All you have to do, is fork and die. If the parent process dies, then init will adopt the orphan child.
The other part of demonetisation is to close stdin/stdout/stderr, or at least disconnect from a terminal.
None of this changes the owning user of the process. Only a process with capability CAP_SETUID (root) can do this. Allowing process owner to change by orphaning it would make security useless.
As for why. I don't know.


text:
Q: How should I integrate React with Rails? I know there is a lot of similar information out there, but I couldn't find anything specific to my use-case...
I'm on rails 5.2 using webpack and react is installed (and functioning). I'm trying to update a semi-complicated filter page I have, which functions as a very large multi-select checkbox filter (using form_for with remote=true). When the user checks a box, an AJAX call is made to rails and new data is displayed. The form is created dynamically based on data in my postgres db.
I have a basic react filter component already created using static data and it is updating my state fine (still working on creating the actual query). I just need some direction with the BEST (as in 'the most correct that you would do for the company you work for even if it is more complex and takes more time') way to pass in data to my react component and render it with the dynamic data.
I've seen main types of ways to do this. The first (which seems like a terrible idea) is to render a dummy div element with data attributes and then read that into the react component. The second is to 'do it in the controller' or 'use an api'. Does this mean setting up your rails project with an api endpoint and calling it via the react component? Does it mean using your existing controller routes and making the call that way?
edit: I've also seen several gems being used like webpacker-react, react_on_rails

A: I ended up going the API route. However, with Rails server-side rendering, I was getting two get requests, once via HTML and when the component mounted and made the API call, once again. I ended up switching the entire front-end to React because of this...
There must be an easier way to work this...


text:
Q: alt-text in images in keyboard tags We use a workaround where we use an image inside a keyboard tag   to depict things like the windows key in superuser. We recently got a post on meta.su from a visually impaired user who's requesting the use of alt-text for that sort of thing, since his screenreader dosen't pick it up. Is this possible within the realm of markdown? Can we have this as a feature if its not already in place? Shouldn't be too hard to fix existing questions if its doable, and would help loads with accessibility

A: Yes. It's possible. In fact, you did it right in your question. See:
![Windows Logo Key][2]
       ^^^ ALT TEXT ^^^

  [2]: http://i.stack.imgur.com/GIQBX.png

Renders as:

You can even add a title (tooltip text) by doing something like this:
  [2]: http://i.stack.imgur.com/GIQBX.png "Windows Logo Key"
                                           ^^^   TITLE  ^^^


text:
Q: UWP TabView Control not working with target version 16299 I am trying to use UWP(Community Toolkit) TabView Control, but it's throwing below exception:

Cannot find a Resource with the Name/Key UseSystemFocusVisuals [Line:
  35 Position: 91]'

Min Version and Target Version both are set to Build 16299. As per this MSDN documentation, it supports device family Universal, 10.0.16299.0 or higher
Windows 10 OS build is 17763. If I change the target version to 17763 then it's working as expected.
Any reason why it's not working when the target version is set to 16299?

A: Strictly speaking this isn't the UWP control but rather Windows Community Toolkit control. As it isn't made by Windows team the documentation is based on the human input and clearly there can be errors in it. It may also be a bug, the best thing to do is to submit the issue to their github: https://github.com/windows-toolkit/WindowsCommunityToolkit/issues

A: With the input from @Ivan, I checked for similar issue on WindowsCommunityToolkit GitHub site and seems that this issue was already reported.
According to the discussion on the issue, Fix is already implemented but will only be available when a new version of the toolkit is published. So until then if anybody else wants to have a fix, you need to define UseSystemFocusVisuals in your App.xaml as below:
<x:Boolean x:Key="UseSystemFocusVisuals">True</x:Boolean>


text:
Q: Array from server causing strange append behaviour in ajax success callback function? //FIRST ARRAY OF DATA FROM SERVER: arrayOne = A:1,B:2,C:3.
//SECOND ARRAY OF DATA FROM SERVER: arrayOne = A:4,B:5,C:6.

//ajax success call back:

function (data) {
    var i = data.arrayOne.length - 1;
    var Parent = $('
',{'class':'parent'}).appendTo('body');
    var A = $('
',{'class':'columns a','text':data.arrayOne[i].A}).appendTo('.parent');
    var B = $('
',{'class':'columns b','text':data.arrayOne[i].B}).appendTo('.parent');
    var C = $('
',{'class':'columns c','text':data.arrayOne[i].C}).appendTo('.parent');
}

//FIRST CALLBACK RETURNS: "123" appended as expected
//SECOND CALLBACK RETURNS: "123456 456" appended (expected output = 123 456).

After both callbacks, the "Parent" div from the first callback has "123456" appended to it, The "Parent" div from the second callback has "456" appended to it). Why is this happening, if I console.log instead of create the elements, it doesn't happen, so it has specifically to do with the elements being created.
Image of problem in Chrome for clarity: http://oi57.tinypic.com/10ygfhx.jpg
(Using Node.js and Express).

A: When the second callback is executed, you have two

 on the page.
You should change .appendTo('.parent'); to .appendTo(Parent); - that way you will reference the newly created div, not all .parent divs on the page.


text:
Q: dot error when displaying the number in the text return TextFormField(
      controller: _nameController,
      onChanged: (v) => _MyFormState.friendsList[widget.index] = v,
      decoration: InputDecoration(
        hintText: '$widget.index .nci eleman'
      ),
      validator: (v){
        if(v.trim().isEmpty) return 'kutulara eleman girişi yapınız';
        return null;
      },
    );

With the above code
'$widget.index .nci eleman'
in a post.
I want to get the 'widget.index' number.
But does not allow this.
In other languages
'$widget.\index'

did not work in the structure.
So how can I get data from a class using a dot with the $ keyword in flutter?

A: You need to use curly braces like this:
 InputDecoration(
    hintText: '${widget.index} .nci eleman'
  ),

Here is more about string interpolation in Dart.


text:
Q: Java Filters Performance Question I have two questions.  The first is do Filters add a lot of overhead to request.  We have a filter and it is set to run on the URL pattern /*.  This means it also runs on all the image request.  I think that this is not good for performance, but my co-workers think that it doesn't matter if the filter runs 5 or 6 times per request because the filter only has a couple of if statements.
Is there a way to have the filter run once per request, ignoring the image request.
Thanks Doug

A: Measuring is knowing. If well-written, I'd say, it's negligible. But if it's for example grabbing the session regardless of it's been created (and thus there's a chance that it will unnecessarily be created), then it may have a noticeable impact on performance and/or memory usage because creation of sessions isn't per-se cheap and sessions are stored in sever's memory for a longer term than the requests.
You may want to replace the url-pattern of /* by *.jsp or to move the restricted pages to a specific folder, e.g. /secured, /private, /pages, etc and alter the url-pattern accordingly to /secured/*, /private/*, /pages/*, etc and put all the static content in a different place, e.g. /static. This way the filter won't be invoked for static content anymore.

A: First, I agree with the Profile-first approach.
Second, as far as I know it depends, web-server use the same technique to invoke a specific servelt(/JSP)  as they use for filters.
In case the filter is filtering a static resource(e.g. jpg file), it's a bit of a waste,
In case the filter is filtering a dynamic resource (e.g. Servlet) it's negligible..
(Most of the Java web frameworks like struts and Jboss-seam are using filters heavily..)

A: It almost never useful to speculate about the performance implications of code without first profiling it. Unless the code being proposed in the filters is doing some operations you know to be slow then measure first before optimising.
Remember even though when you are writing a servlet it may seem like the only thing that happens is the code in your doGet() or doPost() methods a lot of other things happen before your servlet/filter code gets invoked. The servlet container processes the HTTP request bundles it up in Java objects and does all sorts of other processing before it hands over to your code.
If your servlet filters really are only a couple of if statements operating on data that is cheap to get (such as the request itself), it is unlikely this is going to be an issue for you.


text:
Q: Python 2.7 - Using Classes as Decorators for Timing and Memoization I'm completely new to Python and I'm currently working on a project where I have a Timer and Memoize class, both of which should have the ability to be used as decorators and can work with functions with any number of parameters.
Problem
My current problem is that I am trying to use both of them as decorators on a function; however, the Timer is only called on the first call of the function and not the second. For instance, using this code:
# Import the Memoize class from the memoization module
from memoization import Memoize

# Import the time module
import time

# Import the logging module
import logging

# Import the Timer class from the timer module
from timer import Timer

@Memoize
@Timer
def pass_and_square_time(seconds):
    # Call time.sleep(seconds)
    time.sleep(seconds)
    # Return the square of the input seconds amount.
    return seconds**2

def main():
    logging.getLogger().setLevel(logging.ERROR)

    print '\nFor pass_and_square_time({30}):'.format(n=num)
    print '\n\tThe initial call of pass_and_square_time(30) yields: {ret}'.format(ret=pass_and_square_time(30))
    print '\n\tThe second call of pass_and_square_time(30) yields: {ret}'.format(ret=pass_and_square_time(30))

returns the following:
For pass_and_square_time(30):

<function pass_and_square_time at 0x02B9A870> 30.003000021 seconds

    The initial call of pass_and_square_time(30) yields: 900

    The second call of pass_and_square_time(30) yields: 900

when I want it to return the seconds above that second call as well (Since that'd be the time of the second. The time above the initial call is the initial call's time). I believe that the @Memoize decorator is working properly on that second call since it shows up pretty much initially after the first rather than performing the time.sleep(30) call.

Timer
My Timer class is implemented as follows:
class Timer(object):
    def __init__(self, fcn, timer_name='Timer'):
        self._start_time = None
        self._last_timer_result = None
        self._display = 'seconds'
        self._fcn = fcn
        self._timer_name = timer_name
        self.__wrapped__ = self._fcn

    def __call__(self, *args):
        self.start()
        fcn_res = self._fcn(*args)
        self.end()
        print '\n{func} {time} seconds'.format(func=self._fcn, time=self.last_timer_result)
        return fcn_res

    '''
    start(), end(), and last_timer_result functions/properties implemented
    below in order to set the start_time, set the end_time and calculate the
    last_timer_result,  and return the last_timer_result. I can include more
    if you need it. I didn't include it just because I didn't want to make
    the post too long
    '''

Memoize
My Memoize class is implemented as follows:
class Memoize(object):
    def __init__(self, fcn):
        self._fcn = fcn
        self._memo = {}
    self.__wrapped__ = self.__call__

def __call__(self, *args):
    if args not in self._memo:
        self._memo[args] = self._fcn(*args)

    return self._memo[args]

References Used
The references I looked at and tried to model my classes off or are:
Python Class Decorators

*

*https://krzysztofzuraw.com/blog/2016/python-class-decorators.html

*Using classes as method decorators

*Python decorator best practice, using a class vs a function
Python Memoization

*

*https://www.python-course.eu/python3_memoization.php

Thank You for Reading and for Any Help You Can Provide!

A: With your code, you are memoizing a timed function, which means the timing code is also skipped when the arguments are found in the cache. If you reverse the order of the decorators
@Timer
@Memoize
def pass_and_square_time(seconds):
    # Call time.sleep(seconds)
    time.sleep(seconds)
    # Return the square of the input seconds amount.
    return seconds**2

now you are timing a memoized function. Whether or not the arguments are found in the cache, you time the call to the memoized function.


text:
Q: Yii URL configuration I am creating an yii application and i made some changes to it :
I created a default folder and admin folder and i put all folders(MVC) in side each one and i  redirected all unknown request like :
127.0.0.1/myframework to 127.0.0.1/myframework/default with .htaccess and it work just fine.
It works when i go to default page but when i want to go deeper to another controller like 127.0.0.1/myframework/default/contactus it return not found (I made MVC for contactus) so i was thinking i should make changes to main.php in 'urlManager' section but i don't know how and all my efforts fails . so any help would be appreciated .
my structure is like:

root
admin

    asset

    protected

    ...

default

    asset

    protected

    ...

A: Thank you all guy's for your comments they lead me to the solution and the solution is :
First - the complete URL is something like :

127.0.0.1/myframework/default/index.php/services

works just fin with my previous configuration , i just missed typing index.php , without any configuration in main.php with "urlManager" section , pretty obvious , i know .
For getting ride of annoying  "index.php" in URL , .htaccess do the magic .
So i put two .htaccess in my project one in the root other in the default folder.
Root htaccess contain :

RewriteEngine on
RewriteRule ^$ http://[local-host]/myframework/default/index.php

and default folder htaccess:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME}
  !-d
RewriteRule . index.php


text:
Q: Make Controller get information from a directive I have a directive, that in its scope has an object. This is static information right now and I want to make this visible for every controller in my app. Is there any way to do this?

A: Use global scope ($rootScope ) for example, if you want to use it everywhere
UPDATE:
some example and answer here:
How do I use $rootScope in Angular to store variables?


text:
Q: MaaS server with local kvm - How to bridge to dhcp interface I have a MaaS server, it has two network interfaces. One external eth0, and one for the internal network eth1(Nodes network). eth1 is where the DNS and dhcp server managed interface. I want a mix of physical servers, and one KVM VM run on the MaaS server. I manage to create VM's to PXE Boot, and created a bridge br01 bridged with the eth1 interface.
auto br0
iface br0 inet dhcp
        bridge_ports eth1
        bridge_stp off
        bridge_fd 0
        bridge_maxwait 0

And that bridge is associated with the VM's network.
Now this works if created on an external server connected to the eth1 network(tried earlier as proof of concept).
But what I want is to move this KVM setup over to the MaaS Server itself(to free up a physical server as Node), and then this network configuration is not working.
The network part of the VM's xml file:
<interface type='bridge'>
      <mac address='52:54:00:3c:a5:18'/>
      <source bridge='br0'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>

I created the VM using:
sudo virt-install --name=bootstrap-juju --ram=2048 --vcpus=1
--disk path=/var/kvm/images/bootstrap-juju.qcow2,bus=virtio,size=20
--pxe --graphics=vnc --hvm --network bridge=br0,model=virtio
--os-variant=ubuntuprecise

It seems that there is a problem with the bridge, when I sudo ifup br0 I get:
DHCPDISCOVER on br0 to 255.255.255.255 port 67 interval 3 (xid=0xcb27ff35)
No DHCPOFFERS received.

So it seems the bridge is not getting DHCP address from the internal dhcp server.
Does anyone have any pointers here?

A: Ok, I had a few problems. My eth1 was still defined as static in my /etc/network/interfaces. I had to remove it, and change my br0 with matching static settings. Then on the Cluster master in MaaS, change the Managed DHCP-DNS interface from eth1 to br0.
Hope this helps someone.


text:
Q: Find and replace with contents of a file I have a file that begins with a few "include" statements, like this:
include foo.xyz
include bar.xyz
do c
do d

Suppose the file foo.xyz contains do a and the file bar.xyz contains do b. How can I write a script that replaces each include file.xyz statement with the contexts of file.xyz? I want to end up with the following output:
do a
do b
do c
do d

I tried the solution in "Replace string with contents of a file using sed" but there the filename is hard-coded. I would like the filename to be dynamically generated, depending on the include argument.

A: Here's a simple recursive version with awk. You must create a script in your PATH with
#!/bin/bash
awk '
$1=="include" && NF>=2 {
   system("'$0' " $2)
   next
}
{print}' "$@"

It assumes filenames have no special chars (including spaces) in them.
The awk checks the first word for include, then calls the script to process the file given as 2nd word. Other lines are printed. Note that the $0 here is outside the single quotes of the awk, so is a shell $0, ie the script name.

A: grep -n '^include ' yourfile |
sed  -e 's/:[^ ]* /{ r /'    \
     -e 'G;s/.$/&b&}/'       |
sed -nf - -ep       yourfile

that should work. grep finds those include line numbers, the first sed modifies its output to line-number-specific [num]{r fname\nb\n} commands, and the second sed prints every line which isn't one of those the first scripts for it.
{   for   x in  a b
    do    echo "do $x">"file$x.xyz"
          echo "include file$x.xyz"
    done; printf "do %s\n"  c d
}   >yourfile
cat  yourfile

include filea.xyz
include fileb.xyz
do c
do d

That just generates your sample and shows yourfile.
And this works:
grep -n '^include ' yourfile |
sed  -e 's/:[^ ]* /{ r /'    \
     -e 'G;s/.$/&b&}/'       |
sed -nf - -ep       yourfile

do a
do b
do c
do d

the read files can be any size, though, of course, and are not restricted to the single line. The filenames themselves are restricted to a single line, though, but are otherwise more or less unrestricted (depending on your sed - some older seds had arbitrary name-length limits, but most used today don't).

A: cat  $(grep '^include' file.txt | cut -d" " -f2); grep -v '^include' file.txt

First command will grep the line starting with include in file.txt, cut the file name part and then cat it.
Next command will print all lines except line starting with include in file.txt


text:
Q: Error using pip install on ubuntu 16.04 LTS I was trying to install a python module for both python3 and python2, and I had to upgrade pip, however, after running
pip install --upgrade pip

it would give me the following error:
Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/ubuntu/.local/lib/python3.5/site-packages/pip/__main__.py", line 21, in <module>
    from pip._internal.cli.main import main as _main
  File "/home/ubuntu/.local/lib/python3.5/site-packages/pip/_internal/cli/main.py", line 60
    sys.stderr.write(f"ERROR: {exc}")
                                   ^
SyntaxError: invalid syntax

I am not sure what the issue is, and whenever I use the command to install anything else, it's the same issue
Edit: I also tried to use pip3 and ran into the same error

A: Not sure but I think that f-strings syntax is only available python3 and onwards, maybe trying pip3 install --upgrade [pip|pip3]


text:
Q: What is the metric used here? Suppose we consider a set of all $n\times n$ matrices and if we consider them as metric space what is the metric we are using?
Is that determinant the metric we are following or is there any metric
(other than discrete metric)
( I'm working on the problem : is $GL(n,\mathbb R)$ dense in $M(n,\mathbb R)$

A: Since the set of square matrices of size $n$ is finite-dimensional, it does not matter: all norms are equivalent, they induce the same topology.
By the way, there is a ambiguity in your question, the title says norm and the core of the question metric, the claim above is false for metrics.


text:
Q: WPF DesignTime Support for generated control I'm trying to build a control or a style that will take care of the usual "label on the left, control on the right" situation. The label column should be same width for all labels.
My ultimate goal is to have a syntax something like this:
<l:LayoutGroup>
    <TextBox  l:LabelHelper.Label="111" />
    <ComboBox l:LabelHelper.Label="Nice Box" ItemsSource="{Binding list}"/>
    <ComboBox />
    <Calendar l:LabelHelper.Label="Nice Calendar" HorizontalAlignment="Left"/>
    <TextBox l:LabelHelper.Label="eyyoo"/>
</l:LayoutGroup>

I actually got this working in 2 different ways. But both do not offer design time support.
The shortest / best setup i could come up with that does offer designtime support is the following:
<StackPanel Orientation="Vertical" Grid.IsSharedSizeScope="True">
    <l:LayoutItem Title="cool textbox">
        <TextBox />
    </l:LayoutItem>
    <l:LayoutItem Title="short">
        <TextBox />
    </l:LayoutItem>
    <l:LayoutItem Title="ye">
        <ComboBox />
    </l:LayoutItem>
</StackPanel>

A LayoutItem is a usercontrol with as the following content:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto" SharedSizeGroup="Whatever"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding Path=Title}"/>
    <ContentPresenter Grid.Column="1" Content="{Binding Child"}/>
</Grid>

So its essentially just a bunch of grids, with exactly one child and a shared sizegroup.
What i do to get my goal version to work:
public static readonly DependencyProperty LabelProperty = DependencyProperty.RegisterAttached("Label",
    typeof(string), typeof(LabelHelper), new UIPropertyMetadata("", Callback));

private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var child = d as Control;
    var parent = LogicalTreeHelper.GetParent(child);
    if (!(parent is StackPanel pnl))
        return;

    pnl.Children.Remove(child);

    var wrapper = new LayoutItem
    {
        Title = GetLabel(child),
        Child = child
    };

    pnl.Children.Add(wrapper);
}

public static string GetLabel(DependencyObject d) => (string)d.GetValue(LabelProperty);
public static void SetLabel(DependencyObject d, string value) => d.SetValue(LabelProperty, value);

I take whatever control has the attached property, remove it, wrap it in a layoutitem and add that layoutitem instead.
It works, but there is no designtime support. And i see why its difficult for the designer to support this. I'm creating a different control "at runtime", but its not really runtime, because i noticed that this "Callback" method does update the designtime view, if its not too complicated...
Is there any way to get my desired Syntax to work? I feel very close, but all approaches either add a Textblock, a grid, anything to the logical tree that isn't actually in xaml at designtime. That seems to be the main problem and i dont know if its solvable?
I just realized there almost is desintime support now. It works when i add a new Control with the LabelHelper. It just does not adjust if i change the longest label. So the Callback fires in design time, but something isnt quite right.


text:
Q: Uploading multiple images with random file names Right now, all the images upload fine with their file names, but I want to change the file names to random names (to avoid names with symbols) but when I try to do so, if I upload more than one image, they will all be the same image of the last selected file.
<input type='file' name='file[]'>

And the conditions:
 $allowed = array('jpg', 'JPG', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
        $max_file_size = 2048*1000;
        $path = "images/images/"; // Upload directory
        $count = 0;
        if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
            if ($_FILES['file']['name'] != "") {
                foreach ($_FILES['file']['name'] as $f => $name) {
                    if ($_FILES['file']['error'][$f] == 4) {
                        continue;
                    }
                    if ($_FILES['file']['error'][$f] == 0) {
                        if ($_FILES['file']['size'][$f] > $max_file_size) {
                            $errors[] = "$name is too large!";
                            continue;
                        }
                        else if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $allowed) ){
                            $errors[] = "$name is not a valid format";
                            continue;
                        }
                        else{
                            if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))
                            $images = array(
                                'images'    => $path.$name,
                                'ad_id'     => $_POST['id']
                                );
                                add_images($images);
                            $count++;
                        }
                    }
                }
            }
        }

A: You can prepend the index to the image name. Try to change
if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))

to
if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$f.$name))

(and the same principle for 'images'    => $path.$name,)


text:
Q: Possible Borel subgroups of GL_n? I am trying to understand the interaction between Borel subgroups of $GL_n$ and its roots. Is it correct to say that for any choice of roots among each pair of reciprocal roots
there is a Borel subgroup containing those root subgroups? (Meaning that exactly those roots appear on the decompsition of its Lie algebra) If not, what is the precise condition on the choice of roots that is needed for such a Borel to exist?

A: The question itself seems too elementary for this site, since it just involves the standard axiomatic treatment of root systems as in Bourbaki Groupes et algebres de Lie,
VI.1.7.   The question is really about an arbitrary reductive algebraic group (with nontrivial derived group) over an algebraically closed field, along with its Borel subgroups in natural bijection with systems of positive roots relative to a fixed maximal torus.   Such a torus $T$ lies in exactly $|W|$ Borel subgroups, where $W=N_G(T)/T$ is the Weyl group.   At this point the axiomatic theory takes over and provides straightforward criteria for a given "closed" set of roots to be the positive roots for some choice of simple roots: the set has to be disjoint from its negative and together with its negative exhaust all roots (Prop. 20, Cor. 1).

A: Not every collection of choices between roots $\alpha$ and $-\alpha$ is "allowed". Yes, there is a partition of the set of all roots into positive $\Phi$ and negative $-\Phi$, but, also, $\Phi$ must be closed under addition. In the case of $GL(n)$, the Weyl group (permutation matrices, if you like) acts simply-transitively on the set of such choices, and/so there are exactly $n!$ such choices, rather than the $2^{n(n-1)/2}$ choices of sign.
[Edit:] In response to @Brad H-D's comment/query: yes, I was a bit glib... Indeed, it is not the case that all possible (iterated) sums of positive roots are roots, since this would (erroneously) require that there be infinitely-many, etc. Rather, as Brad H-D leadingly-asked, it means that either the sum of two "positive" roots is a "positive" root, or is not a root at all. (Thx, Brad H-D.)


text:
Q: Geometric understanding of the Cross Product Say you have vectors $v$ and $w$. Let there cross product be denoted by $x$ so that:
$$v \times w = x$$
According to Wikipedia:
$$x_x = v_yw_z - v_zw_y$$
$$x_y = v_zw_x - v_xw_z$$
$$x_z = v_xw_y - v_yw_x$$
This is equivalent to saying:
$$x_x = \left|\begin{matrix}v_y&v_z\\w_y&w_z\end{matrix}\right|$$
$$x_y = \left|\begin{matrix}v_z&v_x\\w_z&w_x\end{matrix}\right|$$
$$x_z = \left|\begin{matrix}v_x&v_y\\w_x&w_y\end{matrix}\right|$$
The determinant can be interpreted as the area spanned by the column vectors. Could you give me a geometric explanation of why the area of those above vectors give the coordinates of the cross product? Thanks!
EDIT: An interpretation for a 2x2 matrix is fine too

A: Let $P$ be the paralellogram spanned by the vectors $a$ and $b$ and let $\phi$ be the angle between $a$ and $b$. Then we have
\begin{eqnarray*}
(Area(P))^2 & = & |a|^2|b|^2(\sin(\phi))^2 \\
& = & |a|^2|b|^2-|a|^2|b|^2(\cos(\phi))^2 \\
& = &|a|^2|b|^2-(a\cdot b)^2 \\
& = & (a_1^2+a_2^2+a_3^2)(b_1^2+b_2^2+b_3^2)-(a_1b_1+a_2b_2+a_3b_3)^2\\
& = &(a_2b_3-a_3b_2)^2+(a_3b_1-a_1b_3)^2+(a_1b_2-a_2b_1)^.2
\end{eqnarray*}
So the area of $P$ is equal to the length of the vector $(a_2b_3-a_3b_2,a_3b_1-a_1b_3,a_1b_2-a_2b_1) = a \times b$. With the coordinates you gave.

A: There is a geometric interpretation of this in terms of the areas of the projections of the parallelogram $P$ spanned by $\bf{v}$ and $\bf{w}$ to the coordinate planes. Let $\bf{n}$ be a unit vector perpendicular to the plane spanned by $\bf{v}$ and $\bf{w}$. Projecting this plane to the $yz$-plane is a map which decreases area by a factor of $\bf{i}\cdot \bf{n}=\bf{n}_x$, where $\bf{i}=(1,0,0)$. The two planes intersect in a line, for which projection preserves length, and for a line orthogonal to this line of intersection, the projection multiplies length by $\bf{n}_x$, so area changes by a factor of $\bf{n}_x$. As you note, each coordinate of the cross product is the (signed) area of the parallelogram spanned by the projections of $\bf{v}$ and $\bf{w}$ to each coordinate plane (which are the column vectors you refer to). So the length of the cross product is $|\bf{n}|\cdot Area(P) = Area(P)$. So this derives this formula (modulo signs) from the property that the cross product $\bf{v}\times \bf{w}$ is perpendicular to $\bf{v}$ and $\bf{w}$, and has magnitude $|\bf{v}\times \bf{w}|=Area(P)$, up to choices of signs. The sign choices are forced by the choice of dot product, which by changing the coefficients could be of different signatures.

A: There is indeed a geometric interpretation of $\bf{u}\times\bf{v}$ in terms of the areas of the projections of the parallelogram $\bf{P}$ spanned by $\bf{v}$ and $\bf{w}$ onto the coordinate planes.
I'll start from scratch.

Motivating problem:  We wish to create a vector perpendicular to u,v, i.e. construct w s.t. $\bf{w}\cdot \bf{u} = \bf{w}\cdot \bf{v} = 0$.

Two equations in 3 unknowns: we can derive w as $\lambda(u_2 v_3 - u_3 v_2,$ [3&1], [1&2]$)$.

So let's define $\bf{u}\times \bf{v}$ as ($u_2 v_3 - u_3 v_2$, [3&1], [1&2]).

Observe $u_2 v_3 - u_3 v_2$ is just the signed area of the $(u_2, u_3)$, $(v_2,v_3)$ parallelogram. (2D determinant -- you can work it out with triangles).  So we can rewrite our definition:

Define $\bf{u}\times \bf{v}$ as $(A_{yz}, A_{zx}, A_{xy})$   where $A_{\text{plane}}$ = signed area of u,v parallelogram projected onto that plane

Notice by symmetry, switching u and v just changes the sign of $u_p v_q - u_q v_p$, so we have:

$\bf{u}\times \bf{v} = -\bf{v}\times \bf{u}$

Notice also:

$\bf{i} \times \bf{j} = \bf{k}$

So we get our 'Right Hand Rule'.

Now it makes sense to ask: "Could we have skipped the algebra?" i.e. arrived at this definition purely from geometric insight. And the answer is yes!
Let n be the unit vector perpendicular to u,v.

WAIT! There is a problem here -- there are 2 choices: -n also is a valid candidate.
So if you are given i,j your choices are k,-k. So let's choose k.  Looking at our right-hand, i for thumb, j for index finger and k corresponds to the direction the next finger is pointing. So we have an orientation. Let's call this the Right Hand Rule.
So let's choose the n that satisfies the same orientation.

We can show that the ratio of the area of the uv-parallelogram to it's yz projection gives $\bf{n}_x$, similarly for xz$\to \bf{n}_y$ and xy$\to \bf{n}_z$:

Here is a simplification that will illustrate this...
Let's say we have y as depth, z going upwards. We have some near-flat plane (so the normal is pointing nearly straight up). Suppose we draw a unit grid on it. Now we are going to drop each point onto the xy-plane so $(x,y,z)\to(x,y,0)$ and calculate the change in area. Furthermore let's say we have rotated things so that our plane's normal vector has depth component = 0.
So alternatively we could set this up by imagining two xy-planes. And rotate one of them slightly around the y-axis, give it a unit grid, and "drop" this grid onto the other (axis-aligned) plane.
We want the area of a projected grid square.
It should be obvious that the depth-component (y) of any point on our plane is unchanged by this projection. And a simple calculation reveals that the x-component is just $cos(\theta)$, where $\theta$ is the angle between the normals, otherwise known as $\bf{k}\cdot \bf{n}=\bf{n}_z$, where $\bf{k}=(0,0,1)$.
So, the xy-area multiplier is $\bf{n}_z$ as required: $A\bf{n}_z = A_{xy}$

Let's write these parallelogram areas using $A$.
So we have: $A_{xy} = A \bf{n}_z$, sim. for y & z.
So $A\bf{n} = (A_{yz}, A_{zx}, A_{xy})$
(EDIT: Bold rendering incorrectly for $A_{xy}$ in the above line, anyone?)
So if we define $\bf{u}\times \bf{v}$ as $(A_{yz}, A_{zx}, A_{xy})$ then we have $\bf{u}\times \bf{v} = A \bf{n}$, i.e. $\bf{u}\times \bf{v}$ is perpendicular to u,v and of length $A$.
QED!

A: Basically we want a coordinate-free proof that if $\mathbf{n}$ is a unit normal vector of an oriented plane $\Pi$ then $(\mathbf{a}\times\mathbf{b})\cdot\mathbf{n}$ is the signed area of the parallelogram spanned by the orthogonal projections of the two vectors $\mathbf{a}$ and $\mathbf{b}$ onto $\Pi$. (My definition of $\mathbf{a}\times\mathbf{b}$ is the unique vector whose size is the area of the parallelogram spanned by $\mathbf{a}$ and $\mathbf{b}$ and whose direction is perpendicular to it, oriented according the right-hand rule.) Then we can apply this with $\mathbf{n}=\mathbf{e}_1,\mathbf{e}_2,\mathbf{e}_3$.
Decompose $\mathbf{a}=\mathbf{a}_{\|}+\mathbf{a}_\perp$ and $\mathbf{b}=\mathbf{b}_{\|}+\mathbf{b}_\perp$ as parallel and perpendicular components with respect to the plane $\Pi$. Then FOIL out the terms of $\mathbf{a}\times\mathbf{b}$ and notice that $\mathbf{a}_{\|}\times \mathbf{b}_\perp$ and $\mathbf{a}_\perp\times\mathbf{b}_{\|}$ are both orthogonal to $\mathbf{n}$ (since the $\perp$ components are parallel to $\mathbf{n}$) hence vanish when the dot product with $\mathbf{n}$ is applied, and $\mathbf{a}_\perp\times\mathbf{b}_\perp=\mathbf{0}$ since the vectors are parallel, leaving at last the equality $(\mathbf{a}\times\mathbf{b})\cdot\mathbf{n}=(\mathbf{a}_{\|}\times\mathbf{b}_{\|})\cdot\mathbf{n}$. Observe $\mathbf{a}_{\|}\times\mathbf{b}_{\|}$ is parallel to $\mathbf{n}$ and its signed length is the signed area of the parallelogram of $\mathbf{a}_{\|}$ and $\mathbf{b}_{\|}$ spanned within $\Pi$, so the result follows.


text:
Q: DotNetOpenAuth with log4net 1.2.11 Is there a way to make DotNetOpenAuth logging  work with the new version of log4net?
For some reason it doesn't seem to work for me (I tried both the old and the new publicKeyToken of log4net).
Thanks

A: Have you tried a binding redirect?
<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="log4net" publicKeyToken="**key**" />
            <bindingRedirect oldVersion="**versionDNOAbuiltWith**" newVersion="**yourversion**" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>


text:
Q: Tkinter-Python- Run a class loop with multiple variables I need to re-iterate an algorithm (written as a class) for a certain number of times depending from the input ( a couple of values in this case) which I give him.
For example:
class Main:

    def __init__(self, master):

        #here I decide the numbers of iterations (and number of couples values)
        self.n=tk.Entrywidget( master, textvariable=StringVar)
        # now I must create something for the n couple of values,
        # thinking about n couples of entry, don't know how to bind
        # the number of entry widgets to the value of n
        # so I'll create just one
        self.aentry=tk.Entrywidget( master, textvariable= StringVar)
        self.bentry= tk.Entrywidget (master, textvariable= StringVar)
        runbutton= tk.Button( master, command= self.run)

    def run(self):

        self.class1= Class1(self)

class Class1:  #here I'll write the algoritm

    def __init__(self,master):

        self.a= master.aentry.get()
        self.b= master.bentry.get()
        self.c= self.a +  self.b

So I would like to write n couples of values, for example:
n=2 with a1=1, b1=3 and a2=3, b2=5 with 4 and 8 as a result from the Class1 algorithm!
I was thinking about a for cycle but can't do it with multiple variables!