text:
Q: Agent Analyst/Agent-Based Modeling in ArcGIS Book Chapter 6 implementation problem I want to study on Agent Based Modeling in ArcGIS with Agent Analyst extension. I'm doing the tutorials of the book that is written by Kevin M.Johnston (http://resources.arcgis.com/en/help/agent-analyst/) In Chapter 6 there is an exercise about agents on network. I'm not experienced on Java therefore I can not make a comment about the errors Java give. I want to implement the codes on sample work into my study with changing the destination paths and parameters (Figures below).

It is compiled but it gives the error below.
"Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Active"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Float.valueOf(Float.java:388)
    at java.lang.Float.(Float.java:489)
    at default_package.Exercise3.setupPlaces(Unknown Source)
    at default_package.Exercise3.initAgents(Unknown Source)
    at default_package.Exercise3._build(Unknown Source)
    at uchicago.src.simbuilder.base.gis.GISSimModelImpl.begin(GISSimModelImpl.java:107)
    at uchicago.src.sim.engine.BaseController.beginModel(BaseController.java:331)
    at uchicago.src.sim.engine.AbstractGUIController.beginModel(AbstractGUIController.java:218)
    at uchicago.src.sim.engine.Controller.beginModel(Controller.java:646)
    at uchicago.src.sim.engine.BaseController.startSim(BaseController.java:346)
    at uchicago.src.sim.engine.Controller.startSim(Controller.java:602)
    at uchicago.src.sim.engine.Controller$2.actionPerformed(Controller.java:388)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)
    at java.awt.Component.processMouseEvent(Component.java:6297)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
    at java.awt.Component.processEvent(Component.java:6062)
    at java.awt.Container.processEvent(Container.java:2039)
    at java.awt.Component.dispatchEventImpl(Component.java:4660)
    at java.awt.Container.dispatchEventImpl(Container.java:2097)
    at java.awt.Component.dispatchEvent(Component.java:4488)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
    at java.awt.Container.dispatchEventImpl(Container.java:2083)
    at java.awt.Window.dispatchEventImpl(Window.java:2489)
    at java.awt.Component.dispatchEvent(Component.java:4488)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:674)
    at java.awt.EventQueue.access$400(EventQueue.java:81)
    at java.awt.EventQueue$2.run(EventQueue.java:633)
    at java.awt.EventQueue$2.run(EventQueue.java:631)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:647)
    at java.awt.EventQueue$3.run(EventQueue.java:645)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:644)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)"

Is there any one encountered this problem?

A: Due to my limited Java experience I can't really completely help you unfortunately, but seeing the answer is taking a bit of time, I hope to be able to get you on your way again.
The actual error is in the first line:
"Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Active"

Where NumberFormatException  is the error you're looking for. In the second line we can see what the problem is:
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)

Where FloatingDecimal.readJavaFormatString comes up. At this point I'm not sure, I'm guessing that it is expecting a decimal (float) input, but getting something else? I would suggest reading further into this on SO, for a possible answer.
Otherwise: as Java is an object-oriented language try to use your IDE's debugger to step into the error and see what object is "Active" at the moment the error is thrown.
It might also be better to ask this question on StackOverflow instead, where the actual Java programmers are at. Java is used very little in GIS (from personal experience).


text:
Q: How can i alert if the input is not enough after submit with jquery I have a form and want to sum all persons which where entered and alert something like: "thats not enough what you have entered" after submit. The minimum sum must be 10, if there not enough people the form will not be sent. I've tried something like:
jQuery(function($){
    //if submit button is clicked
    $('#submit').click(function () {
        var $form = $('#booking'),
        $summands = $form.find('.persons'),
        $form.delegate('.persons', 'change', function() {
            var sum = 0;
            $summands.each(function() {
                var value = Number($(this).val());
                if (!isNaN(value))
                    sum += value;
            });
            alert( " + sum + " );
        });
    else {
        send email or something
    }

Could someone give me a hint please?
Thank you

redpajama_set_name: RedPajamaStackExchange


text:
Q: Divergence of Riemann sums in the Itô integral Some motivation:
Let $W$ be a standard Brownian motion, and $X$ an integrable process with respect to $W$, i.e. progressively measurable with respect to the natural filtration of $W$ and square integrable on compacts almost surely.
It is known that if $X$ is continuous, then for any sequence of partitions $\mathcal P_n$ of $[0, T]$ with mesh going to $0$, the Riemann sums
$$\sum_{i = 0}^{K_n - 1} X_{t^n_i} (W_{t^n_{i+1}} - W_{t^n_i})$$
converge in probability to the Itô integral
$$\int_0^T X_t \, dW_t.$$
Here we have written $\mathcal P_n := \{t^n_0, \dots, t^n_{K_n}\}$.
Now it follows that if we take a suitable subsequence of partitions, the Riemann sums converge almost surely to the Itô integral. But I am wondering how almost sure convergence fails to begin with! It is unclear to me how a certain choice of partitions could lead to the limit fluctuating instead of existing.
Questions:

*

*Can anyone provide an explicit example of an almost surely continuous process $X$, integrable with respect to $W$, and a sequence of partitions $\mathcal P_n$ with mesh going to $0$ such that

$$\lim_{n \to \infty} \sum_{i = 0}^{K_n - 1} X_{t^n_i} (W_{t^n_{i+1}} - W_{t^n_i})$$
fails to exist with some positive probability, or even full probability?

*For a given $X$, are there some growth conditions on $\mathcal P_n$ that ensure the integral would converges a.s.?

A: Here is an example of an integrand $X$ and a deterministic sequence of partitions such that almost surely, the limit fails to exist.
Indeed, consider $X = W$. The associated Riemann sums are
$$\lim_{n \to \infty} \sum_{[u, v] \in \mathcal P_n} W_u (W_{v} - W_{u}).$$
We may rewrite this as
$$\frac{1}{2} W^2_T - \frac{1}{2} \sum_{[u, v] \in \mathcal P_n} (W_u - W_v)^2.$$
Now, Exercise 1.15 in Peres and Mortens' Brownian Motion yields a sequence of deterministic partitions $\mathcal P_n$ such that $\limsup_{n \to \infty} \frac{1}{2} \sum_{[u, v] \in \mathcal P_n} (W_u - W_v)^2 = \infty$, almost surely, whence the result follows.

A: Here is a rough idea. Let
$$X_{t}^{N}=\sum_{\lvert n\rvert\leq N} e_{n}\xi_{n}\text{ and } Y_{t}^{N}=\sum_{\lvert n\rvert\leq N}\operatorname{sgn}(n) e_{n}\xi_{n},$$
for independent $\xi_{n}$ Gaussians and eigenbasis $e_n$, both of which converge to Brownian motion. Then
\begin{equation*}
\int_{0}^{2\pi }Y^{N}_{t}d X^{N}_{t}=\frac{\xi_{0}^{2}}{2}+\sum_{n=1}^{N}\frac{\xi_{n}^{2}+\xi_{-n}^{2}}{n}\to \infty
\end{equation*}
diverges even though $X^N,Y^N \rightrightarrows \text{Brownian motion}$.
But then due to the uniform convergence to Brownian motion, we should be able to compare the above diverging integral to the sum from the main question.
In terms of the mesh, Bananach gave an answer to What is the explicit obstruction to almost sure convergence in stochastic integrals?:

If the meshes are chosen regularly with meshwidth $h_n\to 0$ such that
$$
 \sum_{n=1}^{\infty}\mathbb{E}\left[
 \int_{0}^{1}(f(\omega,x)-f(\omega,\lfloor x/h_n\rfloor h_n)^{2}\;dx\right]<\infty, $$ then the
Itô sums converge almost surely to the Itô integral (under usual conditions on the integrand).

This is proven, for example, in Remark 7.7 of the textbook Brownian motion by Mörters and Peres. It is an immediate consequence of Itô's isometry.
If $f$ is Lipschitz, this basically means that any $h_n=n^{-1-\epsilon}$ guarantees pathwise convergence.

At Understand better stochastic integral through a.s. convergence, TheBridge answered:

So first why is stochastic integration impossible (*) ?
The proof of this lies on the Banach–Steinhaus Theorem which allows us to prove that:

Th. 56 of Protter's book :
If the sum $S_n=\sum_{i=1}^{n} f(t^{(n)}_i).(B_{t^{(n)}_{i+1}} - B_{t^n_i})$
converges to a limit for every continuous function $f$ then $B$ is of finite variations.

(*) You can take a look at the argument in Philip E. Protter's book "Stochastic Integration and Differential Equations" at Chapter 1 Section 8.


text:
Q: 'REQUEST' object always undefined in NestJS dynamic module I create some dynamic module(log.module.ts)
@Global()
@Module({})
export class LoggerModule {
 public static forRoot(options: WinstonModuleOptions = null):  DynamicModule {

 const providers = createWinstonProviders(options);
 return {
   module: LoggerModule,
   providers: providers,
   exports: providers,
  };
 }
}

And provider(log.provider.ts)
export function createWinstonProviders(loggerOpts:WinstonModuleOptions): Provider[] {
   return [
   {
    provide: 'logger',
    useFactory: () => new LoggerService(loggerOpts),
    scope: Scope.TRANSIENT
   }];
}

My problem is that on 'LoggerServie' I try to get 'REQUEST' object like in documantion : https://docs.nestjs.com/fundamentals/injection-scopes but get always undefined.. (log.service.ts)
@Injectable({ scope: Scope.REQUEST })
export class LoggerService {
 private readonly logger: any;
 constructor(loggerOpts: WinstonModuleOptions = null,
 @Inject(REQUEST) private readonly request?: Request) {
 this.logger = createLogger({});
 }

  test(message) {
   console.log(this.request)-----> undefined!
   return "test";
  }
}

My case is different from documentation because I initialise my service with new keyword and return that on 'useFactory' ...
Thanks for your help !

A: So, for anyone have a similar issue: The problem was with the 'winston' options implemention .
This is my implementation for logger using winston,if you have any question you could ask me :
logger.module.ts
import { DynamicModule, Module } from '@nestjs/common';
import { WinstonModuleOptions } from './logger.interfaces';
import { createWinstonProviders } from './logger.providers';
import { LoggerService } from './logger.service';

@Module({
  providers: [LoggerService],
  exports: [LoggerService],
}) export class LoggerModule {
  public static forRoot(options?: WinstonModuleOptions): DynamicModule {
    const providers = createWinstonProviders(options);
    return {
      module: LoggerModule,
      providers: providers,
      exports: providers,
    };
  }
}

logger.providers.ts
  import { Provider, Scope } from '@nestjs/common';
  import { WinstonModuleOptions } from './logger.interfaces';

  export function createWinstonProviders(loggerOptions: WinstonModuleOptions): Provider[] {
  return [
    {
      provide: 'loggerOptions',
      useValue: loggerOptions || null,
      scope: Scope.TRANSIENT
    },
  ];
}

logger.service.ts
 import * as winston from 'winston';
    import { Injectable, Scope, Inject } from '@nestjs/common';
    import { REQUEST } from '@nestjs/core';
    import { Request } from 'express';
    import { WinstonModuleOptions } from './logger.interfaces';
    import { defaultLoggerOptions } from './logger.constants';

    @Injectable({
      scope: Scope.TRANSIENT
    })
    export class LoggerService {
      private name: string;

      constructor(@Inject('loggerOptions') private readonly loggerOptions: WinstonModuleOptions, @Inject(REQUEST) private readonly request: Request) {
        this.name = loggerOptions.name;
        winston.loggers.add(this.loggerOptions.name, loggerOptions.options || defaultLoggerOptions());
      }

      private logMessage(message, level) {
        const logger = winston.loggers.get(this.name);
        if (logger) {
          logger.log({
            level,
            message: message
          })
        }
      }

      error(message: string) {
        this.logMessage(message, 'error');
      }

      log(message: string) {
        this.logMessage(message, 'info');
      }

      warn(message: string) {
        this.logMessage(message, 'warn');
      }

      info(message: string) {
        this.logMessage(message, 'info');
      }
    }

logger.interfaces.ts
import { LoggerOptions } from 'winston';

export type WinstonModuleOptions = { options: LoggerOptions, name: string };

logger.interfaces.ts
import * as winston from 'winston';

export const defaultLoggerOptions = () => ({
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(), winston.format.simple())
    })
  ],
});

export const loggerOptions = (logGroupName: string, logStreamName: string, format: string = 'simple', level: string = 'error') =>
  ({
    transports: [
      new winston.transports.Console({
        format: format === 'json' ? winston.format.combine(
          winston.format.colorize(),
          winston.format.json()
        ) : winston.format.combine(
          winston.format.colorize(),
          winston.format.simple()
        )
      })
    ]
  });

and...you can use that in any other module in your project.
in your module file you add the LoggerModule in 'import':
  LoggerModule.forRoot({
  options: loggerOptions('user', 'user', 'json', 'error'), name: 'user'
})

Then, in your controller/service you get the logger object in constructor using dependency injection:
constructor(private readonly logger: LoggerService ) { }


text:
Q: Will CoreData and NSUserDefaults have always loaded by the time the initial ViewController ViewDidLoad is called? On app launch I try to auto-login the user if they already have credentials on the device. In my testing I sporadically observe the auto-login fail when it should have succeeded. Is it possible that the ViewDidLoad is being called before CoreData has fully initialised?
To check for auto-login I check:

*

*That the user object exists, stored in CoreData. I store a reference to this user in NSUserDefaults that I use to fetch the CoreData object.

*That the auth key exists, stored in Lockbox
override func viewDidLoad() {
        super.viewDidLoad()

          if self.findUser() != nil && self.getAuthToken() != nil {
              self.autoLogIn()
          }else{
              self.showLogInScreen()
          }
}

func findUser() -> User? {

        let objectURL = NSUserDefaults.standardUserDefaults().URLForKey("userURI")
         if (objectURL == nil) {
             Debug().printString("objectURL == nil")
             return nil
         }

         let objectID = self.managedObjectContext?.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(objectURL!)
         if objectID == nil {
             Debug().printString("objectID == nil")
             return nil
         }

         var currentUser: NSManagedObject?
         do {
             currentUser = try self.managedObjectContext?.existingObjectWithID(objectID!)
         } catch let error1 as NSError {
             currentUser = nil
             Debug().printString("error1.localizedDescription")
         }

        return currentUser as? User
}

func getAuthToken() -> String? {
    let authToken = Lockbox.stringForKey("authToken")
    return authToken
}

A: This issue turned out to be caused by an old version of Lockbox (1.4.x). Upgrading to v3 fixed the issue.
Thanks for all of the responses.

A: Core Data is initialized whenever you initialize it. There's absolutely no magic to it, the initialization is done by your code. If you're using the code from Xcode's project templates, that happens in your app delegate class, and it happens automatically the first time you access the managed object context. If you're using your own code then obviously it happens whenever your code runs.
NSUserDefaults does not need to be initialized. If your code is running, user defaults is available. You don't need to do anything to get it ready, it's just there fore you.


text:
Q: Importing the contents of a folder with Meteor I have a folder containing individual files for different Mongo Collections. I want to read the contents of the directory and dynamically create each collection in meteor. Kind of like:
let collections = {};
let fs = Npm.require('fs');
let files = fs.readDirSync('path-to-my-folder');
files.forEach(fileName, () => {
    let schema = Npm.require('path-to-my-folder/'+fileName);
    let collection = new Mongo.Collection(fileName);
    collections[fileName] = collection; //store collection

    // Create method, and publications for each collection
});

// export function to get any collection by name
export default function(name){
    return collections[name];
}

The issue here is that when I load the site I get the error
Npm is not defined
I understand that this is because Npm is only available server side. But I need these collections to be available on the client as well. Is this kind of a thing possible with Meteor?

A: If you're using Meteor on the server with 1.3, you probably want something like this:
import { Mongo } from 'meteor/mongo';
import { readDirSync } from 'fs';

export let collections = {};

readDirSync('some-dir/').forEach(file => {
  const schema = require(`./${file}`);
  const collection = new Mongo.Collection(file);
  collections[file] = collection;
})

export default function getCollection(name) {
  return collections[name];
}


text:
Q: Toggle Div in Polymer 3 I am trying to show and hide a div in Polymer 3 by clicking on the button. But when I console log the value of showhide boolean its showing undefined? My code is as below
static get properties() {
    return {
      showNotification: Boolean
    };
  }

connectedCallback() {
    super.connectedCallback();
    this.showNotification = false;
}

4

_showHideNotification() {
    this.showNotification != this.showNotification;
    console.log(this.showNotification);
  }

A: To be sure the changes are notified you should use the set method, instead of directly assigning to the property. So your connectedCallback would be:
connectedCallback() {
    super.connectedCallback();
    this.set('showNotification', false);
}

and in your toggle function you have only an unused comparison, you're not even trying to change the value.. so maybe that would be:
_showHideNotification() {
    this.set('showNotification', !this.showNotification);
    console.log(this.showNotification);
}

I don't know the full logic of what you're doing there, maybe this is not a problem, but just keep in mind that you're calling the property showNotification and you're hiding something when it's value is true. So you might want to make sure you don't mean it the other way around..


text:
Q: dropzonejs: acceptedFiles: "video/* doesn't accept m4v in Safari I'm using a dropzone with the option
acceptedFiles: "video/*"

In Safari, when I click it, I can't select .m4v-files (works in FireFox) in the Explorer-window. However, it works via drag & drop.

A: From the example above its looks like you missed a quota ("), if not, try to change the accepted files value to files extension, its should fix this:
acceptedFiles: ".mp4,.mkv,.avi"

From DropZone:

The default implementation of accept checks the file's mime type or
  extension against this list. This is a comma separated list of mime
  types or file extensions. Eg.: image/*,application/pdf,.psd. If the
  Dropzone is clickable this option will be used as accept parameter on
  the hidden file input as well.

See more: http://www.dropzonejs.com/#config-acceptedFiles


text:
Q: Activity.getColor() not working where Application.getColor() works on a Library defined Color I'm trying to use Afollestad's Material Dialog Library in Android.  When creating the Builder I'm getting a NPE being thrown internally as it initializes colors.  I've tracked it down to simply calling "getColor()" on the passed in Activity Context and a color value from the Material Dialog Library.  If I use the Application Context, getting the value works, but then I get other failures related to presenting a dialog with an Application Context rather than Activity.
Gradle File:
...
dependencies {
    // APP COMPAT
    compile 'com.android.support:appcompat-v7:25.0.0'
    // MATERIAL
    compile 'com.afollestad.material-dialogs:core:0.9.1.0'
}
...

Pertinent Java Code:
// FAILING CODE
int material = activityContext.getColor(com.afollestad.materialdialogs.R.color.md_material_blue_600);

// SUCCEEDING CODE
int material = applicationContext.getColor(com.afollestad.materialdialogs.R.color.md_material_blue_600);

My Activities inherit from "AppCompatActivity" and my Application's base theme inherits from "@style/Theme.AppCompat.Light".
Pertinent Stack Trace:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
android.content.ContextWrapper.getResources(ContextWrapper.java:87)
android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:81)
android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:555)
android.content.Context.getColor(Context.java:441)

Thank you for any insights.


text:
Q: If Marketplace App project is modified, do domain admins have to re-install the app? If I modify the scopes of a Marketplace App project, I understand that domain admins have to re-grant data access to my application. If I make other minor changes such as the app name or setup URL, but leave the scopes as-is, will this affect existing installations in any way?

A: No, minor changes like that should be fine.


text:
Q: How to enable Live Visual Tree and Live Property Explorer in Visual Studio I'm running a .Net 4.5 WPF application in Visual Studio 2015 Update 1 in a Debug build configuration.
In Tools > Options > Debugging > General I have checked Enable UI Debugging Toos for XAML and Preview selected elements in Live Visual Tree.
However, when I run my application, both the Live Property Explorer and Live Visual Tree Windows display the following message.
UI Debugging is either disabled, not supported by the current application or the application execution is paused.
What am I missing?

A: In Visual Studio go to Tools --> Options --> Debugging --> General
and uncheck "Use Managed Compatibility Mode" and the Live Visual Tree should show up.

A: Nothing worked for me except for a reboot (log out/in probably would have sufficed). I'm guessing a supporting process got into a bad state and wasn't closing when Visual Studio did.

A: I had the same issue and resolved it by also selecting the "Preview selected elements in Live Visual Tree" sub-option (i.e. under Tools > Options > Debugging > General > Enable UI Debugging Toos for XAML).  Whenever I unchecked that option, the Live Property Explorer and Live Visual Tree windows would go back to showing the "UI Debugging is either disabled..." message again.

A: Steps can be seen below, it works well for me.
Open VS, then type "Enable UI Debugging Tools for XAML" in the Quick Lanch box, enter to go to setting detail page (see screenshot below).

*

*Uncheck "Use Managed Compatibility Mode"

*Check "Enable UI Debugging Tools for XAML" and its sub options

You can refer from Microsoft:
How to: Display WPF Trace Information - Visual Studio | Microsoft Docs

A: On my end, the issue was that the Target device under the project Properties\Debug\Start Options had somehow changed from "Local Machine" to "Simulator". Going back to "Local Machine" (without changing any of the other debug options mentioned in the other answers) brought back the live visual tree and the live property explorer.

A: Another thing that can cause this to fail is security common in a corporate environment.  If the other solutions do not work for you (and your code is not already there), try moving your code to a location under your Documents folder.  There are sometimes exceptions to security constraints on your Documents folder, and those security constraints can keep this feature from working.


text:
Q: Is "tame the infinite" becoming the popular expression or buzz word to mean challenging a difficult question? I came across the phrase, "tame the infinite" in the following sentence of the article of New York Times (May 4) Travel column, titled "Easy China, 3 Ways":
"For the first-time visitor to China, planning a trip to the most populous country on earth can be an exercise in trying to tame the infinite. Where to begin? Since most people will be flying into Beijing, Hong Kong or Shanghai, we suggest basing yourself in one of these three cities, each in its own state of frenzied transformation."
I guessed "tame the infinite" means "It's a very difficult question like challenging the infinite of mathematics" from the context of the sentence, and checked the phrase with Cambridge, Oxford and Merriam-Webster online dictionaries to make sure of its meaning. None of them registers "tame the infinite" as an idiom. Google Ngram shows no incidence either.
I found however, the book written by Kim Stewart, titled "Taming the Infinite - the Story of Mathematics" on amazon.
Does the use of the phrase (an exercise / attempt /plan to) "tame the infinite" by the New York Times writer suggests that the phrase is getting currency as a popular phrase or trendy expression?

A: I have no way of knowing for sure, but I wonder if the Times reporter was familiar with Stewart's book (or at least the title of it), and simply liked the idiom.
A Google search reveals only 5,000 hits for "tame the infinite" (as opposed to well over 100,000 for "tame the lion"); Google books finds only a very finite 100 or so hits for the expression.  Moreover, most of the time, the expression seems to be put into a mathematical context, not applied to more everyday tasks such as travel planning or housecleaning (although my wife and I would probably both tell you that it's a great expression to describe housecleaning).

However, once the West embraced zero, mathematicians began to tame the infinite...
  (Charles Seife, Zéro: The Biography of a Dangerous Idea)

So, I would conclude that the idiom is not popular and widespread yet.  That said, every idiom has its origin, and maybe this one is about to catch on.  Every mighty river starts as a trickling stream; every raging forest fire starts as a small blaze.  In ten years, the expression "tame the infinite" might even sound trite, but today it sounds rather fresh.  If it ever becomes stale and overused, though, at least I'll be able to remember when it first started catching on.

A: No. "Tame the infinite" is not an idiom, and your research does not suggest either that it is a popular phrase or that its popularity is increasing.
In the article you've quoted, the reference is to the overwhelming amount of information that tumbles out when you start planning your trip to a place like China.
Contending with this information overload is what the sentence implies by 'taming the infinite.' It is almost literal (almost because though huge, the data is afterall, finite.)


text:
Q: Rules in .gitignore 1.
I add this in my .gitignore:
temp/cache/
!temp/cache/.htaccess

But it still skip (dont commit) everything in cache dir including .htaccess.
How fix it?
2.
Is ok that I commit my .gitignore on github?

A: yes you do commit and push your .gitignore to your github. It just ignores any changes you made to those files.
e.g.
.gitignore file
*~
/application/config/config.ini

this will ignore any changes made to config.ini


text:
Q: How to connect Apps Script to a Google Form submit button? I have a simple Google-form for registration users on my service and they need to enter time when they will come. Its a problem when they can enter the same time that another user had placed and I need to check it when user push the submit button.
How can I do it with Apps Script? I have found few examples but still dont understand how to connect my script with submitting.

A: It's not possible to use Apps script to check data entered into a form pre-submission (Even with triggers, which are all dependent on the data being submitted). In order to do something similar using Apps script, you would need to use the HTML service to write a custom form with a function that allows you to check what data is submitted, and return an error message/refuse to accept the date if it clashes with a pre-existing date.

A: You are essentially trying to do something similar as the choice Eliminator Forms add-on.
Search the documentation for on form submit trigger. And it will give you an example.
But the catch 22 of it, is that your script runs after the form is submitted, so there is no way to stop the submission if it fails your check.


text:
Q: Refresh a table after upload file with Alpine js I'm developing a Laravel application and I've got a view where displayed file data in a table.
When I upload a file via Filepond input type file, I want the view to refresh using Alpine js to display the new uploaded file.
How can i do?
This is the view
And this is the main .js file where I use Alpine and Filepond

A: From Rik's answer I would assume the simplest way to integrate is to store the file's information into Alpine.js state post upload by FilePond.
Alpine.store('fileInfo', {
  loading: false,
  file: null,
  setFileInfo(file) {
    this.file = file;
  }
});

// Alpine initialisation code

// onreadystatechanged wrapper etc

FilePond.create(element, {
  // other config
  process: {
    // other config
    onprocessfile: (error, file) => {
      Alpine.store('fileInfo').setFileInfo(file);
    }
  }
})

In your template or in your Alpine component you can do $store.fileInfo.file or this.$store.fileInfo.file respectively.
Here are the docs for Alpine.store: https://alpinejs.dev/globals/alpine-store


text:
Q: Score system in game. PYTHON 3.5 def LoginScreen():
    global User_Points
    User_Points = 5
    print("Welcome to Area Trainer")
    print("Please enter the username for your account")
    global user_name
    user_name = str(input())
    save = open(user_name + '.txt', 'w')
    points = open(user_name + 'Score' + '.txt', 'w+')
    points.write(str(User_Points))

    PasswordCheck= True
    while PasswordCheck:
        user_password = input("type in your password: ")
        if len(user_password) < 8:
            print("your password must be 8 characters long")
        elif not any(i.isdigit() for i in user_password):
            print("you need a number in your password")
        elif not any(i.isupper() for i in user_password):
            print("you need a capital letter in your password")
        elif not any(i.islower() for i in user_password):
            print("you need a lowercase letter in your password")
        else:
            PasswordCheck = False

def MenuTriangle():
    global User_Points
    print('''Here is a triangle with a height of 12cm and a width of 29cm
    /\     |                *Not to scale.
   /  \    |
  /    \   | 12cm
 /      \  |
 <------->
    29cm
    You must find out the area and select the correct answer from these options''')
    print('''A) 175
        B) 174
        C) 2000
        D) 199

           ''')
    user_input = input().upper()

    if user_input == "A":
            print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
            MenuTriangle2()

    elif user_input == "C":
            print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
            MenuTriangle2()

     elif user_input == "D":
             print("I'm sorry this is incorrect but you still have a chance to get 1 point!")
             MenuTriangle2()

    elif user_input == "B":
            print("Congratulations! You got it right, someone's a smart cookie. Here have two points!")
            reading = open(user_name + 'Score' + '.txt')
            score = reading.read()
            score = int(score) + 2
            print("Your score is", score)
            points = open('ok' + 'Score' + '.txt', 'w+')
            points.write(str(score))
            MenuStart()

def MenuStart():

    print("Welcome to the mathematical area game!")
    print("In this game you will be required to calculate the area of multiple shapes.")
    print("To do this you must know how to calculate the area of different shapes with increasing difficulty")
print('''Please select a shape you want to play,
    A) Triangle
    B) Square
    C) Circle''')
user_input = input().upper()

    if user_input == "A":
        print("You have chosen to calculate the area of a triangle!")
        MenuTriangle()

    elif user_input == "B":
        print("You have chosen to calculate the area of a square!")
        MenuSquare()

    elif user_input == "C":
        print("You have chosen the calculate the area of a circle!")
        MenuCircle()

    else:
        print("Oops! I didn't understand that >:")
        MenuStart()

LoginScreen()
MenuStart()

Hello, I am trying to make a small game where the user has to guess what the area of the shape is and if they get it right then they get 2 points however, I am using an external file to store the score of the game in but every time I play through the game by entering my name, password I will see that the value of the score will be changed to 2 after I get the answer right but then when it calls the menu function the score in the file is reset and I don't know why
CORRECT ANSWER TO SAVE PRESSING BUTTONS IS B
THE ONLY OPTION AVAILABLE TO PLAY IS TRIANGLE FOR NOW. If anyone could please figure this out it would be greatly appreciated.

A: This is because Python automatically overrides data in a file every time it is being opened. You are opening the file multiple times by calling the function multiple times.


text:
Q: How to align pseudo element :before :after and span element I am practicing pseudo element and want to insert an image before a span on my custom button.
First, I create a custom button without pseudo element and everything is align center.
And then, I insert the pseudo element :before but the pseudo element and span can not align center anymore.
How to make them align?
Thanks

.x-box-item {
  border: 1px solid black;
  width: 300px;
  height: 50px;
  position: absolute;
  right: auto;
  left: 0px;
  margin: 0px;
}
.x-btn-wrap {
  width: 100%;
  height: 100%;
  display: table;
}
.x-btn-button {
  text-align: center;
  vertical-align: middle;
  display: table-cell;
  white-space: nowrap;
}
.x-btn-inner {
  display: inline-block;
  vertical-align: middle;
  max-width: 100%;
}
.x-btn-inner:before {
  content: '';
  width: 50px;
  height: 50px;
  background-image: url("https://gradschool.uoregon.edu/sites/gradschool1.uoregon.edu/files/facebook-like-icon-small.png");
  display: inline-block;
  background-size: 50px 50px;
}

      LIKE

A: Just give vertical-align: middle; to .x-btn-inner::before to make it align proper.

.x-box-item {
  border: 1px solid black;
  width: 300px;
  height: 50px;
  position: absolute;
  right: auto;
  left: 0px;
  margin: 0px;
}
.x-btn-wrap {
  width: 100%;
  height: 100%;
  display: table;
}
.x-btn-button {
  text-align: center;
  vertical-align: middle;
  display: table-cell;
  white-space: nowrap;
}
.x-btn-inner {
  display: inline-block;
  vertical-align: middle;
  max-width: 100%;
}
.x-btn-inner:before {
  content: '';
  width: 50px;
  height: 50px;
  background-image: url("https://gradschool.uoregon.edu/sites/gradschool1.uoregon.edu/files/facebook-like-icon-small.png");
  display: inline-block;
  background-size: 50px 50px;
  vertical-align:middle;
}

      LIKE


text:
Q: Apache on XAMPP not running on windows 11 on windows 10 apache was running without any issues after I updated my windows from windows 10 to 11,
I tried everything on this link and it didn't work at all and I tried to install deferent versions of XAMPP and it didn't work at all
and the only thing that I notice that windows defender didn't give me an alert for access,
idk if that is the problem, and I tried to give it access manually and it didn't work as well
note: MySQL running perfectly.


text:
Q: Why can I not save a page rendered as a PDF? I have rendered a visualforce page as a pdf.  It displays perfectly in the browser and I can zoom, scroll and print it.  Why can I not save it?  Neither the save button, not the Save As... option on the context menu work.

A: Probably PDF was incorrectly embed into HTML content. Should be something like:
<embed width="100%" height="100%" name="plugin" src="http://..." type="application/pdf"> on your page. You can install Adobe web plugin. It works fine. Plugin's save menu occurs in the right bottom corner.


text:
Q: Adding Image column based DataGridViewCheckBoxCell This is what I have coded:
private void DeleteButton_Click(object sender, EventArgs e)
    {
        //Add column for status
        DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
        imageColumn.Name = "ImageColumn";
        imageColumn.HeaderText = "Status";
        FilesDataGridView.Columns.Add(imageColumn);
        FilesDataGridView.Columns[2].Width = 45;

        foreach (DataGridViewRow dr in FilesDataGridView.Rows)
        {
            DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dr.Cells["ChkColumn"];

            DataGridViewImageCell cell = dr.Cells[2] as DataGridViewImageCell;

            if (checkCell.Selected == true)
            {
                //need code to display the Image for this column here..
            }
            else
            {
                //need code to display the Image for this column here..
            }
        }
    }


text:
Q: Executable Scriptspython.EXE not found for pre-commit (lose slashes) We created a pre-commit hook for our project. But when we ran that pre-commit on Windows, we got an error:
Check copyright notices...................................................................Failed
- hook id: check-copyright
- exit code: 1

Executable `C:Userstore.cachepre-commitrepoq2jv0lxhpy_env-python3.9Scriptspython.EXE` not found

So, pre-commit lose slashes for Windows machine. How to fix it? In pre-commit script we have #!/usr/bin/env python shebang, could it be a problem with that?
For Unix-systems everything is ok
.pre-commit-config.yaml
- repo: https://github.com/espressif/check-copyright/
  rev: v1.0.0
  hooks:
    - id: check-copyright
      args: ['--ignore', 'tools/ci/check_copyright_ignore.txt', '--config', 'tools/ci/check_copyright_config.yaml']

.pre-commit-hooks.yaml:
- id: check-copyright
  name: Check copyright notices
  entry: check_copyright.py --verbose --replace
  language: python
  files: \.(py|c|h|cpp|hpp|ld|s|S)$
  require_serial: true

Full repository: https://github.com/espressif/check-copyright

A: the hook you are using is packaged poorly -- it doesn't properly support windows installations
their usage of scripts generates a file in the bin directory with a (bogus) shebang:
C:\Users\Anthony\workspace\check-copyright>head -1 venv\Scripts\check_copyright.py
#!C:\Users\Anthony\workspace\check-copyright\venv\Scripts\python.exe

the supported way to make platform-agnostic entrypoints is to utilize console_scripts:
the easiest fix is to submit a pull request which adjusts their usage of scripts to instead utilize console_scripts:
diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml
index dd2ebf1..9ed932b 100644
--- a/.pre-commit-hooks.yaml
+++ b/.pre-commit-hooks.yaml
@@ -1,6 +1,6 @@
 - id: check-copyright
   name: Check copyright notices
-  entry: check_copyright.py --verbose --replace
+  entry: check-copyright --verbose --replace
   language: python
   files: \.(py|c|h|cpp|hpp|ld|s|S)$
   require_serial: true
\ No newline at end of file
diff --git a/setup.py b/setup.py
index 97b5cc6..c5c01bb 100644
--- a/setup.py
+++ b/setup.py
@@ -33,5 +33,6 @@ setuptools.setup(
     url=URL,
     install_requires=REQUIRES,
     py_modules=['check_copyright'],
-    scripts=['check_copyright.py']
+    scripts=['check_copyright.py'],
+    entry_points={'console_scripts': ['check-copyright=check_copyright:main']},
 )

disclaimer: I created pre-commit

A: Don't forget that in Python \ is an escape character. For Windows paths, you'd need to double them up with a second \. Depending on if you're using Python 2 or Python 3, you can use the following approaches to make your file path OS agnostic.
os.path.join()
Prior to Python 3.4, you would use os.path.join() to create an agnostic path. It is a little awkward to use however, since you need to issue a new call for each directory in your path. For example, if I want to have a path to the folder source_code/my_clones/projA, I would have to use the following code:
clone_path = os.path.join("source_code", "my_clones")
proj_path = os.path.join(clone_path, "projA")

As you can see, this is not particularly nice and is very cumbersome for large file paths.
Pathlib
The Pathlib library was introduced in Python 3. Its handling of paths is much better. Simply specify the UNIX-style path and the library will handle the OS-specific path conversions for you. Taking a look at our previous example, source_code/my_clones/projA, you could write:
proj_path = Path("source_code/my_clones/projA")

Most file operations will handle the conversion for you when using pathlib.


text:
Q: Munkres Analysis on Manifolds, Differentiation Question Munkres (pg. 45). Munkres states that if a function $g:\mathbb{R}^2 \to \mathbb{R}$ is differentiable then its matrix $Dg(0) = [a \text{ } b]$ and that $g'(0;u) = ah + bk$. The latter part makes sense since if a function is differentiable then its derivative is given by $Dg(a) \cdot u$, in this case $0$. However, how does he know that $Dg(0) = [a \text{ } b]$. I tried going back to the defintion of the derivative but we don't know anything about $g(h)$ or $g(0)$, so can someone provide an explanation of how $Dg(0)$ was found?
Or is he saying that it must be a $1$ by $2$ matrix, where $a$ and $b$ don't have to be constants (i.e. can be dependent on $x$ and $y$)? But, that doesn't quite make sense he just says $a$ and $b$. Is that because $x = 0$ and $y=0$ so any terms dependent on $x$ or $y$ are removed?

A: $ Dg(0)$ (by which Munkres means $Dg(0,0)$) is meant to denote the derivative of $g$ at the point $(0,0)$.
It may be meant to denote a linear transformation, or perhaps the matrix of that transformation with respect to the standard basis. Either way, it's a constant.
By analogy, think of the function
$$
f: \Bbb R \to \Bbb R : x \mapsto x^3.
$$
Then
$Df(2)$ is (in a Calculus 1 class) the number $3 \cdot 2^2 = 12$, and in a more sophisticated view, it's the linear transformation from the reals to the reals given by "multiply by 12". And in a still more sophisticated case, it's a linear transformation from "the tangent space to $\Bbb R$ at $2$" to "the tangent space to $\Bbb R$ at $8$", again given by multiplication by $12$ (with respect to the natural bases on each). In all cases, however, it's a constant.

A: If $f:\mathbf{R}^d \to \mathbf{R}$ is differentiable at a point $p,$ then $f(p + he_i)=f(p)+h f'(p)\cdot e_i+o(h).$ We know that $f'(p) \cdot e_i$ is the $i$th entry of the vector representation of the linear form $f'(p)$ and also $f'(p)\cdot e_i = \partial_i f.$ Thus, the result you were asking.


text:
Q: Using IBM Cloud for SaaS API management with on premise gateways Been going through documentation and threads on different fora the last days. (will ask our local IBM expert, but he is quite busy these days).. So turning to you wonderful people :-)
Part of implementing our new cloud strategy we want to move as much as possible to the cloud (as many others do), but it will take some time.
During that migration period, we will have a lot of internal applications using internal API's. But we would love to have our API management solution running in the cloud as SaaS - for many reasons not needing to be discussed here, he he.
So the question is - is it all possible to have our API management in the IBM cloud, but spinning up secure gateways (datapower instances) on premise, connecting to the API management solution in the cloud, pulling down the configuration and run as they do "today", where we have the IBM API connect on premise as well.
We would not want our internal applications to use the gateways in the cloud, the latency would not be acceptable for us at the moment.
Hope a quick "yes" or "no" can be found here - so we can look in the right direction.
Thanks in advance!

A: Yes - You can connect to Gateways on-premise, while having the rest of the API Connect components (Portal, Manager, Analytics) running on our cloud and managed by us. - The offering is referred to as API Connect Reserved Instance, where you get your own reserved single-tenant API Connect.


text:
Q: Parsing a key/value from a json string I am having trouble with parsing a specific key from a json string in a table. Below is my code to read a csv file and extract "employee_id" from the json column in each row:
with open('data.csv') as csvFile:
    csv_reader = csv.reader(csvFile, delimiter=',')

for row in csv_reader:
    event_data = row[4] # the output
    data = json.loads(event_data)
    print(data['employee_id'])

Here is a sample event_data output:
"{\"py/object\": \"employee_information.event_types.EmployeeCreated\", \"employee_id\": \"98765\", \"employee_first_name\": \"Jonathan\", \"employee_last_name\": \"Smith\", \"application_id\": \"1234\", \"address\": \"1234 street\"}"

But I get an error saying
Traceback (most recent call last):
  File "/Users/someuser/Documents/python_test/main.py", line 12, in <module>
    data = json.loads(event_data)
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

When I pass the actual json string into json.loads(), it works fine but passing event_data doesn't for some reason.


text:
Q: Testng-failed.xml is not getting generated when we execute test through maven command I am using Testng version 7.4.0 and Maven version 3.8.4.
When I am  executing tests using maven surefire command as
mvn clean test -Dsurefire.suiteXmlFiles=Testng.xml
some tests got failed but I can't see testng-failed.xml in either target/surefireReport or target/customreport folder.
Is any plugin or jar or listener overriding this?
pom.xml
 <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${surefire.version}</version>
        <configuration>
            <suiteXmlFiles>
                <suiteXmlFile>${surefire.suiteXmlFile}</suiteXmlFile>
            </suiteXmlFiles>

            <includes>
                <include>*.*</include>
            </includes>
            <testFailureIgnore>true</testFailureIgnore>
            <redirectTestOutputToFile>true</redirectTestOutputToFile>
            <reportsDirectory>target/test-report</reportsDirectory>
            <properties>

            </properties>
        </configuration>
        <dependencies>
        </dependencies>
    </plugin>


text:
Q: can we relate a property with other property of same vertex A sample vertex
g.addV('a').property('vehicle','v1').property('time',1000).property(list,'vehicle','v2').property(list,'time',830)

how can we map the values in property 'vehicle' to the values in property 'time'.
I tired the following code
g.V(1).hasKey('vehicle').map(hasKey('time'))

To find path I tired following code
g.V().hasLabel('a').repeat(out().simplePath()).until(hasLabel('h')).path().by(union(label(),values('vehicle','time')).fold())

can you help me please

A: Changing the data model makes these kinds of queries easier to write. If you use vertices and edges to model the vehicles and times instead of lists stored as properties then you can do something like this.
g.addV('A').as('a').
  addV('B').as('b').
  addV('C').as('c').
  addV('vehicle').as('v1').property('time',10).property('name','V1').
  addV('vehicle').as('v2').property('time',8).property('name','V2').
  addV('vehicle').as('v3').property('time',5).property('name','V3').
  addV('vehicle').as('v4').property('time',6).property('name','V4').
  addV('vehicle').as('v5').property('time',5).property('name','V5').
  addV('vehicle').as('v6').property('time',6).property('name','V6').
  addE('route').from('a').to('b').
  addE('route').from('b').to('c').
  addE('vehicle_info').from('a').to('v1').
  addE('vehicle_info').from('a').to('v2').
  addE('vehicle_info').from('b').to('v3').
  addE('vehicle_info').from('b').to('v4').
  addE('vehicle_info').from('c').to('v5').
  addE('vehicle_info').from('c').to('v6').
  iterate()

gremlin> g.V().hasLabel('A').
......1>   repeat(out('route').simplePath()).
......2>     until(hasLabel('C')).
......3>   path().
......4>     by(union(label(),out('vehicle_info').values('name','time').fold()).fold())

==>[[A,[V1,10,V2,8]],[B,[V3,5,V4,6]],[C,[V5,5,V6,6]]]

EDITED to add:
You can filter by the time as follows:
gremlin> g.V().hasLabel('A').
......1>   repeat(out('route').simplePath()).
......2>     until(hasLabel('C')).
......3>   path().
......4>     by(union(label(),out('vehicle_info').has('time',between(5,10)).values('name','time').fold())
.fold())
==>[[A,[V2,8]],[B,[V3,5,V4,6]],[C,[V5,5,V6,6]]]

A: This can be accomplished like this:
g.V(18).property('time', __.values('vehicle'))

Which will map the list property like this:
gremlin> g.addV('a').property('vehicle','v1').property('time',1000).property(list,'vehicle','v2').property(list,'time',830)
==>v[18]
gremlin> g.V(18).valueMap()
==>[time:[1000,830],vehicle:[v1,v2]]
gremlin> g.V(18).property(list, 'time', __.values('vehicle'))
==>v[18]
gremlin> g.V(18).valueMap()
==>[time:[v1,v1],vehicle:[v1,v2]]


text:
Q: Angular - pre-select a select option with [ngValue] [(ngModel)] being objects Goal
I want to pre-select an option of a select with [ngValue] and [(ngModel)] with the values being an object TypeConge:
{ "id": 2, "libelle": "Holidays" }

First Try

                 Type congé
                <select class="form-control" id="typeConge" name="typeConge"  [(ngModel)]="conge.typeConge" >
                    <option [ngValue]="null"></option>
                    <option [ngValue]="typeCongeOption" *ngFor="let typeCongeOption of typeConges; trackBy: trackTypeCongeById">{{typeCongeOption.libelle}}</option>
                </select>

            {{conge.typeConge| json}}

Problem: The select option is not preselected.
Second Try

                 Type congé
                <select class="form-control" id="typeConge" name="typeConge" [compareWith] = 'customCompareTypeConge' [(ngModel)]="conge.typeConge" >
                    <option [ngValue]="null"></option>
                    <option [ngValue]="typeCongeOption" *ngFor="let typeCongeOption of typeConges; trackBy: trackTypeCongeById">{{typeCongeOption.libelle}}</option>
                </select>

            {{conge.typeConge| json}}

...
customCompareTypeConge(tc1: TypeConge, tc2: TypeConge){
        return tc1.id == tc2.id;
    }

Problem: In the console I find: Cannot read property 'id' of null
EDIT
Link to stackblitz.
EDIT 2
A full explanation of this issue can be found at this adress.
Could you help me please?
Thanks!

A: I think you are confused on how the relationship between ngModel and ngValue work to default the select. It has to be a 1:1 explicit comparison between the ngModel value and the ngValue.
You appear to be using typeConges to define your options in your loop with typeCongeOption as the option value which is a complete index item, and then using conge.typeConge to define your ngModel... there has to be a 1 === 1 comparison between these two, you cannot compare complete index items to a value and expect a match.
Please review this stackblitz example.
https://stackblitz.com/edit/angular-13wnyq?embed=1&file=app/select-overview-example.ts


text:
Q: How can I improve performance of a many-to-many SQL query? I have a many-to-many relationship between Books and Genres. For example "The Hobbit" Book may have the Genres "Kids", "Fiction" and "Fantasy".
Here's the schema:
CREATE TABLE "genre" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(50) NOT NULL
)
;
CREATE TABLE "book_genres" (
    "book_id" integer NOT NULL REFERENCES "book" ("id"),
    "genre_id" integer NOT NULL REFERENCES "genre" ("id"),
    CONSTRAINT book_genres_pkey PRIMARY KEY (book_id, genre_id)
)
;
CREATE TABLE "book" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(255) NOT NULL,
    "price" real NOT NULL
)
;

And the indexes:
CREATE INDEX "book_genres_36c249d7" ON "book_genres" ("book_id");
CREATE INDEX "book_genres_33e6008b" ON "book_genres" ("genre_id");
CREATE INDEX "book_5a5255da" ON "book" ("price");

Row counts:

*

*genre: 30

*book_genres: 800,000

*book: 200,000

I am trying to write a query in SQL which brings back all the Books for specific Genres ordered by price without duplicates.
Here's my query which does this:
SELECT name, price
FROM book
WHERE book.id
IN
    (SELECT book_id
    FROM book_genres
    WHERE genre_id = 1
    OR genre_id = 2)
ORDER BY price LIMIT 10

My problem is performance. This query can take up to 2000ms to execute. How can I improve the performance?
I have full control over the database (Postgres 9.3) so can add views, indexes or denormalise. I am also using Django so could perform multiple queries perform operations in memory using Python/Django.

A: SELECT b.name, b.price
FROM book b
WHERE EXISTS (
    SELECT *
    FROM book_genres bg
    WHERE bg.book_id = b.id
    AND bg.genre_id IN( 1 , 2)
    )
ORDER BY b.price
LIMIT 10
        ;

The order by price+LIMIT can be a performance killer: check the query plan.
PLUS: replace the one-column indices by a "reversed" index:
make book_id a FK into books.id
and (maybe) omit the surrogate key id

CREATE TABLE book_genres
        ( book_id integer NOT NULL REFERENCES book (id)
        , genre_id integer NOT NULL REFERENCES genre (id)
        , PRIMARY KEY (book_id, genre_id)
        ) ;
CREATE INDEX ON book_genres  (genre_id,book_id);

A: In most cases you can improve you performance using JOIN instead of subqueries (Although it depends on many factors so ) :
SELECT *
FROM
(
   SELECT b.name, b.price
   FROM book b JOIN book_genres g ON b.book.id = g.book_id
                              AND g.genre_id = 1
   UNION

   SELECT b.name, b.price
   FROM book b JOIN book_genres g ON b.book.id = g.book_id
                              AND g.genre_id = 2
)
ORDER BY price LIMIT 10


text:
Q: JSONGenerator writeString() Internal Error - Can not write text value, expecting field name I'm using the JSONGenerator writeString() method, and I'm receiving the following internal server error, "Can not write text value, expecting field name"?  The debug logs indicate no errors, and neither does firebug.  The documentation says that the writeString() method excepts a String and will write the specified string value (simple enough).
I've checked the known issues site; am I doing something wrong?
Class
public class ctrl_extjs_tree4_json {

    public String strJSON {get; private set;}

    public ctrl_extjs_tree4_json()
    {
        List<Account> accounts = [select id, name from Account Limit 3];
        this.strJSON = generateJSON(accounts);
    }

    public String generateJSON(List<Account> accounts)
    {
        JSONGenerator g = JSON.createGenerator(true); //boolean indicates pretty format
        g.writeStartArray();
        g.writeStartObject();
        g.writeString('test');
        g.writeEndObject();
        g.writeEndArray();

        return g.getAsString();
    }
}

Page
<apex:page controller="ctrl_extjs_tree4_json" contentType="text/javascript" showHeader="false" standardStylesheets="false" sidebar="false">
{!strJSON}
</apex:page>

I'm trying to ultimately produce a list of Accounts with sub list of Contacts (top 5), for an ExtJs tree panel.  Something similar to the example below:
[{
    "success": true,
    "children": [
        { "id": 2, "name": "Phil", "leaf": true },
        { "id": 3, "name": "Nico", "expanded": true, "children": [
            { "id": 4, "name": "Mitchell", "leaf": true }
        ]},
        { "id": 5, "name": "Sue", "loaded": true }
    ]
}]

A: With JSON being essentially a key:value pair, it looks like you're attempting to assign a value to a missing attribute. Take a look at the writeFieldName method, to see how to define a JSON field.
Modifying the code to define a key, "Key" to assign the string 'Value' to, should do the trick.
JSONGenerator g = JSON.createGenerator(true); //boolean indicates pretty format

g.writeStartArray();
g.writeStartObject();
g.writeFieldName('Key'); // <-- Need to set this
g.writeString('Value');
g.writeEndObject();
g.writeEndArray();

system.debug(g.getAsString());

Will output the following:

21:57:54.101 (101039000)|USER_DEBUG|[9]|DEBUG|[ {   "Key" : "Value" }
  ]


text:
Q: progress-bar при чтении текста У меня есть такой вот недоскрипт прогресс бара, который движется, когда скроллиш вниз-вверх.
var o = $('body').scrollTop() / ($(document.getElementById('progress_bar')).height() - $(window).height());
            $(".progress-bar").css({
                "width": (100 * o | 0) + "%"
            });
            $('progress')[0].value =

но скрипт не совсем правильный. Так вот как сделать как по ссылке?

A: Могу подсказать только в какую сторону копать, вот так работает, но нужно кое что подправить.

*{
 margin: 0;
}

.nav{
 width: 100%;
 height: 15px;
 border-bottom: 1px solid black;
 position: fixed;
 top:0;
 left:0;
 background: white;
}

.nav-add{
 width: 0%;
 height: 100%;
 background: blue;
 transition: all 0.1s linear;
}

.block{
 height: 1000px;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi, corrupti, molestias? Esse, dicta. Fugiat laborum nobis porro aliquam dolores beatae, maxime quo similique dicta unde, qui in deserunt, reprehenderit nihil quod ratione mollitia magnam? Consequatur repellendus tenetur ab molestiae accusantium quas reprehenderit cum dolorem magnam, ratione distinctio nisi vel fugit provident! Distinctio praesentium neque fuga. Enim sunt, quo consequatur iste beatae odio. Id magni, a rem. Alias eveniet nam tempora totam, inventore quia eius reiciendis, fugiat excepturi! Debitis qui quaerat itaque deleniti facere nisi quis dolorem, quo voluptatibus dolore commodi excepturi praesentium consectetur at hic aut maiores distinctio alias assumenda.

Debitis alias accusantium quae autem, dolore saepe porro corrupti quos sapiente a ipsum quia ad, totam necessitatibus sunt expedita? Tempore tenetur repudiandae corporis dicta iste enim, veniam odit veritatis, labore reprehenderit doloribus consequuntur quibusdam illum maiores voluptas qui animi quasi, obcaecati laborum quos numquam minima pariatur cumque possimus. Cumque sit cum impedit dolorem deserunt consequatur voluptatum numquam sapiente mollitia, esse omnis nulla, hic a. Id velit recusandae atque consequatur voluptates animi alias qui, dignissimos dolore nisi cupiditate doloremque maiores vero optio saepe illo nobis ipsa fuga labore, assumenda deleniti doloribus! Minima fugiat quasi incidunt ratione quia magni accusamus dolor consequuntur!

Architecto ad quaerat dignissimos, ducimus incidunt officia, distinctio soluta tempora sit quae illo eveniet? Consequuntur nesciunt veniam culpa voluptate eius obcaecati, et, deleniti dicta rem molestias sit, iusto, distinctio architecto inventore id. Molestias dolorum hic corporis odit obcaecati sapiente facere amet. Neque vel praesentium a dicta esse, inventore nihil deserunt veniam nulla tenetur dolorem quibusdam fugiat! At similique aspernatur eos illum laborum molestiae dolores aperiam autem, perspiciatis tempore ut beatae quos mollitia, dignissimos maiores deleniti impedit nostrum enim adipisci quidem? Dicta temporibus quis molestias, possimus quia enim dolor nam eveniet animi perspiciatis unde nobis, id asperiores in quisquam, voluptas quidem!

Eaque in et odio, veritatis consequatur voluptate id, voluptatem rerum molestias, maxime necessitatibus obcaecati explicabo ipsum. Vero quidem incidunt cum praesentium unde, accusamus exercitationem! Ullam sed inventore id distinctio sint ipsam labore temporibus molestiae, animi quo, dolore odit alias! Minus, tempora culpa doloremque. Magni eligendi deserunt nobis accusamus. Repudiandae laborum assumenda, et magnam earum totam. Ipsam rerum voluptatibus aliquam nisi ad eligendi doloribus unde sed cumque, sapiente ullam sunt fugit repellendus! Esse ullam, nostrum praesentium, non placeat sapiente rerum, recusandae vel magni illum tenetur at amet sunt fugiat similique distinctio mollitia dolorum soluta, voluptatibus unde modi earum harum. Odio, eos!

Expedita odio similique ipsa perferendis aspernatur quidem, est sequi officia, obcaecati a. Culpa beatae nostrum accusamus quia nobis voluptatum ipsum nulla reprehenderit ratione optio ducimus, cupiditate porro, odit commodi obcaecati. Laborum incidunt voluptate odio voluptatibus deserunt laboriosam hic at praesentium animi quia modi ut veniam recusandae voluptatem ipsum quaerat sequi blanditiis eaque consequatur maiores debitis, harum cumque nostrum! Repellendus incidunt, praesentium quod adipisci facere placeat blanditiis pariatur, est consequuntur, reprehenderit reiciendis nostrum enim sunt porro! Totam placeat delectus eveniet repellat, nihil architecto molestias, distinctio aspernatur hic. Reprehenderit quisquam, nisi culpa cupiditate laboriosam ea iure, neque, omnis officiis voluptate dolorem dolorum.


text:
Q: Uncaught ReferenceError: li is not defined This is to do list project, but I don't know why this isn't working.
Can anyone help me? I have checked this several times, and all files are good. Also, CSS code is not mine, it's copied.
Of course, this project is not finished, but I'm testing this now (I'm beginner).
I got this error when I click on span:
script.js:4 Uncaught ReferenceError: li is not defined
    at newTask (script.js:4:2)
    at HTMLSpanElement.onclick (index.html:14:46)

function newTask() {
    let task = document.createElement('li');
    let inputText = document.querySelector('#inputText').value;
    li.appendChild(inputText)
}
body {
  margin: 0;
  min-width: 250px;
}

* {
  box-sizing: border-box;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  list-style-type: none;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;

  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

ul li:nth-child(odd) {
  background: #f9f9f9;
}

ul li:hover {
  background: #ddd;
}

ul li.checked {
  background: #888;
  color: #fff;
  text-decoration: line-through;
}

ul li.checked::before {
  content: '';
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

.close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 12px 16px 12px 16px;
}

.close:hover {
  background-color: #f44336;
  color: white;
}

.header {
  background-color: blue;
  padding: 30px 40px;
  color: white;
  text-align: center;
}

/* Clear floats after the header */
.header:after {
  content: "";
  display: table;
  clear: both;
}

/* Style the input */
input {
  margin: 0;
  border: none;
  border-radius: 0;
  width: 75%;
  padding: 10px;
  float: left;
  font-size: 16px;
}

/* Style the "Add" button */
.addBtn {
  padding: 10px;
  width: 25%;
  background: #d9d9d9;
  color: #555;
  float: left;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
  border-radius: 0;
}

.addBtn:hover {
  background-color: #bbb;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> To Do List </title>
    <link rel="stylesheet" type="text/css" href="style.css">

 Lista zadataka

        <input type="text" id="inputText" placeholder=" Naziv zadatka ">
        Dodaj

A: First, you need to get the  ul element which has list id, also you need to set the value of the li element after create it with input value.
Also, If wanted to reset the input value after adding the task

const input = document.querySelector('#inputText')
function newTask() {
    let task = document.createElement('li');

    let inputText = input.value;
    task.textContent = inputText;
    input.value = ''
    const list = document.getElementById('list');
    list.appendChild(task)
}
body {
  margin: 0;
  min-width: 250px;
}

* {
  box-sizing: border-box;
}

ul {
  margin: 0;
  padding: 0;
}

ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  list-style-type: none;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;

  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

ul li:nth-child(odd) {
  background: #f9f9f9;
}

ul li:hover {
  background: #ddd;
}

ul li.checked {
  background: #888;
  color: #fff;
  text-decoration: line-through;
}

ul li.checked::before {
  content: '';
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

.close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 12px 16px 12px 16px;
}

.close:hover {
  background-color: #f44336;
  color: white;
}

.header {
  background-color: blue;
  padding: 30px 40px;
  color: white;
  text-align: center;
}

/* Clear floats after the header */
.header:after {
  content: "";
  display: table;
  clear: both;
}

/* Style the input */
input {
  margin: 0;
  border: none;
  border-radius: 0;
  width: 75%;
  padding: 10px;
  float: left;
  font-size: 16px;
}

/* Style the "Add" button */
.addBtn {
  padding: 10px;
  width: 25%;
  background: #d9d9d9;
  color: #555;
  float: left;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
  border-radius: 0;
}

.addBtn:hover {
  background-color: #bbb;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title> To Do List </title>
    <link rel="stylesheet" type="text/css" href="style.css">

 Lista zadataka

        <input type="text" id="inputText" placeholder=" Naziv zadatka ">
        Dodaj


text:
Q: Dataframe bar plot not consistent x axis with plt.plot df = pd.DataFrame({"segments": [2, 2, 2, 5, 3, 3, 3, 4, 4], "values": [1, 2, 3, 4, 5, 6, 7, 8, 9]})
df.groupby("segments").size().plot(kind="bar")

plt.plot([3, 3], [0, 5])

Let's say I have a dataframe with columns segments and values. I want to plot bar graph for frequencies of segments and a line graph on a same axes.
But when I run the code above x axis is not consistent within the graphs. The x values of the line should have been in "3" in the x-axis. (see image below).
What am I suppose to do to fix this issue. (I want to use groupby().size() on dataframes)

A: When overlapping graphs with the pandas plotting function, write the code to plot them consecutively. Also, in this case, the x-axis is a categorical variable, so set use_index to false.
df.groupby("segments").size().plot(kind="bar")
df.groupby("segments").size().plot(kind="line", use_index=False)


text:
Q: Sending a raw packet to a NetworkInterface in Android doesn't work? I'm trying to send packets via a VPN out of the VPN onto the proper hardware without any real VPN server used, so I can log the packets being sent through.
I'm able to get an InetAddress for the wlan0 interface I want the packet to actually go to, but I'm not too sure if that's the right place at all (it shows my current IP address).
I then use a DatagramChannel (called socket and the IntetAddress is uplink) on it:
socket.connect(new InetSocketAddress(uplink, 0));

And write packets to it:
socket.write(packet);

But nothing sticks, I just get
java.net.SocketException: sendto failed: EINVAL (Invalid argument)

A: I'm trying to do something similar in creating a firewall/filtering application for Android. I'm in the middle of this, so take what I say with the appropriate sized grain of salt. :-)
The trouble with your/my situation is that you're taking packets off the virtual network interface given to you by VpnService, but then you're taking those packets and writing them out with a socket. A socket is intended to handle the transfer of application payload between client and server, not packets.
The socket will take any data you hand it, and wrap that data within a packet of its own creation (TCP if using Socket, UDP if using DatagramSocket as you are). In your case, the data you are handing the socket is itself a packet, and thus you end up with a packet within a packet (likely a TCP packet inside a UDP packet).
When the wrapped packet arrives at the server for your socket, the network interface and ServerSocket on that end will unwrap the payload and find that it is another packet. Probably not going to work because whatever is reading from the server-side socket (e.g. web server) is expecting application payload (e.g. HTTP headers/etc.).
Now, when you have a real VPN tunnel, the server-side of that tunnel is probably pulling your 'wrapped packet' payload out of the UDP packet it receives and is then handing that packet directly to a network interface that can interpret the packet itself.
Without this real VPN tunnel, your VpnService impl essentially has to become a virtual network interface itself, handling the TCP/UDP/etc. protocol between the virtual network interface and your code. Basically, packets read from your VPN interface have to be treated as an application data stream (packets collated and reassembled) before writing to your outgoing socket. Then, you have to somehow acknowledge the packets you just consumed from the interface. Then, you have to take incoming data from your Socket (which is a payload data stream), and break it up into packets that you can then send back to the output stream of your VPN interface. Finally, you need to handle acknowledgement traffic your virtual VPN interface will send in response to the packets you send it. This is not trivial to do.
I really hope I'm wrong about all this, and someone has a simple 'virtual network interface' written in Java that could be used to take the place of the real VPN tunnel. I haven't been able to find it.

A: You can use NetworkInterface APIs to get wlan0 address programmatically.
I'm also trying to do similar thing.. I'm able to see packets at virtual interface.. But I'm not able to send packet via local interface..
I'm able to connect to wlan0 with DatagramChannel, but connection to outside server from wlan0 is stuck at SYN_SEND..

A: You can try a higher port. This works for me:
InetSocketAddress(uplink, 3022)
I do not know how to make sure the port is not in use.
How did you get the address of the wlan0?
I used adb shell ifconfig and pasted the address.


text:
Q: Understanding Async/Await pattern for multi-tasking Currently, i am having difficulties to understand multi-tasking using async and await pattern. In order to get some basics, i have written the following test case;
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    private int global_int = 10;
    public async Task<int> RunAsyncTask()
    {
       // This method runs asynchronously.
       await Task.Run(() => Calculate());
       return global_int;
    }

    private int Calculate()
    {
        Console.WriteLine("Ticket count: " + --global_int);
        return global_int;
    }

    private async void  Start_Button_Click(object sender, RoutedEventArgs e)
    {
        List<Task<int>> list = new List<Task<int>>();

        Console.WriteLine("\nReseting: " );
        global_int = 10;

        for (int i = 0; i < 10; i++)
        {
            var task = RunAsyncTask();
            list.Add(task);
        }

       await Task.WhenAll(list.ToArray<Task<int>>());

       Console.WriteLine("\nFinished: " + global_int);

    }
}

Idea/Target:
10 customers, 10 tickets, every customer buys a ticket and at the end there will be no availiable ticket.
Problem:
When I run the code, i am actually getting not always the same result (Expecting 0 ticket always). Where is the actuall problem?
So, how can I write the code in a way that, result would be always same.
Output1:
Reseting:
Ticket count: 9
Ticket count: 8
Ticket count: 8
Ticket count: 7
Ticket count: 5
Ticket count: 6
Ticket count: 4
Ticket count: 3
Ticket count: 2
Ticket count: 1

Finished: 1

Output2:
Reseting:
Ticket count: 9
Ticket count: 8
Ticket count: 7
Ticket count: 6
Ticket count: 5
Ticket count: 4
Ticket count: 3
Ticket count: 2
Ticket count: 1
Ticket count: 0

Finished: 0

A: --global_int

This is not a thread-safe operation.  Multiple threads are reading and writing to global_int, causing a race condition.  There's a handy class called Interlocked to keep simple int operations atomic, change your Calculate method to:
Console.WriteLine("Ticket count: " + Interlocked.Decrement(ref global_int);

A: If you want to understand how tasks might be scheduled in a single-threaded fashion while still making use of async patterns, you may be interested in this code.
class Program
{
   static void Main(string[] args)
   {
     InitiateCalculations().Wait();
     Console.WriteLine("Finished: {0}", global_int);
   }

   // LimitedConcurrencyLevelTaskScheduler from
   // https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler
   // Provides a task scheduler that ensures a maximum concurrency level while
   // running on top of the thread pool.
   public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler
   {
      public static TaskFactory SingleFactory { get; private set; }

      static LimitedConcurrencyLevelTaskScheduler()
      {
         SingleFactory = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(1));
      }

      // Indicates whether the current thread is processing work items.
      [ThreadStatic]
      private static bool _currentThreadIsProcessingItems;

      // The list of tasks to be executed
      private readonly LinkedList<Task> _tasks = new LinkedList<Task>(); // protected by lock(_tasks)

      // The maximum concurrency level allowed by this scheduler.
      private readonly int _maxDegreeOfParallelism;

      // Indicates whether the scheduler is currently processing work items.
      private int _delegatesQueuedOrRunning = 0;

      // Creates a new instance with the specified degree of parallelism.
      public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism)
      {
         if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism");
         _maxDegreeOfParallelism = maxDegreeOfParallelism;
      }

      // Queues a task to the scheduler.
      protected sealed override void QueueTask(Task task)
      {
         // Add the task to the list of tasks to be processed.  If there aren't enough
         // delegates currently queued or running to process tasks, schedule another.
         lock (_tasks)
         {
            _tasks.AddLast(task);
            if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
            {
               ++_delegatesQueuedOrRunning;
               NotifyThreadPoolOfPendingWork();
            }
         }
      }
      // Inform the ThreadPool that there's work to be executed for this scheduler.
      private void NotifyThreadPoolOfPendingWork()
      {
         ThreadPool.UnsafeQueueUserWorkItem(_ =>
         {
            // Note that the current thread is now processing work items.
            // This is necessary to enable inlining of tasks into this thread.
            _currentThreadIsProcessingItems = true;
            try
            {
               // Process all available items in the queue.
               while (true)
               {
                  Task item;
                  lock (_tasks)
                  {
                     // When there are no more items to be processed,
                     // note that we're done processing, and get out.
                     if (_tasks.Count == 0)
                     {
                        --_delegatesQueuedOrRunning;
                        break;
                     }

                     // Get the next item from the queue
                     item = _tasks.First.Value;
                     _tasks.RemoveFirst();
                  }

                  // Execute the task we pulled out of the queue
                  base.TryExecuteTask(item);
               }
            }
            // We're done processing items on the current thread
            finally { _currentThreadIsProcessingItems = false; }
         }, null);
      }

      // Attempts to execute the specified task on the current thread.
      protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
      {
         // If this thread isn't already processing a task, we don't support inlining
         if (!_currentThreadIsProcessingItems) return false;

         // If the task was previously queued, remove it from the queue
         if (taskWasPreviouslyQueued)
            // Try to run the task.
            if (TryDequeue(task))
               return base.TryExecuteTask(task);
            else
               return false;
         else
            return base.TryExecuteTask(task);
      }

      // Attempt to remove a previously scheduled task from the scheduler.
      protected sealed override bool TryDequeue(Task task)
      {
         lock (_tasks) return _tasks.Remove(task);
      }

      // Gets the maximum concurrency level supported by this scheduler.
      public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } }

      // Gets an enumerable of the tasks currently scheduled on this scheduler.
      protected sealed override IEnumerable<Task> GetScheduledTasks()
      {
         bool lockTaken = false;
         try
         {
            Monitor.TryEnter(_tasks, ref lockTaken);
            if (lockTaken) return _tasks;
            else throw new NotSupportedException();
         }
         finally
         {
            if (lockTaken) Monitor.Exit(_tasks);
         }
      }
   }

   static private int global_int = 10;
   public static Task<int> RunAsyncTask()
   {
      return LimitedConcurrencyLevelTaskScheduler.SingleFactory.StartNew<int>(Calculate);
   }

   private static int Calculate()
   {
      Thread.Sleep(500);
      Console.WriteLine("Ticket count: {0} Thread: {1}", --global_int, Thread.CurrentThread.ManagedThreadId);
      return global_int;
   }

   private static async Task InitiateCalculations()
   {
      List<Task<int>> list = new List<Task<int>>();

      Console.WriteLine("\nReseting: ");
      global_int = 10;

      for (int i = 0; i < 10; i++)
      {
         var task = RunAsyncTask();
         list.Add(task);
      }

      await Task.WhenAll(list.ToArray<Task<int>>());
   }
}


text:
Q: Error handling from backend to fronted (javascript) using enums, where do I put translations? I'm tinkering with an error system where I use enums to identify errors. The enums are contained serverside and converted into JS objects, but I don't know where to keep my error messages.
Errors enum
public enum MyError
{
    InvalidThingFormat = 1001,
    AllowedThingsExceeded = 1002
}

Generated JavaScript "enum"
var MyError= {InvalidThingFormat :1001,AllowedThingsExceeded:1002};

And do checking like
switch(data.error) {
    case MyError.InvalidThingFormat:
        alert("Format validation failed");
        break;
    // etc.
}

So far I like how this feels but I don't like the hardcoded error messages; so where would I put my localization/internationalization of the human readable error message?
Should there also be a backend translation set that I push out in JS or should the translations be only on the JS side, handled by some other method? What would the code look like; Error.GetMessage(MyError.AllowedThingsExceeded)?

A: You would have several javascript files, each named for their localization. IE:
en-us.js:
var ErrorMessages = {
    "1001" : "Invalid thing",
    "1002" : "Too many things."
};

es-mx.js: (Note, I don't actually know spanish)
var ErrorMessages = {
    "1001" : "Cosa no válido",
    "1002" : "Demasiadas cosas"
};

So on and so forth.
So you would include en-us.js as a default, then after that, include whatever the appropriate localization is.
You could then use it like so:
 var errMsg = ErrorMessages[MyError.InvalidThingFormat];

or
 var errMsg = ErrorMessages["1001"];


text:
Q: PHP ¿Como puedo mostrar en alert o toastr que el dato ya existe? Como podria mostrar un mensaje que el dato ya existe para el usuario, el dato ya esta validado para que no repita,pero necesito mostrar al usuario. En este caso el campo que no debe repetir es solo un campo. El codigo de abajo es el modelo donde hace el insert. Antes hace un select para verificar si el dato ya existe, que funciona no guarda repetido, solo necesito mostrar el mensaje.
public function add($v0,$v1,$v2) {
//Sentencia preparada.
$stmt = $this->conexion->prepare('SELECT descripcionlinea FROM lineasproducciones WHERE descripcionlinea=?');
//Ligamos parametros marcadores (?)
$stmt->bind_param('s',$v1);//s si es cadena y i si es integer.
//Ejecutar sentencia
$stmt->execute();
//Transfiere un conjunto de resultados desde una sentencia preparada
$stmt->store_result();
//Comprobamos si existe registro
if($stmt->num_rows > 0) {
    //cerrar statement
    $stmt->close();
    //Mensaje
   echo "";
} else {

    $stmt->close();
    //crear statement
    $stmt = $this->conexion->prepare('INSERT INTO lineasproducciones VALUES (?,?,?)');
    if ( false===$stmt ) {
       die('prepare() fallo: ' . htmlspecialchars($this->conexion->error));
    }
    //parametro a statement
    $rc= $stmt->bind_param('sss',$v0,$v1,$v2);
    if ( false===$rc ) {
       die('bind_param() fallo: ' . htmlspecialchars($this->conexion->error));
    }
    //ejecutar el query
    $rc= $stmt->execute();
    if ( false===$rc ) {
       die('execute() fallo: ' . htmlspecialchars($this->conexion->error));

    }
    //cerrar statement

    $stmt->close();
}

Tambien uso Codigo Javascript

    //boton guardar
    $('#guardar').on('click', function(){
    var v0 = $('#p0').val();
    var v1 = $('#p1').val();
    var v2 = $('#p2').val();
        if (v0.length>0 && v1.length>0 && v2.length>0)
        { //valida requerido
            $('#mensaje').html('

');
            var parametros = $('#formAdd').serialize();
                       $.ajax({  //envia POST a otro php
            type: 'POST',
            url: 'lineaproduccion.iud.php',
            data: parametros,
            success: function(data){
                 if(data.success == true ){
           alert('true');
        } else {
           alert('false')
                    }
                var url = document.URL;
                location.href = url;
            }
        });
    }
    else {
        toastr["warning"]("FALTAN ALGUNOS DATOS", "ATENCION");
    }

})

A: Hola alexis tu quieres que cuando esta repetido te llege una alerta en tu vista diciendo que el dato ya esta repetido? en ese caso te recomiendo devolver a tu ajax un success o un err asi condiciones si es success insertas y si es err pues te lanza un el toast o el alert
si ha insertado data le retornas un succes y si no le retoras un error en tu ajax le pones algo as
    if(data == 'success'){
       alert("genial se inserto correactamente")
}else{
       alert("Algo salio mal") //o el toast
}


text:
Q: Unexpected keyword argument 'pipeline' I'm trying to store the following query into a dataframe.
db = conn["daune_leasing"]
collection = db["clienti_daune"]
pipeline=[{'$group':{
    "_id": {'MARCA': '$MARCA', "MODEL": "$MODEL"},
    "VENIT_ANUAL": {'$sum': '$VENIT_ANUAL'},
    "DAUNA": {'$COUNT': '$DAUNA'},
    "VALOARE_DAUNA": {'$sum': '$VALOARE_DAUNA'},
}},
    {"$sort": {"_id": 1}}]

cursor = collection.find({"AN_FABRICATIE": {'$lt': 2010,'$gt': 2012},
        "VALOARE_DAUNA": {'$gt': 30000}}, pipeline=pipeline)

df  = pd.DataFrame.from_dict(list(cursor))
cursor.close()

pprint(df)

df_plot=df.loc[(df['DAUNA']>100)]
df_plot.bar(x='_id', y='DAUNA',rot=0)
plt.xlabel("MODEL")
plt.ylabel("DAUNA")
plt.show();

I'm receving the following error
cursor = collection.find({"AN_FABRICATIE": {'$lt': 2010,'$gt': 2012},
  File "C:\Users\andre\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymongo\collection.py", line 1523, in find
    return Cursor(self, *args, **kwargs)
TypeError: __init__()

 got an unexpected keyword argument 'pipeline'

A: Do it this way:
pipeline = [
    {
        "$match" : {
            "AN_FABRICATIE" : {
                "$lt" : 2010,
                "$gt" : 2012
            },
            "VALOARE_DAUNA" : {
                "$gt" : 30000
            }
        }
    },
    {
        "$group" : {
            "_id" : {
                "MARCA" : "$MARCA",
                "MODEL" : "$MODEL"
            },
            "VENIT_ANUAL" : {
                "$sum" : "$VENIT_ANUAL"
            },
            "DAUNA" : {
                "$COUNT" : "$DAUNA"
            },
            "VALOARE_DAUNA" : {
                "$sum" : "$VALOARE_DAUNA"
            }
        }
    },
    {
        "$sort" : {
            "_id" : 1
        }
    }
]

cursor = collection.aggregate(pipeline)


text:
Q: Обновление с JDK 6.0 до JDK 7.0 под Windows 7 У меня установлена версия JDK 1.6.0.0_25, я так понимаю это JDK 6
сегодня вышшла JDK 7.0. Как можно безболезненно обновиться до этой версии под Windows 7 ?

A: Что там обновляться-то, это же Windows. Качаете и устанавливаете.


text:
Q: rights protected photo on android I've been tasked with writing an iphone application that displays a set of images (think powerpoint slideshow).  The content of these images need to be protected from forwarding
this task seems quite simple with one exception - I'd like to prevent the user from taking a screenshot
it's not like i'm protecting the crown jewels here, so I'm not looking for military grade super ninja protection.
thoughts?

A: If the user has the Android SDK, they can take a screenshot. There is nothing you can do to stop it.
OTOH, without the Android SDK, there is no way to take a screenshot in Android.


text:
Q: Azure App Service outbound request timeout My .NET site is hosted on Azure App Service.
I have a background task that calls an external API which returns a json (~5MB) and that takes typically 3-4 minutes to complete when I test it in my browser.
But this call fails when executed from the Azure server.
var request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Timeout = request.ReadWriteTimeout = 15 * 60 * 1000; // 15 mins
request.Accept = "application/json";

var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var result = reader.ReadToEnd();
    ...
}

I've tried calling other API endpoints which are faster on the same domain and they work fine, so it is not a matter of Azure servers being blocked or anything.
I have the feeling that Azure kills the connection at some point.
My logs are showing the following:
18/02/2019 12:00:00 PM Downloading the packages data from https://xxxx/api/grouptours/
18/02/2019 12:15:00 PM System.Net.WebException: The operation has timed out
EDIT: although the site is running on multiple instances, we do not have a Load Balancer nor Traffic Manager setup.

A: Azure Load Balancer has a default idle timeout setting of little less than four minutes (230 Sec) according to documentation : Why does my request time out after 230 seconds?
For a background task you could look at webjob or azure function.


text:
Q: Resize NSWindow with "semi-fixed" aspect ratio (I hope the tile makes sense...) I'm trying to make my NSWindow resizing be "constrained" by it's content, which is a view with a fixed aspect ratio, and a spacing at the bottom, like in the picture.

The constraints are, from ContextBackedView to superview, leading, trailing and top space equals to 0, and bottom space equals to 37, plus the aspect ratio constraint (418:263)
Here's the output for constraintsAffectingLayoutForOrientation (0x6000001217c0 is the window contentView)
NSLayoutConstraintOrientationHorizontal
<NSAutoresizingMaskLayoutConstraint:0x618000080af0 h=-&- v=-&- H:|-(0)-[NSView:0x6000001217c0]   (Names: '|':NSThemeFrame:0x1003060c0'Window' )>,
<NSAutoresizingMaskLayoutConstraint:0x618000080b40 h=-&- v=-&- H:[NSView:0x6000001217c0]-(0)-|   (Names: '|':NSThemeFrame:0x1003060c0'Window' )>,
<NSLayoutConstraint:0x618000080870 'NSWindow-current-width' H:[NSThemeFrame:0x1003060c0'Window'(418@500)] priority:500>

NSLayoutConstraintOrientationVertical
<NSAutoresizingMaskLayoutConstraint:0x618000080af0 h=-&- v=-&- H:|-(0)-[NSView:0x6000001217c0]   (Names: '|':NSThemeFrame:0x1003060c0'Window' )>,
<NSAutoresizingMaskLayoutConstraint:0x618000080b40 h=-&- v=-&- H:[NSView:0x6000001217c0]-(0)-|   (Names: '|':NSThemeFrame:0x1003060c0'Window' )>,
<NSLayoutConstraint:0x6000000828a0 H:[NSView:0x600000121860]-(0)-|   (Names: '|':NSView:0x6000001217c0 )>,
<NSLayoutConstraint:0x600000082990 H:|-(0)-[NSView:0x600000121860]   (Names: '|':NSView:0x6000001217c0 )>,
<NSLayoutConstraint:0x618000080870 'NSWindow-current-width' H:[NSThemeFrame:0x1003060c0'Window'(418@500)] priority:500>,
<NSAutoresizingMaskLayoutConstraint:0x618000080b90 h=-&- v=-&- V:[NSView:0x6000001217c0]-(0)-|   (Names: '|':NSThemeFrame:0x1003060c0'Window' )>,
<NSLayoutConstraint:0x6000000828f0 V:|-(0)-[NSView:0x600000121860]   (Names: '|':NSView:0x6000001217c0 )>,
<NSLayoutConstraint:0x600000082940 V:[NSView:0x600000121860]-(37)-|   (Names: '|':NSView:0x6000001217c0 )>,
<NSLayoutConstraint:0x6000000800f0 NSView:0x600000121860.width == 1.58935*NSView:0x600000121860.height>

Using auto layout, it only works if I resized the window's width, but not if I try to change it's height.
I can't use -[NSWindow setAspectRatio:] since the ratio of the window is not actually a fixed number (due to the bottom space having to stay the same)
I also tried using -windowWillResize:toSize: but I couldn't find a way to make it work reliably (resizing only width or height is fine but when changing both it usually broke...)
Does anyone knows a way to achieve this?

A: If you add a constraint (Aspect Ration Constraint) to your ContextBackedView, with the multiplier property being the aspect ratio you'd like (e.g 4:3), you should be able to achieve what you want.
It's easy if you are building this through IB-- first select your ContextBackedView, and on the bottom-right click on the box with lines icon, and select "Aspect Ratio".  That will maintain your view's current aspect ratio after being resized.
If you want to do it programmatically you'll have to look into instantiating and applying NSLayoutConstraints onto NSViews.  I have never done it with Aspect Ratio Constraints, but it should be pretty straight forward.  If you want a code sample let me know I can spin one up :)


text:
Q: How do I create unique values for labeling daylight saving extra hours? I need to manage daylight saving time data, so hours that repeat twice in my table or lack  data for that specific hour need to be coded with a unique value that will make me understand which hour corresponds to the daylight saving time hour. I am trying to do this in Pentaho Kettle

A: If you need a sequence or timeseries, base it on UTC
There's a conflict in your requirements, because there just is no clean sequence to daylight saving time hours on the switching days that will still map automatically to a 24-hour clock.
If you use sequential numbers you end up with 23 or 25 records for the switching days, which means you would need to have a custom mapping back to UTC time to keep things working after hour 3. For any kind of time series, UTC is much more convenient and less error-prone.
If you keep 24 hours in a day and loosen the sequence, you will need to insert something like a 2.0 for the lost hour in spring and a 2.1 and 2.2 for the autumn switch. It just adds more complexity though:

*

*The dummy 2.0 record cannot have activity associated with it (as by definition it is skipped entirely) and if it had, it would break date parsing wherever you try to use it.

*The 2.1 and 2.2 records at least would help you see which activity occurred first, but you would need custom coding for this case everywhere, both splitting and merging the records from the double hour based on their UTC timestamps... notice a pattern here?


text:
Q: asp.net mvc 6 without IdentityUser? is it possible to use ASP.NET MVC 6 identity without deriving from IdentityUser?
I want to completely customize the shape and persistence of my user objects, but i still want, for example, '[Authorize]' to work.
there are lots of docs on how to get the whole default kitchen sink, but i can't find anywhere where it describes what all the moving pieces are and how to swap out the different parts. is it now an all-or-nothing deal?

A: Take a look at Microsoft.Aspnet.Identity.EntityFramework which is likely where your IdentityUser is coming from.
You can then use the above as a template for rolling your own.  Then just reference your own one, rather than the one above.


text:
Q: What is the sum of the infinite telescopic series $\sum_{n=1}^\infty \arctan (n+4)-\arctan(n+2))$? Trying to find the sum of the telescopic series. Can't seem to figure it out! Please Help!
$$\sum_{1}^{\infty}(\tan^{-1}(n+4)-\tan^{-1}(n+2))$$
I've tried looking at other examples, but they're not helping.

A: Hint.  It doesn't matter much what the function is, telescopic series always work much the same way.  For example if we have a finite sum,
$$\eqalign{\smash{\sum_{n=1}^N \bigl(f(n+4)-f(n+2)\bigr)}
  &=f(5)-f(3)+f(6)-f(4)\cr
  &\quad{}+f(7)-f(5)+f(8)-f(6)\cr
  &\quad{}+\cdots\cr
  &\quad{}+f(N+3)-f(N+1)+f(N+4)-f(N+2)\ .\cr}$$
Now if you look carefully you will see that many terms cancel and we get
$$\sum_{n=1}^N \bigl(f(n+4)-f(n+2)\bigr)
  =-f(3)-f(4)+f(N+3)+f(N+4)\ .$$
For your problem you need to replace $f$ by $\arctan$, then see what happens as $N\to\infty$.
Good luck!

A: Compute the first few terms of the sum and try if you can spot something obvious. So the sum is:
$$(\arctan(1+4) - \arctan(1+2)) + (\arctan(2+4) - \arctan(2+2)) + (\arctan(3+4) - \arctan(3+2)) + (\arctan(4+4) - \arctan(4+2)) + ...$$
You can spot that after the $5$th term cancelling begins. Note that there isn't "partner" for $\arctan(1+2)$, $\arctan(2+2)$, $\arctan(\infty +3)$ and $\arctan(\infty +4)$
So after telescoping the sum is:
$$\sum_{n=1}^{\infty} \arctan(n+4) - \arctan(n+2) = \arctan(\infty +3) + \arctan(\infty +4) - \arctan(3) - \arctan(4) = 2\arctan{\infty} - \arctan(3) - \arctan(4)$$


text:
Q: Displaying a WPF dialog from the main thread in a .NET library I've read several posts here and via references from google, but haven't come up with the proper solution.
I have an assembly that displays a dialog, but that dialog needs to be shown from the main thread.  The caller could be a .NET application or native application.
Conceptually, it seems like I simply need to get the application's main thread ID, and then call System.Windows.Threading.Dispatcher.FromThread( main_thread_id_here) to get the Dispatcher, and then call Invoke to display my dialog from the main thread.  However, I haven't been able to figure out how to get the main thread ID.
My next approach was to (following advice from another SO question) iterate over Process.GetCurrentProcess().Threads, and get the thread ID of the ProcessThread that was started first.  But now that I have this ProcessThread, I don't have a way to get the corresponding Thread object.  I figured that I could next get a list of all running .NET threads in the current process, and compare their thread IDs via GetHashCode to determine which one is the main thread.  I could then use FromThread to get the Dispatcher... but I haven't been able to find any information on retrieving anything but ProcessThreads!
Does anyone have tips on how to solve this problem using either approach I have explained above, or maybe another approach?  Please keep in mind that I don't have control over the calling application.

A: Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
    // Show dialog
}));

You could also grab the dispatcher from the Window.Dispatcher property.