text:
Q: Unable to Create Backup Image With Gnome-Disk-Utility New to the forums and running 18.04. Probably a rookie mistake I am making, but scoured the forums and tutorials.
The gnome-disk-utility tutorials are simple enough and appear to be working in the os they are backing up - just select the partition or whole disk image and choose a destination.
I have a 3 partitions:

*

*fat... /dev/sda1

*ext4... /dev/sda2 the linux image I am actually trying to backup

*swap partition... /dev/sda3

If I attempt to image the whole disk, after I authenticate I get this error:
Error unmounting /dev/sda2:target is busy (udisks-error-quark, 14)
Another error I see is just trying to create a backup of the /dev/sda1 partition alone:
Error opening file "/media/freebird/FBbackup/Disk Image of sda1 (2019-11-24 1620).img": Permission denied (g-io-error-quark, 14)
The closest I have been to getting any of the 3 partitions to image is with the swap partition, but only after I disable swapping with sudo swapoff -a then it works just like in the tutorials and to any destination location. I obviously don't care about the swap partition, but I get errors if I try to use gnome-disk to do the whole drive or either of the other two partitions individually.
I also tried running from Live USB, but then I get permissions issues and similar errors. What am I missing?
Thanks!
Brian

A: Applause for wanting to make a System Backup!
The easiest way to accomplish this is with a bootable USB stick and an external USB HDD using CloneZilla Live:

*

*Download and "Burn" the CloneZilla Live ISO (Instructions are provided over there)

*Boot the CloneZilla Live USB stick

*Use the Save Disk Image system

*Insert the external HDD when CloneZilla asks you to do so:

*Wait until done.

The best way to accomplish this is to copy the CloneZilla ISO to your existing system and just boot it from grub on your own system (one less USB Stick that you can lose) and follow the same steps as above.  (CloneZilla Live is the very last example in that answer).
:-)


text:
Q: can i click on a link that is not visible using webdriver My test case is to click on any link of a webpage. I am getting all the links and operation is performed successfully, but when i try to click on some of them then it gives following Exception
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
System info: host: 'ADMINPC', ip: '192.168.1.79', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.28.455520 (cc17746adff54984afff480136733114c6b3704b), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir1932_20343}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: f622cb046f2dcc4e7ddd5621497cb602
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
    at newpackage.AllLinks.main(AllLinks.java:32)

A: This error means the link you are trying to click is not visible. Try to wait for the links to be displayed before clicking them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I reload a view controller once I have signed into Parse I have a Master Detail app in which I am storing a boolean in NSUserDefaults which controls access of the app. Once a user signs in with Parse, I update this value.
However, the problem is that when I go back to the Master View Controller, it does not run the ViewDidLoad code in which I check for the access variable and does not update.
Is there a way to reload a view controller programmatically or could there be another solution?
Thanks so much in advance!

A: I would just check if the value of the Bool Variable has changed, and if it does then run the viewDidLoad() method.
To check if a value is changed in a Bool run the willSet method as such:
var myBool: Bool = Bool() {

      willSet {

            println("the value of the variable has changed")
            viewDidLoad()

      }

}

this code that I wrote automatically checks if the value of the variable changes, and if it does then it will run the code in the willSet method. in this case it will run the viewDidLoad() statement again and print: "the value of the variable has changed".
I am assuming that the viewDidLoad(), when refreshed, will reset the content settings and make sure the user has access to whatever he/she needs access to.
Also if you are just having trouble reloading the viewDidLoad() method than just run the viewDidAppear method:
override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    viewDidLoad()

    //OR JUST RELOAD THE CONTENT SETTINGS
}


text:
Q: cgroups in CentOS I am using a KVM to manage my VMs.
I would like to limit the CPU usage of a particular VM (set a cap on the VM). I was using xen all along, and was able to do this using credit scheduler. I am new to KVM and am searching for some tools to do the same thing.
I found that cgroups can do it but I'm not sure how to install and use cgroups in CentOS. I did some searching but couldn't find any how tos for CentOS.
Does anyone have any ideas how to do this?

A: RHEL's and Fedora's Resource Management Guide is a good place to look for decent documentation on cgroups.
Do you have any specific questions about cgroups?


text:
Q: If $M$ is an $L^2$-bounded continuous local martingale, then $M^2-[M]$ is uniformly integrable Let

*

*$(\Omega,\mathcal A,\operatorname P)$ be a probability space

*$(\mathcal F_t)_{t\ge0}$ be a filtration of $\mathcal A$

*$M$ be a real-valued continuous $L^2(\operatorname P)$-bounded local $\mathcal F$-martingale on $(\Omega,\mathcal A,\operatorname P)$ with $M_0=0$

How can we show that$^1$ $M^2-[M]$ is a uniformly integrable $\mathcal F$-martingale?

I've tried the following:

*

*Let $$[M]_\infty:=\lim_{t\to\infty}[M]_t$$ and $(\tau_n)_{n\in\mathbb N}$ be a localizing sequence for $M^2-[M]$

*Then, $$\operatorname E\left[\left(M^2-[M]\right)^{\tau_n}_t\right]=0\;\;\;\text{for all }t\ge0\tag3$$ for all $n\in\mathbb N$ and hence \begin{equation}
\begin{split}
\operatorname E\left[[M]_\infty\right]&=\lim_{n\to\infty}\operatorname E\left[[M]_n^{\tau_n}\right]\\
&=\lim_{n\to\infty}\operatorname E\left[M^2_{\tau_n\:\wedge\:n}-\left(M^2-[M]\right)_n^{\tau_n}\right]\\
&=\lim_{n\to\infty}\operatorname E\left[M^2_{\tau_n\:\wedge\:n}\right]
\end{split}\tag4
\end{equation} by Lebesgue's monotone convergence theorem
Now, the idea is to show that $$\operatorname E\left[[M]_\infty\right]\le\sup_{t\ge 0}\operatorname E\left[M^2_t\right]<\infty\tag5$$ and $$\sup_{t\ge 0}M_t^2\in\mathcal L^1(\operatorname P)\tag6\;.$$ Then we could conclude that $$\left|M^2-[M]\right|\le\sup_{t\ge 0}M_t^2+[M]_\infty=:X\in\mathcal L^1(\operatorname P)\tag7\;.$$ By $(7)$, $M^2-[M]$ is an $\mathcal F$-martingale.

So, how can we show $(5)$ and $(6)$. And how can we show that $M^2-[M]$ is uniformly integrable?

$^1$ If $X$ is a real-valued continuous local $\mathcal F$-martingale on $(\Omega,\mathcal A,\operatorname P)$, there is a real-valued $\mathcal F$-adapted stochastic process $[X]$ on $(\Omega,\mathcal A,\operatorname P)$, unique up to indistinguishability, with

*

*$[X]_0=0$

*$[X]$ is continuous

*$[X]$ is of locally bounded variation

*$X^2-[X]$ is a local $\mathcal F$-martingale

*$[X]$ is nondecreasing

If $(\sigma_n)_{n\in\mathbb N}$ is a localizing sequence for $X$, then $(\sigma_n\wedge n)_{n\in\mathbb N}$ is a localizing sequence for both $X$ and $X^2-[X]$. If $X$ is an $\mathcal F$-martingale, then $X^2-[X]$ is an $\mathcal F$-martingale. If $\tau$ is an $\mathcal F$-stopping time on $(\Omega,\mathcal A)$, then $$[X^\tau]=[X]^\tau\tag1\;.$$ If $X_0=0$, then $$\operatorname E\left[[X]_t\right]\le\operatorname E\left[\sup_{s\in[0,\:t]}\left|X_s\right|^2\right]\le 4\operatorname E\left[[X]_t\right]\;\;\;\text{for all }t\ge0\tag2\;.$$

A: Let $X_t:=M^2_t-[M]_t$, $t\ge 0$. Because $M$ is $L^2$-bounded, you have that $\lim_{t\to\infty}M_t=M_\infty$ exists, both a.s. and in $L^2$. Therefore $M^2_t$ converges in $L^1$ to $M_\infty^2$. Also, $[M]_t$ converges monotonically to the integrable r.v. $[M]_\infty$; thus $[M]_t\to[M]_\infty$ in $L^1$ as well. It follows that the martingale $(X_t)$ converges in $L^1$, and   therefore $(X_t)$ is uniformly integrable.


text:
Q: apk failed on android 12 Last week I passed from a Android 10 phone to Android 12.
I had some apks decompiled/recompiled with apktool and autosigned with jarsigner, and in Android 10 I could installed them, but in Android 12 it just shows me the apk is invalid when I try to install them at the phone.
If I just decompile one and compile again, and then signed it gives me the same error. I also tryed to install it via adb install with the same result.
I also get the same doing it with Apk Edit app in the phone, so I asume with Android 12 google restringed the apk installations in the phone, but not for all of them, because I installed some apk that I had for more than 5 years and they were installed fine.
Could it be some attribute in the manifest?
I will appreciatte some light to the topic.
Regards

A: You problem is jarsigner. Jarsigner creates an Android APK signature v1 which is no longer accepted on modern devices.
If you want to resign an app you have to use apksigner from Android SDK as it is capable of creating an APK signature v2 and v3. It is included in build tools for each platform, for example build tools for platform API 30.
Apksigner is a Java program so it doesn't mater if you download Linux, MacOS or Windows version:

*

*Download build-tools_r30.0.1-windows.zip

*Extract from the downloaded ZIP file android-11/lib/apksigner.jar

*Execute java -jar apksigner to execute Apksigner.

For a full list of commands how to generate the necessary signing keys and sign an APK please refer to this answer: https://android.stackexchange.com/a/226152/2241

A: Since play store started to accept AAB upload, APKs are started to build for spesific ABIs and OS versions by play store. Your problem may be caused from this situation.
For example; you can't install an apk that build for armeabi-v7a to your arm64-v8a based phone.
if this is the problem you can download appropriate apk variation from apkmirror.


text:
Q: Mongoose aggregate pipeline: sorting indexed date in MongoDB is slow I've been working with this error for some time on my App here and was hoping someone can lend a hand finding the error of this aggregation query.
I'm using a docker container running MongoDB shell version v4.2.8. The app uses an Express.js backend with Mongoose middleware to interface with the database.
I want to make an aggregation pipeline that first matches by an indexed field called 'platform_number'. We then sort that by the indexed field 'date' (stored as an ISODate type). The remaining pipeline does not seem to influence the performance, its just some projections and filtering.
{$sort: {date: -1}} bottlenecks the entire aggregate, even though there are only around 250 documents returned. I do have an unindexed key called 'cycle_number' that correlates directly with the 'date' field. Replacing {date: -1} with {cycle_number: -1} speeds up the query, but then I get an out of memory error. Sorting has a max 100MB cap on Ram and this sort fails with 250 documents.
A possible solution would be to include the additional option { "allowDiskUse": true }. But before I do, I want to know why 'date' isn't sorting properly in the first place. Another option would be to index 'cycle_number' but again, why does 'date' throw up its hands?
The aggregation pipeline is provided below. It is first a match, followed by the sort and so on. I'm happy to explain what the other functions are doing, but they don't make much difference when I comment them out.
    let agg = [ {$match: {platform_number: platform_number}} ] // indexed number
    agg.push({$sort:  {date: -1}}) // date is indexed in decending order
    if (xaxis && yaxis) {
        agg.push(helper.drop_missing_bgc_keys([xaxis, yaxis]))
        agg.push(helper.reduce_bgc_meas([xaxis, yaxis]))
    }
    const query = Profile.aggregate(agg)

    query.exec(function (err, profiles) {
        if (err) return next(err)
        if (profiles.length === 0) { res.send('platform not found') }
        else {
            res.json(profiles)
        }
    })

Once again, I've been tiptoeing around this issue for some time. Solving the issue would be great, but understanding the issue better is also awesome, Thank you for your help!

A: The query executor is not able to use a different index for the second stage.  MongoDB indexes map the key values to the location of documents in the data files.
Once the $match stage has completed, the documents are in the pipeline, so no further index use is possible.
However, if you create a compound index on {platform_number:1, date:-1} the query planner can combine the $match and $sort stages into a single stage that will not require a blocking sort, which should greatly improve the performance of this pipeline.


text:
Q: Multiple ingress controllers using same host I have two ingress controllers (for public/internal traffic), what I would like is for all endpoints to use the public ingress except for /metrics, which should be internal, all using the same host.
E.g.
example.com/ -> public ingress
example.com/metrics -> internal ingress

This is what I have tried:
internal ingress
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example-metrics-ingress
  annotations:
    kubernetes.io/ingress.class: ingress-internal
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path: /metrics
        backend:
          serviceName: example-servicename
          servicePort: 80

and public ingress
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: example.com
    http:
      paths:
      - path:
        backend:
          serviceName: example-servicename
          servicePort: 80

The internal ingress is currently being ignored when I visit example.com/metrics (it uses the public one instead).
If I change the internal ingress to use the same ingress controller as the public one and change the service port to 81 (as an example), this provides an error (which is expected), this shows that the two different ingresses are being used. However, as soon as I use two different ingress controllers, then the one ingress' rules are not being picked up.
How can I configure my ingresses to achieve my desired result?

A: When running multiple ingress-nginx controllers, it will only process an unset class annotation if one of the controllers uses the default  --ingress-class  value (see  IsValid  method in  internal/ingress/annotations/class/main.go), otherwise the class annotation become required.
If  --ingress-class  is set to the default value of  nginx, the controller will monitor Ingresses with no class annotation  and  Ingresses with annotation class set to  nginx. Use a non-default value for  --ingress-class, to ensure that the controller only satisfied the specific class of Ingresses.
In your case use the combination of the annotation kubernetes.io/ingress.class: "EXTERNAL|INTERNAL" and the flag --ingress-class=EXTERNAL|INTERNAL allows you to filter which Ingress rules should be picked by the nginx ingress controller.
Take a look: multiple-ingress, ingress-nginx-traffic.

A: I have had an issue like that on AKS (K8s version 1.22.4). I have two Nginx Ingress Controllers, Internal and External.
Only one worked at a time, Internal or external.
After specifying a unique election-id for each one the problem was fixed.
The following post may help: https://stackoverflow.com/a/72591382/4049017


text:
Q: Read and rewrite the URL in angular 1 app I have a php framework that handles the routes. One of this routes is set to render an index.html that runs an Angular app:
URL                      My server file system
mysite.com/a/:id  --->   somewhere/index.html

The parameter id is needed in the Angular app that uses a route like this: /#/app/:id/section1.
How can the angular app read the id and rewrite the url to go from:
mysite.com/a/:id to mysite.com/a/#/app/:id/section1
Angular routing
$stateProvider

    .state('login', {
        url: '/login',
        cache: false,
        templateUrl: '/_/lno_admin_panel_v2/templates/login.html',
        controller: 'login'
    })

    .state('app', {
        url: '/app/:listId',
        abstract: true,
        templateUrl: '/_/lno_admin_panel_v2/templates/menu.html',
        controller: 'menu'
    })

    .state('app.list', {
        url: '/weddingList',
        views: {
            sectionHolder: {
                templateUrl: '/_/lno_admin_panel_v2/templates/wedding-list.html',
                controller: 'weddingList'
            }
        }
    })


text:
Q: GCP CLB: how to get X-Forwarded-For IP in Nginx.conf? According GCP doc, https://cloud.google.com/load-balancing/docs/https#target-proxies, X-Forwarded-For contains multiple IPs, eg 1.2.3.4, 5.6.7.8, where 1.2.3.4 is the real client IP, 5.6.7.8 is the CLB IP.
How can I get 1.2.3.4 in nginx.conf? I want to use it with geoip.

A: You can use the real IP module to break down X-Forwarded-For and set the $remote_addr variable with the proper value.
For example:
set_real_ip_from  5.6.7.8;
real_ip_header    X-Forwarded-For;
real_ip_recursive on;

The value of $remote_addr is changed from 5.6.7.8 to 1.2.3.4.
In many distributions of Nginx, this module is already present. Use nginx -V to confirm which modules are present.


text:
Q: can't use another account when testing in angularfire2 app I'm using Angularfire2 Typescript, I have finished my testing application but whenever I try to login with another facebook account with ingconito. It showing me an error that I dont have any permission as test user.
Does that mean that i have to set up my other account on firebase too? Or when I deploy it my app using firebase tool. It will work? I want to make it sure first. Thanks!


text:
Q: Googlescript code with namedvalues not working I am trying to send an automatic email to my students with feedback on the coursework.  I have developed a google form with the marking scheme where I enter the student number, but the script doesn't read the named values method.
I have tried to do one by one student numbers and the rest of the code it works.
The code is as follows:
    function sendNotification(e){
    var s = SpreadsheetApp.getActiveSheet();
    var message = "";
    var headers =s.getRange(1,1,1,s.getLastColumn()).getValues()[0];

    message += "This automated email includes the marks and feedback for
    your Main report Assignment.\n\n";

    var studentNumber = e.namedValues[headers[3]].toString();
    Logger.log("column 3: " + studentNumber);

    message += "Student Number: " + studentNumber + "\n\n";

    var recipients = studentNumber + "@email.com";
    var subject = "Test Email";

    MailApp.sendEmail(recipients, subject, message);
    }

I want to be able to gather the student email from the google form, that is already saved in column 3 of the spreadsheet that is attached to the form.

A: Sorry my answer is a little rushed as I am literally leaving. (As is my code.) Normally don't do this, but since you are a teacher willing to make an exception.
Hope the below code helps. (This is how I would accomplish the task you are trying to do.)
function helpingTheTeacher() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("YOUR_SHEET_NAME_HERE");

  var values = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();

  for (var i = 0; i < values.length; i++){

  var timeStamp = values[i][0];
  var studentName = values[i][1];
  var studentNumber = values[i][2];
  var studentGrade = values[i][3];

  var message = "Hi " +studentName + " your grade is " +studentGrade + "."

  var email = studentNumber + "@email.com";

  var subject = "ALERT: MESSAGE FROM TEACHER!!!";

  MailApp.sendEmail(email, subject, message)

  }//END OF FOR LOOP
  }//END OF FUNCTION


text:
Q: Rails - undefined method `' Rails is throwing a
"*** NoMethodError Exception: undefined method `' for #<Marketplace::Item:0x000001019dd148>"

After a .save  or .valid? on @item (example below), I don't see where is the problem, from my Rails knowledge I would say that a column or a method were not setup correctly, but the model is pretty straight and there not much in the controller as well, could my .valid? getting lost due some attribute/param?
item.rb:
class Marketplace::Item < ActiveRecord::Base
include Shared::AttachmentHelper

extend FriendlyId
belongs_to :musico
has_many :anuncios
has_many :item_images, :dependent => :destroy

#Paperclip
has_attachment :cover,
    :styles => {
        :large => "741x570>",
        :medium => "470x611>",
        :thumb => "235x",
        :thumb_anuncio => "90x90#"
    },
    :convert_options =>{
        :large => ["-strip","-quality 80"],
        :medium => ["-strip","-quality 80"],
        :thumb => ["-strip","-quality 80"]
    },
   :default_url => "missing-image.png"

validates_attachment :cover,
    :content_type => { :content_type => ['image/jpeg', 'image/png', 'image/jpg', 'image/bmp'] },
    :size => { :in => 0..8.megabytes }

#Opcoes do DropDown de STATUS
STATUS = [  "ATIVO",
            "INATIVO"]

end

items_controller.rb
def create
    @item = Marketplace::Item.new(item_params)

    respond_to do |format|
        byebug
        if @item.save
            if params[:images]
                params[:images].each { |image|
                    @item.item_images.create(image: image)
                }
            end

            format.html { redirect_to @item, notice: "Item criado." }
            format.json { render json: @item, status: :created, location: @item }
        else
            format.html { render action: "new" }
            format.json { render json: @item.errors, status: :unprocessable_entity }
        end
    end
end

Backtrace: http://pastebin.com/GrDywzKR

A: Posting the comment:
@Max is right, looks like friendly_id ends up doing a send(something_that_is_nil.to_s) while trying to build the "friendly ID" for your model. The lack of a friendly_id :some_column call in your model and some poor argument specification/parsing and error handling on friendly_id's part would explain the error you're seeing.
Friendly it was, indeed, the problem, I was missing an include.


text:
Q: Windbg disassembler address resolution I was analysing a complete memory dump and I applied Windbg uf command to see what a function does
0: kd> uf profsvc!CUserProfileService::_RegisterGPNotification

This is the part of the output. I wonder why the address in parentheses is different than the address  of profsvc!CUserProfileService::_RegisterGPNotification+0x44 which should be
000007fe fb149276
but is
000007fe fb155019.
When I try to unassembled the address 000007fe fb155019 with u it points to
profsvc!CUserProfileService::_RegisterGPNotification+0x44:
I'm really puzzled, any help deeply appreciated.
OUTPUT from WinDBG
….
profsvc!CUserProfileService::_RegisterGPNotification+0x2e:
000007fe`fb14925e ba01000000      mov     edx,1
000007fe`fb149263 488bc8          mov     rcx,rax
000007fe`fb149266 ff157c410200    call    qword ptr [profsvc!_imp_RegisterGPNotification (000007fe`fb16d3e8)]
000007fe`fb14926c 85c0            test    eax,eax
000007fe`fb14926e 0f84a5bd0000    je      profsvc!CUserProfileService::_RegisterGPNotification+0x44 (**000007fe`fb155019**)

profsvc!CUserProfileService::_RegisterGPNotification+0x40:
000007fe`fb149274 33db            xor     ebx,ebx
000007fe`fb149276 eb00            jmp     profsvc!CUserProfileService::_RegisterGPNotification+0x66 (000007fe`fb149278)  Branch

profsvc!CUserProfileService::_RegisterGPNotification+0x66:
000007fe`fb149278 488b0d31b00200  mov     rcx,qword ptr [profsvc!WPP_GLOBAL_Control (000007fe`fb1742b0)]
000007fe`fb14927f 488d052ab00200  lea     rax,[profsvc!WPP_GLOBAL_Control (000007fe`fb1742b0)]
000007fe`fb149286 483bc8          cmp     rcx,rax
000007fe`fb149289 740a            je      profsvc!CUserProfileService::_RegisterGPNotification+0x94 (000007fe`fb149295)  Branch

0: kd> u 000007fe`fb155019
profsvc!CUserProfileService::_RegisterGPNotification+0x44:
000007fe`fb155019 ??              ???
                         ^ Memory access error in 'u 000007fe`fb155019'

A: This is due to optimization, see the following MSDN article:
https://msdn.microsoft.com/en-us/library/windows/hardware/ff541382(v=vs.85).aspx


text:
Q: Clojure SOAP server JAX-WS I am trying to do a simple SOAP webserver with Clojure and jax-ws
(ns test-ws.routes.home
(:import (javax.jws WebMethod WebService)
       (javax.xml.ws Endpoint)))

(defprotocol Calculator (add [this a b]))

(deftype ^{WebService {:targetNamespace "test.seltzer" }}
     CalcWeb [] Calculator (^{WebMethod []} add [this a b] (+ a b)))

(def endpoint (Endpoint/publish "http://localhost:8080/calcWeb" (CalcWeb.)))

After that WSDL is available at http://localhost:8080/calcWeb?wsdl but when I am trying to call it from SOAP-UI I got:
com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to java.lang.Number
My idea was that clojure cannot map SOAP request to number so I added annotation
(defprotocol Calculator (add [this ^Integer a ^Integer b]))
(deftype ^{WebService {:targetNamespace "test.seltzer" }}
     CalcWeb [] Calculator (^{WebMethod []} add [this ^Integer a ^Integer b] (+ a b)))

Now on compile time I have the following error: Can't find matching method: add, leave off hints for auto match.
I also tried this
(defprotocol Calculator (add [this ^Integer a ^Integer b]))

(deftype ^{WebService {:targetNamespace "test-ws.routes.home"}}
     CalcWeb [] Calculator (^{WebMethod []} add [this
                               #^{WebParam {:name "param0"} :tag Integer} a
                               #^{WebParam {:name "param1"} :tag Integer} b] (+ a b)))

I gave me same error.
Am I missing something ?

A: I really was close to solve the problem. The trick was to use interface instead of protocol.
I hope that this will be useful for some one:
(ns wstest.core
  (:import (javax.jws WebMethod WebService WebParam)
       (javax.xml.ws Endpoint)
       (wstest.java Person)))

(definterface IFooService
  (^int add [^int a ^int b])
  (^String sayHi [^String name])
  (^wstest.java.Person makePerson [^String firstName ^String lastName])
  (^String sayHiTo [^wstest.java.Person person]))

(deftype ^{WebService {:targetNamespace "o.m.g"}} FooService []
  IFooService
  (^int ^{WebMethod []} add [this ^int #^{WebParam {:name "a"}} a ^int #^{WebParam {:name "b"}} b]
    (int (+ a b)))
  (^String ^{WebMethod []} sayHi [this ^String #^{WebParam {:name "name"}} name]
    (str "Hello, " name "!"))
  (^wstest.java.Person ^{WebMethod []} makePerson [this ^String #^{WebParam {:name "firstName"}} firstName ^String #^{WebParam {:name "lastName"}} lastName]
    (doto (wstest.java.Person.)
      (.setFirstName firstName)
      (.setLastName lastName)))
  (^String ^{WebMethod []} sayHiTo [this ^wstest.java.Person #^{WebParam {:name "person"}} person]
    (str "Hello, " (.getFirstName person) " " (.getLastName person) "!")))

(def endpoint (atom nil))

(do
  (if-not (nil? @endpoint)
    (.stop @endpoint))
  (reset! endpoint (Endpoint/publish "http://localhost:8080/fooService" (FooService.))))

Person.java:
package wstest.java;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "Person")
 public class Person {
@XmlElement
protected String firstName;
@XmlElement
protected String lastName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String value) {
    this.firstName = value;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String value) {
    this.lastName = value;
}
}

A: Looks like you were using my code in the example from Japila's blog.  I've posted my full source with directions:
https://gist.github.com/seltzer1717/f67e77bb5b47d08612fd7f636832a4ff


text:
Q: odbc_execute(): supplied resource is not a valid ODBC result resource using PHP I'm trying to connect to an Oracle database with PHP. This is how my code currently looks:
$user = "myuser";
$password = "myuser";
$con = odbc_connect("Driver={Devart ODBC driver for Oracle};Direct=true;Host=host;Port=1521;Service Name=serv;User ID=myuser;Password=myuser", $user, $password);

$insercion = "INSERT INTO `table` (`attr1`, `attr2`, `attr3`) VALUES (?, ?, ?)";
**$rs = odbc_execute($con, array($attr1, $attr2, $attr3));**

if($rs)
    echo "Inserted";

I'm getting the following error:

Warning: odbc_execute(): supplied resource is not a valid ODBC result resource in C:\xampp\htdocs\ddsi\server\funciones.php on line 63

Line 63 is the one between ** in the code above. Am I missing something? This whole Oracle thing seems a mess... Thanks in advance!
Additional Info
I've created a new System DSN under OBDC Data Sources (32 bits). When clicking "Test Connection" it says "Connection successful".
Doing var_dump($con); shows the following:

resource(5) of type (odbc link)


text:
Q: Can an idea "make common sense"? Can I use the phrase common sense like that?
The United Kingdom can reverse #Brexit...if it wants to. The statement of the Court of Justice of the EU makes common sense.

A: No, not really.
We typically say, "it makes sense" or "it is common sense."
The only way "sense" is commonly modified in the phrase "it makes sense" is in degree:
It makes a lot of sense
It doesn't make much sense


text:
Q: How to retrive loan borrowers from the database keeping retun months as columns names? In my database, loan returned is stored this way
---------+------------+------+-------------+------------+
borrower |loan_amount | rate | date_issued | instalment |
---------+------------+------+-------------+------------+
1        |       10000|    50| 2019-04-20  |           4|
---------+------------+------+-------------+------------+
2        |       20000|    50| 2019-04-20  |           3|
---------+------------+------+-------------+------------+

i want to achieve this output
---------+------------+-------+------+-------+------+
                      |   Installment per Months    |
---------+------------+-------+------+-------+------+
name     |       Total|     4 |    5 |     6 |    7 |
---------+------------+-------+-------------+-------+
John     |       15000|   3750|  3750|   3750|  3750|
---------+------------+-------+-------------+-------+
James    |       30000|  10000| 10000|  10000|     -|
---------+------------+-------+-------------+-------+

This is the logic behind.

*

*The maximum number of installment is 4 and minimum is 1

*Number of installment determine number of months loan should be returned and amount

*total = (loan_amount + ((loan_amount*rate)/100))

*if i want to retrive customers took loan on january, number of months should be 1, 2, 3, 4. For february should be 2, 3, 4, 5

*at the bottom of each month total should be computed.


text:
Q: Fast forward merge after git flow hotfix I have three branches production , develop and a fix branch as shown below (A,B and C are commits) :
  A (production,fix)
   \
    B   (develop)

I want to be able to only perform fast forward merges using the git flow strategy . However on the scenario where fix and develop have been moved to newer commit C this cant be done f.e.:
    C (fix)                           C (fix,production)
   /                                /
  A (production)     --->>         A
   \                                \
    B (develop)                      B (develop)

I would avoid rebasing develop as it is a public branch . Is there a different way I can achieve only fast forward merges (thus keeping a clean history) without having to rebase the development branch ?

A:
Is there a different way I can achieve only fast forward merges (thus keeping a clean history) without having to rebase the development branch ?

No. When you merge two branches, if the two branches have diverged, you must either have a merge commit, or you must rewrite at least one of the branches such that it is based off of the other. There is no way around this.
Side Note: One of the great features of Git is the fact that simultaneous development can be easily merged, which has the side effect of producing merge commits (if you don't wish to rewrite either development path). Note also, since you mentioned Git Flow, that merge commits are highly recommended in your scenario, for multiple reasons.


text:
Q: Is $B_x = c\circ f(x)$ in the proof of Lemma 13.1 on p.80 in "Topology 2nd Edition" by James R. Munkres? (Question about choice function) I am reading "Topology 2nd Edition" by James R. Munkres.
I am new to the axiom of choice.
Unfortunately, Munkres declared on pp. 60-61 as follows:

You will find few further specific uses of a choice function in this book; we shall introduce a choice function only when the proof would become confusing without it. But there will be many proofs in which we make an infinite number of arbitrary choices, and in each such case we will actually be using the choice axiom implicitly.

Munkres used the axiom of choice in his proof of Lemma 13.1.:
Is the axiom of choice used in the proof that every open set is the union of basis elements (Mukres, Lemma 13.1)
Did he use $c\circ f$ in his proof? (Is $c\circ f(x) = B_x$?)
Let $f:U\to2^{\mathcal{B}}$ be a function such that $U\ni x \mapsto \{B\in\mathcal{B}\mid x\in B\subset U\}\in 2^{\mathcal{B}}$.
Then, by Lemma 9.2, there exists a function $$c:f(U)\to\bigcup_{\mathcal{D}\in f(U)} \mathcal{D}$$ such that $c(\mathcal{G})$ is an element of $\mathcal{G}$, for each $\mathcal{G}\in f(U)$.

Lemma 13.1. Let $X$ be a set; let $\mathcal{B}$ be a basis for a topology $\mathcal{T}$ on $X$. Then $\mathcal{T}$ equals the collection of all unions of elements of $\mathcal{B}$.
Proof. Given a collection of elements of $\mathcal{B}$, they are also elements of $\mathcal{T}$. Because $\mathcal{T}$ is a topology, their union is in $\mathcal{T}$. Conversely, given $U\in\mathcal{T}$, choose for each $x\in U$ an element $B_x$ of $\mathcal{B}$ such that $x\in B_x\subset U$. Then $U=\bigcup_{x\in U} B_x$, so $U$ equals a union of elements of $\mathcal{B}$.

Lemma 9.2 (Existence of a choice function). Given a collection $\mathcal{B}$ of nonempty sets (not necessarily disjoint), there exists a function $$c:\mathcal{B}\to\bigcup_{B\in\mathcal{B}} B$$ such that $c(B)$ is an element of $B$, for each $B\in\mathcal{B}$.

A: We can see that in another way, by taking $x \in U$, Since the sets of $\mathcal{B} $ cover $ X$, there must exists a set $ Y_x \in \mathcal{B} $ such that $ x \in Y_x$.
and now we just take $ B_x=Y_x \cup U $ to get $ x \in B_x \subset U$ with  $ B_x \in \mathcal{B} $.


text:
Q: Databricks how to exit the entire 'job' in the notebooks orchestration workflow? Say I have a simple notebook orchestration :
Notebook A -> Notebook B

Notebook A finish first then trigger Notebook B
I am wondering if there is an out of box method to allow Notebook A to terminate the entire job? (without running Notebook B).
Putting dbutils.notebook.exit in Notebook A  will exit Notebook A but Notebook B still can run.
P.S.
Passing parameters between Notebooks to terminate all the down streamNotebooks one-by-one is an alternative solution but not ideal.
I want a solution to kill the job at the root Notebook.
And, I do not want to raise Exceptions in Notebook Aand kill the job by running into an "error" status.

A: As of now there is no way to stop the present cell after a successful run in "run all" scenario.
Additionally, you can always put an error in the cell where you want run all to stop since errors stop "run all".
Also, you can run all cells above and run all cells below. For example: If you want to run all cells up to cell X, go to cell X+1 and "run all cells above".


text:
Q: Sum of the jumbled digits of $abc_{10}$ is $3194$ In the book that I am reading, the author denotes $abc_{10}$ as $100a+10b+c$ where $a, b, c \lt 10$. So if $a = 3$, $b=2$ and $c=8$ then $abc_{10} = 328$.
The author asks the following problem:
In a parlor game, the 'magician' asks one of the participants to think of a three-digit number $abc_{10}$. The the magician asks the participant to add the five numbers $acb_{10}$, $bac_{10}$, $bca_{10}$, $cab_{10}$ and $cba_{10}$. Suppose the sum was $3194$. What was $abc_{10}$ originally?
I changed the five numbers to $100a+10b+c$ form and added the five numbers that way, resulting in the equation $122a+212b+221c=3194$. Or you could add them another way and factor the result to make $100(a+2b+2c)+10(2a+b+2c)+1(2a+b+c)$.
I am not sure what to do next, but the author hinted at using modular arithmetic to get bounds on the three variables. The only thing I can get with modular arithmetic is the following equation:$$2a+2b+c \equiv 4 \pmod{10} $$ I also found that $c$ is an even number.
Thank you for any help.
Note: If anyone has a better title, please tell me.

A: If you add all six numbers $abc_{10}+acb_{10}+bac_{10}+bca_{10}+cab_{10}+cba_{10}$, you should obtain the single number
$$
(2a+2b+2c)(2a+2b+2c)(2a+2b+2c)_{10} = 111(2a+2b+2c) = 222(a+b+c)
$$
Therefore,
$$
3194+abc_{10} = 222(a+b+c)
$$
We find that $3194 \bmod 222 = 86$, so $abc_{10}$ must be $222k-86$ for some positive integer $k$.  Trial and error: We try $k = 1$ and find that
$$
3194+136 = 3330 = 222(15)
$$
but $1+3+6 = 10 \not= 15$.  However, $k = 2$ yields
$$
3194+358 = 3552 = 222(16)
$$
and $3+5+8 = 16$, so $abc_{10} = 358$.  By way of confirmation, $385+538+583+835+853 = 3194$.  (I leave the exercise of determining whether there are other solutions to the reader.)

A: Imagine that we accumulate without carries in each value place. Then the digit total of $acb+bac+bca+cab+cba$ would be divisible by $5$. However each time we have a carry operation, that digit value reduces by $9$.
Now the lower limit on what the pre-carry sum was is $31+9+4 = 44$, because there weren't any "native"  thousands digits going in to the sum. Now we can add the "lost" $9$s back into that to find a multiple of $5$, getting to $80$ (which gives $a+b+c = 16$) and then $125$ (which gives $a+b+c=25$) as our two feasible initial digit sums.
We also know that the last digit after adding $abc$ will be even, so $c$ is even. With $a+b+c=25$, the target digit would be $0$ (since $2\cdot 25=50$) and $c=6$ but this doesn't work with $a+b+c=25$. So now we know that $a+b+c=16$ and thus $\fbox{c=8}$ to reach $2$ in the units digit of the final sum to match $2\cdot 16=32$.
Now we can subtract out the $32-8=24$ and then divide by $10$ to get $ac+ba+bc+ca+cb = 317$. Since $a+b=8$ and we need $ab\equiv 3 \bmod 16$ with $b$ odd, we can check $\{17, 35, 53, 71\}$ to find that we need $ab_{10}=35$ and thus $\fbox{$abc_{10} = 358$}$


text:
Q: Retrieve data from inner document embedded in array How do I retrieve data from inner document embedded in array in MongoDB using Spring?
{
    "project" : "proj001",
    "sourcevo" : [
        {
            "name" : "HpAlm",
            "type" : "database",
            "source" : "mysql",
            "toolvo" : {
                "url" : "https://123.com",
                "userName" : "123user",
                "password" : "password"
            },
            "dbvo" : {
                "servername" : "",
                "userName" : "",
                "password" : ""
            }
        }
    ]
}

A: Using the MongoDB db.collection.find() method, the query below would return all documents where the sourcevo array contains an element whose name field is equal to "HpAlm".
db.collection.find("{ sourcevo.name : { $eq : 'HpAlm' } }");

In MongoTemplate, the query should look something like the following:
BasicQuery myQuery = new BasicQuery("{ sourcevo.name : { $eq : 'HpAlm' } }");
List<Document> docsList = mongoOperation.find(myQuery, Document.class);


text:
Q: Custom App Folder I am trying to figure out if I can create a custom menu in the start menu. I would like to create a menu something like this, but for some custom apps that we use in house. Below are an example of a menu that I use to connect to different places and a example of the Programs I want to make a menu out of. As you can see I have made a start menu folder for them and created shortcuts to the real deal, and pinned that to the start menu, but I want to be able to select one app to open like how I would select one RDP file to open or one excel file.
EDIT: I want a way to pin multiple programs to the start menu as a menu. The fact that I have a folder with them is just my workaround thats closer than before.
Any suggestions?

A: Partial answer as I'm offering an alternative rather then a solution

2nd Attempt at giving a work around (First attempts below this)

You could sacrifice your document link to be an expandable folder

Start menu > right-click > Properties > Start menu > Customize

Right-click (Documents) > Properties > Select folder to display

End result:

Original answer

Windows 7 includes pin able objects onto the task bar, Now the cool thing about this is you can pin application relevant files to a pinned item

So from here you can build your pinned items the same way you would a folder.
Note: I'm not aware of a file count limit, This  doesn't mean there isn't one just that I don't know of one


text:
Q: Symfony messenger install for mailer: PHP Warning: PHP Startup: Unable to load dynamic library 'amqp.so' When I run composer require symfony/mailer
I have this screen:

If you want to send emails asynchronously:
1. Install the messenger component by running composer require messenger;
2. Add 'Symfony\Component\Mailer\Messenger\SendEmailMessage': amqp to the
config/packages/messenger.yaml file under framework.messenger.routing
and replace amqp with your transport name of choice.

I run composer require messenger
My config/packages/messenger.yaml:
framework:
    messenger:
        failure_transport: failed

        transports:
            # https://symfony.com/doc/current/messenger.html#transport-configuration
            async:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                options:
                    use_notify: true
                    check_delayed_interval: 60000
                retry_strategy:
                    max_retries: 3
                    multiplier: 2
            failed: 'doctrine://default?queue_name=failed'
            # sync: 'sync://'

        routing:
            #Symfony\Component\Mailer\Messenger\SendEmailMessage: async
            Symfony\Component\Mailer\Messenger\SendEmailMessage: amqp
            Symfony\Component\Notifier\Message\ChatMessage: async
            Symfony\Component\Notifier\Message\SmsMessage: async
            # Route your messages to the transports
            #'App\Message\YourMessage': async

I have now :

PHP Warning:  PHP Startup: Unable to load dynamic library 'amqp.so'
(tried: /usr/lib/php/20200930/amqp.so (/usr/lib/php/20200930/amqp.so:
cannot open shared object file: No such file or directory),
/usr/lib/php/20200930/amqp.so.so (/usr/lib/php/20200930/amqp.so.so:
cannot open shared object file: No such file or directory)) in Unknown on line 0

I tried to install amqp library and I can't use phpize,
I tried to install php-dev and many others, it crashed in all...

A: I ran sudo apt install php8.1-amqp
and add new error
--show-private options doesn't exist

It be a Bug for VSCode that I 've resolved by change --show-private by --show-hidden in ~/.vscode/extensions/thenouillet.symfony-vscode-1.0.2/out/symfony/provider/ConsoleContainerProvider.js

A: I don't have error in the VSCode console but I have this one in my deBug Bar of Symfony:
Invalid Messenger routing configuration: the "Symfony\Component\Mailer\Messenger\SendEmailMessage" class is being routed to a sender called "amqp". This is not a valid transport or service id.


text:
Q: How to find out why application didn't finish the execution? I have an application which has last statement System.out.println("Done");, it is written but after that the program is still running. How can I check why is it running?
Is it ok to use System.exit(0)?
The app is using only one (main) thread. Everything after Done is:
 System.out.println("Done.");

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

}

Could it be database connection?

A: Generate a thread-dump when you think the program has finished and look at the output to see where execution currently is. You may find it is not where you expect.
On Unix you should be able to do this using the kill -QUIT  command (where pid is your process id). I believe on Windows you can use Ctrl + Break to do the same.

A: We've just had a similar issue (albeit with a Ruby test system).
It turns out we'd run subprocesses which had become detached from the parent process, were hung waiting for something, but still held the stdout open, preventing our stream-monitoring loop from terminating, and holding the process alive.
I located the issue by running 'lsof' on the process that had apparently hung, seeing it had PIPEs still open, and tracking those down with more lsof.


text:
Q: PUT trouble in rest api I am using the rest API in Yii. I want to implement an update function using PUT, but it doesn't work and always returns an unchanged result from the database.
public function actionUpdate(){
    $json = file_get_contents('php://input');
    echo $json;
    $put_vars = CJSON::decode($json,true);  //true means use associative array
    echo count($put_vars);
    ...

The above code is my function. I detected the problem in line  $put_vars = CJSON::decode($json,true);
because $json is not empty after submitting key/value pairs, but after decoding, the data becomes empty.
You may try in some rest client and see results by yourself:
http://www.taxitaxi.kz/dispatcher/index.php/api/test/1
key/value: rating/8
echo of $json gives following response:
string(232) "------WebKitFormBoundarypsSvnRl0DUwJooRP Content-Disposition: form-data; name="rating"
8 ------WebKitFormBoundarypsSvnRl0DUwJooRP Content-Disposition: form-data; name="date"
333 ------WebKitFormBoundarypsSvnRl0DUwJooRP--
key/value pairs was: rating/8, date/333
Is it parceble json response?

A: I have very similar code in a live site and I use:
parse_str(file_get_contents("php://input"), $_PUT);

Then $_PUT is an array of your PUT data just like $_GET or $_POST would be. You can then do whatever you like with it.


text:
Q: Why does type subclass object? I am learning the Python data model. I have read this article.
In this question @poke answered how the built-in function isinstance works. It explained:
>>> isinstance(type, object) #Because type.__base__==object
True
>>> isinstance(object, object)
True

So my question is why type.__base__==object? and issubclass(object,object)==True when object.__bases__==() ?
Is it just for keeping unification of "everything is a instance of object"?


text:
Q: Rx.Observable.range is missing in Typescript I am trying to use RxJS with Typescript and downloaded everything what I need.
Then I wanted to test if the code works:

As you can see Rx.Observable.range the range method is marked as red.
I look into the Observable.ts and search for range method, it does not find.
But it exists under the folder observable a range.ts file.
What am I doing wrong?


text:
Q: Shortening an almost-repeating code in python3 I have a code in python 3 that "almost repeats" itself and I'm looking for an easy way to shorten it.
What I have is a function f(x1, ..., xN) with N variables. The user selects a variable, say x5, and gets a plot of f vs x5 with other variables fixed. I can always write by hand N functions, each doing the following for a different xi:
def get_Array_To_Plot_x5(x1, ..., x5Start, x5End, numberOfX5, ..., xN):
      return [f(x1, ..., xN) for x5 in numpy.linspace(xiStart, xiEnd, numberOfXi)]

Then I'd call the proper get_Array_To_Plot_xi function (get_Array_To_Plot_x5 in this example) in my main script depending on user input, and plot this array.
Is there a better way of writing this code? I can write another code that writes this script as a text file for me, but I'm hoping for a more elegant solution if possible.
Edit: Adding sample code as requested by Mad Physicist:
Here's the code I've written (I'm calculating energy levels of an s-wave topological superconductor using the Kwant library):
def get SWaveEnergies(V0, mu, B_Zeeman, alpha, Delta, W, L, noOfLevels, a, t):
   return some_floating_number

def SWave_vsMu(muStart, muEnd, noOfmu, V0, B_Zeeman, alpha, Delta, W, L, noOfLevels=6, a=1, t=1.0):
    return [SWaveEnergies(V0, mu, B_Zeeman, alpha, Delta, W, L, noOfLevels, a, t) for mu in np.linspace(muStart, muEnd, noOfmu)]

I've written this with different xiStart, xiEnd, noOfxi. User's command line input will determine the function I call.

A: The variable in a for loop or list comprehension can actually be any expression you can assign to (a "lvalue"), not just a simple variable name.  This means that if you have all of your parameters in a list, you can iterate an arbitrary element of that list via indexing, without duplicating any code.  Something like this:
def get_Array_To_Plot(whichParam, start, end, number, *args):
    args = list(args)   # must be writable list, not tuple
    values = numpy.linspace(start, end, number)
    return [f(*args) for args[whichParam] in values]

You would need to provide a dummy value in the parameter list for the parameter you will be looping over.


text:
Q: I am learning socket but my code but i am not being able to connect to a port #server
import socket
s = socket.socket()
print("Socket connected")
s.bind((socket.gethostname(),9999))
s.listen(3)
print("waiting for connection")
while True:
    c, addr = s.accept()
    print("connected with",addr)
    c.send(bytes("Welcome!","utf-8"))
    c.close()

#client
import socket
c = socket.socket()
c.connect((socket.gethostname(),9999))
msg = c.recv(1024)
print(msg.decode("utf-8"))

i am getting error after running client saying : OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

A: The error is stating that the port you are trying to bind to is currently in use.
Even if you stop the program, after binding the port remains occupied for a time duration of few minutes.
You need to enable the reuse address option before binding to ports in your code.
Here is how you can do that:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

You can get details in below link :
http://hea-www.harvard.edu/~fine/Tech/addrinuse.html


text:
Q: What are the odds of 3 out of 8 people sharing the same birthday? I work on a team of 8 people. Three share the same birthday. I'm no mathematician but I imagine the odds are literally astronomical in measure.
A figure in this instance may be meaningless to me. Does the answer give a clue to how many times in human history has this likely happened?
Could we be the 1st or is this more likely than common sense assumes.

A: The chance of a particular three people sharing a particular birthday is $\frac 1{365^3}$.  If we ignore the chance four people will share a birthday or two triplets will exist, which will cause overcounting, we can multiply by the ${8 \choose 3}=56$ ways to select three people and $365$ birthdays we could choose, leaving $\frac {56}{365^2}\approx 0.00042$ or $1$ in about $2380$.  Not such a low chance at all.


text:
Q: Is there a way to define a generic parameter type explicitly in a lambda expression? I have here a Handler class, which is supposed to handle Events of a certain type:
public interface Handler<E extends Event>
{
    public void handle(E event);

    @SuppressWarnings("unchecked")
    public default Class<E> getEventType()
    {
        for(Method method: this.getClass().getDeclaredMethods())
        {
            if(method.getName().equals("handle")) return (Class<E>)method.getParameterTypes()[0];
        }
        throw new NullPointerException("Couldn't find the 'handle' method in this handler.");
    }
}

As you can see, it will try, by default, to get the type of Event by returning the first parameter type of the handle() method whenever you execute getEventType() (as opposed to a Handler that returns it explicitly). This works correctly with the following JUnit test:
public static class EmptyEvent extends Event
{
    public void test() { }
}

public static Handler<EmptyEvent> genericHandler = new Handler<EmptyEvent>()
{
    @Override
    public void handle(EmptyEvent event)
    {

    }
};

@Test
public void testEventGenerics()
{
    //prints the name of EmptyEvent
    System.out.println(genericHandler.getEventType());
}

Intellij IDEA tells me that I can simplify genericHandler to a lambda expression, so I do that:
public static class EmptyEvent extends Event
{
    public void test() { }
}

public static Handler<EmptyEvent> genericHandler = event -> { };

@Test
public void testEventGenerics()
{
    //prints the name of the base Event class
    System.out.println(genericHandler.getEventType());
}

however, the test prints out the name of Event, not EmptyEvent.
So my question is, Is there a way to explicitly define the generic parameter type of a lambda expression?
I tried doing something like this, but it doesn't do anything (also it's an error)
public static Handler<EmptyEvent> genericHandler = (EmptyEvent)event -> { };

A: Yes you can define the type of a lambda expression parameter:
public static Handler<EmptyEvent> genericHandler = (EmptyEvent event) -> { };

In general it is not necessary because it is implied by context. However it often makes the code easier to read.
See https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27 for more details

A: You are making assumptions about the class of the object that the lambda evaluates to, and I don't think those assumptions are valid. It is sufficient that the lambda overrides the method handle() from Handler, and at runtime, a handle() method that takes Event is sufficient to override the handle() from Handler, which after erasure takes Event. Nowhere is it guaranteed that the lambda must have a handle() method that can be introspected to say that it takes EmptyEvent.

A: The following variables might all point to the same object!
Handler<EventA> handlerA = event -> { };
Handler<EventB> handlerB = event -> { };

Consumer<String> consumer1 = string -> {}
Consumer<Integer> consumer2 = integer-> {}

You cannot really reason about the exact runtime type of a lambda expression; the only guarantee is that the lambda body works at runtime.
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4

The [runtime] method's body has the effect of evaluating the lambda body


text:
Q: Flask IntegerField widget validator not working I'm likely missing something obvious, but I can't get this to work properly. What I want is for the "spinner" widget to stop at the max (min) value and not allow the user to pick a higher (lower) value. What am I doing wrong?
The view:
<html>
    <head>
        <title>Widget Question</title>
    </head>

    <body>
        <form method=post action=''>
            {{ template_form.my_intfield.label }} {{ template_form.my_intfield }}
        </form>
    </body>
</html>

The controller:
from flask import Flask, render_template, request
from wtforms import Form, IntegerField, widgets, validators

app = Flask(__name__)
app.secret_key='some secret'

class InputForm(Form):
    # This is the problem line - I can spin past max or min.
    my_intfield = IntegerField(label='My integer field', widget=widgets.Input(input_type='number'), validators=[validators.InputRequired(), validators.NumberRange(min=0, max=100)], default=100)

@app.route('/', methods=['GET', 'POST'])
def index():
    form=InputForm(request.form)
    return render_template('view.html', template_form=form)

if __name__ == '__main__':
    app.run(debug=True)

I don't get an error, it just doesn't work properly; i.e., the spinner doesn't stop at 100, it keeps on going. I'd like it to stop at 100 on the top end and not allow negative numbers on the bottom end.

A: WTForms validation is done on the server side. You'll need to add JavaScript validation too - such as Parsley JS.


text:
Q: How to get first and last value by same item in sequence, with possibility of the same item occurring again Similar to this question but with the possibility that the same name can appear again in the following rows.
I have this table:
id name     value
1  Daniel   3
2  Daniel   7
3  Daniel   2
4  Carol    9
5  Carol    4
6  Carol    9
7  Ray      5
8  Charles  1
9  Daniel   6
10 Daniel   5
11 Daniel   5

I would like to get the first and the last value (ordered by id) in a table like:
name    value_1st  value_last
Daniel  3         2
Carol   9         9
Ray     5         5
Charles 1         1
Daniel  6         5

A: WITH
cte1 AS ( SELECT *,
                 CASE WHEN name = LAG(name) OVER (ORDER BY id)
                      THEN 0
                      ELSE 1
                      END the_same
          FROM test ),
cte2 AS ( SELECT *, SUM(the_same) OVER (ORDER BY id) group_num
          FROM cte1 )
SELECT DISTINCT
       name,
       FIRST_VALUE(value) OVER (PARTITION BY group_num ORDER BY id) value_1st,
       FIRST_VALUE(value) OVER (PARTITION BY group_num ORDER BY id DESC) value_last
FROM cte2;

fiddle

A: SELECT s.name,(CASE WHEN s.name =t.name THEN MAX(s.id) END) AS 'value_1st',(CASE WHEN s.name=t.name AND  s.id =MAX(s.id) THEN s.value END) AS 'value_last'
FROM tableA s,(SELECT distinct name FROM tableA)t
WHERE s.name = t.name


text:
Q: Linux won't load my images for my game I am using C++ and using the G++ compiler to compile my game. It compiles fine, but I'm linking to images, and they aren't showing up in-game. I tried using local links and full links but I couldn't get either one to work. Is there a special way to link to a file in Linux?
Code Example:
StatBack.load_image("\\Dropbox\\Pirate_Entertainment\\images\\hud_thumbnails\\backdrop.png");
StatBack.apply_image_surface(nCurrentX - 180,nCurrentY-230,0);
StatBack.v_DeleteImages();

A: Unless you are using some kind of portability wrapper which transforms your backslashes to forward slashes, you probably want to use forward slashes:
StatBack.load_image("/Dropbox/Pirate_Entertainment/images/hud_thumbnails/backdrop.png");

or, more likely, using a relative path:
StatBack.load_image("Dropbox/Pirate_Entertainment/images/hud_thumbnails/backdrop.png");

A: In fact it is safe to use a forward slash in windows as well. The ANSI C standard allows forward slashes to be used in file names as the path separator.

A: you should use / as a path separator instead of \ (that C++ reduces to ).


text:
Q: How to populate DataGridView in static method? I am trying to fill DataGridView. However, since I am doing it on FileSystemWatcher handler, which is static class, it gives me error:
An object reference is required for non-static field, method, or property

If I change class to non-static then EventHandler gives same error. I am currently in loop and couldnt find solution. Could you please help me to solve this issue?
    class FCheck
    {
        public static void tpCard_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + "File:" + e.FullPath);

            if (Path.GetExtension(e.FullPath) == ".f")
            {
// Do something....

                Form1.populateTable(tp);
            }

        }
    }

Here is Main Form1:
        public void checkTPFiles()
        {
            FileSystemWatcher fw = new FileSystemWatcher(@"F:\tmp");
            fw.Created += LSCheck.tpCard_Created;
            fw.EnableRaisingEvents = true;
        }

        public static void populateTable(TpCard tpCard)
        {
            DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
            row.Cells[1].Value = tpCard.FNumber;
            dataGridView1.Rows.Add(row);
        }

A: One simple solution is to pass a Form1 instance to your FCheck class.
In your Form1:
    public void checkTPFiles()
    {
        FileSystemWatcher fw = new FileSystemWatcher(@"F:\tmp");

        var fCheck = new FCheck(this);       // <= passes Form1 instance
        fw.Created += fCheck.tpCard_Created; // <= no static call anymore
        fw.EnableRaisingEvents = true;
    }

    public void populateTable(TpCard tpCard)
    {

    }

In your class FCheck:
class FCheck
{
    private readonly Form1 _form;

    public FCheck(Form1 form)
    {
        _form = form;  // <= remember Form1 instance for future use
    }

    public void tpCard_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("ThreadId:" + Thread.CurrentThread.ManagedThreadId + " " + "File:" + e.FullPath);

        if (Path.GetExtension(e.FullPath) == ".f")
        {
            // Do something....

            _form.populateTable(tp);  // <= now it is possible to call instance methods
        }

    }
}

This is not the finest solution of all, because the classes are tightly coupled.
Using events and delegates so that FCheck raises an event and Form1 is reacting to it, would be a better approach. The above solution is meant to be a first step to get you running.


text:
Q: How to convert amount in crores to decimal value in xslt I have a price list of my product like this Rs 148573769277.60 (Rs 14857.38 crores) in xslt.
if i have amount 818354941.60 then i want to convert into this Rs 81.84 (Crores) (Indian numbering system)
How to this do in xslt?

A: I think you are looking for something like this:
<fo:block>
    <xsl:variable name="orignumber" select="'Rs 148573769277.60'"/>
    <!-- filter only the numbers and the '.' from the text -->
    <xsl:variable name="number" select="translate($orignumber, translate($orignumber, '0123456789,.', ''), '')"/>
    <!-- this sets the format to 2 decimals - the multiplication is based on your text. -->
    <!-- concat just adds your chosen text(unit) to the number/string -->
    <xsl:value-of select="concat('Rs ', format-number(number($number) * 0.0000000001,'##.##'), ' (Crores)')"/>
</fo:block>

Alternative you can filter just the numbers and set the '.' by yourself.


text:
Q: Analytics Reporting v4 with API key I need to integrate a very basic report from Google Analytics in the dashboard page of a CMS web application I'm building with asp.net web forms (C#).
I remember I was able to do it on a test made in 2015 with API V3, but now, with V4, I get always an error message that OAuth2 is needed for authentication.

I need to access to a specific analytics account I own, not the account of the user that navigate in the CMS!

So I use the API KEY given by Google API Manager. I have given to that API Key all the permission.
The API key is similar to this: "d471c3ce04612f143ff0Be319aac2e17d0159add"
here is the code
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.Services;
using System;
using Google.Apis.AnalyticsReporting.v4.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using System.Web;

public static class GoogleAnalyticsAPI
{

static string vmcApiKey = "<<API-KEY>>";

public static void Test()
{
    AnalyticsReportingService ars = GetService(vmcApiKey);

    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2017-01-01", EndDate = "2017-04-28" };

    // Create the Metrics object.
    Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

    //Create the Dimensions object.
    Dimension browser = new Dimension { Name = "ga:browser" };

    // Create the ReportRequest object.
    // Create the ReportRequest object.
    ReportRequest reportRequest = new ReportRequest
    {
        ViewId = "<<VIEW-ID>>",
        DateRanges = new List<DateRange>() { dateRange },
        Dimensions = new List<Dimension>() { browser },
        Metrics = new List<Metric>() { sessions }
    };

    List<ReportRequest> requests = new List<ReportRequest>();
    requests.Add(reportRequest);

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

    // Call the batchGet method.
    GetReportsResponse response = ars.Reports.BatchGet(getReport).Execute();
}

public static AnalyticsReportingService GetService(string apiKey)
{
    try
    {
        if(string.IsNullOrEmpty(apiKey))
            throw new ArgumentNullException("api Key");

        return new AnalyticsReportingService(new BaseClientService.Initializer()
        {
            ApiKey = apiKey,
            ApplicationName = "AnalyticsReporting API key example",
        });
    }
    catch(Exception ex)
    {
        throw new Exception("Failed to create new AnalyticsReporting Service", ex);
    }
}

On the last line of Test() method, ars.Reports.BatchGet(getReport).Execute(); I get the error:

Google.Apis.Requests.RequestError
  Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.

But again with OAUTH2 authentication I access the user data and is not what I want.
I need to access a specific account I own, independently by the user that is browsing the CMS.

A: API key is for accessing public data only which means you could only use it with the metadata api.
Google Analytics data is private data owned by a user.  Since this is your own data that you are trying to access you should create a service account.  Service accounts are preauthorized. Go to Google developer console and create service account credentials. Then take the service account email address and add it as a user at the ACCOUNT level in the admin section of the google analytics website.  It MUST be the ACCOUNT level.  You have now authorized the service account to access the data of that account.
Service account Auth
// Copyright 2017 DAIMTO :  www.daimto.com
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
//     Template File Name:  ServiceAccount.tt
//     Build date: 01/02/2017 22:31:50
//     C# generater version: 1.0.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

// About
//
// Unoffical sample for the AnalyticsReporting v4 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Accesses Analytics report data.
// API Documentation Link https://developers.google.com/analytics/devguides/reporting/core/v4/
//
// Discovery Doc  https://www.googleapis.com/discovery/v1/apis/AnalyticsReporting/v4/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.AnalyticsReporting.v4/
// Install Command: PM>  Install-Package Google.Apis.AnalyticsReporting.v4
//
//------------------------------------------------------------------------------
using Google.Apis.AnalyticsReporting.v4
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace GoogleSamplecSharpSample.AnalyticsReportingv4.Auth
{

    public class static ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static AnalyticsReportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them
                string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };             // View your Google Analytics data

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new AnalyticsReportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "AnalyticsReporting Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  AnalyticsReporting service.
                    return new AnalyticsReportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "AnalyticsReporting Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Create service account AnalyticsReportingService failed" + ex.Message);
                throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex);
            }
        }
    }
}

Code ripped from my Google-api-Dotnet samples project for Reporting API
Once you have created your service you should be able to use the code on the samples page for C#
I have an old tutorial on Service accounts with V3.  Google Analytics Authentication


text:
Q: Unwanted  tags in shortcode output. wpautop filter already removed I've written a simple shortcode for Wordpress that outputs a group of  inside yet another  according to a particular content search.
Problem is, I keep getting this  tags in my output, which mess up my code a bit. While I can live with it, I can't live happily.
I have already added
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

in the "functions.php" of my theme. But the result is the same.
Shortcode code is as follows:

$return = "
";
$n = 0;
if ($wp_qry->have_posts()):
    while ($wp_qry->have_posts()): $wp_qry->the_post();
        $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($wp_qry->post->ID), 'thumbnail');
        $return .= "

post->guid}'>{$wp_qry->post->post_title}
";
        $return .= "post->guid}'>$div_precio";
        $return .= "
";
    endwhile;
endif;
$return .= "
";

return $return;

I don't even have newlines on the constructed code. Yet I get this:

Roble Blanco Arena

10,93

Roble Marrón Rojo

11,03

It's driving me crazy.
Again: I already removed wp_autofilter in functions.php.

A: Yes, some crazy plugin.
Check every plugin ... Enable and Disable every plugin


text:
Q: Issue with parallax/smooth-scolling and mouse wheel scrolling of Bootstrap modal popup windows I am having issue with parallax/smooth-scolling and mouse wheel scrolling of Bootstrap modal popup windows.
The Bootstrap modal popup appears when user clicks "Learn More" button.
The modal popup window have the scrollbar. The issue is that user is not able to scroll using mouse wheel because that event is intercepted by parallax/smooth-scolling script.
I am not able to insert code here because the amount of code is too big.
The issue can be reproduced on this website.
Is it possible to solve this issue with adding custom javascript to the website?

A: I think the issue stems from adding parallax-3d to the body tag which is adding an onscroll event listener to your popups. I can see this from inspecting the events for the popup elements in developer tools.
I would suggest adding parallax-3d to main-container.
<div class="main-container parallax-3d">

Edit: Ok, so the parallax-3d library adds for all elements in the body, irrespective of placement.
I just removed the scroll events for the modals and it works.
Try this to remove scroll events.
$('.foundry_modal').unbind('scroll');


text:
Q: How can I force bind particular process in Windows to use specific network interface and to route all its traffic via this interface? I need to allow users inside my lan to use BitTorrent clients, but I need to route all BitTorrent (and only BitTorrent) traffic via Bulletproof VPN. In other words, I need to prevent advertising my router's WAN address as a BitTorrent peer address.
Well, I can establish VPN connection on every Windows PC (via Bulletproof VPN) and it seems I can bind every BitTorrent client to the VPN interface using forcebindip, but how can I instruct Windows to use different gateway for the VPN interface/address? Is there something like PBR in Linux?
Edit: Maybe I'm wrong, but basic routing is the same in Windows and Linux – it is destination-based. All IP packets regardless of source address will be routed to the same gateway. But If I want to send packets to the same destination using different gateways, I need some kind of policy-based routing (in this case – source-based routing)


text:
Q: Proving an eigenspace is a T-Invariant subspace. I want to know if I'm going about this proof the correct way.
Problem Statement: Let $T$ be a linear operator on a vector space $V$, and let $λ$ be a scalar. The eigenspace $V^{(λ)}$ is the set of eigenvectors of $T$ with eigenvalue $λ$, together with $\textbf{0}$. Prove that $V^{(λ)}$ is a $T$-invariant subspace.
So I need to show that $T(V^{(λ)})\subseteq V^{(λ)}$.
Since $V^{(λ)}$ is the set of eigenvectors of the matrix $T$ corresponding to $λ$, that meants that for any $\textbf{v}\in V^{(λ)}$, we have $T\textbf{v}=λ\textbf{v}$.
Clearly, $T\textbf{v}\in T(V^{(λ)})$.
Then we know that for any $\textbf{v}\in V^{(λ)}$, $\text{span}(\textbf{v})\in V^{(λ)}$. Thus, $λ\textbf{v}\in V^{(λ)}$. Since $T\textbf{v}=λ\textbf{v}$, then $T\textbf{v}\in V^{(λ)}$. So then $T(V^{(λ)})\subseteq V^{(λ)}$?

A: Your proof is correct. Just a small thing to add.
If $\textbf{v}\in V^{(λ)}$ then $T \textbf{v}= \lambda \textbf{v}$.
Claim: If $\textbf{v} \in V^{(\lambda)}$ then, $k\textbf{v} \in V^{(\lambda)}$, for any scalar $k$.
Proof: $T(k\textbf{v})= k\ (T(\textbf{v}))=k\ (\lambda\textbf{v})= \lambda (k\textbf{v}) \implies k\textbf{v}\in V^{(\lambda)}$
Similarly you can show that, $\textbf{v}_1,\textbf{v}_2 \in V^{(\lambda)} \implies \textbf{v}_1+\textbf{v}_2 \in V^{(\lambda)}$.


text:
Q: What does a "Team Flare Bag" do in Super Training? It says - "For some reason knocking the stuffing out of this bag feels so good" in the description. Considering its rarity I dont want to waste it if it is any good, so anyone has any idea what this thing is for?
Update - I did some save scumming, and upon using the bag I got a message saying - "Your Haxorus is bursting with Energy". And nothing of notice happened.

A: A Team Flare bag increases the "punching" speed of your Pokémon, just as if you woke them up after a rest, but they will stay in this state far longer than if they simply rested. This means that they will use up punching bags faster and will find other punching bags at a higher rate when punching the default bag.


text:
Q: What ISO date format is this? I could not locate this format, can you tell me please what ISO format is this?
2016-09-30T09:18:29.044Z

I need to recreate this in PHP.
It is similar to ISO-8601 (date('c')) but the ending is different.

A: It still is ISO 8601, but there are different versions for this available.
Check the W3C about this. There are 6 different versions:
Year:
  YYYY (eg 1997)
Year and month:
  YYYY-MM (eg 1997-07)
Complete date:
  YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
  YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
  YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
  YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)

A: This is still a valid ISO date. The 'Z' at the end of 2016-09-30T09:18:29.044Z simply means that it's a UTC date.


text:
Q: SQL Select where one field equals another, but with an additional character in the middle I've got 2 tables of invoice data and I am trying to use one of them to update the other, based on a PO Number.
UPDATE Reconcile
SET Reconcile.Customer = Invoices.Customer,
Reconcile.InvoiceNum = Invoices.InvoiceNumber
FROM Invoices
WHERE Reconcile.PONumber = Invoices.PONum

Simple enough. My problem is that the PO Numbers don't always match perfectly. Some of them have a dash in them. So instead of just FM000112345678 to match on, I might have FM0001-12345678, but I still need to match them. I've been testing some SUBSTRING queries in a SELECT with no luck.
SELECT * FROM Reconcile AS A
WHERE A.PONumber IN (
SELECT DISTINCT PONum
FROM Invoices AS B
WHERE (B.PONum LIKE (SUBSTRING(A.PONumber,0,5) + '%'))
AND B.PONum LIKE ('%' + SUBSTRING(REVERSE(A.PONumber),0,8)))

This returns no results. I tried with CHARINDEX.
SELECT * FROM Reconcile AS A
WHERE A.PONumber IN (
SELECT DISTINCT PONum
FROM Invoices AS B
WHERE (B.PONum LIKE (SUBSTRING(A.PONumber,0,5) + '%'))
AND B.PONum LIKE (RIGHT(A.PONumber,CHARINDEX('-',REVERSE(A.PONumber))-1)))

Still no results. I am obviously missing something.
Any help would be appreciated.

A: If the issue is just hyphens, you can use replace():
WHERE REPLACE(Reconcile.PONumber, '-', '') = REPLACE(Invoices.PONum, '-' ,'')


text:
Q: Error when running SvelteKit's skeleton app locally I am very new to programming and I have chosen to learn sveltekit. I am following this YouTube tutorial however he lost me when my skeleton project was not working!
Here is the output that I received in the terminal `$ npm run dev

client@0.0.1 dev /home/runner/svelte-chat/client
svelte-kit dev

file:///home/runner/svelte-chat/client/node_modules/@sveltejs/kit/dist/cli.js:861
https = https || !!vite_config.server?.https;
^
SyntaxError: Unexpected token '.'
at Loader.moduleStrategy (internal/modules/esm/translators.js:140:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! client@0.0.1 dev: svelte-kit dev
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the client@0.0.1 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2021-11-30T00_11_38_289Z-debug.log `
Any help at all is appreciated as I am a total beginner. I am using a MacBook Pro 13" running MacOS Monterey.

A: @SvelteNewbie.
Please take time to properly display the code and the error messages in your post.
The solution to your problem is to simply update your node version (please perform background research before posting your question to stack overflow).
To update your node version, refer to a similar question.
Hope this helps and enjoy your programming journey!


text:
Q: Making unordered items in an array to always in same order My app has a VC with tableview which contains 10 cells(questions). User selects whatever they apply to them and press "next" button.  Then, it goes to next VC has a table view and initialize corresponding section to the questions.
For example, if I select "Question1, Question 2" out of 10 questions, then it should make two sections which have titles of "Question1" and "Question 2".
Right now I add a question selected in an array like following:
   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        result.append(allCriteria[indexPath.row])
    }

Then, when "next" button is pressed, it passes result array to next VC. Based on the array "result" is passed, it initializes sections in order.
The problem is that it changes the order of section if I press the questions in random order. And this is expected.
Would there be anyway solve this?
In short, even if a user selects questions in order of "Question2, Question1", I would like sections to be made in order of "Question1, Question2"
result array is type of [Question]! and Question class is like below:
class Question {

    var documents: [Document] = []
    var title: String
    var description: String

    init(dict: [String:AnyObject] ) {
        // parse dict to generate a bunch of documents, add them to self.documents
        self.title = dict["Title"] as! String
        self.description = dict["Description"] as! String

        let documentsDicts = dict["Documents"] as! [Dictionary<String,AnyObject>]

        for dictionary in documentsDicts {
            let document = Document(dict: dictionary)
            self.documents.append(document)
        }
    }
}

A: Instead of adding the Question to the result array when user selects a cell, you can just add the indexPath of that cell to an array. When user clicks next, you just sort that indexPath array by ascending order, then based on that, you just generate the result array and pass it to the next view controller, something like:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    indexPathArray.append(indexPath)
}

func next() {
    let sorted = indexPathArray.sort(<)
    let result = sorted.map {
        (var index) -> Question in
            return allCriteria[index]
    }
    // ........
}

A: Reading from here, a solution can be to sort your array alphabetically by question's title and do something like this:
result.sort { $0.title < $1.title }

A: In Swift 3
self.resultArry.sort(by: { $0.title < $1.title })


text:
Q: Pra que serve o comando LOCK TABLES? Esses dias me deparei com um trecho de um SQL que tinha o comando LOCK TABLES.
Eu nunca tinha visto isso antes e, pelo pouco que pude ver, parece-me que isso seria para travar a tabela durante a inserção ou atualização.
Mas eu queria poder entender melhor o funcionamento:

*

*Como funciona LOCK TABLES? Gostaria de alguns exemplos.

*Quando eu devo usar esse comando?

*Devo evitar usar esse comando em alguns casos? Existe algum risco?

A: Para usar LOCK TABLES, você precisa do privilégio global LOCK TABLES e de um privilégio SELECT sobre as tabelas envolvidas.
As principais razões para usar LOCK TABLES são para emular transações ou para obter maior velocidade ao atualizar tabelas.
LOCK TABLES funciona da seguinte maneira:

*

*Ordena todas as tabelas a serem bloqueadas em uma ordem definida internamente (do ponto de vista do usuário, a ordem é indefinida).

*Se uma tabela for bloqueada com um bloqueio de leitura e um de gravação, colocará o bloqueio de gravação antes do de leitura.

*Bloqueia uma tabela de cada vez até que a thread obtenha todos os bloqueios.

A politica garante que o bloqueio de tabelas esteja livre de deadlosks*. Há, todavia, outras coisas das quais você deve estar ciente com este esquema:
Se você estiver usando um bloqueio de gravação LOW_PRIORITY em uma tabela, isso significa apenas que o MySQL esperará por este bloqueio específico até que não existam threads que queiram um bloqueio de leitura. Quando a thread possuir o bloqueio de gravação e estiver esperando para obter o bloqueio da próxima tabela na lista de tabelas a bloquear, todas as outras threads esperarão pelo bloqueio de gravação ser liberado. Se isto se tornar um problema sério com a sua aplicação, você deverá converter algumas das suas tabelas em tabelas de transação.
Você pode terminar com segurança uma thread que estiver esperando por um bloqueio de tabela com KILL.
Observe que você não deve bloquear tabelas que estivar usando com INSERT DELAYED. Isto porque, neste caso, INSERT é feito por uma thread separada.
Normalmente, você não tem de bloquear tabelas porque todas as declarações UPDATE únicas são atomicas, nenhuma outra thread pode interferir com alguma outra declaração SQL correntemente em execução. Há alguns casos nos quais você gostaria de bloquear tabelas de qualquer forma:

*

*Se você for executar muitas operações em múltiplas tabelas, é muito mais rápido bloquear as tabelas que você for usar. O problema é que nenhuma outra thread pode atualizar uma tabela com bloqueio de leitura e nenhuma outra thread pode ler uma tabela bloqueada para gravação.
O motivo pelo qual algumas coisas são mais rápidas sob LOCK TABLES é que o MySQL não descarregará a cache de chaves das tabelas bloqueadas até que UNLOCK TABLES seja chamada (normalmente a cache de chaves é descarregada após cada declaração SQL). Isto aumenta a velocidade de inserção, atualização e exclusão em tabelas MyISAM.

*Se você estiver usando um mecanismo de armazenamento no MySQL que não suporte transações, deverá usar LOCK TABLES se quiser assegurar-se de que nenhuma outra thread fique entre um SELECT e um UPDATE. O exemplo mostrado aqui requer LOCK TABLES para executar rapidamente:
mysql> LOCK TABLES trans READ, clientes WRITE;
mysql> SELECT SUM(valor) FROM trans WHERE id_do_cliente=algum_id;
mysql> UPDATE cliente SET valor_total=soma_das_declarações_anteriores
    ->   WHERE id_do_cliente=algum_id;
mysql> UNLOCK TABLES;

Sem UNLOCK TABLES há uma chance de outra thread inserir uma nova linha na tabela trans entre a execução das declarações SELECT e UPDATE.

*Deadlock no contexto de banco de dados(MS-SQL/MySQL), caracteriza uma situação em que ocorre um impasse e dois ou mais processos ficam impedidos de continuar suas execuções, ou seja, ficam bloqueados.

Fonte: MySQL Guia de Estudo para Certificação (tradução: Acauan Fernandes)
Esta matéria também está publicada em 6.7.5. Sintaxe LOCK TABLES e UNLOCK TABLES
O Manual está disponível on-line em diversos formatos e línguas no Web site da MySQL AB (http://www.mysql.com/)

A: Como funciona LOCK TABLES? Gostaria de alguns exemplos.
Simplesmente faz o lock explícito da tabela, bloqueando exclusivamente para sessão que executou o comando.
Documentação do MySQL:
https://dev.mysql.com/doc/refman/5.5/en/lock-tables.html:

"A table lock only protects against inappropriate reads or writes by
  other sessions"

Ou seja, protege os registros durante alguma alteração
Exemplo:
LOCK TABLES nome-da-tabela WRITE;

... comandos ...

UNLOCK TABLES;

LOCK TABLES pode fazer dois tipos de lock:
LOCK TABLES READ: bloqueia para leitura e permite ler uma tabela bloqueada. Multiplas sessões podem usar esse lock ou mesmo tempo.
LOCK TABLES WRITE: bloqueia para alterações. Somente uma sessão pode executar esse bloqueio por vez.
Quando eu devo usar esse comando?
Você deve usar quando deseja que, durante alguma alteração (insert, update ou delete) outros usuários não tenham acesso à tabela.

"Locks may be used to emulate transactions or to get more speed when
  updating table"

Ou seja, para trabalhar como se estivesse numa transação ou melhorar a performance. Uma sequência de comandos que exija muita alteração por exemplo é um caso que pode ser usado o lock tables.
Devo evitar usar esse comando em alguns casos? Existe algum risco?
A não ser para uma operação muito específica, não deve usar esse comando.
O mysql automaticamente faz o lock necessário quando executa alterações, inclusive um lock de linha e não de tabela quando necessário, por isso deixe o mysql gerenciar isso.
O risco é óbvio: deixar a tabela locada, deixando o banco lento e prejudicando outras operações.
Diferente de um lock que a engine do mysql faz, a tabela não sairá do lock automaticamente, sendo necessário executar UNLOCK TABLES ao final do processo.

A: Uma coisa que me confundiu um pouco e acho que não ficou bem esclarecido é que:

*

*Read locks são locks "compartilhados", eles previnem que um write lock seja adquirido, mas não outro read lock, ou seja outras sessões podem ler tabela, só não poderão gravar até que seja liberado o lock.

*Write locks são "exclusivos", previnem qualquer outro lock tanto de escrita, como de leitura, outra sessões que tentar ler ou gravar algum registro, ficará em estado de espera, até que seja liberado o lock.


text:
Q: Live editing SCSS files in Chrome DevTools with Prepros I just started using Prepros to compile my SCSS files and I can't seem to figure out how to enable live editing of those files in Chrome Developer Tools.
I'm not really sure how this is supported nowadays, but I've found some examples showing this in action (such as this video) and I know it used to be an experimental feature in earlier versions of Chrome.
In Prepros, I have Source Map enabled and the map is showing up in my filesystem properly.
Chrome is also showing all the SCSS files correctly, but I can't save any changes to the file system (basically, whenever I change something, it only changes in the compiled main.css file).
As you can see here, there are no green dots next to the SCSS files:

...and when I try to edit and save them in the Sources panel, this shows up:

Here's my Prepros project structure (everything gets compiled into the main.css file):

Is there any way to set this up so that I could edit anything in DevTools and save it to the file system from there? I want to avoid copying code over to my text editor as much as possible.


text:
Q: Mongoose how to update document array item for given document array property item Consider the following collection of documents with an array of documents inside:
PurchaseOrder {
   id: '5b675d8180db9c13ac5b5c16',
   productItems: [
      {
          quantity: 10,
          discount_id: '5af6452dcab5ce0ee2d47e63'
      },
      {
          quantity: 10,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      },
      {
          quantity: 12,
          discount_id: null
      },
      {
          quantity: 9,
          discount_id: '5af6452dcab5ce0ee2d47e63'
      },
      {
          quantity: 7,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      },
      {
          quantity: 3,
          discount_id: null
      },
      {
          quantity: 5,
          discount_id: '5af6452dcab5ce0ee2d47e66'
      }
   ]
}

I need to update, programatically using mongoose, for all collection, all discount_id's where discount_id equals certain id (example: 5af6452dcab5ce0ee2d47e63).
Here is my try:
let selectedDiscount = {
   _id: '5af6452dcab5ce0ee2d47e63'
}

PurchaseOrderModel.update(
        {},
        { $set: { "productItems.$[item].discount_id": null } },
        {
            multi: true,
            arrayFilters: [{ "item.discount_id": selectedDiscount._id }]
        }
    );

Unfortunatelly I'm getting an error Can't use $set with the above statement.
How can I achieve such an operation in a single mongoose call ?