text:
Q: Which is correct between "and" or "but" Situation is like as follows:

The more A is reduced, the better the performance is.
The more B is reduced, the better the performance is.
The more C is increased, the better the performance is.

The sentence is like this:

Since blah~blah~blah, both A and B have been significantly reduced, (and, but) C also has been increased.

1st thought: increased is a counterpart of reduced, so "but" is correct.
2nd thought: the former sentence gives better performance, the latter one also gives better performance, so "and" is correct.
I do not know which is correct.

A: I think your perplexity arises because you are working with a sentence fragment rather than an entire sentence.
Because A and B have been reduced and [because] C has been increased, the performance of D has been improved.
Use of but instead of and in the preceding sentence would be grammatical, but it would be inconsistent with the overall meaning of the complete sentence. The choice of the correct word depends on that overall meaning, not words or clauses considered in isolation from the rest of the sentence.

A: but indicates a contrast, while and and also indicates a similarity. In this case, A, B and C share two relations, a common cause "blah-blah-blah" and a common outcome "performance".
Now the "performance" doesn't matter at all in your example sentence. That's not the problem. The only problem you have is but also, and that's a minor problem here. It indicates both a similarity and a contrast. That is technically correct, because C is similar in being influenced in blah-blah, but different in the direction in which it is influenced.
This isn't a problem particular to English. You just need to choose what you are trying to communicate, the similarity or the difference. (if at all)

Since blah~blah~blah, both A and B have been significantly reduced, **and also ** C has been increased.

(Stressing similar cause)

Since blah~blah~blah, both A and B have been significantly reduced, but C has been increased.

(Stressing  Different direction of change)

Since blah~blah~blah, both A and B have been significantly reduced and C has been increased.

(Not stressing either, just listing all three effects)
Note that but also does occur in the common pattern not only X but also Y. We here see that but indicates a contrast here, between (not) only X and X and also Y


text:
Q: Looping a recorded macro in Excel I am not familiar with VBA so please forgive the simplicity of this question. I have a recorded macro which selects, opens then saves a file from a hyperlink in one of my columns. I just want to make a loop to repeat this macro down all of the rows in the worksheet which have data in them. Below is the code for the recorded macro, thank you all for your assistance.
Sub Extract()
'
'Extract Macro
'

'
Range("D2").Select
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
Workbooks.Open Filename:= _
    "https://channele.corp.etradegrp.com/communities/teams02/performance-monitoring/TPEF%20Library/A2Consulting_Tech_5650_VSAF.xlsm"
ActiveWindow.Visible = False
Windows("A2Consulting_Tech_5650_VSAF.xlsm").Visible = True
ChDir "O:\Procurement Planning\QA"
ActiveWorkbook.SaveAs Filename:= _
    "O:\Procurement Planning\QA\Copy of A2Consulting_Tech_5650_VSAF.xlsm", _
    FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWindow.Close
End Sub

A: Something like this might work already:
Sub Extract()

    Dim RngTarget As Range
    Dim StrFileName As String

    Set RngTarget = Range("D2")

    Do Until RngTarget.Value = ""

        RngTarget.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
        Workbooks.Open Filename:=RngTarget.Value
        StrFileName = Split(RngTarget.Value, "/")(UBound(Split(RngTarget.Value, "/")))
        Windows(StrFileName).Visible = True
        Workbooks(StrFileName).SaveAs Filename:="O:\Procurement Planning\QA\Copy of " & Split(StrFileName, ".")(0) & ".xlsm", _
                                      FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
                                      CreateBackup:=False
        Workbooks(StrFileName).Close

        Set RngTarget = RngTarget.Offset(1, 0)
    Loop

End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: request.path and url_for don't match up in Flask under mod_wsgi In Flask, is there a way to get the request.path that includes any "decorations" that WSGI or something else may add on?
Running in the test mode (just on port 5000), my request.path and url_for('settings') match up just fine, but once under WSGI, as expected, my url_for('settings') becomes /manage/settings/, but the request.path yeilds /settings/.
I have the following in my httpd.conf and am working on moving an application from development into a live site.
WSGIScriptAlias /manage /sw/servermanager/servermanager.wsgi
WSGIDaemonProcess servermgr user=user group=grp threads=4
<Directory /sw/servermanager>
    WSGIProcessGroup servermgr
    WSGIApplicationGroup %{GLOBAL}
    WSGIScriptReloading On
    Order deny,allow
    Allow from all
</Directory>

I like the idea of having the templates be pretty generic and then display the navigation information on the fly using CSS. I've used the technique provided in this answer to structure my views to this point, but the issue arises when I add mod_wsgi into the equation.
I took a look around the request object and didn't see as much as I'd like other than possibly using the url_rule but then the parameters evaded me.
Just for good measure, a link for the WSGI Script that I'm using: https://github.com/FernFerret/servermanager/blob/master/servermanager.wsgi
I'd also be interested in the documentation for the request object, I found my way around it by using the built in debugger and help(request).
EDIT: I should say, that the urls don't match up under Apache running mod_wsgi.

A: That's a feature, not a bug. Check out documentation for the URL-related attributes on the request and for the request object itself.
You may want to use request.script_root + request.path.


text:
Q: KMeans implementation in python with OOP? I am trying to implement KMeans algorithm as a class and when i done all code i test with creating object and than train the dataset. But i get the following error.
self.distances = np.zeros((self.N, self.n_clusters))
TypeError: only integer scalar arrays can be converted to a scalar index
from abc import ABC, abstractmethod

class KMeansInterface(ABC):

    @abstractmethod
    def fit(self, X):
        pass

    @abstractmethod
    def predict(self, X):
        pass

class Kmeans(KMeansInterface):
    def __init__(self, n_clusters):
        self.n_clusters = n_clusters
        self.labels = None
        self.distances = None
        self.N = X.shape[0]
        self.data_points = X
        self.prev_labels = None

    def choose_clusters(self, k, X):
        self.n_clusters = k
        size = X.shape[0]
        numbers = np.random.choice(size, k, replace=False)
        return X[numbers]

    def calculate_sum_squared_distance(self, data_points, clusters):
        self.distances = np.zeros((self.N, self.n_clusters))
        for i, centroid in enumerate(clusters):
            distance = np.sum(np.square(data_points-centroid), axis=1)
            self.distances[:, i] = distance
        return self.distances

    def calculate_closest_clusters(self, distances):
        self.closest_clusters = np.argmin(self.distances, axis=1)
        return self.closest_clusters

    def update_clusters(self, labels, data_points):
        new_clusters = []
        for i in range(self.n_clusters):
            points_in_cluster = data_points[labels==i]
            values = np.mean(points_in_cluster, axis=0)
            new_clusters.append(values)
        return np.array(new_clusters)

    def fit(self, X):
        self.n_clusters = self.choose_clusters(self.n_clusters, X)

        for i in range(20000):
            self.distances = self.calculate_sum_squared_distance(X, self.n_clusters)
            self.labels = self.calculate_closest_clusters(self.distances)
            self.new_cluster = self.update_clusters(self.labels, X)
            if self.prev_labels is not None:
                if np.all(self.prev_labels == self.labels):
                    break
            self.prev_labels = self.labels
            fitted = True
        return self.labels

    def predict(self, X, clusters):
        self.distances = self.calculate_sum_squared_distance(X, clusters)
        self.labels = self.calculate_closest_clusters(self.distances)
        return self.labels

kmean_object = KMeans(2)
kmean_object.fit(X)


text:
Q: Questions about the proof of the Gauss-Bonnet Theorem for surfaces with boundary (This comes from the proof of the Gauss-Bonnet Theorem for surfaces with boundary. See Do Carmo's 'Differential Forms and Applications' Chapter 6, Theorem 2.)

Let $M$ be an oriented, compact, two-dimensional differentiable manifold with boundary $\partial M$.
Let $X$ be a differentiable vector field on $M$ such that it is transversal to $\partial M$.
Now choose a metric on $M$ and consider in $M$ the orthonormal oriented moving frame $\bar{e}_1=X/|X|,\; \bar{e}_2$.
Choose in a neighborhood $V\subset M$ of $\partial M$ another oriented moving frame $e_1,e_2$ such that restricted to $\partial M$, $e_1$ is tangent to $\partial M$. Then
$$
i^*\bar{\omega}_{12}=i^*\omega_{12}+d\phi
$$
where $i:\partial M\to M$ is the inclusion map, and $\phi$ is the angle between $\bar{e}_1$ and $e_1$ along $\partial M$.
Then in the proof of the Gauss-Bonnet Theorem for surfaces with boundary. A key step states that:

Since $\bar{e}_1=X/|X|$ is nowhere tangent to $\partial M$, $\int_{\partial M}d\phi=0$.

This statement confuses me.
My main question is, how to prove this statement?

My initial thought is, by Stokes Theorem, it seems that $\int_{\partial M}d\phi=\int_{M} d^2\phi=0$ is always true, soon I realized that $d\phi$ is not a 1-form defined in $M$.
So my second question is, if there are two moving frames $\{e_1,e_2\}$ and $\{\bar{e}_1,\bar{e}_2\}$ satisfying:
$$
\bar{e}_1=fe_1+ge_2\\
\bar{e}_2=-ge_1+fe_2
$$
with $f,g$ being differentiable functions, and $f^2+g^2=1$, then the connection forms satisfy:
$$
\omega_{12}=\bar{\omega}_{12}-\tau
$$
where $\tau$ is the differential of the "angle function" between $e_1$ and $\bar{e}_1$ along a curve.
My question is, is the 1-form $\tau$ exact?

Again, I think the answer should be no. For instance, the differential of the "angle function" in $R^2$ is closed but not exact, since it is defined in $R^2-\{0\}$, but I still struggle to prove this in a more general 2-d manifold.

It is a long post, thank you for reading, and any hints are appreciated!


text:
Q: enter text in a popup, cant find elements with python selenium Im trying to get some text entered into the username and password boxes in a popup
https://fantasy.espn.com/football/players/add?leagueId=1
I assume that there is a popup so I believe Ive switched to it. Im not able to find any elements that I can select. I tried doing
driver.find_element_by_xpath("//input[@type='email']")
or
driver.find_element_by_xpath("//input[@placeholder='Username or Email Address']")
Both times I'm getting the error stating element not found:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get("https://fantasy.espn.com/football/players/add?leagueId=1")
time.sleep(15)
driver.find_element_by_xpath("//input[@placeholder='Username or Email Address']")

A: The pop-up is loading within an iframe. You have to first switch to the iframe and then find rest the fields using xpath or other selectors.
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = Chrome('drivers/chromedriver')
driver.get('https://fantasy.espn.com/football/players/add?leagueId=1')
iframe_xpath = '//*[@id="disneyid-iframe"]'
iframe = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable(
        (By.XPATH, iframe_xpath)
    )
)
driver.switch_to_frame(iframe)
username_field = driver.find_element_by_xpath("//input[@type='email']")
password_field = driver.find_element_by_xpath("//input[@type='password']")
login_button = driver.find_element_by_xpath(
    '//*[@id="did-ui-view"]/div/section/section/form/section/div[3]/button'
)
username_field.send_keys('username')
password_field .send_keys('password')
login_button.click()

Edit
Searching for players
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
capabilities = DesiredCapabilities.CHROME
capabilities["pageLoadStrategy"] = "none"
driver = Chrome('drivers/chromedriver', desired_capabilities=capabilities)
driver.get('https://fantasy.espn.com/football/leaders')
player_xpath = '//*[@id="espn-analytics"]/div/div[5]/div[2]/div[1]/div[1]/div/div[2]/div[1]/div/div/div/input'
player_input = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable(
        (By.XPATH, player_xpath)
    )
)
player_input.send_keys('chris\n')


text:
Q: Missing "session stickiness" from ELB I'm new to AWS so I'm surely missing something basic but I've created a new ELB and I see no "Edit stickiness" configuration under the "Description" section of the ELB, as described in this AWS tutorial .
Any help will be appreciated,
thanks!

A: For anyone stumbling across that - you are most likely using an "application load balancer" which means you need to follow these steps to enable stickiness.


text:
Q: How to paste text into Vim Visual Mode? i am working in vim and I would like to paste yanked text into Visual Mode. Is it possible?

A: The p command works in visual mode, too (cp. :help v_p). However, the default register contents will be overwritten. (My ReplaceWithRegister plugin has an alternative command that keeps it.)
Alternatively, you can s or c to replace the visual selection, and then use one of the insert mode commands like <C-R>{register} to insert the register contents. For pasting the default register, you need to use "_s to avoid overwriting its contents.


text:
Q: making a phone call through asp.net web portal my landline phone is connected to my computer. Now in my asp.net website there is a textbox and a button . i filled a telephone number in the textbox and on button click i want that a call get connected to the no. in the textbox through my landline phone.
Is there any workaround for this in .net framework?

A: If it's connected to a MODEM in your computer you might be able to use .NET Serial Port communication to talk to the modem to get it to dial for you.  Look at the Serial communication classes and your modem manual.
System.IO.Ports contains a class called SerialPort which you can use like this ...
        var sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);

        sp.ReadTimeout = 5000;
        sp.NewLine = "" + (char)13;
        sp.WriteTimeout = 5000;
        sp.DtrEnable = true;
        sp.RtsEnable = true;
        sp.Handshake = Handshake.None;

        sp.Open();

        SerialPort.DataReceived += new SerialDataReceivedEventHandler(SerialDataReceivedEventHandler);

Now you can send the appropriate autodial commands to the modem (ATDT ...) and you can create an event handler 'SerialDataReceivedEventHandler' to receive messages back from the modem.


text:
Q: Why does iOS obtain app thread startup time sometimes exceeds the actual startup time I get app thread start time via sysctl. Then, when the app starts in the background (such as receiving an incoming call), I calculate the preMain duration of the app. Most of the time, the data is normal (hundreds of milliseconds). But occasionally a very large duration (such as tens of seconds) appears. It feels like restarting the mobile phone test has a higher probability.
    // Code in main.swift
    let appStartLaunchTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()

    // Calculate preMain time
    var preMain = appStartLaunchTime - appLaunchTime! + kCFAbsoluteTimeIntervalSince1970

    public var appLaunchTime: Double? = {
        var processInfo = kinfo_proc()
        var size = MemoryLayout<kinfo_proc>.stride
        var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
        guard sysctl(&mib, u_int(mib.count), &processInfo, &size, nil, 0) == 0 else {
            return nil
        }
        let startTime = processInfo.kp_proc.p_starttime
        let time = (Int64(startTime.tv_sec) * 1000) + Int64(startTime.tv_usec / 1000)
        return Double(time) / 1000.0
    }()


text:
Q: Terraform Apply hangs and crashes ever since force quitting a previous apply Currently, when I try to run terraform plan or terraform apply, my code hangs for a very long time before eventually throwing this command
Error: error configuring Terraform AWS Provider: error validating provider credentials: error calling
sts:GetCallerIdentity: operation error STS: GetCallerIdentity, exceeded maximum number of attempts, 25,
https response error StatusCode: 0, RequestID: , request send failed, Post
 "https://sts.us-east-1a.amazonaws.com/": x509: "Kubernetes Ingress Controller Fake Certificate"
certificate is not trusted

│
│   with module.test.provider["registry.terraform.io/hashicorp/aws"],
│   on asg-launch-configuration/provider.tf line 1, in provider "aws":
│    1: provider "aws" {
│

This only stared to happen after I believe a previous terraform apply was interrupted with a Control + C.  I have deleted all of the terraform state files (I believe) and have even deleted the entire folder where the code was, but the error persists when I try to run other terraform apply commands.  I have also went into the aws console and I believe deleted all the items that are provisioned by that terraform code.
Any idea what issue may have occurred?
Edit:
I am using a module, but the provider block is only this:
provider "aws" {
     region = var.region
}

Edit 2:
It turns out there was a ec2_instance_profile that had not been deleted.  I was able to change the aws region and when running terraform apply it told me that the above was still there, and I was able to delete it using the AWS CLI.  Now everything works as expected.

A: It turns out there was a ec2_instance_profile that had not been deleted. I was able to change the aws region and when running terraform apply it told me that the above was still there, and I was able to delete it using the AWS CLI. Now everything works as expected.


text:
Q: a single decisive word for a "positive result" It says:

The sweeping prevalence of technology is an undeniable fact today. Both
  fruits and repercussions of such prevalence have reached epidemic
  proportions.

Can fruit mean a positive result, here? and if yes, is it because of the context (mainly due to its contrast to repercussion) or it independently sounds that way?
Dictionaries are not forthcoming enough about this, attributing fruit to both
results and consequences(implicitly conveying a negative result). So my question is:
What's really a decisive, yet general word for a positive result? I'm saying "general" to rule out the words like harvest[n.] which mean "result of an effort"
I also came across similar questions here on the website, but they seem fail to be frank enough.
Thanks in advance

A: For greater clarity, I would have used "benefits and drawbacks" instead of"fruits and repercussions".


text:
Q: Is there a way to automatically disable the UAC each time Windows 7 boots (I'm an administrator)? At work, we have a group policy (I think it is a group policy, correct me if I use the wrong term!) that automatically resets the UAC to "Default" every two days or so.
I'm administrator on the computer and I have the rights to disable the UAC. For some reasons (please no discussion about this...) I want the UAC to always be disabled.
Is there a way to set up a scheduled task or something to automatically disable the UAC each time the computer boots?


text:
Q: Boot from live Tails SD card on Mac OSX El Capitan Goal: Boot into Tails from an SD card on a Macbook Air running El Capitan.
Specs: Macbook Air, 8Gb RAM, i5, Running OSX 10.11 "El Capitan".
Solutions tried and problems with each:

*

*Follow Tails instructions for Mac OSX

*

*Problem: After everything is done, reboot, only the Mac HD shows up

*Use rEFInd (v0.9.2):

*

*Created two partitions on the SD card, with a GUID Partition Table (GTP). Both Journaled (HFS+).

*

*/dev/disk2s2 - Tails (dd'd following the instructions from 1.)

*/dev/disk2s3 - rEFInd: ./install.sh --alldrivers --ownhfs /dev/disk2s3 (Also tried without the --alldrivers flag)

*Problem: rEFInd option shows up when rebooting. After selecting it I get three options: Boot Mac OSX, boot Tails (has the Tails logo), or boot legacy BIOS Tails (just shows a windows-like logo in grey).

*

*If I select the one with the Tails logo, it goes to a new screen that says:
rEFInd - Booting OS

Starting bootx64.efi
Using load options ''
Failed to read blocks: 0x2

I have already tried erasing the Tails partition and redoing it a couple of times, with the same output.

*If I select the one that says legacy BIOS Tails... I get a black screen that says the usual No bootable devices found... Insert one and press any key to continue.
Let me know if there is anything missing that could help debug this problem.

A: I'm just guessing here, but a conversation on Mac rumors recomends not using units on the dd bs parameter, so try the guide again using bs=16000000 instead of bs=16m.

A: I eventually found the issue, I had formatted the partition where I put Tails as an ExFAT partition, which doesn't work even though it shows up on the boot menu.
Formatting it as FAT fixed it.


text:
Q: Сокращение времени билда приложения Билд и запуск приложения в Android Studio 3.0 слишком долгий(иногда 20-25 минут) при развертывании на Android 4.3. При этом при развертывании этого же приложения, на устройствах с 5-6 андроидом билдится всего пару минут. От чего вообще может зависеть скорость билда? И как можно сократить это время, оптимизировать

A: две полезные ссылки на эту тему:
https://developer.android.com/studio/build/optimize-your-build.html
https://medium.com/@kevalpatel2106/how-to-decrease-your-gradle-build-time-by-65-310b572b0c43
В частности почитайте как сделать профилирование билда. Как минимум локализуете проблему.
также может быть Вам поможет выделение модулей из проекта. Они будут кэшироваться и билдиться параллельно(если в gradle.properties пропишите org.gradle.parallel=true)
выжимка из второй статьи - измените gradle.properties так:
#Enable daemon
org.gradle.daemon=true

# Try and findout the best heap size for your project build.
org.gradle.jvmargs=-Xmx3096m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# Modularise your project and enable parallel build
org.gradle.parallel=true

# Enable configure on demand.
org.gradle.configureondemand=true


text:
Q: including customized header files in c I am simply trying to implement my own header file in C.
 First up, I have a file INC2.h
void diffadd(int b[], int n);
int diffcheck(int m);

Then I make a file INC2.cpp
void diffadd(int b[], int n)
     {
     int i=0;
     for (i=0; i < n; i++)
          {
          b[i]=b[i]+1;
          printf("\n%d",b[i])
           }
      }
 int diffcheck(int m)
     {
      return (m*5);
      }

Then in the main file LETS.cpp
  #include"inc2.h"
  void main()
      {
       clrscr();
       int a[5]={1,2,3,4,5};
       diffadd(a,5);
       int t=diffcheck(5);
       printf("t=%d",t);
       getch();
       }

Now I compile inc2.cpp.   FINE!
Then I compile lets.cpp.
I get the following errors:
Undefined symbol diffcheck(int) in module LETS.cpp
Undefined symbol diffadd(int near*, int) in module LETS.cpp
Interestingly, if I include inc2.cpp in LETS.cpp, IT WORKS.
If I create a separate header file HEAD.h and define all the functions here, IT WORKS.
PLease Explain what is happening here!

A: You should look up some tutorials on the internet about program linking.
When you compile a single .c/.cpp file, compilers often do linking work for you and you have a complete executable on its output. But when you have more than one source file, things get complicated: each of the source files (not .h, headers!) is compiled to an intermediate file, object file, which contains a list of symbols (function/variables names/addresses in memory - all that resides in memory and is visible to external files) that the file provides and a separate list of symbols that the file requires. This stage is called compilation itself. Then you have a bunch of object files that can be combined with a special program, linker, into the executable you want - this is called linking a program. The linker gets the lists of required/provided symbols of all files and looks up whether all required symbols can be found in the given set of provided symbols in all object files and then links provided functions to places where they're required.
Header files are just text stubs that are included literally into source files (.c/.cpp), they're not a subject for compilation (with some exceptions).
Thus: compile your inc2.cpp into an object file, compile lets.cpp into another object file and then let the linker combine them into the executable.

A: When First time I define my own header file I also got the same error. Then I define a header file with definition of function and that worked for me.
You just need to do is. Define header file like
//inc2.h
void diffadd(int b[], int n)
 {
 int i=0;
 for (i=0; i < n; i++)
      {
      b[i]=b[i]+1;
      printf("\n%d",b[i])
       }
  }

int diffcheck(int m)
     {
      return (m*5);
      }
After that call the funciton in main file like
//Lets.cpp
#include"inc2.h"
void main()
  {
   clrscr();
   int a[5]={1,2,3,4,5};
   diffadd(a,5);
   int t=diffcheck(5);
   printf("t=%d",t);
   getch();
   }

It might work for you too.
Either you can also write your header file like name
     #include"inc2.pp"
That will also work.


text: Q: Share files and folders between Mac, Windows and Linux I've read a lot about this but I want this a little bit different. The articles about FTP and folder sharing all needs a specific software at both end hosts like SAMBA. But I want to connect the server using the address and a password without installing additional software, so me and my friends could share some documents with ease. I want to host an FTP server on my Arch Linux and copy files in there from other OSes wirelessly(MAC/Windows). The ones connecting the server would need to provide passwords to access the FTP server but wouldn't need any additional software. We're all on the same WiFi. Is it possible?


text:
Q: Git hooks: Change commit message depending from diff of specific files If specific files changed(list of path to files are stored in a file), then need to append some text to commit message, like New OSB config needed and of course commit it. What hook I need to use?

A: You can't change a commit once it's made (because it is stored by its object ID, which is a checksum of its contents, so that if you attempt to change anything you get a new, different object ID).  This means you must use a hook that runs before the commit is made.  So, consulting the githooks documentation, we find three hooks run before making a commit (and one after, which is too late):

*

*pre-commit

*prepare-commit-msg

*commit-msg
The first one runs too early, before the commit message exists in any form.  That leaves only two possibilities: before the commit message is given to you to edit (prepare-commit-msg), or after you have finished editing it but before it gets used as part of the commit creation (commit-msg).
Choose which you prefer, noting the --no-verify point as well.  In general I find hooks that do stuff I can't see to be obnoxious (which for me would push me towards the "prepare" hook), but presumably this hook will be your own creation, used only by you, so you can set it up however you prefer.


text:
Q: How to search a word in a dictionary with a document in R? I have created a dictionary of words. Now I need to check whether the word in the dictionary is present in the document or not. The sample of the document is given below:
Laparoscopic surgery, also called minimally invasive surgery (MIS), bandaid surgery, or keyhole surgery, is a modern surgical technique in which operations are performed far from their location through small incisions (usually 0.5–1.5 cm) elsewhere in the body.

There are a number of advantages to the patient with laparoscopic surgery versus the more common, open procedure. Pain and hemorrhaging are reduced due to smaller incisions and recovery times are shorter. The key element in laparoscopic surgery is the use of a laparoscope, a long fiber optic cable system which allows viewing of the affected area by snaking the cable from a more distant, but more easily accessible location.

From this document, I have split each paragraph into each sentence as follows:
[1] "Laparoscopic surgery, also called minimally invasive surgery (MIS), bandaid surgery, or keyhole surgery, is a modern surgical technique in which operations are performed far from their location through small incisions (usually 0.5–1.5 cm) elsewhere in the body."
[2] "There are a number of advantages to the patient with laparoscopic surgery versus the more common, open procedure."
[3] "Pain and hemorrhaging are reduced due to smaller incisions and recovery times are shorter."
[4] "The key element in laparoscopic surgery is the use of a laparoscope, a long fiber optic cable system which allows viewing of the affected area by snaking the cable from a more distant, but more easily accessible location."

The dictionary includes the following words:
Laparoscopic surgery
minimally invasive surgery
bandaid surgery
keyhole surgery
surgical technique
small incisions
fiber optic cable system

Now I want to search for all words in the dictionary with those in each sentence using R? The code that I have worked out is given below.
c <- "Laparoscopic surgery, also called minimally invasive surgery (MIS), bandaid surgery, or keyhole surgery, is a modern surgical technique in which operations are performed far from their location through small incisions (usually 0.5–1.5 cm) elsewhere in the body.

   There are a number of advantages to the patient with laparoscopic surgery versus the more common, open procedure. Pain and hemorrhaging are reduced due to smaller incisions and recovery times are shorter. The key element in laparoscopic surgery is the use of a laparoscope, a long fiber optic cable system which allows viewing of the affected area by snaking the cable from a more distant, but more easily accessible location."

library(tm)
library(openNLP)

convert_text_to_sentences <- function(text, lang = "en") {
sentence_token_annotator <- Maxent_Sent_Token_Annotator(language = lang)
text <- as.String(text)
sentence.boundaries <- annotate(text, sentence_token_annotator)
sentences <- text[sentence.boundaries]
return(sentences)
}

q <- convert_text_to_sentences(c)

A: Assuming q is a character vector (or list) of the sentences and you're interested in exact matches of the keywords only, then you can use regular expressions:
matches = lapply(q, function(x) dict[sapply(dict, grepl, x, ignore.case=T)])

You get a list of the length of q. Every list element contains a vector of the dictionary words found in the according sentence.


text:
Q: Can not connect to VM instance via SSH Today I found out I can not connect to my VM instance via SSH anymore.
I have checked and even re-added firewall rule to open port 22, yet I see the port is closed. I have done nothing that I can recollect that could have ended up closing that port.
I have also tried logging in via serial port, but I have no login password for that (I always let google just log me in with key).
Can anyone help me?


text:
Q: How can i subtract a column vector from each column of a given matrix in R? I thought about generating a blank matrix and then updating each element using a double loop, but it returns the blank matrix once again.
Here is my code: (dataset.df is the initial matrix, riskfree.df is the column i want to subtract, asset.names is simply a list of length 25 and dataset_corretto.df is the name of the new matrix i want to create)
**dataset_corretto.df = matrix(0, 618, 25)
for (j in dataset.df) {
  for (i in asset.names){
    dataset_corretto.df[j,i] = dataset.df[j,i] - riskfree.df[j,1]
  }
}
dataset_corretto.df**


text:
Q: how to dynamically get the list of messaging apps on the phone I know how to get the list of installed applications on the mobile phone.
Is it possible to dynamically get the list of installed messaging apps on the phone like whatsapp, viber etc?
How to achieve this through code?
EDIT: I am specifically looking for apps which are capable of sending messages through mobile data or wifi.. amongst which some examples include whatsapp or viber.


text:
Q: How to read a paragraph from cli for a message body using Java I'm working on a program which reads and writes an Excel file containing data about different companies, such as its location, telephone number and e-mail addresses. Since I'm still studying in college and I haven't studied yet how to make a proper interface, the program runs as a cmd window, and you have to navigate through the program's menu writing text using keyboard.nextLine() each time you want to pass to the next line.
One of the functionalities of the program will be sending a personalized mail to a specific or a list of companies using the associated e-mail address. The struggle comes when I ask the user to write the body paragraph of the message. Since I'm using keyboard.nextLine() for inputs, each time that the user would want to pass to the next line using the "Intro" key, the Scanner will stop reading. I could make a method to keep adding the String input to a String variable until the user say so, but I would want the user to be completely able and free to write, re-write and delete the message as much as he/she wants; so using this idea would be too annoying for the user.
I've thought about opening a text file as a window right when the user have to write down the text and then making the program write that file into a String variable; but I haven't been able to implement this succesfully. I've tried to recycle a method I found to clear the cmd window, changing the clear command to text.txt, but it didn't work at all:
public static void openText(){

    try {
        if (System.getProperty("os.name").contains("Windows")) {
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        } else {
            Runtime.getRuntime().exec("c:Body.txt");
        }
    } catch (IOException | InterruptedException ex) {}
}

So, I would like to know how to either open an editable text window as I've thought to do or another solution to this problem that I haven't thought of.

A: Did you take a look at Swing?
It's not that much harder than doing command line interactions.
Basically what you need is a JFrame with a JTextArea in it and an 'OK' button.
Here's a nice example with even cut/copy/paste buttons in it:
Java Swing | Create a simple text editor


text:
Q: Getting Array out of bound exception in my code The code below throws an Array out of bound exception. I want to print the blank value also.
Here sourceDir[i].length=3 and targetDir[i].length=10. If I remove sourceDir[i].getName then it works fine.
int compareSize = sourceDir.length > targetDir.length ? sourceDir.length : targetDir.length;
    String[] resultArr = null;
    String resultFilename = null;

    for(int i = 0; i < compareSize; i++){
        resultFilename = currDir + "\\Results\\Result" + (i+1) + ".htm";
        readReport = new BufferedReader(new FileReader(resultFilename));
        resultArr = getResult(readReport);

        bw.write("
" + (i+1) +  "	" + sourceDir[i].getName() + "	"
                + targetDir[i].getName() + "	" + resultArr[0] + "	" + resultArr[1]
                + "	" + "Link to Result
");
    }

    bw.write("

");
    bw.close();
}

A: The answer to this question is straight forward.

*

*Consider sourceDir.length=5 and targetDir.length=3.

*In this case compareSize=5

*Now you are running a for loop from i=0 to 4.

*When i=3,  sourceDir[3].getName() works fine, but targetDir[3].getName() will throw an ArrayIndexOutOfBoundsException since targertDir[3] does not exist!

You will get the same ArrayIndexOutOfBoundsException for sourceDir[i].getName() if targetDir.length>sourceDir.length

A: Ok compareSize will equal the larger number length. Your problem is in your loop one of your dir is smaller so when [i] reaches a number higher then the length of the smaller dir it will go out of bounds.
One solution is change resultArr to:
List<String> resultArr = new ArrayList<>();

And inside the for loop (makes sure nothing goes out of bounds):
 if(i < sourceDir.length){
        System.out.println(sourceDir[i]);   //just so you can see value
        resultArr.add(sourceDir.get(i));    //add everything to an arrayList
    }
 if(i < targetDir.length){
        System.out.println(targetDir[i]);   //just so you can see value
        resultArr.add(targetDir.get(i))     //add everything to an arrayList

    }

outside of 1st for loop you can iterate through the resultArr arrayList now:
  for(int j =0; j < resultArr.size(); j++){
         //do the code you done before from first for loop in here
  }

You could use a for each loop as well but if your new to java then you're understanding of objects is probably non existent


text:
Q: Asp.Net: Is a GridView really able to handle for all browsers or only a pain? I am Asp.Net Developer since 3 years now.
I had different projects in which we used the ASP.Net-GridView-Control.
The problem ist, we had really really a pain by designing the GridView. We need around 2-10 hours per GridView only for a simple design. It was such a pain, you didn't believe. (and Yes, we really used CSS and so on!). Even after very much work on the GridViews it doesn't look the same in every browser. In IE7/8 it looks still different as in FF 3/4 or IE9.
My newest project need to 100% a same looking user interface in every browser and need 100% well design and style. So there is no space for CSS&GridView-Bugs (I can list you over 20 of these!) or hours after hours for a simple GridView to design.
So my question is:

*

*Is it able to handle the different lookings in browsers for the GridView?

*Did I miss anything in styling a gridView, which can cause my unlimited pain with GridViews?

*Is there another easy and good control, which I can bind on an ObjectDataSource and work with, which has nearly the same functions as a GridView? (Example: bind ImageButtons on a coloum)

A: Use a ListView. It makes no difference if you use CSS with the GridView because the GridView will still create a table-based layout. By using the ItemTemplates with the ListView , you can have total control over the markup generated with CSS. Of course, tabular data still warrants the use of tables...
http://msdn.microsoft.com/en-us/magazine/cc337898.aspx
Once you have your CSS-based layout being generated, you can use the HTML5Boilerplate project to gain cross-browser compatibility in a 'graceful degradation' manner:
http://html5boilerplate.com/

A:
We need around 2-10 hours per GridView
  only for a simple design.

and

need to 100% a same looking user
  interface in every browser and need
  100% well design and style.

By the sound of it, you need to buy a third party toolset like DevExpress, Infragistics,  Telerek, or etc. instead.  These companies have already figured out how to solve these needs.  The cost can be easily justified based on the first need alone.
So the answer is: buy a third-party toolkit.


text:
Q: Writing single CSV header with pandas I'm parsing data into lists and using pandas to frame and write to an CSV file. First my data is taken into a set where inv, name, and date are all lists with numerous entries. Then I use concat to concatenate each iteration through the datasets I parse through to a CSV file like so:
counter = True
data = {'Invention': inv, 'Inventor': name, 'Date': date}

if counter is True:
  df = pd.DataFrame(data)
  df = df[['Invetion', 'Inventor', 'Date']]

else:
  df = pd.concat([df, pd.DataFrame(data)])
  df = df[['Invention', 'Inventor', 'Date']]

  with open('./new.csv', 'a', encoding = utf-8) as f:
    if counter is True:
      df.to_csv(f, index = False, header = True)
    else:
      df.to_csv(f, index = False, header = False)

counter = False

The counter = True statement resides outside of my iteration loop for all the data I'm parsing so it's not overwriting every time.
So this means it only runs once through my data to grab the first df set then concats it thereafter. The problem is that even though counter is only True the first round and works for my first if-statement for df it does not work for my writing to file.
What happens is that the header is written over and over again - regardless to the fact that counter is only True once. When I swap the header = False for when counter is True then it never writes the header.
I think this is because of the concatenation of df holding onto the header somehow but other than that I cannot figure out the logic error.
Is there perhaps another way I could also write a header once and only once to the same CSV file?

A: It's hard to tell what might be going wrong without seeing the rest of the code.  I've developed some test data and logic that works; you can adapt it to fit your needs.
Please try this:
import pandas as pd

early_inventions = ['wheel', 'fire', 'bronze']
later_inventions = ['automobile', 'computer', 'rocket']

early_names = ['a', 'b', 'c']
later_names = ['z', 'y', 'x']

early_dates = ['2000-01-01', '2001-10-01', '2002-03-10']
later_dates = ['2010-01-28', '2011-10-10', '2012-12-31']

early_data = {'Invention': early_inventions,
    'Inventor': early_names,
    'Date': early_dates}

later_data = {'Invention': later_inventions,
    'Inventor': later_names,
    'Date': later_dates}

datasets = [early_data, later_data]

columns = ['Invention', 'Inventor', 'Date']
header = True
for dataset in datasets:
    df = pd.DataFrame(dataset)
    df = df[columns]
    mode = 'w' if header else 'a'
    df.to_csv('./new.csv', encoding='utf-8', mode=mode, header=header, index=False)
    header = False

Alternatively, you can concatenate all of the data in the loop and write out the dataframe at the end:
df = pd.DataFrame(columns=columns)
for dataset in datasets:
    df = pd.concat([df, pd.DataFrame(dataset)])
    df = df[columns]
df.to_csv('./new.csv', encoding='utf-8', index=False)

If your code cannot be made to conform to this API, you can forego writing the header in to_csv altogether.  You can detect whether the output file exists and write the header to it first if it does not:
import os

fn = './new.csv'
if not os.path.exists(fn):
    with open(fn, mode='w', encoding='utf-8') as f:
        f.write(','.join(columns) + '\n')
# Now append the dataframe without a header
df.to_csv(fn, encoding='utf-8', mode='a', header=False, index=False)

A: I found the same problem. Pandas dataframe to csv works fine if the dataframe is finished and no need to do anything beyond any tutorial.
However if our program is making results and we are appending them, it seems that we find the repetitive header writing problem
In order to solve this consider the following function:
def write_data_frame_to_csv_2(dict, path, header_list):
    df = pd.DataFrame.from_dict(data=dict, orient='index')
    filename = os.path.join(path, 'results_with_header.csv')
    if os.path.isfile(filename):
        mode = 'a'
        header = 0
    else:
        mode = 'w'
        header = header_list

    with open(filename, mode=mode) as f:
        df.to_csv(f, header=header, index_label='model')

If the file does not exist we use write mode and header is equal to header list. When this is false, and the file exists we use append and header changed to 0.
The function receives a simple dictionary as parameter, In my case I used:
model = { 'model_name':{'acc':0.9,
                    'loss':0.3,
                    'tp':840,
                    'tn':450}

      }

Using the function form ipython console several times produces expected result:
write_data_frame_to_csv_2(model, './', header_list)

Csv generated:
model,acc,loss,tp,tn
model_name,0.9,0.3,840,450
model_name,0.9,0.3,840,450
model_name,0.9,0.3,840,450
model_name,0.9,0.3,840,450

Let me know if it helps.
Happy coding!

A: just add this check before setting header property if you are using an index to iterate over API calls to add data in csv file.
if i > 0:
        dataset.to_csv('file_name.csv',index=False, mode='a', header=False)
    else:
        dataset.to_csv('file_name.csv',index=False, mode='a', header=True)


text:
Q: Ngbdropdown click event not working on ios phonegap with angular 8 running cordova All my NgbDropdown has stopped working on ios devices (cordova app) after upgrade to Angular 8, NGBootstrap 5.
The ngbdropdown works perfect on all browsers on Windows, Apple and Android Cordova, but when used in a Cordova App on a ios device the click event is not triggered. No error is triggered in xcode.
Here is a simple example that should trigger testclick function when you click on a item:
<div ngbDropdown class="d-inline-block">
   <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>Toggle dropdown</button>
      <div ngbDropdownMenu aria-labelledby="dropdownBasic1">
         <button ngbDropdownItem (click)="testclick(1)">Action - 1</button>
         <button ngbDropdownItem (click)="testclick(2)">Another Action</button>
          <button ngbDropdownItem (click)="testclick(3)">Something else is here</button>
      </div>
</div>

Unfortunately the event is not triggered, but the ngbdropdown closes. Tried using focus event with no luck.
The testclick() function is never triggered, but the ngbdropdown closes normally.
If the button is placed outside the ngbdropdown everything works as expected even with the ngbDropDownItem tag:
<div class="col col-12 col-sm-4">
   <button ngbDropdownItem (click)="testclick(1)">Action - 1</button>
</div>

Versions used:

*

*Angular CLI 8.3.18

*Bootstrap: 4.3.1

*NgBootstrap: 5.1.2

Have tried to downgrade Angular, but ran into a big dependency mess with my large project.
Any suggestions?

A: Switched to Ngx-bootstrap dropdown. It works.


text:
Q: Integrals involving functions with big O notation Let,
$$f(x)=g(x)+\mathcal{O}(h(x))$$
As $x\to\infty$.
And suppose $F$ is integrable in some interval $[a,b]$.
Then is,
$$\int_{a}^{b}F(x)df(x)=\int_{a}^{b}F(x)dg(x)+\mathcal{O}\left(\int_{a}^{b}F(x)dh(x)\right)$$
True??
If yes then what's the intuition behind?
So basically my problem is this,
Poisson showed that,
$$\pi(x)=\operatorname{li}(x)+\mathcal{O}\left(\frac{x}{e^{a\sqrt{x}}}\right)$$
As $x\to\infty$
I was thinking about,
$$\theta(x)=\sum_{p\leq x}\ln p$$
and show that $\theta(x)$ is asymptotic to $x$.
I did it like this but just wondering if it's true.
$$\theta(x)=\sum_{p\leq x}\ln p =\sum_{k=2}^{x}\ln k\left(\pi(k)-\pi(k-1)\right)$$
So I doubt the next step and request an explanation,
$$\theta(x)=\int_{2}^{x}\ln k d\pi(k)$$
So from the PNT,
$$\int_{2}^{x}dk+\int_{2}^{x}\ln k dR(k)$$
Where $R(x)=\mathcal{O}\left(\frac{x}{e^{a\sqrt{x}}}\right)$
Using by parts it's easier to show that the second integral is $\mathcal{O}(1)$. Which completes the proof.
I was just wondering if I am right??

A: If $a,b$ are bounded then I don't see why this claim would be true. We don't know how $f$ behaves on the interval of interest.
Also, we need a limit for the last big O notation you use as well.


text:
Q: Fourier analysis an Introduction Chap 4. Exercise 5

*Prove that the sequence {$\gamma_{n}$}$_{n=1}^{\infty},$ where $\gamma_{n}$ is the fractional part of
$$\bigl( \frac{1+\sqrt{5}}{2}\bigr)^{n},$$
is not equidistributed in $[0,1].$
[Hint: Show that $U_{n}=\bigl( \frac{1+\sqrt{5}}{2}\bigr)^{n}+\bigl( \frac{1-\sqrt{5}}{2}\bigr)^{n}$ is the solution of the difference equation $U_{r+1}=U_{r}+U_{r-1}$ with $U_{0}=2$ and $U_{1}=1.$ The $U_{n}$ satisfy the same difference equation as the Fibonacci numbers.]
I got the answer from this site :
Proof. According to the hint, one observes that $U_{n}= W_{n}+\bar W_{n}$ satisfies $U_{r}=U_{r-1}+U_{r-2}$ for $r \ge 2$ and $U_{0}=2$ and $U_{1}=1.$ So $U_{n}\in \Bbb N$ for all $n\in \Bbb Z_{\ge 0}.$ Note that $\bar{W}_{n}\to 0$ as $n\to \infty$ since $\vert \frac{1-\sqrt{5}}{2}\vert<1.$ So we complete the proof since $\gamma_{n}\notin (\frac{1}{4},\frac{3}{4})$ for all large $n$.
I can't understand why particularly $\gamma_{n}\notin (\frac{1}{4},\frac{3}{4})$.

A: $\overline W_n\to0$ as $n\to\infty$ means that, for sufficiently large $n, |\overline W_n|<\frac14.$
(In fact, that would be true for any positive $\epsilon$ in place of $\frac14.)$
If $|\overline W_n|=|U_n-W_n|<\frac14<1$ and $U_n$ is an integer, then
if $W_n>U_n$ then  $\gamma_n=W_n-U_n<\frac14$
and if $W_n\lt U_n$ then $\gamma_n=W_n+1-U_n=1-\overline W_n>\frac{3}4,$
so $\gamma_n \not\in(\frac14,\frac34)$.


text:
Q: Where to ask question about extracting data from optical media? I have several hundreds of optical media disks (mainly DVD-R & CD-R) that stores data, that needs to be transferred to a hard disk drive to improve accessibility.
I need to ask a question about how to make a strategy (software/hardware system) to optimise the time used to perform extraction of this data from all of the disks.
In which community should this type of question be raised?
Sample question:

I need a good strategy for extracting data from several hundreds of optical media disks to a filesystem.
The process of extracting should be as easy as inserting the media into a drive, get extracted, then automatically ejected when finished. Alternatively, inserting several media disks into a media carrousel, inserted the carrousel into the "drive", and give feedback when it is finished extracting all of the disks, either by playing a sound or sending an e-mail.
Are there any solutions already available, and if not; What hardware and what software / operating system would I need?

A: Since it is effectively a hardware and software recommendation question, your best bet is on Software Recommendations and Hardware Recommendations. Since the technical part is the most important in my opinion (if you buy a carousel, it probably tells you what OS you need, etc), I would try to see if it is on-topic on Hardware Recommendations.
Read their help center or ask on their meta before posting your question!


text:
Q: Tool that automatically keeps old versions of a file? Shadow Copy in Win7? When I'm working with a Graphics App, I press CTRL+S a lot to Quicksave. Sometimes, I just went too far and made a bad decision, sometimes to the point Undo wouldn't help either.
I would love to retain old versions of a file. Normally, Source Control would be of use here, but that's a manual process (same as just making some copies).
I wonder if there is an automatic way to do that? Everytime the file changes, keep a backup. I believe that in Windows Server, Shadow Copies can do that. When I check in my Windows 7 (Ultimate), I do see "Previous Versions" as a tab, but that seems to be part of the backup function which is once again manual.
Is there a way to get that type of automatic versioning?

A: Try using DropBox is mostly a service of online storage, but it keeps snapshots of every saved change in your Dropbox folder over the last 30 days.
More info here:
https://www.dropbox.com/help/11

A: Windows shadow copies are automatic; go to System Properties => System Protection and make sure protection is enabled on your drive.  Normally it's tied to System Restore but if you go to "Configure..." you can set it to only manage versions of files and not system state.  You can also configure how much space to allocate.

A: Also, if you're using Adobe flavour of graphic software, they have something called version cue which is basically a version control system for graphic files.
Verson Control on adobe.com

A: The best of the best:

*

*MOGWare. FileHamster

Others:

*

*AJC softWare. AJC Active Backup

*AJC softWare. AJC Sync

*AJC softWare. AJC Revision Archive

*AutoVer                                (http://beanland.net.au/autover)

*TrackMyFiles Iternum (End of life on 31-12-2010) --> DownLoad: 10,50 MB (http://www.filefactory.com/file/4bbrw7z5jo1z/n/Backup_SVN_TrackMyFiles_Iternum_Enterprise_1_5_12_End_of_life_on_31-12-2010_rar)

Good luck!


text:
Q: Why is the ACK flag in a tcpdump represented as a period "." instead of an "A"? This is the output of the three way handshake of a TCP connection:
23:40:36.011400 IP 10.1.1.11.44733 > 73.5.9.44.80: Flags [S], seq 106492654, win 64240, optio0
23:40:36.013994 IP 73.5.9.44.80 > 10.1.1.11.44733: Flags [S.], seq 712839050, ack 106492655, 0
23:40:36.014026 IP 10.1.1.11.44733 > 73.5.9.44.80: Flags [.], ack 1, win 502, options [nop,no0

Inside the brackets are the flags for each packet: [S] [S.] [.]
The man page for tcpdump describes these values:

The general format of a TCP protocol line is:
src > dst: Flags [tcpflags], seq data-seqno, ack ackno, win window,
  urg urgent, options [opts], length len
Src and dst are the source and destination IP addresses and ports.
  Tcpflags are some combination of S (SYN), F (FIN), P (PUSH), R (RST),
  U (URG), W (ECN CWR), E (ECN-Echo) or '.' (ACK), or 'none' if no flags
  are set

Why is the ACK flag represented by a period (.) instead of an A?
Some googling lead me to this:
https://github.com/the-tcpdump-group/tcpdump/issues/319
Which implies the reason for not using an A is described here:
http://article.gmane.org/gmane.network.tcpdump.devel/6383
But this link has been giving me a 522 error =/


text:
Q: Why is there no `keyCode` value on the synthetic event in react using Semantic UI's Search component? I have created a simple Search with Semantic UI's Search Component like this:
<Search
    value={searchString}
    onSearchChange={onSearchChange}
    showNoResults={false}
    size="massive"
    placeholder="eg. Huberdo"
    input="text"
  />

This is my onSearchChange func:
const onSearchChange = (e, data) => {
console.log(e.keyCode);
if (e.keyCode === 13) {
  submit();
}
setSearchString(e.target.value);
};

Here is a minimum example of my problem. https://codesandbox.io/s/blue-leaf-7mzvo?fontsize=14
The Problem:
When I console log the event, I can't find any information about the keyCode that was pressed. e.keyCode is undefined as is e.charCode.
I need this so I can submit the search when the user hits enter.
Where is the keyCode hidden?
According to the Semantic UI Doc's the func gets passed in a normal synthetic react event.
e.target.value is working as expected.

A: You can do this by adding an onKeyDown prop:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Search } from "semantic-ui-react";

import "./styles.css";

function App() {
  const [searchString, setSearchString] = useState("");

  const handleEnter = e => {
    if (e.keyCode === 13) {
      submit();
    }
  };

  const onSearchChange = (e, data) => {
    setSearchString(e.target.value);
  };

  const submit = () => {
    console.log("submitted");
  };

  return (
    <Search
      value={searchString}
      onSearchChange={onSearchChange}
      showNoResults={false}
      size="massive"
      placeholder="eg. Huberdo"
      input="text"
      onKeyDown={handleEnter}
    />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: Unable to autowire dozer Mapper in component class in spring boot I am new to Spring Boot. I was trying to develop small application in spring boot mvc with neo4j database. Following is my Server
@Configuration
@ComponentScan({ "myproject" })
@EnableAutoConfiguration
@EnableNeo4jRepositories(basePackages = "myproject")
public class Server extends Neo4jConfiguration implements CommandLineRunner
{

public Server()
{
    setBasePackage("myproject");
}

@Bean
SpringRestGraphDatabase graphDatabaseService()
{
    return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}

@Bean
Mapper mapper()
{
    return new DozerBeanMapper();
}

public void run(String... args) throws Exception
{
}

public static void main(String[] args) throws Exception
{
    SpringApplication.run(Server.class, args);
}

}

Following is my main class
@Configuration
@ComponentScan({ "myproject.business" })
@EnableNeo4jRepositories(basePackages = "myproject")
public class MainWithStructure extends Neo4jConfiguration implements CommandLineRunner
{
@Autowired
private MyService myService;

public MainWithStructure()
{
    setBasePackage("myproject");
}

@Bean
SpringRestGraphDatabase graphDatabaseService()
{
    return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}

.......
......
public static void main(String[] args) throws Exception
{
    FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));

    SpringApplication app = new SpringApplication(MainWithStructure.class);
    app.setWebEnvironment(false);
    app.run(args);
}

}

Following is my Component class
@Component
public class MyService
{

@Autowired
private Mapper mapper;  //Fails to autowire org.dozer.Mapper

.....
}

Following is my Controller class
@RestController
@RequestMapping("/rest")
public class MyController
{
@Autowired
private Mapper mapper;  //autowire sucess org.dozer.Mapper
}

I got following Exception when I run main class MainWithStructure

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainWithStructure': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myproject.business.MyService myproject.main.MainWithStructure.MyService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.dozer.Mapper myproject.business.MyService.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dozer.Mapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Following is my project structure

demo_project

*

*src/main/java

---myproject.main
------MainWithStructure.java
------Server.java
---myproject.business
------MyService.java
---myproject.rest
------MyController.java

If I autowire org.dozer.Mapper in Controller, it sucessfuly autowired it. BUT if I autowire org.dozer.Mapper in Component class it fails to autowire.
Why it is failing to autowire org.dozer.Mapper only on Component class?
Please make me correct if I wrong. Thank you :)

A: Your Server is not in one of the packages that you @ComponentScan, so the Mapper is indeed not a bean. Try removing the explicit package from the @ComponentScan (since everything is in a subpackage of the main class that will pick up all the components).

A: You can add @SpringBootApplication in your main class which has @ComponentScan
which will scan all your sub components in project.


text:
Q: Azure Data Lake Storage Gen1 Metadata ( in terms of folder structure and size information) into Power BI On Azure portal - I have couple of "Data Lake Storage Gen1" resource and I need to build a Power BI Dashboard that can show the
1. Storage Information  ( how much of data resides on the resource)
2. Storage Information at folder level ( at least until Level-2 ) , something like below
Parent_Folder (10TB)
    Sub_Folder_1 (3TB)
    Sub_Folder_2 (6TB)
    Sub_Folder_3(1TB)
This data should be displayed in Power BI as a report - so that we can have multiple users view this data.
I understand - currently thsi is available in Azure portal - but here is a ask to make it easy for some platform and operations team to get it via Power BI Dashbaord - so that they dont need to get access onto Azure portal and look for navigating to this resource.
Is this feasible ? If yes - can you help me out with what option -I can retrieve this meta data from ADLS and what credentials/role should be granted on the resource in Azure portal ?
Thanks,
Aravind

A: You can get the meta data from the Azure Datalake Store API. More details in the link
https://learn.microsoft.com/en-us/rest/api/datalakestore/webhdfs-filesystem-apis
It will return a JSON object.
It will give file sizes based on folders it also outline the permissions you need. I would set up a data flow to hit the API then transform the returned JSON in to something useful. You could also if you are using ADL and are using Azure Datalake Analytics or Azure Databricks use those to get the list of folder and iterate though the them to get the information.


text:
Q: Magento 2 Observer class print event data I want to preview all the details inside the object such as Order, Customers after saving the event. I tired below way but it not printing the object inside attributes....
Customer Object Magento\Customer\Model\Data\Customer
$order = $observer->getEvent()->getOrder();
$var_dump($order);

and

$customer= $observer->getEvent()->getCustomer();
$var_dump($customer);

also

print_r($customer->debug());

A: Try this
$order = $observer->getEvent()->getOrder();
print_r($order->getData());
// or specific variable name like
print_r($order->getOrderId());
and

$customer= $observer->getEvent()->getCustomer();
print_r($customer->getId());
print_r($customer->getName());
print_r($customer->getEmail());


text:
Q: Almost sure equality if $P(X_n = x \text{ infinitely often})=1$ presumed Let's say $(X_n)_{n\in N}$ is a non-negative supermartingale. From the Martingale convergence theorem follows that there exists $lim_nX_n = X_\infty$ a.s.
I presume that $P(X_n = x \text{ infinitely often})=1$ for some $x$.
Is this statement true: $x = X_\infty$ a.s.? If yes, how can I show it?

A: Just do it for each fixed $\omega$ for which $X_{\infty} (\omega)=\lim X_n(\omega)$. For real sequences $a_n=x$ for infinitely many $n$ and $a_n \to a$ implies $a=x$ right?


text:
Q: Running long processes inside threads in wxwidgets Can anyone please provide me with some tutorials, explaining running processes inside threads.
I mean process control, with in wxwidgets. I'm trying to implement a gui for a console application.

A: Some points to remember:

*

*The main thread is special and is the only one which can support the GUI.  Worker threads can however prepare bitmaps and then use AddPendingEvent or QueueEvent to tell the main thread they have data it can use.

*Never free an area of memory in a different thread from the thread in which you allocated it.

*wxString is not thread safe.  It is risky to use it to communicate between threads.


text:
Q: unable to lock a file in RHEL6.4 Trying to lock a file in RHEL but seeing following issue
Stopped the services
service rpcbind stop
service nfslock stop
rm -rf /var/lib/nfs/statd/sm/*
rm -rf /var/lib/nfs/statd/sm.bak/*
service rpcbind start
service nfslock start

After this I'm using C program mentioned in https://community.microfocus.com/microfocus/cobol/net_express__server_express/w/knowledge_base/6215/c-program-to-validate-nfs-locking-ability
to :-
•   Open File(Create)
•   Lock File
•   Close File
But seeing below errors
[root@mywebappsserver shared]$ ./nfs_lock
FATAL ERROR: Could not lock file
Even after restarting rpcbind  and nfslock not seeing any entry under
# ls -l /var/lib/nfs/statd/sm/
Need your help in same

A: Fixed it after changing /var/lib permissions
Before:-
ls -ld lib
drwx------. 34 root root 4096 Jul  7 08:32 lib
After:-
ls -ld lib
drwxr-xr-x. 34 root root 4096 Jul  7 08:32 lib


text:
Q: Formula for $\prod_{n=0}^{\infty} (1 \pm x^n)$ I would like to find a formula for
$$f(x) = \prod_{n=0}^{\infty} (1 + x^n)$$
$$g(x) = \prod_{n=0}^{\infty} (1 - x^n)$$
In particular, $f(1/4)$ appears as the normalization factor for the CORDIC, the coefficients of $f(x)$ gives, coefficient gives the number of partitions of n into distinct parts; number of partitions of n into odd parts.1.
I only know that that these functions can be expressed in terms of q-Pochhammer symbol.
Are there closed forms for $f(x)$ and $g(x)$ in terms of common functions. In particular, can $f(1/4)$ be expressed in a closed form?
Are there general any solutions for the finite products that could have some advantage compared to this definition?


text:
Q: How to change file name in QLPreviewController? I have saved a normal ".txt" file with a customized file name. While displaying this file in QLPreviewController and tapping "Mail" option, the attached file name is same as that i have given while saving it. I want to change the name of the file while displaying in "MAIL".
Is it possible to do so?
Thanks for your answer

A: You can do it the other way round: save under the name you want to appear in Mail.app and customize name in QLPreviewController by implementing:
- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx

and customizing QLPreviewItem returned from it (previewItemTitle).

A: I hope this is what you need..
[mailComposer addAttachmentData:[NSData dataWithContentsOfFile:self.yourFilePath]
                               mimeType:@"application/txt" fileName:[NSString stringWithFormat:@"MAIL.txt"]];


text:
Q: ¿Este código está hecho de la manera correcta? Buenas tardes soy nueva en programación y estoy aprendiendo sobre bucles. He hecho un código donde la idea era con el uso de los bucles crear un juego de ahorcados en c++, pero no estoy segura se la manera en la que lo hice es muy correcta o la mejor. Por eso quisiera saber si el siguiente código si esta hecho de la manera correcta:
#include <iostream>

using namespace std;

int main()

{

    int i, vidas=3;
    string palabra;

    cout << "********************************************Juego Ahorcados********************************************"<<endl;
    cout <<endl << "Bienvenido a ahorcados, este juego está compuesto de una serie de adivinanzas donde la respuesta es una" <<endl <<"palabra y tu tienes que adivinarla."<<endl<<"Solo tienes 3 vidas, si se acaban antes de adivinar la palabra habrás perdido"<<endl;

    cout <<endl <<"Partida I" <<endl;

    for(i=1;i<=3;i++)
     {

    cout <<endl << "Instrumento que mide la densidad de los aceites: " <<endl;
    cout<<"Ingresa la palabra: ";
    cin>>palabra;

    if(palabra=="Oleometro")
    {
    cout<<endl<<"¡Respuesta correcta!" <<endl;

    cout <<endl <<"Partida II" <<endl;

     for(i=1;i<=3;i++)
     {

    cout <<endl << "Técnica que describe y representa detalladamente la superficie de un terreno: " <<endl;
    cout<<"Ingresa la palabra: ";
    cin>>palabra;

    if(palabra=="Topografía")
    {

    cout<<endl<<"¡Respuesta correcta!" <<endl;

    cout <<endl <<"Partida III" <<endl;

    for(i=1;i<=3;i++)
     {
    cout <<endl << "Material con el que Miguel Angel esculpió «La Piedad» ubicada en el Vaticano: " <<endl;
    cout<<"Ingresa la palabra: ";
    cin>>palabra;

    if(palabra=="Marmol")
    {

    cout<<endl<<"¡Respuesta correcta!" <<endl;

    cout<<endl<<"¡Felicidades! Ha ganado el juego";

    return 0;

    }
    else
    {  cout<<endl<<"¡Respuesta incorrecta!" <<endl;

         if(vidas==1)
        {
            vidas--;
            cout <<endl<< "Vidas restantes: " <<vidas;
            cout <<endl<< "Lamentablemente tus vidas se han agotado, has pérdido el juego.";
            return 0; }
        vidas --;
        cout <<endl<<"Vidas restantes: " <<vidas <<endl;
    }
     }
    }
    else
    {  cout<<endl<<"¡Respuesta incorrecta!" <<endl;

         if(vidas==1)
        {
            vidas--;
            cout <<endl<< "Vidas restantes: " <<vidas;
            cout <<endl<< "Lamentablemente tus vidas se han agotado, has pérdido el juego.";
            return 0; }
        vidas --;
        cout <<endl<<"Vidas restantes: " <<vidas <<endl;
    }
     }
    }
    else
    {  cout<<endl<<"¡Respuesta incorrecta!"<<endl;

         if(vidas==1)
        {
            vidas--;
            cout <<endl<< "Vidas restantes: " <<vidas;
            cout <<endl<< "Lamentablemente tus vidas se han agotado, has pérdido el juego.";
            return 0; }
        vidas --;
        cout <<endl<<"Vidas restantes: " <<vidas<<endl;
    }
     }

    return 0;
}

Quiero agregar que soy estudiante, apenas estoy iniciando a aprender sobre c++ y programación en general agradecería que fueran lo más sincer@S y respetuos@s posible, muchas gracias de antemano.

A: El problema que tiene tu código es que es poco escalable ... es relativamente complicado corregir, añadir y eliminar respuestas. Quizás ahora mismo no, pero si siguieses añadiendo preguntas el programa se volvería inmanejable.
Piensa por ejemplo que te piden cambiar el formato de la pregunta ... o el texto de cuand el usuario se ha equivocado, ¿vas a ir pregunta por pregunta actualizando todo el programa?
Sería preferible almacenar las preguntas y sus respuestas en una estructura. Por ejemplo:
struct Tarjeta
{
    std::string pregunta;
    std::string respuesta;
};

std::vector<Tarjeta> tarjetas= {
    { "Instrumento que mide la densidad de los aceites", "oleometro" },
    { "Técnica que describe y representa detalladamente la superficie de un terreno", "Topografia" },
    // ...
};

int vidas=3;

for (auto const& tarjeta: tarjetas)
{
    bool acertada = false;
    for (int i=0; i<vidas && !acertada; i++)
    {
        std::cout << tarjeta.pregunta<< ":\n";
        std::string respuesta;
        std::cin >> respuesta;

        if (respuesta==tarjeta.respuesta)
            acertada = true;
        else
            std::cout << "Respuesta incorrecta!!!\n"
                      << "Vidas restantes: " << vidas << '\n';
    }

    if (!acertada) break;
}

Este diseño te aporta una gran flexibilidad:

*

*Facil de mantener: el programa no crece por muchas preguntas que le pongas

*Facil de actualizar: todas las preguntas se gestionan con el mismo bucle

*Podrías meter las preguntas en un archivo de texto o base de datos en vez de en el programa

*Podrías mostrar las preguntas en orden aleatorio

En otro orden de cosas:
No abuses de std::endl
std::endl no solo añade un salto de línea sino que fuerza al vaciado del buffer.
El vaciado del buffer representa una tarea del Sistema Operativo. Cada vez que el buffer se vacía se realiza una petición al SO y ese tipo de peticiones son bastante costosas (por eso se usan buffers).
Por otro lado esta tarea ya se realiza de forma automática, lo que nos permite despreocuparnos el 99% de las veces.
Únicamente en unos pocos casos contados está justificado el vaciado de un buffer. En el resto de las situaciones lo deseable es dejar al sistema elegir el mejor momento para realizar esta operación.
Cuidado con los números mágicos
for(i=1;i<=3;i++)

Este bucle se repite 3 veces en tu programa, una vez por cada pregunta. Ese 3 se considera un número mágico, por que ¿De dónde viene ese número? ¿Por qué 3 exactamente? ¿Qué pasaría si ponemos cualquier otro valor?
Esas son preguntas típicas que se podría hacer alguien que revisase tu código, por ejemplo buscando un error.
Los números mágicos hay que intentar evitarlos ya que suelen ser fuente de errores, sobretodo si el número mágico se usa en varias partes del código.
Es preferible usar una constante:
// Hasta C++03
const int MaxIntentos=3;

// C++11 en adelante
constexpr int MaxIntentos=3;

Quedando el bucle:
for (int i=0; i<MaxIntentos; i++)


text:
Q: form submission reverts to index.php template I have created a contact us form which sends an email when submitted. While the email triggers successfully, the submission leads to a page with my index.php template without any change in the URL. It might have to do with the template hierarchy, but I've tried all other methods mentioned, and none of them have worked. Here's my code for the contact us page with the form.
<?php /* Template Name: Contact Us */ ?>
<?php get_header(); ?>
<?php
  $name = $_POST['name'];
  $from = $_POST['email'];
  $message = $_POST['message'];
  $subject = "Message for Aria Event Planners from '$name' ";
  $to = "ramya.evani@gmail.com";
  $headers = "MIME-Version : 1.0" . "\r\n";
  $headerx .= "Content-type:text/html;charset=UTF-8" . "\r\n";
  $headers = "From: <$from> \r\n";
?>

Contact Us

    <form method="POST">

        Name
        <input type="text" name="name" placeholder="Your Name" class="input" id="name" required>

        E-Mail Address
        <input type="email" name="email" placeholder="Your E-Mail" class="input" required>

        Message
        <textarea rows="3" cols="30" class="input" name="message" placeholder="Your Message Here" required></textarea>

        <button type="submit" name="submit" id="submit">Send Message</button>

        <?php
          if(isset($_POST['submit'])){
            if(mail($to, $subject, $message, $headers)){
              get_site_url('/email-success/');
            } else {
              get_site_url('/email-failure/');
            }
          }
        ?>

    </form>

<?php get_footer(); ?>

A: I did some testing locally with your code. I think the problem is your form input names clashing with names reserved by WP. Also redirecting to success/error page should happen before get_header() to avoid any headers sent errors.
So, add some prefix/suffix to your input names, like so
<input type="text" name="my-name" placeholder="Your Name" class="input" id="name" required>

And move the submitting routine up,
if(isset($_POST['my-submit'])){
    if(mail($to, $subject, $message, $headers)){
      wp_redirect( home_url( '/email-success/' ) );
      exit;
    } else {
      wp_redirect( home_url( '/email-failure/' ) );
      exit;
    }
  }

get_header(); ?>


text:
Q: Unity. Синхронизация UI счёта игроков Я делаю пинг-понг игру на Юнити Миррор. Это мой первый мультиплеер проект, поэтому буду рад услышать любую критику по коду от вас.
Началась проблема с того, что я не знал как наладить взаимодействие между клиентом и сервером в моих двух скриптах - ball.cs (в нем находится условие, при выполнении которого срабатывает метод другого скрипта ScoreScript.cs, отвечающего за изменение счётчика очков игроков)
ball.cs:
public override void OnStartServer()
{
    base.OnStartServer();
    ScoreScript = GameObject.Find("ScoreManager").GetComponent<Score>();
    if (ScoreScript == null)
        Debug.Log("There's no GameObject ScoreScript");

    rb.velocity = Vector2.zero;
}

void FixedUpdate()
{
    SpeedLimit();
    if(hasAuthority)
    GoalUpdate();
}
[Command]
private void GoalUpdate()
{
    if (rb.transform.position.x > 10.0)
    {
        rb.velocity = Vector2.zero;
        rb.transform.position = startPosition2;
        ScoreScript.Increment(1); //increment score for p1
        Debug.Log("Goal for Player 1 in GoalUpdate, Yeah!");
    }
    else if (rb.transform.position.x < -10.0)
    {
        rb.velocity = Vector2.zero;
        rb.transform.position = startPosition1;
        ScoreScript.Increment(2); //increment score for p2
        Debug.Log("Goal for Player 2 in GoalUpdate, Yeah!");
    }
}

Score.cs:
[SerializeField] int scorePlayer1, scorePlayer2;
    public Text ScoreText1, ScoreText2;
    public void Start()
    {
        scorePlayer1 = 0;
        ScoreText1.text = 0.ToString();
        scorePlayer2 = 0;
        ScoreText2.text = 0.ToString();
    }

    [ClientRpc]
    public void Increment(int whichScore)
    {
        if (whichScore == 1)
        {
            ScoreText1.text = (++scorePlayer1).ToString();

            Debug.Log("Plus Score for Player 1 in ScoreScript.Increment(), Yeah!");
        }
        if (whichScore == 2)
        {
            ScoreText2.text = (++scorePlayer2).ToString();

            Debug.Log("Plus Score for Player 2 in ScoreScript.Increment(), Yeah!");
        }

    }

После определения GoalUpdate() как [Command] и Increment как [ClientRpc] возникла проблема того, что при выполнении условия, то есть мяч вышел за границы x, начинается спам очков , т.е. бесконечное выполнение ScoreScript.Increment(). При этом в коде видно, что сначала меняется положение этого мячика на начальное, а только потом идет присвоение счёта. На сцене видно, что, при выходе мяча за x, скорость мячика равна 0, а его изменение положения на стартовое просто игнорируется. Единственный вывод, который я сделал - это то, что при использовании [Command] нельзя давать новую позицию объекту. Тогда можно обратиться в Score.cs к RigidBody мяча и там уже в том же методе отредактировать новое положение и оно действительно работает. Но, на мой взгляд, это ужасное решение и я, наверное, что-то упускаю.
rb.velocity = Vector2.zero;
rb.transform.position = startPosition;


text:
Q: How to validate both attribute together in Yii 1.x I have an issue in Yii1.x (1.1.14), but I haven't yet find a solution for it.
In my form, I have two text fields, [Text Field A] and [Text Field B]. I want to validate both of them together follow rules below:

*

*If A && B empty, return 1 error required message.
Ex: Verifying username and password, one of them does not right, output 1 message for both: Your username or password not right.

*If A || B available, validate numerical of attribute which is available. It also means If both are available, validate numerical both.

I have tried to use custom validation, but it validated each attribute. Therefore, I can't validate both of them together.
Does anyone know a solution for this issue?

A: You can write your own validator. Just add a method to your model:
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return  array(
        'A',
        'requiredIf',
        'isSet' => 'B'
   );

/**
 * Validator-Rule
 * @param string $attribute
 * @param array $params
 */
public function requiredIf($attribute, $params){
    //validate
    $isSet = $params['isSet'];
    if(! empty($isSet)) {
        $attr = $this->{$isSet};
        $other = $this->{$attribute};
        if(! empty($attr) && empty($other)) {
            $this->addError($attribute, 'Error Text');
        }
    }
}

This validator will throw a error when B ist set, but A isnt.


text:
Q: Rename multiple files having variable strings with a single batch script
*

*Fullcast 01 [3m].jpg

*Fullcast 01 [5m].jpg

*KingPin - 02 [3m].jpg

*KingPin - 02 [5m].jpg

*ThemaCast - 8745 [3m].png

*ThemaCast - 8745 [5m].png

I have multiple groups of files [group - Fullcast,KingPin,etc...] which follow the above pattern .I want to replace the strings [3m] with BZC and [5m] with HZC in all those files and also replace the strings "Fullcast" with "Fllcst" ; "KingPin" with "KngPn" ; "Themecast" with "ThemaCst"    and so on.........  using a single bat file.
I got answer but only for a single string - How to rename file by replacing substring using batch in Windows
I can create multiple bat files but How to rename those using a single bat file ?
Note : the files are in "D:\Images\"  and i want to launch the bat file from Desktop [C:\Documents and Settings\XXX\Desktop]

A: You didn't say how your script was going to get the list of files on which to operate. This example assumes that you're looking at all the files in the current directory.
@ECHO OFF
SETLOCAL

FOR %%i IN (*.jpg) DO CALL :CUSTOM_RENAME "%%~i"
FOR %%i IN (*.png) DO CALL :CUSTOM_RENAME "%%~i"

EXIT /B

:CUSTOM_RENAME
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "delims=*" %%f IN ("%~1") DO (
    SET "SOURCE=%%~f"
    SET "NEWNAME=%%~nxf"
)
SET "NEWNAME=!NEWNAME:[3m]=BZC!"
SET "NEWNAME=!NEWNAME:[5m]=HZC!"
REM Other substitutions would go here, assuming they don't overlap.

@ECHO "!SOURCE!" --^> "!NEWNAME!"
rename "!SOURCE!" "!NEWNAME!"
ENDLOCAL
EXIT /B


text:
Q: Prove that $\Gamma (x)=\int_0^\infty t^{x-1}e^{-t}dt$ is continuous at $x=1^+$. A question from Introduction to Analysis by Arthur Mattuck:

Prove that $\Gamma (x)=\int_0^\infty t^{x-1}e^{-t}dt$ is continuous at $x=1^+$.
(Method: consider $|\Gamma(1+h)-\Gamma(1)|.$ To estimate it, break up the interval $[0,\infty)$ into two parts. Remember that you can estimate differences of the form $|f(a)-f(b)|$ by using the Mean-value Theorem, if $f(x)$ is differentiable on the relevant interval.

$|\Gamma(1+h)-\Gamma(1)|=\int_0^\infty (t^h-1)e^{-t}dt$. I don't know how to apply the Mean-value Theorem to it. I haven't learned differentiating under the integral sign.

A: For any $h>0$
$$\int_{0}^{+\infty}(t^h-1)e^{-t}\,dt\stackrel{t\mapsto-\log x}{=}-1+\int_{0}^{1}\left(-\log x\right)^h\,dx \tag{1}$$
but for any $x\in(0,1)$
$$0<-\log x=\int_{x}^{1}\frac{du}{u}\stackrel{\text{Cauchy-Schwarz}}{\leq}\sqrt{\int_{x}^{1}du\int_{x}^{1}\frac{du}{u^2}}=\frac{1}{\sqrt{x}}-\sqrt{x} \tag{2}$$
and by assuming $h\in(0,1)$
$$\begin{eqnarray*} \int_{0}^{+\infty}(t^h-1)e^{-t}\,dt &\leq& -1+\int_{0}^{1}\left(\frac{1}{\sqrt{x}}-\sqrt{x}\right)^h\,dx\\&=&-1+\int_{0}^{1}(1-x)^h x^{-h/2}\,dx\\&\leq&-1+\sqrt{\int_{0}^{1}(1-x)^{2h}\,dx\int_{0}^{1}x^{-h}\,dx} \\&=&-1+\sqrt{\frac{1}{(1+2h)(1-h)}}\tag{3}\end{eqnarray*}$$
On the other hand
$$ \int_{0}^{+\infty}(t^h-1)e^{-t}\,dt \geq \int_{0}^{1}(t^h-1)e^{-t}\,dt $$
and
$$0\leq \int_{0}^{1}(1-t^h)e^{-t}\,dt\leq \int_{0}^{1}(1-t^h)\,dt = \frac{h}{h+1} $$
imply
$$ -\frac{h}{h+1}\leq\int_{0}^{+\infty}(t^h-1)e^{-t}\,dt \leq -1+\frac{1}{\sqrt{(1+2h)(1-h)}}\tag{4}$$
and the claim follows by squeezing.


text:
Q: Pexpect: Not able to redirect outputs to a file Problem: Outputs from the device not getting redirected to a file.
Program: According to my program I have logged into one device and trying to collect few outputs.Here is the program.
     #!/usr/bin/python
     import pexpect
     import time
     import sys

     IP_Address= '10.197.225.226'
     Username = 'hey'
     Password= 'hey'

     session = pexpect.spawn("telnet " + IP_Address)
     result= session.expect(["Username:"])

     if result!=0:
      print("-----Failure connection")
      exit()
     session.sendline(Username)
     result= session.expect(["Password:"])
     session.sendline(Password)

     result= session.expect(["#"])
     print('success')

     C2=input('How many commands you want to enter:')
     for i in range (0,C2):
       C1=raw_input('Enter the commands:' )
       session.expect('#')
       session.sendline(C1)
       session.logfile= open("Result1.txt","w")

     print('Done')

Please help!
Note: I am new here.
I am using Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.

A: I fixed it myself.
Using a+ in open function.


text:
Q: XAMPP: Apache shutdown unexpectedly occurred when UPDATED my XAMPP Version I tried to install new version of xampp. The folder that containing the xampp. I named it as xampp1 then i deleted the older version/folder of xampp. After that i changed the xampp1 folder to xampp when i finally installed the newest version of xampp and started the apache and mysql this error occurred and says:
10:22:13 AM  [Apache]   Error: Apache shutdown unexpectedly.
10:22:13 AM  [Apache]   This may be due to a blocked port, missing dependencies,

10:22:13 AM  [Apache]   improper privileges, a crash, or a shutdown by another method.

10:22:13 AM  [Apache]   Press the Logs button to view error logs and check
10:22:13 AM  [Apache]   the Windows Event Viewer for more clues
10:22:13 AM  [Apache]   If you need more help, copy and post this
10:22:13 AM  [Apache]   entire log window on the forums

I've been searching for the solution of this like reading some blogs and stackover flow thread. I tried also to change some line of codes in httpd.conf and httpd-ssl.conf from 80 to 8080 and 443 to 4433 and restart the xampp and start it again. But it doesn't work for me. Help me out please. I was afraid to do the youtube tutorials on how to update xampp. But i needed to update my xampp and i think there's something wrong with my actions when i updated my xampp.


text:
Q: Filling a drawn path using QPainterPath in pyqt5 I have a QGraphicsView which an image is loaded into. I then made it so you can draw over the image with your pointer with QPainterPath and then the path is closed by connecting the beginning and end points. I am wondering how to have that region then filled after the mouse is released and then make this object selectable but not movable.
I tried using QPaint and filling the path as seen in the addGraphicsItem function.
class GraphicsView(QGraphicsView):
    def __init__(self, parent = None):
        super(GraphicsView, self).__init__(parent)
        self.setGeometry(300, 300, 250, 150)
        self.setScene(GraphicsScene(self))
        self.pixmapItem = QGraphicsPixmapItem() # check if everytime you open a new image the old image is still an item
        self.scene().addItem(self.pixmapItem)
        self.initial_path()

    def initial_path(self):
        self._path = QtGui.QPainterPath()
        pen = QtGui.QPen(QtGui.QColor("green"), 4, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap)
        self._path_item = self.scene().addPath(self._path, pen)

    @QtCore.pyqtSlot()
    def setImage(self):
        filename, _ = QFileDialog.getOpenFileName(None, "select Image", "", "Image Files (*.png *.jpg *jpg *.bmp)")
        if filename:
            self.image = QPixmap(filename)
            self.pixmapItem.setPixmap(QtGui.QPixmap(filename))

    def mousePressEvent(self, event):
        self.start = event.pos()
        if not self.pixmapItem.pixmap().isNull():
            self._path.moveTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if not self.pixmapItem.pixmap().isNull():
            self._path.lineTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        self.end = event.pos()
        if not self.pixmapItem.pixmap().isNull():
            self._path.lineTo(self.mapToScene(event.pos()))
            self._path.closeSubpath()
            self._path_item.setPath(self._path)
            self.addGraphicsItem()
            self.initial_path()
        super(GraphicsView, self).mouseReleaseEvent(event)

    def addGraphicsItem(self):
        pixmap = self.pixmapItem.pixmap()
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen(QtGui.QColor("green"), 4, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap)
        brush = QBrush(QColor('green'))
        painter.fillPath(self._path, brush)
        painter.end()

I expected the addGraphicsItem function to then fill in the object but nothing changes.

A: Instead of using QPainter you can continue to use the QGraphicsPainterPath using the setBrush method you can set the background color, plus you can set the flag QGraphicsItem::ItemIsSelectable to be selectable:
from PyQt5 import QtCore, QtGui, QtWidgets

class GraphicsView(QtWidgets.QGraphicsView):
    def __init__(self, parent=None):
        super(GraphicsView, self).__init__(parent)
        self.setGeometry(300, 300, 250, 150)
        self.setScene(QtWidgets.QGraphicsScene(self))
        self.pixmapItem = (
            QtWidgets.QGraphicsPixmapItem()
        )  # check if everytime you open a new image the old image is still an item
        self.scene().addItem(self.pixmapItem)
        self._path_item = None

    def initial_path(self):
        self._path = QtGui.QPainterPath()
        pen = QtGui.QPen(
            QtGui.QColor("green"), 4, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap
        )
        self._path_item = self.scene().addPath(self._path, pen)

    @QtCore.pyqtSlot()
    def setImage(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            None, "select Image", "", "Image Files (*.png *.jpg *jpg *.bmp)"
        )
        if filename:
            self.pixmapItem.setPixmap(QtGui.QPixmap(filename))

    def mousePressEvent(self, event):
        start = event.pos()
        if (
            not self.pixmapItem.pixmap().isNull()
            and event.buttons() & QtCore.Qt.LeftButton
        ):
            self.initial_path()
            self._path.moveTo(self.mapToScene(start))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if (
            not self.pixmapItem.pixmap().isNull()
            and event.buttons() & QtCore.Qt.LeftButton
            and self._path_item is not None
        ):
            self._path.lineTo(self.mapToScene(event.pos()))
            self._path_item.setPath(self._path)
        super(GraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        end = event.pos()
        if (
            not self.pixmapItem.pixmap().isNull()
            and self._path_item is not None
        ):
            self._path.lineTo(self.mapToScene(end))
            self._path.closeSubpath()
            self._path_item.setPath(self._path)
            self._path_item.setBrush(QtGui.QBrush(QtGui.QColor("red")))
            self._path_item.setFlag(
                QtWidgets.QGraphicsItem.ItemIsSelectable, True
            )
            self._path_item = None
        super(GraphicsView, self).mouseReleaseEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = GraphicsView()
    w.setImage()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())


text:
Q: Stretch image in ImageView I have an ImageView that has its height and width set to "fill_parent" with a Relative Layout that has the same values set.Set Image scaleType="fitXY"
Here The XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitXY"
    android:src="@drawable/background_image" />

</RelativeLayout>

Fits the width and height but the image is stretched.

A: That's what fitXY is supposed to do. You can try with centerInside if you don't want to crop your image, or centerCrop if you want to fill all the space (and cropping your image).
Here is a nice list with examples to understand better all the scaleTypes.

A: These two properties solved issue for me:
android:scaleType="fitXY"
android:adjustViewBounds="true"

A: package utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by Navneet Boghani on 7/7/16.
 */
public class ProportionalImageView extends ImageView {

    public ProportionalImageView(Context context) {
        super(context);
    }

    public ProportionalImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ProportionalImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Drawable d = getDrawable();
        if (d != null) {
         //   int w = MeasureSpec.getSize(widthMeasureSpec);
          //  int h = w * d.getIntrinsicHeight() / d.getIntrinsicWidth();
            int h = MeasureSpec.getSize(heightMeasureSpec);
            int w = h * d.getIntrinsicWidth() / d.getIntrinsicHeight();
            setMeasuredDimension(w, h);
        }
        else super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

A: That is what fitXY will do. It will not respect the aspect ratio of the image and fill the image to your imageview without maintaining the original aspect ratio of the image. If you want to match size of your image to your view ,you can scale your image yourself or  you can look glide library to do that for you . Glide is a very useful library when it comes to image in android