text:
Q: How to find trigonometric values using triangles as fractions? How to find trigonometric values using triangles? I only know how to find values of $30^\circ, 60^\circ, 45^\circ$  using triangle ( in fractional form ). Is there is any way to find values of angle $40^\circ, 90^\circ, 120^\circ, 180^\circ, 360^\circ$ as fractions
My calculator give me answer in decimals but i need answer in fractional form. Is there is any way to find out values using triangle like we find for $30^\circ, 60^\circ, 45^\circ$?

A: By far the most interesting of your questions is the one about $40^\circ$, and I'll leave that to the end. The trig functions of the other angles are determined by using the unit circle, as your trigonometry course should have explained to you. Take the circle $x^2+y^2=1$ in the plane, and, starting at the positive $x$-axis, make an angle $\theta$ with vertex at the origin, turning counterclockwise (anticlockwise if you're British). Then the other leg of the angle will intersect the unit circle at a point $(\xi,\eta)$, and you have: $\sin\theta=\eta$, $\cos\theta=\xi$, and $\tan\theta=\eta/\xi$. This will allow you to answer your question for all your angles but $40^\circ$.
Now for the interesting question. For some angles, like $15^\circ$, you can get an expression for the trigonometric functions involving square roots, perhaps repeated. For others, such as $10^\circ$, $20^\circ$, and $40^\circ$, the cosine of the angle satisfies a polynomial with rational coefficients that is irreducible and cubic. The verification of this fact is an essential part of at least one of the proofs that there are angles that can't be trisected with the traditional methods of compass and unmarked straightedge. In particular, you're not going to be able to construct a triangle or describe in any decent geometric way a triangle whose angles include one of $40^\circ$. Even if you used the Cubic Formula, you wouldn't get anywhere in this task. So your hope of finding a triangular description for $\sin40^\circ$ must remain forlorn.


text:
Q: Read azure ServiceConfiguration file's certificate section using c# Can we read certificate section withi ServiceConfiguration.cscfg file using c#? There is method inside RoleEnvironment class to read ConfigurationSettings, but not certificate section.
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="WindowsAzureProject7" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="1" osVersion="*">
  <Role name="MvcWebRole1" >
    <Instances count="1" />
       <Certificates>
      <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="625FBBB3B7A25C4B9D1C49D1CB1E3AE196C1A083" thumbprintAlgorithm="sha1" />
    </Certificates>
  </Role>
</ServiceConfiguration>

A: Yes, there is no API to read certificate details as far as i know, however what you can do is create a configuration setting and add your certificate specific details and read it directly from the same API. Here is the trick, I used in past:
<ServiceConfiguration serviceName="RW" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration">
 <Role name="RR">
  <Instances count="1" />
   <ConfigurationSettings>
    <Setting name="AppFolder" value="RailsApp" />
    <Setting name="CertificateThumb" value="*************" />
   </ConfigurationSettings>
   <Certificates>
    <Certificate name="Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption" thumbprint="*****************************" thumbprintAlgorithm="sha1" />
   </Certificates>
 </Role>
</ServiceConfiguration>

Now, in my role specific code, I can call RoleEnvironment.GetConfigurationSettingValue to get the certificate thumb as below:
string certThumb = RoleEnvironment.GetConfigurationSettingValue("CertificateThumb");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Newsvendor problem with Poisson demand Problem:
The demand for a particular weekly magazine in a newsstand follows a Poisson distribution averaging 5.2 copies per week. The value paid for each magazine is 15.00 and the sale price is 30.00. Admit that, by the end of the week, the newsvendor can sell all the magazines left over for the price of 8.00 per unit. What's the weekly amount of magazines the newsvendor should buy?
Partial Solution:
Let $q$ be the weekly amount of magazines the newsvendor should buy:
$$X = \text{Poisson}(5.2)$$
$$Y = \left\{\matrix{22X - 7q, &X \le q \\
                    15q, &X \gt q.}\right.$$
We want to maximize newsvendor's profit, so we need to compute $q^* = \arg\max(E[Y])$:
$$E[Y]=\sum_{k=0}^{q} (22k - 7q)  \frac{e^{-5.2} 5.2^k}{k!} + \sum_{k=q+1}^{\infty} (15q) \frac{e^{-5.2} 5.2^k}{k!}.$$
Question:
Am I on the right track? If so, how to solve $\frac{\partial E[Y]}{\partial q} = 0$?

A: Let's think about this the way a street-wise vendor might: that is, somebody who already orders $q$ copies per week, is wondering whether changing their order might increase their expected profit, and wants to do as little arithmetic as possible to get the answer.

If I buy one more copy each week, then I will make an extra $30-15=15$ dollars each time the weekly demand is at least $q+1$.  Otherwise, I will lose another $15-8=7$ dollars.  Is this worth it?

This is a binary event--it has just two possibilities.  If we write $F(q)$ for the chance the demand is less than or equal to $q,$ the two events have chances $1-F(q)$ in the first case and $F(q)$ in the second.  The expected change in profit therefore is
$$(30-15)(1-F(q)) + (8-15)F(q).$$
Thus, the vendor might elect to increase her weekly order provided this yields a positive (or even non-negative) result.  This inequality is easily solved for $F(q)$ because algebra tells us it's equivalent to
$$ 15 - 22 F(q) \ge 0.\tag{*}$$
Now (to continue the streetwise reasoning), it would be worthwhile reducing the weekly stock from $q$ to $q-1$ exactly when it would not be worthwhile increasing it from $q-1$ to $q.$  Thus we needn't do a second calculation because it's clear that if any value of $q$ yields an expected positive profit, then that value should be successively increased by one right up to the point where $(*)$ stops holding.
Therefore you can solve this problem in two easy steps:

*

*Find a value of $q$ that yields a positive expected profit.  If there is no such value, then the solution is not to buy any copies of this magazine!

*Assuming you can find such a value, find the largest $q$ that solves equation $(*)$--and increase it by $1.$
At this point you have information no real-world vendor has: you can compute $F$ for any $q.$  I leave it to you to exploit your special ability to find the unique solution to this problem.  If you can compute $F^{-1},$ the solution is particularly easy to find.  (Use the qpois function in R, for instance.)


text:
Q: Demonstrating microservices in spring and eclipse is not working I am trying to build a proof of concept for microservices in java (eclipse) using Spring libraries and following this tutorial.
Due to certain restrictions, I am not using Maven, but I rather downloaded the following jar files manually and imported them to my java project.

My java code is very simple as the following:
package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableAutoConfiguration
public class HelloWorld {

    @RequestMapping("/")
    //http://localhost:port/
    String hello()
    {
        return "Hello World!!!";
    }

    public static void main (String[] args) throws Exception
    {

        SpringApplication.run(HelloWorld.class,args);
    }

}

The problem is: When I run the code, the server does NOT start, but no errors are there, except the following output, and the application shuts down instantly:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2019-08-29 09:41:17.999  INFO 14096 --- [           main] hello.HelloWorld                         : Starting HelloWorld on HQTPM146609D with PID 14096 (D:\Ramesh\ADMWorkspace\HelloWorldMicroservice\build\classes started by abdallah.alhodaly in D:\Ramesh\ADMWorkspace\HelloWorldMicroservice)
2019-08-29 09:41:18.002  INFO 14096 --- [           main] hello.HelloWorld                         : No active profile set, falling back to default profiles: default
2019-08-29 09:41:18.078  INFO 14096 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d36e4cd: startup date [Thu Aug 29 09:41:18 GST 2019]; root of context hierarchy
2019-08-29 09:41:19.408  INFO 14096 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-08-29 09:41:19.426  INFO 14096 --- [           main] hello.HelloWorld                         : Started HelloWorld in 1.86 seconds (JVM running for 2.504)
2019-08-29 09:41:19.430  INFO 14096 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d36e4cd: startup date [Thu Aug 29 09:41:18 GST 2019]; root of context hierarchy
2019-08-29 09:41:19.432  INFO 14096 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

How can I fix my code so that the message Hello World!!! is displayed on the web page? Thank You.
Update: Following the below answer, I set the context of my application to WebApplicationType.SERVLET. Now, I am getting the following errors:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.0.RELEASE)

2019-08-29 11:03:28.515  INFO 9416 --- [           main] hello.HelloWorld                         : Starting HelloWorld on HQTPM146609D with PID 9416 (D:\Ramesh\ADMWorkspace\HelloWorldMicroservice\build\classes started by abdallah.alhodaly in D:\Ramesh\ADMWorkspace\HelloWorldMicroservice)
2019-08-29 11:03:28.518  INFO 9416 --- [           main] hello.HelloWorld                         : No active profile set, falling back to default profiles: default
2019-08-29 11:03:28.616  INFO 9416 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@62e136d3: startup date [Thu Aug 29 11:03:28 GST 2019]; root of context hierarchy
2019-08-29 11:03:29.521  WARN 9416 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
2019-08-29 11:03:29.534  INFO 9416 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-08-29 11:03:29.542 ERROR 9416 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at hello.HelloWorld.main(HelloWorld.java:29) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:204) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE]
    ... 6 common frames omitted

A: In main class, you need write "SpringApplication.run(HelloWorldApplication.class,args);"

A: Your application context is wrong, it should of web application context. To fix this try either of these
setApplicationContextClass(…) or setWebApplicationType(WebApplicationType) using SpringApplication.


text:
Q: Does Bulma Buefy support VUE 3? Does Bulma Buefy support VUE 3? I am trying to install buefy but I am running into this error.
This is the error I am facing

A: In quick start guide in Buefy they wrote :

Quick start You need Vue.js version 2.6+. (Vue 3 is not supported)

So it does not support Vue3.


text:
Q: Regex to check for open tags I am having trouble fabricating a Regex which will returns tags that are not self-closing. So I would want it to returns tags which are like so:
<blah>

But not tags which are like:
<blah/>

I have the following regex:
<(o|p)(.*?)>

Which is slightly simplified, ignore the rest it does what it is meant to do despite it's oddness. This will match all tags though while I need one that will ignore matches where the tag is self-closing.
Cheers

A: Try this regular expression:
<(?:o|p)(?:[^"'>/]+|"[^"]*"|'[^']*')*>

Valid XHTML syntax is presumed.


text:
Q: Can i use a domain name on a subsite? Background: Our company is using SharePoint. We have now created a subsite which is related to a club. The club just bought a domain name, and we want to promote the domian name, so that people go directly into the clubs subsite.
Question: Is it possible to use a Domain name on a subsite?
Thanks in advance.

A: As you are using Sharepoint online there is no such possibility.
For on Prem there is this feature called hosted site collections. (and this is used in SHarepoint online but you cannot manage it and you can have just one url per tenant. Apart from few test to see i never used in site collection.
Have read through this article it should give you a good start:
https://blogs.msdn.microsoft.com/kaevans/2012/03/27/what-every-sharepoint-admin-needs-to-know-about-host-named-site-collections/
REf: https://social.technet.microsoft.com/Forums/lync/en-US/d4328551-eab1-44c6-b4e7-b3b424ab9ff3/use-of-host-named-site-collections-in-sharepoint-online?forum=sharepointadmin


text:
Q: Replacing all integers in a string Let's say I have some expression like,
expr = 1*a + 2*b +3*c + 4*d

I want to write this to a string that I can then use in some other Fortran script. I want all the integers to be of the form "X.0_dp". To do this I can simply do,
StringReplace[
  ToString[expr, FortranForm], {"1" -> "2.0_dp", "2" -> "2.0_dp",
  "3" -> "3.0_dp", "4" -> "4.0_dp"}]

which works a treat.
Now, is there a way such that I don't have to do this by hand, and generalizes to all integers? e.g. something of the form,
StringReplace[
  ToString[expr, FortranForm], {"x" -> "x.0_dp"}]

Thanks for any help

A: If you want all integers to be formatted in the same way, you can override the FortranForm formatting of Integer:
Unprotect[Integer];
Format[i_Integer, FortranForm] := Format[
    ToString @ i <> ".0_dp",
    OutputForm
]
Protect[Integer];

Then:
ToString[1*a + 2*b +3*c + 4*d, FortranForm]

"a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"

If you want to retain the 1 before the a, just use HoldForm to prevent evaluation:
ToString[HoldForm[1*a + 2*b +3*c + 4*d], FortranForm]

"1.0_dp*a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"

A: Try this:
ToString[(expr /.
    Times[x_Integer, y_Symbol] :>
     ToString[x, FortranForm] <> ".0_dp " <>
      ToString[y, FortranForm]) /. a :> "1.0_dp a"]

(* "1.0_dp a + 2.0_dp b + 3.0_dp c + 4.0_dp d"  *)

Have fun!


text:
Q: Ffmpeg on idle python Mac I am trying to use FFMPEG on idle 3.7.4 python on macOS Catalina.
I ran brew install ffmpeg and it successfully installed.
However, when I go to IDLE and run my script (the script is to convert a .mp3 file to a .wav):
from os import path
from pydub import AudioSegment

src = "transcript.mp3"
dst = "test.wav"

sound = AudioSegment.from_mp3(src)
sound.export(dst, format="wav")

This is what I get in return:
Warning (from warnings module):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydub/utils.py", line 165
    warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning)
RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work

Warning (from warnings module):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydub/utils.py", line 193
    warn("Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work", RuntimeWarning)
RuntimeWarning: Couldn't find ffprobe or avprobe - defaulting to ffprobe, but may not work
Traceback (most recent call last):
  File "/Users/edenhikri/Desktop/transcript.py", line 9, in <module>
    sound = AudioSegment.from_mp3(src)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydub/audio_segment.py", line 716, in from_mp3
    return cls.from_file(file, 'mp3', parameters=parameters)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydub/audio_segment.py", line 665, in from_file
    info = mediainfo_json(orig_file)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pydub/utils.py", line 263, in mediainfo_json
    res = Popen(command, stdin=stdin_parameter, stdout=PIPE, stderr=PIPE)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1522, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ffprobe': 'ffprobe'

A: Your python execution environment is not able to find your ffmpeg installation. Because I simply copy pasted your code and it works.
Your error literally says No such file or directory: 'ffprobe': 'ffprobe'
There's also a warning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
please check the environment in which your script is executing. Maybe IDLE is doing something. Try running your script via the terminal in which you get an output for ffmpeg and ffprobe as:
python3 script_file.py


text:
Q: How to copy conditional formatting between different spreadsheets in Google Apps Script I have multiple spreadsheets titled: Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday.  Each spreadsheet has 3 sheets titled:  Plan, Class, and Coach.  Each spreadsheet has near-identical formatting, the only difference being the height of merged cells in the first and last 8 columns of "Plan!".
I am constantly changing values in my spreadsheets, so while each spreadsheet has the same format, the values are very different.  I also don't want to combine all of the sheets into one spreadsheet because I would have nearly 20 tabs to navigate through, making it very confusing and time consuming.
The problem I have is when I need to change something on every sheet.  My sheet needs to be something I can update and change throughout the year depending on my needs, and as you would expect, it can be very annoying to have to open each individual sheet and change the same thing in every one.  I have found the IMPORTRANGE function to be very useful in keeping my header rows and other constants updated between sheets, but I have not found a way to do so with conditional formatting, which is the most annoying thing to have to change.
I have multiple conditional format rules on each sheet, and I really need a way to have each sheet update automatically whenever I change or add a rule to say, "Monday".

*

*I only want to copy conditional format rules.

*I need each sheet to update whenever I update conditional format rules for "Monday"

This is what I wrote:

function copyConditional(){
  var target = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Plan");
  var source = SpreadsheetApp.openById("1RJVmCimFh24NbAlENJvH5pT3zRq_KLJmFdEWqUN_Fo8").getSheetByName("Plan");
  var targetR = target.getRange('I3:AN59');
  var sourceR = source.getRange('I3:AN59');

  sourceR.copyTo(targetR,SpreadsheetApp.CopyPasteType.PASTE_CONDITIONAL_FORMATTING)
}

When I run my code, I get an error message stating, "Exception: Target range and source range must be on the same spreadsheet. (line 14, file 'Code')"
Now, I don't know if what I am looking to do is actually possible, but I am hoping there is some workaround to what I am trying to do.  My experience with code is small, but I am starting to understand a lot more of it (all thanks to this great community at Stack Overflow!).  I would appreciate any help you can give me.

A: Solution:

*

*Although the solution of Tanaike might work, here I propose a
more straighforward approach.

*The following solution uses the ConditionalFormatRuleBuilder
class:
   function copyConditional(){
      var target = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Plan");
      var source = SpreadsheetApp.openById("1RJVmCimFh24NbAlENJvH5pT3zRq_KLJmFdEWqUN_Fo8").getSheetByName("Plan");

      var rules = source.getConditionalFormatRules();
      target.setConditionalFormatRules(rules);
    }

Limitations:

*

*This approach copies all the conditional format rules of the
source sheet Plan to target sheet Plan and may not be what you are looking for.

*However, this solution might still work for you if you haven't used multiple conditional format rules within the sheet.

Alternative approach:
In order to copy the conditional formatting of particular ranges, then you need to use the ConditionalFormatRule class to get the ranges to which the conditional format rules are applied. Since, I don't have access to your sheet and can't test it myself, I can't tell how many different conditional format rules you use and in which ranges. As a starting point, this is an array of all the rules and the ranges that these rules are applied in the source sheet:
var rules = source.getConditionalFormatRules();

Then you iterate through the ranges to find exactly which ranges contain which rules:
var rule = source.getConditionalFormatRules()[0];
var ranges = rule.getRanges();
for (int i = 0; i < ranges.length; i++) {
  Logger.log(ranges[i].getA1Notation());
}

Alternative solution:
Based on the latter, you can determine the rules you would like to copy to the target file, instead of copying all the rules. For example, if range is I3:AN59 then copy the conditional format rules to the target sheet:
function copyConditional(){

var target = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Plan");
var source = SpreadsheetApp.openById("1RJVmCimFh24NbAlENJvH5pT3zRq_KLJmFdEWqUN_Fo8").getSheetByName("Plan");

var rules = source.getConditionalFormatRules();

for (let i = 0 ; i < rules.length; i++){

var ranges = rules[i].getRanges();
for (let j = 0; j < ranges.length; j++) {
  if(ranges[j].getA1Notation() == 'I3:AN59'){
   target.setConditionalFormatRules([rules[i]]);
 }
}
}
}

This approach assumes that the conditional format rules are the same for I3:AN59.
I hope my answer was helpful to you.

A: Just a thought here: I understand you don't want one sheet with a million tabs but you can handle that with a menu and some very basic code.
Prefix each sheet name with the day abbreviation or or a number (eg 3 for Wednesday).
Write some code to show the relevant day and hide everything else
Use the onOpen function to show today's tabs and hide everything else.
And a whole bunch of menu options to show a particular day.


text:
Q: Refreshing page quite a few times takes server down I have a website/webapp which I developed in JSP/Servlets. On the main the data is collected from the database, so I run the Servlet first to collect data and send it to the JSP. (works fine) The problem is few minutes ago I kept F5 pressed for a while (i.e. refreshed the page quite a few times). Now the server is down and the website displays a Service Temporarily Unavailable message. The bandwidth limit of the account is unlimited, still its saying the account has exceeded the bandwidth limit.
Can anybody tell me how to fix this issue. I know It will be OK in few minutes/hours but I don't want my users to see this message again.
Cheers

A: Set a flag which is set true when the operation starts at first.
Reset the flag once the operation is complete
Now if the user tries to leave the page of refresh the page a pop up would come (which can be done with javascript). This would not let the page be refreshed.
If the user confirms the "Are you sure you want to leave the page " alert then stop the currently executing process.


text:
Q: How to "Retrieved from" without date before URL in biblatex-apa I'm writing a lab report in LaTeX (Overleaf), using the APA style for referencing. I use the biblatex package with the APA style.
However, in my school's reference guide it says to put the words "Retrieved from" in front of a URL which is not required to have a date retrieved, i.e. sources which do not change over time. apa-biblatex does not automatically do this, and I can't seem to find a solution which works. The only solution I've found (after at least an hour of googling) is to switch to the package apacite, but it would be very tedious to do this.
Below is a magazine article from a database which requires a URL but not the date the information was retrieved.
MWE:
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage[style=apa,backend=biber]{biblatex}
\addbibresource{references.bib}

\begin{document}

\begin{filecontents}{references.bib}
@article{DePalma2005,
%Magazine article from electronic database
    author = {DePalma, A.},
    year = {2005},
    title = {Sequencing in the post-genomic age},
    journal = {Bioscience Technology},
    volume = {30},
    number = {4},
    publisher = {Advantage Business Media},
    url = {https://link.gale.com/apps/doc/A132192766/SCIC?u=kungsholmens&sid=SCIC&xid=beac04f2}
}
\end{filecontents}{references.bib}

\parencite{DePalma2005}

\printbibliography

\end{document}

This gives me this output, without the "Retrieved from":

This is my desired output, with the "Retrieved from" in front of the URL:

Do you have any ideas on how this could be solved? It's really bothering me!

A: There has been a change of rules in APA style here. If I understand correctly 6th-edition  APA style wants "Retrieved from" for all URLs and DOIs, whereas 7th-edition APA style only wants "Retrieved from" if you also include an access date (urldate).
That is what biblatex-apa and biblatex-apa6 implement. (If this is not what the Publication Manual of the American Psychological Association requires, please report this as a bug at https://github.com/plk/biblatex-apa/issues. It would help if you could include references to the manual and an example document.)
With style=apa, you get the behaviour from the 7th edition of the APA manual ("retrieved ... from" only with access date [urldate])
\documentclass{article}

\usepackage[style=apa, backend=biber]{biblatex}

\begin{filecontents}{\jobname.bib}
@article{DePalma2005,
  author    = {DePalma, A.},
  year      = {2005},
  title     = {Sequencing in the post-genomic age},
  journal   = {Bioscience Technology},
  volume    = {30},
  number    = {4},
  publisher = {Advantage Business Media},
  url       = {https://link.gale.com/apps/doc/A132192766/SCIC?u=kungsholmens&sid=SCIC&xid=beac04f2},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\autocite{DePalma2005}

\printbibliography
\end{document}

With style=apa6, you get the behaviour from the 6th edition of the APA manual (always "retrieved ... from")
\documentclass{article}

\usepackage[style=apa6, backend=biber]{biblatex}

\begin{filecontents}{\jobname.bib}
@article{DePalma2005,
  author    = {DePalma, A.},
  year      = {2005},
  title     = {Sequencing in the post-genomic age},
  journal   = {Bioscience Technology},
  volume    = {30},
  number    = {4},
  publisher = {Advantage Business Media},
  url       = {https://link.gale.com/apps/doc/A132192766/SCIC?u=kungsholmens&sid=SCIC&xid=beac04f2},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\autocite{DePalma2005}

\printbibliography
\end{document}


text:
Q: Toast message on lock screen in android L I am not able to display toast message on locked screen in android L. I am trying to display the toast on an activity.
Note: The same code works on KitKat
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().addFlags(
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    setContentView(R.layout.activity_main);
    Toast.makeText(this, "Displaying toast!!!!!", Toast.LENGTH_LONG).show();
}


text:
Q: How to run actual robot code in Gazebo Simulation? I am working on Guardian mobile robot. It has 2 ROS packages, one for real robot and other for Gazebo simulation. Mapping and navigation code is available in real robot package and not in Gazebo simulation package. Please tell, how can I run mapping and navigation code in Gazebo package. Thanks

A: gazebo has a node you can start and use it to exchange data:
gazebo_ros_api_plugin

The gazebo_ros_api_plugin plugin, located with the gazebo_ros package,
  initializes a ROS node called "gazebo". It integrates the ROS callback
  scheduler (message passing) with Gazebo's internal scheduler to
  provide the ROS interfaces described below. This ROS API enables a
  user to manipulate the properties of the simulation environment over
  ROS, as well as spawn and introspect on the state of models in the
  environment.
This plugin is only loaded with gzserver.

A: I'll assume you are interested in starting a node in gazebo and not only in ros.
In ros, granted you've got a .launch file, you would start your node as
$roscore
$roslaunch node.launch

In order for the node to run within gazebo you would start it as
roslaunch gazebo_ros node.launch


text:
Q: SCRIPT438: Object doesn't support property or method 'push' in IE Hi i implemented file upload functionality using ajax and i set the ajax is synchronous type
  for this kind of implementation i used the following jQuery files in my ctp file(i followed
   cakePHP Design pattern in my default.ctp i used jquery 1.4)
 'jquery-1_7.js','jquery.form.js','jquery-ui_1_9_1.js'

and every thing is working fine in firefox, coming to IE its not working my code snippet
   is as follows
 var options = {
        complete: function(response) {
            var fileObj = jQuery.parseJSON(response.responseText);
            var fileId = fileObj.FileNo;
            var elemNo = fileId.replace('file', '');

                if(fileObj.Txt == 'SUCCESS'){
                   //copy the id into global; variable
            }
        },
        error: function(response) {
            //display error
        }
    };

ajax call
  $('#sBtn').button().click(function(){
        $.ajaxSetup({async:false});
        files = []; //globalvaraiable
            for(i=0; i<fileCnt; i++){
                if ($('#addFile'+i).length > 0) {
                    $('#addFile'+i).ajaxForm(options);
                    $('#addFile'+i).submit();
                        window.setTimeout($('#addFile'+i).bind($('#addFile'+i)), 100);                      console.log(files);
                }
            }

            $('#ContentId').ajaxForm($('input#contentIds').val(files));
            $('#ContentId').submit();
            $('#loadingImg').addClass('clear');
        }
        return false;
    });

In IE i got the following error
  SCRIPT438: Object doesn't support property or method 'push'
  jquery-1_7.js, line 3008 character 5


text:
Q: When using df1[~df1.isin(df2)].dropna() Question I have a data set filled with invoices columns including:

*

*CaseID

*Customer

*Supplier

*Part Number

*Cost.

This data set includes Charges and Credits. I want to remove the Credits and the Charges they credited from DataFrame. I'd like to remove the rows in original that are credits and the charges they pertain to. But there are some instances where a transaction was charged twice on accident so the information is a duplicate. I do not want to remove the duplicate if there is a credit since the duplicate will need a credit as well.
I have the original df.
I created a charge df where it is all rows with Cost > 0 from the original.
I created a credit df where it is all rows with Cost < 0 from the original.
My question is if I use df1[~df1.isin(df2)].dropna() or in this case:
invoiced[~invoiced.isin(credits)].dropna()

How do I specify that I only want the row dropped one time? Is it possible?
ex:
invoice =

Case| Part_Number | Cost

111 | 2G | 53.00

112 | 7G | 25.00

112 | 7G | 25.00

113 | 8G | 20.00

113 | 8G | -20.00

114 | 9G | 15.00

115 | 2G | 53.00

115 | 2G | 53.00

115 | 2G | -53.00

Charge =

Case| Part_Number | Cost

111 | 2G | 53.00

112 | 7G | 25.00

112 | 7G | 25.00

113 | 8G | 20.00

114 | 9G | 15.00

115 | 2G | 53.00

115 | 2G | 53.00

Credits =

Case| Part_Number | Cost

113 | 8G | -20.00

115 | 2G | -53.00

Output =
df =

Case| Part_Number | Cost

111 | 2G | 53.00

112 | 7G | 25.00

112 | 7G | 25.00

114 | 9G | 15.00

115 | 2G | 53.00

See how it removed 113 since there was 1 charge and 1 credit but kept (1) of 115 since there were 2 charges and 1 credit.

A: Try this:
invoices = pd.DataFrame([['111', '2g', 53],
                         ['112', '7g', 25],
                         ['112', '7g', 25],
                         ['113', '8g', 20],
                         ['113', '8g', -20],
                         ['114', '9g', 15],
                         ['115', '2g', 53],
                         ['115', '2g', 53],
                         ['115', '2g', -53]],
                        columns=['Case', 'PartNo', 'Cost'])

print(f"Original invoices:\n{invoices}\n\n")

newInvoices = invoices.copy()
newInvoices['Charge_Credit'] = 0

for idx, case, part, cost, ch_cr in newInvoices.itertuples():
    creditedDf = newInvoices[(newInvoices.Case == case) &
                          (newInvoices.PartNo == part) &
                          (newInvoices.Cost == -cost) &
                          (newInvoices.Charge_Credit != 'remove')]
    if len(creditedDf):
        newInvoices.loc[creditedDf.iloc[0].name,  'Charge_Credit'] = 'remove'

newInvoices = newInvoices[['Case', 'PartNo', 'Cost']][newInvoices.Charge_Credit != 'remove']
newInvoices.reset_index(drop=True, inplace=True)
print(f"New invoices:\n{newInvoices}\n")

A: From my understanding, outputdf is supposed to show which invoice hasn't been paid yet, even if it is a duplicate, correct? I believe this is the code you're looking for and ill explain it in a bit.
dfinvoice = pd.DataFrame(columns=['Case', 'PartNo', 'Cost'],
                  data=np.array([['111', '2g', 53],
                                 ['112', '7g', 25],
                                 ['112', '7g', 25],
                                 ['113', '8g', 20],
                                 ['113', '8g', -20],
                                 ['114', '9g', 15],
                                 ['115', '2g', 53],
                                 ['115', '2g', 53],
                                 ['115', '2g', -53]
                                 ]))

dfcharge = pd.DataFrame(columns=['Case', 'PartNo', 'Cost'],
                  data=np.array([['111', '2g', 53],
                                 ['112', '7g', 25],
                                 ['112', '7g', 25],
                                 ['113', '8g', 20],
                                 ['114', '9g', 15],
                                 ['115', '2g', 53],
                                 ['115', '2g', 53]
                                 ]))

dfcredits = pd.DataFrame(columns=['Case', 'PartNo', 'Cost'],
                  data=np.array([['113', '8g', -20],
                                 ['115', '2g', -53]
                                 ]))
dfowing = pd.DataFrame(columns=['Case', 'PartNo', 'Cost'],
                  data= np.array([['111', '2g', 53],
                                  ['112', '7g', 25],
                                  ['112', '7g', 25],
                                  ['114', '9g', 15],
                                  ['115', '2g', 53]
                                  ]))
df = dfinvoice
for x, y in df.iterrows():
    for a, b in df.iterrows():
        if y[0] == b[0]:
            if x != a:
                first = int(y[2])
                second = int(b[2])
                if first > 0 and second < 0:
                    print(x, y)
                    print('compared to')
                    print(a, b)
                    df = df.drop(x)
                    df = df.drop(a)
print(df)

dfowing is what the dataframe should look like. I was using that as a reference.
Using a for loop in a for loop you can cross reference you're values. x and a being the index, y and b are the rows of data. in the first if statement I was checking if the invoice numbers matched. in the second if statement I had to make sure that the index didn't match so it would compare itself to the next row, although not exactly necessary. first and last are the the values from the 'cost' column which in my dataframe they were returning as a string and you cant compare integers and strings to check if one is greater or less than 0. in the last if statement check if one is greater than 0 and one is less than 0 and remove that row using the index using df = df.drop() to get rid of each match where an invoice has been charged and then credited.
I'm not the greatest at explaining these things so if anyone wants to edit my explanation feel free :)


text:
Q: OpenMP on os x assembler errors I've been trying to make openMp work on my mac. In the end i finally managed to get it done , sort of.
This program works perfectly
https://computing.llnl.gov/tutorials/openMP/samples/C/omp_hello.c
But this one :
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

static long num_steps = 100000;
double step;

int main(){

int i, nthreads;
double x,pi,sum[2] ;
double start = omp_get_wtime();
double end;

step = 1.0/(double)num_steps;

omp_set_num_threads(2);

#pragma omp parallel
{
    int i, id,nthrds;
    double x;
    id = omp_get_thread_num();
    nthreads = omp_get_num_threads();
    if(id == 0) nthreads = nthrds;

    for(i = 0 ; i < num_steps ; i = i+nthrds){
        x = (i+0.5)*step;
        sum[id] += 4.0/(1.0+x*x);
        //printf("Thread_num : %d ,%f\n", omp_get_thread_num(),sum);
    }

}
//pi = step*sum;

for (int i = 0, pi =0.0; i < nthreads; ++i)
{
    /* code */
    pi += sum[i] * step;
}

end = omp_get_wtime();
printf("%f\n", end-start);

return 0;
}

..throws me these erros
gcc -fopenmp helloWorld.c -o helloWorld
/var/folders/d7/2jjg9ygj7zscb67wnskcxsk40000gp/T//cc4hIbK6.s:19:suffix         or operands invalid for `movq'
/var/folders/d7/2jjg9ygj7zscb67wnskcxsk40000gp/T//cc4hIbK6.s:64:suffix or operands invalid for `movq'
/var/folders/d7/2jjg9ygj7zscb67wnskcxsk40000gp/T//cc4hIbK6.s:68:suffix or operands invalid for `movq'
/var/folders/d7/2jjg9ygj7zscb67wnskcxsk40000gp/T//cc4hIbK6.s:69:suffix or operands invalid for `movq'

I have no idea why it does this. I searched the net before i asked here  , but i couldn't find someone who had this problem with openMP.
(I'm not entirely sure that compiler is well installed either. I installed a bunch of things ,some of them worked , some didn't)

A: For everyone that will read this :
I updated gcc (using brew) and then run the program with gcc-5 .. . Hope you guys make it work too. Best of luck.


text:
Q: Powershell how to triger powershel command on Create New Element, or Edit Element Hello I want to ask a question, how to triger powershell command on Creation new element, or edit new element ?
If I add a element to the list I want to fire one command of powershell.
if I edit a element of list i want to fire another powershell command.
How could I triger this functionality ?


text:
Q: Why do my API endpoints return 404 only when I use pm2? (EC2, Node, nginx, React) I'm running a MERN stack application on an EC2 Ubuntu instance with an nginx proxy. If I start the server using npm start or node app.js my frontend React app can call the API successfully. However if I start the server using pm2, all API calls are returned 404. I'm a devOps noob so please be patient with me.
I tried creating an ecosystem file that blacklisted node_modules and logs after reading a couple blogs but that didn't help either.
Any suggestions? Do you need any additional information? If so, please comment and I'll edit this post.
Thank you in advance!
Here is my default.conf file for nginx
server {
    #listen       80;
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name  _;

    access_log /home/ubuntu/client/server_logs/host.access.log main;

    location / {
        root   /home/ubuntu/client/deploy;
        index  index.html index.htm;
        try_files $uri /index.html;
        add_header X-Frame-Options SAMEORIGIN;
        add_header X-Content-Type-Options nosniff;
        add_header 'Access-Control-Allow-Origin' 'origin-list';
        add_header X-XSS-Protection "1; mode=block";
        add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
    }
    location /api/ {
        proxy_pass http://localhost:8080/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    server_tokens off;

    location ~ /\.ht {
        deny  all;
    }

}

Here is my ecosystem.config.js for pm2
module.exports = {
  apps : [{
    name: 'app',
    script: 'app.js',

    // Options reference: https://pm2.io/doc/en/runtime/reference/ecosystem-file/

    instances: 1,
    watch: true,
    ignore_watch: ["logs",'node_modules'],
    autorestart: true,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production'
    }
  }]
};


text:
Q: Create table on Javascript with numbers from up to down I want to create a table on Javascript from 0 to 49. I want the numbers to be displayed on the table from up to down, but I'm unable to correctly create the elements in order to get my desired result. My actual code is this:
<script type="text/javascript">

            var number = 0;
            var div = document.getElementById("internal");
            var table = document.createElement("table");
            div.appendChild(table);

            for (var i = 0; i < 5; i++) {

                var rows = document.createElement("tr");
                table.appendChild(rows);

                for (var j = 0; j < 10; j++) {

                    var columns = document.createElement("td");
                    var text = document.createTextNode(number);
                    columns.appendChild(text);
                    rows.appendChild(columns);
                    number++;
                }
            }

            document.getElementsByTagName("table")[0].setAttribute("border", 2);
            document.getElementsByTagName("table")[0].children[0].children[0].setAttribute("style", "background-color: red;");
            document.getElementsByTagName("table")[0].children[0].children[0].innerHTML = "";

        </script>

This code right here creates the table almost the way I want, but instead I want the rows to be the columns. I know it may be a dumb question but I'm totally unable to get it the right way.

A: You can do a little calculation in this statement:
var text = document.createTextNode(number);

instead of simply incrementing the number (which will inevitably increase going down the row, not down the column).
Try this:
var text = document.createTextNode(i + (j-1)*5);

Some test values to show how this works, where i is the row number and j is the column number:
+---+---+-------------+
| i | j | output      |
+---+---+-------------+
| 1 | 1 | 1 + 0 = 1   |
| 2 | 1 | 2 + 0 = 2   |
| 3 | 1 | 3 + 0 = 3   |
| 1 | 2 | 1 + 5 = 6   |
| 1 | 3 | 1 + 10 = 11 |
+---+---+-------------+

A: Just iterating a number doesn't do the trick. You need to consider the length of the rows in combination with the current row and column indices.
var rowLength = 5;
var colLength = 10;

for (var i = 0; i < rowLength; i++) {

  var rows = document.createElement("tr");
  table.appendChild(rows);

  for (var j = 0; j < colLength; j++) {

    var columns = document.createElement("td");
    var text = document.createTextNode(i + j * rowLength);
    columns.appendChild(text);
    rows.appendChild(columns);

  }
}

Here is also a JSFiddle: https://jsfiddle.net/ey7hfzfq/


text:
Q: Can't run application with ./ child process Node JS I'm trying to launch Ngrok using Node JS the child process, unfortuantly this isn't working as it thinks the ./ is a non recognised command... how could I resolve this? it works from my terminal within the directory I'm in...
const os = new os_func()

os.execCommand(`./ngrok http file:///my-file`).then(res => {
  console.log(res)
}).catch(err => {
  console.log(err)
})

My OS function is exposed and exported as...
function os_func() {
  this.execCommand = function (cmd) {
    return new Promise((resolve, reject) => {
      exec(cmd, (error, stdout, stderr) => {
        if (error) {
          reject(error)
          return
        }
        resolve(stdout)
      })
    })
  }
}

The error I get is:

'.' is not recognized as an internal or external command


text:
Q: tkinter winfo_children dynamic association I'm trying to figure out if an Entry is blank, but instead it skips over it in my code and appends the next Entry object, if the Entry has data, to the array. When I try to identify the object it gives a reference, but not the type of object (i.e. .140594722293880....).
I've tried if i.get() != "": and None, is there a way to identify an empty Entry?
import os,sys
import Tkinter as tkinter
import ttk
class CLASSTHING():
   def __init__(self):
        top = tkinter.Tk()
        top.geometry('1200x150')
        top.title('')
        master = ttk.Frame(top)
        n = ttk.Notebook(master)
        f1 = ttk.Frame(n)
        for x in range(0,len(labelstr) -1):
            tkinter.Label(f1, text=labelstr[x], width=len(labelstr[x])).grid(row=x,column=0)
            tkinter.Entry(f1, width=100).grid(row=x,column=1)
        submit = tkinter.Button(top,text="submit",command= lambda:
self.enterData([f1])
        submit.place(x=1152,y=25)
        n.add(f1,text='1')
        top.mainloop()

    def enterData(self,Frame):
        ary = []
        for a in frame:
            for i in a.winfo_children():
                ary.append(i.get())

My coding is compatible with both Python 3 and 2. If you have a suggestion, please give whichever you know best.

A: You can use the winfo_class method to get the class for any Tk or Ttk widget. For Entry widgets the class is "Entry", a ttk entry widget would be "TEntry". This is application specific though as the programmer may assign a different class to a widget to associate a different visual style in ttk or different options in standard Tk.


text:
Q: Collapsible table in HTML Email (Outlook 2007-2010) I've sent various HTML emails in the past, and have seen the pretty large limitations associated with it.  What I really need is the ability to have regions with a show/hide ability - click the plus sign or a header to toggle.
I'm figuring JS is out of the picture, CSS might be a possibility.  I only need it to work in Outlook 2007-2010.  Any suggestions?
Thanks!

A: You can do this in Outlook using anchor tags. The trick is to create 2 tables that are separated by a td cell with a large height specified so that you don't see the second table.
Both tables are exact duplicates except that table 1 has the show link, while table 2 has the content you want to show, and a hide link.
When you click the anchor tag, the email moves down to the position specified in your second table. As the content in both tables is the same except for the show/hide box visibility, you've created an illusion that the box is toggling.
If you have more than one show/hide box, you'll need to create more tables. The email will get really long, but the toggling effect still works in Outlook.
The anchor tags:
Click here to show content

Here's a quick example: http://jsfiddle.net/mjcookson/nq3Re/
Update to comment: Also, your email might not fill the entire viewport, so a gap between tables is used to avoid seeing the second table immediately after the first table.

A: You can't do that in Outlook. Its HTML email rendering engine is pretty bad. I have seen it done for the mobile webkit and android browsers.
See this article: http://coding.smashingmagazine.com/2011/08/18/from-monitor-to-mobile-optimizing-email-newsletters-with-css/


text:
Q: Two Tablew in One Screen I want to have two tables and a webview in one iPad screen from the following:

*

*The first table will parse items from an RSS feed, and will have an option for a
checkmark

*The second table will be comprised of all checked items

*The webview will be the content from didSelectRowAtIndexPath from the first table (so basically the first table gives the opportunity to display content from didSelectRow, AND check a box (or whatever) to create the secondary table.

I am told for the second table, I should have the checks write to a plist with NSMutableDictionary, and then the second table will just be a table of the plist...but really, what's the code for this?...where do I put it?...etc etc etc. And if the user unchecks the items, the line in the plist will be cleared, right???
I PRESUME I can show all three classes in one screen with something like
[viewController.view addSubview:someOtherViewControler.view];

Is there any reason why I should not do this??
Thanks so much!
XOXO

A: There is no reason you shouldn't do this, and you will be happier with your proposed approach than you would be if you tried to do it all with one view controller.
Organizing with design patterns is done to simplify design and maintenance of your software. What you have described is clearly three independent data sources each with their own independent views. You can use the MVC design pattern independently on each one of them. This independence lends itself to having separate view controllers that are easy to design and maintain.
The fact that they are collected into one main view for your application is outweighed by the simplification in maintainability that you will obtain with separate view controllers.


text:
Q: Force lowercase - ios swift I would like to force lowercase in an UITextfield when the user is typing.
I came out so far with this code, but seems like it's not lowering characters.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if string.characters.count == 0 {
        return true
    }

    let currentText = textField.text ?? ""
    let prospectiveText = (currentText as NSString).stringByReplacingCharactersInRange(range, withString: string.lowercaseString)

    switch textField {
    // Allow only lower-case vowels in this field,
    // and limit its contents to a maximum of 6 characters.
    case userNameTextField:
        return prospectiveText.characters.count <= 27
    default:
        return true
    }
}

A: You could do like this and lowercase the entire string when something has changed.
textfield.addTarget(self, action: "textViewChanged", forControlEvents: .EditingChanged);

  func textViewChanged(){
        textfield.text = textfield.text?.lowercaseString;
    }

A: First you should set following property on your textfield to restrict auto capitalisation:
textfield.autocapitalizationType = UITextAutocapitalizationType.None

And this is how you can restrict it further:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

    if let _ = string.rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()) {
        // Do not allow upper case letters
        return false
    }

    return true
}

UPDATED FOR SWIFT 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let _ = string.rangeOfCharacter(from: .uppercaseLetters) {
        // Do not allow upper case letters
        return false
    }

    return true
}

A: for swift 3 users, the above code given by Abhinav is just converted to the following
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {

        return false
    }

    return true
}

A: if you want to convert all input characters to lower case you should do this code:
Swift 4:
in override func viewDidLoad() add this:
 textfield.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)

and then add this function to your class:
@objc func textFieldDidChange(_ textField: UITextField) {
        if let text:String = textfield.text {
            DispatchQueue.main.async {
                self.textfield.text = text.lowercased()
            }
        }

}

it is necessary to change it in main thread.


text:
Q: Accessing offset storage from the connector I have a source connector written in Java running is distributed mode with
offset.storage.topic = connect-offsets. The topic is populated when tasks are committing. From my task class (extends org.apache.kafka.connect.source.SourceTask) I can read this topic by using context.offsetStorageReader().
Is there a way to read the offset from within my connector class?
When starting or restarting the connector, I want to be able to use this information to decide how to assign partitions to tasks. I normally have a small number of 'new' partitions and a large number of 'old' partitions, I need to assign all the new partitions to the same task but 'old' partitions can be assigned to any task. Knowing whether an entry exist for a partition would let me figure out which tasks are 'new' (offset topic has no entry) and which are 'old' (offset topic has an entry).


text:
Q: chef-client not starting with chef-client cookbook RHEL 6.7 I am using the 4.3.2 chef-client cookbook, chef-client 12.6, and my run list is - role chef-client, and my chef-client role is as follows:
chef-client
chef-client::config
chef-client::delete_validation
Link to the cookbook - https://github.com/chef-cookbooks/chef-client
My os is rhel 6.7
Also, if it matters, I am using Packer to create the image when this issue occurs.
I log-on to the VM, and I am unable to start the service either.
During the chef-client run, it will error with the following

'mazon-ebs: ================================================================================
    amazon-ebs: Error executing action `start` on resource 'service[chef-client]'
    amazon-ebs: ================================================================================
    amazon-ebs:
    amazon-ebs: Mixlib::ShellOut::ShellCommandFailed
    amazon-ebs: ------------------------------------
    amazon-ebs: Expected process to exit with [0], but received '6'
    amazon-ebs: ---- Begin output of /sbin/service chef-client start ----
    amazon-ebs: STDOUT:
    amazon-ebs: STDERR:
    amazon-ebs: ---- End output of /sbin/service chef-client start ----
    amazon-ebs: Ran /sbin/service chef-client start returned 6
    amazon-ebs:
    amazon-ebs: Resource Declaration:
    amazon-ebs: ---------------------
    amazon-ebs: # In /var/chef/cache/cookbooks/chef-client/recipes/init_service.rb
    amazon-ebs:
    amazon-ebs: 32: service 'chef-client' do
    amazon-ebs: 33:   supports :status => true, :restart => true
    amazon-ebs: 34:   action [:enable, :start]
    amazon-ebs: 35: end
    amazon-ebs:
    amazon-ebs: Compiled Resource:
    amazon-ebs: ------------------
    amazon-ebs: # Declared in /var/chef/cache/cookbooks/chef-client/recipes/init_service.rb:32:in `from_file'
    amazon-ebs:
    amazon-ebs: service("chef-client") do
    amazon-ebs: action [:enable, :start]
    amazon-ebs: updated true
    amazon-ebs: supports {:status=>true, :restart=>true}
    amazon-ebs: retries 0
    amazon-ebs: retry_delay 2
    amazon-ebs: default_guard_interpreter :default
    amazon-ebs: service_name "chef-client"
    amazon-ebs: enabled true
    amazon-ebs: pattern "chef-client"
    amazon-ebs: declared_type :service
    amazon-ebs: cookbook_name "chef-client"
    amazon-ebs: recipe_name "init_service"
    amazon-ebs: end
    amazon-ebs:
    amazon-ebs: [2016-01-20T16:49:04-05:00] INFO: Running queued delayed notifications before re-raising exception
    amazon-ebs: [2016-01-20T16:49:04-05:00] INFO: template[/etc/init.d/chef-client] sending restart action to service[chef-client] (delayed)
    amazon-ebs: * service[chef-client] action restart[2016-01-20T16:49:04-05:00] INFO: Processing service[chef-client] action restart (chef-client::init_service line 32)
    amazon-ebs:
    amazon-ebs:
    amazon-ebs: ================================================================================
    amazon-ebs: Error executing action `restart` on resource 'service[chef-client]'
    amazon-ebs: ================================================================================
    amazon-ebs:
    amazon-ebs: Mixlib::ShellOut::ShellCommandFailed
    amazon-ebs: ------------------------------------
    amazon-ebs: Expected process to exit with [0], but received '6'
    amazon-ebs: ---- Begin output of /sbin/service chef-client restart ----
    amazon-ebs: STDOUT: Stopping chef-client: [FAILED]
    amazon-ebs: STDERR:
    amazon-ebs: ---- End output of /sbin/service chef-client restart ----
    amazon-ebs: Ran /sbin/service chef-client restart returned 6
    amazon-ebs:
    amazon-ebs: Resource Declaration:
    amazon-ebs: ---------------------
    amazon-ebs: # In /var/chef/cache/cookbooks/chef-client/recipes/init_service.rb
    amazon-ebs:
    amazon-ebs: 32: service 'chef-client' do
    amazon-ebs: 33:   supports :status => true, :restart => true
    amazon-ebs: 34:   action [:enable, :start]
    amazon-ebs: 35: end
    amazon-ebs:
    amazon-ebs: Compiled Resource:
    amazon-ebs: ------------------
    amazon-ebs: # Declared in /var/chef/cache/cookbooks/chef-client/recipes/init_service.rb:32:in from_file
     amazon-ebs:
    amazon-ebs: service("chef-client") do
    amazon-ebs: action [:enable, :start]
    amazon-ebs: updated true
    amazon-ebs: supports {:status=>true, :restart=>true}
    amazon-ebs: retries 0
    amazon-ebs: retry_delay 2
    amazon-ebs: default_guard_interpreter :default
    amazon-ebs: service_name "chef-client"
    amazon-ebs: enabled true
    amazon-ebs: pattern "chef-client"
    amazon-ebs: declared_type :service
    amazon-ebs: cookbook_name "chef-client"
    amazon-ebs: recipe_name "init_service"
    amazon-ebs: end
    amazon-ebs:
    amazon-ebs:

A: When using the chef-client cookbook you should put this in your run list: chef-client::config, chef-client:init_service.
Avoid putting chef-client in your run list before including the config, because this will create the service before creating the configuration.
So, remove chef-client::default (aka chef-client) from your run list. That's all. You can use chef-client::config, chef-client::default, chef-client::delete_validation if you prefer. But remember, the config goes first.


text:
Q: Usign iMac as a Display for MacBook Pro I did some research on this and they were saying Press Command+F2
So did I !  But here are the issues I saw with this method:
The youtube video that was previously running on iMac continued to run, I could hear its vocie but no picture. I want iMac programs to stop running if possible.
The Mouse and Keyboard on the iMac stopped working and I had to use MacBook's Mouse and keyborad which is ridiculous!
What I want to achieve:

*

*iMac turn into Display for MacBook Pro.

*Be able to use iMac mouse and Keyboard.

What I have:

*

*Thunderbolt Cable to connect to MacBook and iMac

*iMac model: These new thin 27" ones.

*Macbook model: 15" retinal display ones.

Basically when I am at home and want to work on my work laptop- which is this MacBookPro one - I want to be able to connect it to my iMac and use that as display.

A: Ok got it working:

*

*turn off both devices.

*connect them with thunderbolt cable

*turn on MacBookPro AND keep holding the "T" key on its keyboard. You will see it will go to a disk mode with some thunderbolt icon showing on its screen.

*Turn on your iMac AND keep holding the OPTION key on its keyboard. You will see it will show you some hard disks on the display. Pick the one that is for the MacBookPro.

*Done! Now Nothing from iMac is running in the background, iMac's peripherals are working for MacBookPro AND EVEN better: you are using CPU Power and RAM of your iMac to run MacBookPro.

NOTE: to turn off, don't just unplug the thunderbolt cable, first shut down the computer, then unplug the cable.

A: So they are not going to happen.
First of all the mechanism that turns the iMac to a thunderbolt display that works only with Mac is not documented, so we're in the dark. The applications running on iMac seemed to not know what happened and continued to run.
Second, since your bluetooth devices are connected to your iMac, you can't connect them to your MacBook unless you disconnect them from the iMac.
Lastly, judging from your needs, the easiest way to do them is to sync your work. That way you can use iMac's keyboard and mouse, and have it behave normally.


text:
Q: Yup validation to accept more than 0 input digit. Like user can enter 0.001 or 0.0001. But not only 0 I'm working on a project, where on the admin panel, doctor can set commission for their treatment. But it can be only 2 digit long. But commission can't be 0. It can be anything 0.01 or 0.001.
I have created a form using formik and yup. But don't know how to set input field for this work.
I have tried & searched, but not found any solution.
Yup validation
  commission: Yup.string()
      .required()
      .matches(/^[0-9]+$/, "Commission should contain only digits")
      // .min(1, 'Must be exactly 1 digits')
      .max(2, "Commission should not be more than 2 digits"),

input field code

                          Commission(%) *{" "}

                        <input
                          type="text"
                          className="form-control"
                          name="commission"
                          value={formik.values.commission}
                          onChange={formik.handleChange}
                          onBlur={formik.handleBlur}
                          min="0.01"
                        ></input>
                        {formik.touched.commission &&
                        formik.errors.commission ? (

{formik.errors.commission}

                        ) : null}

```

A: Update your yup validation to:
commission: Yup.number()
      .required()
      .moreThan(0, 'commision should not be zero or less than zero')
      .lessThan(100, "Commission should not be more than 2 digits"),

And also change you input field type:
<input
     type='number'
     ...
   />


text:
Q: Call LaTeX from Python Django Within django, I am using jinja2 to render a template into a .tex file. I then need to call 'xelatex' on this .tex file, and save the output as a django File object.
I've got as far as this:
tex_file = render_to_string("foo.tex", context)

If I save tex_file to a file, and run xelatex on it, I get the expected output, so it works up until this point.
I then tried something like this:
subprocess.run(["xelatex", tex_file], capture_output=True])

The problem is that I don't actually want to capture xelatex's output to STDOUT. I want to capture the output.pdf file that it generates.
I know that I could just have xelatex save this file to /tmp/, and then have python open it and deal with it, but this seems slow and messy. Is there any way of getting subprocess to actually return the output:
output = subprocess.run(["xelatex", tex_file], capture_output=True])
self.file = file


text:
Q: Mapforce: merging changes in Perforce version control In my project I am using mapforce to create XSLT transforms. The problem is that mapforce generates different output even after a minor change (different var names, different object sequence etc.)
If I implement some functionality in, say, Project branch 1.2 and other developer adds another functionality in branch 1.3, and we both submit changes to branches 1.2 and 1.3 respectively, there is no way one can just integrate changes (I am using Perforce for version control) to version 1.3, it has to be reimplemented.
Is there anyway I could overcome this? Maybe a version control plug-in in mapforce?

A: I'm afraid this is just a limitation of code generators.  Most just assign new labels (or numbers) as they go along, so depending on where the added code is, everything generated after that point will be changed.
To fix it, the MapForce code generator would have to save the metadata used when generating code, and re-use it the next time you generate code.  The generator would have to distinguish new items from those that have just moved, and re-use all existing ones.  It might be a major change to their software to do this, depending on how it is currently implemented.
It can't hurt to request/suggest such a feature, and having it would help Altova position Mapforce as more of a production-ready solution, able to support version control of the customer's work.


text:
Q: RSpec how to stub out yield and have it not hit ensure I have an around action_action called set_current_user
def set_current_user
  CurrentUser.set(current_user) do
    yield
  end
end

In the CurrentUser singleton
  def set(user)
    self.user = user
    yield
  ensure
    self.user = nil
  end

I cannot figure out how to stub out the yield and the not have the ensure part of the method called
Ideally I would like to do something like
it 'sets the user' do
  subject.set(user)
  expect(subject.user).to eql user
end

Two errors I am getting

*

*
*

*No block is given

*

*When I do pass a block self.user = nil gets called

Thanks in advance

A: A few things to point out that might help:
ensure is reserved for block of codes that you want to run no matter what happens, hence the reason why your self.user will always be nil. I think what you want is to assign user to nil if there's an exception. In this case, you should be using rescue instead.
def set(user)
  self.user = user
  yield
rescue => e
  self.user = nil
end

As for the unit test, what you want is to be testing only the .set method in the CurrentUser class. Assuming you have everything hooked up correctly in your around filter, here's a sample that might work for you:
describe CurrentUser do
  describe '.set' do
    let(:current_user) { create(:user) }
    subject do
      CurrentUser.set(current_user) {}
    end
    it 'sets the user' do
      subject
      expect(CurrentUser.user).to eq(current_user)
    end
  end
end

Hope this helps!

A: I failed to mention I need to clear out the user after every request.
This is what I came up with. Its kinda crazy to put the expectation inside of the lambda but does ensure the user is set prior to the request being processed and clears it after
describe '.set' do
  subject { described_class }

  let(:user) { OpenStruct.new(id: 1) }

  let(:user_expectation) { lambda{ expect(subject.user).to eql user } }

  it 'sets the user prior to the block being processed' do
    subject.set(user) { user_expectation.call }
  end

  context 'after the block has been processed' do
    # This makes sure the user is always cleared after a request
    # even if there is an error and sidekiq will never have access to it.

    before do
      subject.set(user) { lambda{} }
    end

    it 'clears out the user' do
      expect(subject.user).to eql nil
    end
  end
end

A: I am not sure what you intend to accomplish with this as it appears you just want to make sure that user is set in the block and unset afterwards. If this is the case then the following should work fine
class CurrentUser
  attr_accessor :user
  def set(user)
    self.user = user
    yield
  ensure
    self.user = nil
  end
end

describe '.set' do
  subject { CurrentUser.new }
  let(:user) { OpenStruct.new(id: 1) }
  it 'sets user for the block only' do
    subject.set(user) do
      expect(subject.user).to eq(user)
    end
    expect(subject.user).to be_nil
  end
end

This will check that inside the block (where yield is called) that subject.user is equal to user and that afterwards subject.user is nil.
Output:
.set
  sets user for the block only

Finished in 0.03504 seconds (files took 0.14009 seconds to load)
1 example, 0 failures


text:
Q: how to get div selectionstart and selectionend for firefox and ghroom? when Im using this code inside text area its working perfect bu i need it for my div the selectionstart and selectionend functions gives undefined values why can any one help me with this here are my code
{var textarea = document.getElementById("content_text");

if ($.browser.webkit || $.browser.mozilla) {
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;
        sel = textarea.value.substring(start, end);
    }

A: if you use the onclik event it will not work because its not getting the text but if you use the onmousdown event it will work


text:
Q: CSS Display Empty DIV ONLY if there is content I am attempting to create a div (essentially will become a tooltip) that will display when hovered; however, I need it to display ONLY if there is content in the div

[data-tip] {
    position:relative;
}
[data-tip]:after{
    display: none;
    position: absolute;
    content:attr(data-tip);
    padding: 5px 8px;
    background-color: red;
    z-index: 10;
    height: 12px;
    border-radius: 3px;
    white-space: nowrap;
    word-wrap: normal;
}
[data-tip]:hover:after+[data-tip].active{
    display: block;
}

This should not display

Obviously the CSS is not complete with positioning, etc. but Ineed the most important part to work and thats displaying only when there is content in the data-tip

A: You can check empty attributes.

document.querySelectorAll("[data-tip]").forEach(p => {
  p.getAttribute("data-tip") == '' ? p.style.display = 'none' : '';
});
[data-tip] {
    position:relative;
}
[data-tip]:after{
    display: none;
    position: absolute;
    content:attr(data-tip);
    padding: 5px 8px;
    background-color: red;
    z-index: 10;
    height: 12px;
    border-radius: 3px;
    white-space: nowrap;
    word-wrap: normal;
}
[data-tip]:hover:after+[data-tip].active{
    display: block;
}

This should not display

This will also work when it contains spaces with trim() function.

document.querySelectorAll("[data-tip]").forEach(p => {
  p.getAttribute("data-tip").trim() == '' ? p.style.display = 'none' : '';
});
[data-tip] {
    position:relative;
}
[data-tip]:after{
    display: none;
    position: absolute;
    content:attr(data-tip);
    padding: 5px 8px;
    background-color: red;
    z-index: 10;
    height: 12px;
    border-radius: 3px;
    white-space: nowrap;
    word-wrap: normal;
}
[data-tip]:hover:after+[data-tip].active{
    display: block;
}

This should not display

A: Here is one more solution using css

[data-tip] {
    position:relative;
    height: 40px;
    border: 1px solid lime;
}
[data-tip]:after{
    display: none;
    position: absolute;
    content:attr(data-tip);
    padding: 5px 8px;
    background-color: red;
    z-index: 10;
    height: 12px;
    border-radius: 3px;
    white-space: nowrap;
    word-wrap: normal;
}
[data-tip]:not([data-tip=""]):hover:after{
    display: block;
}

This should not display

div1

This should not display as well

this should display again

A: Maybe try the following selector?
[data-tip]:not([data-tip=''] {

}


text:
Q: Intermittent NullReferenceException during .NET website compilation We have a large web application written using WebForms in C# using .NET and we have a weird problem. Hoping someone can help. We have a testing environment running IIS7 and whenever we upload modified files (.aspx, .aspx.cs, .ascx, .ascx.cs etc.) we get the following exception when trying to access the modified pages - but only for about 30 seconds. Then the application runs correctly.
[NullReferenceException: Object reference not set to an instance of an object.]
   System.Web.Script.Services.WebServiceData.GetWebServiceData(HttpContext context, String virtualPath, Boolean failIfNoData, Boolean pageMethods, Boolean inlineScript) +251
   System.Web.Script.Services.PageClientProxyGenerator.GetClientProxyScript(HttpContext context, IPage page, Boolean debug) +49
   System.Web.UI.ScriptManager.RegisterServices() +511
   System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e) +120
   System.Web.UI.Page.OnPreRenderComplete(EventArgs e) +8699694
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1029

As you can see it appears to be a web service failing to initialise because something's null, HttpContext maybe?!
This only happens on a regular basis in this testing environment, it has happened on our local machines but only very rarely. It never happens in the production environment. I originally thought it was something to do with the AJAX control toolkit, which we're using. I can't find anything documented about it, other than a few forum topics with no replies.
Not entirely sure how I can narrow this down any further. We have a staging environment running on the same machine which doesn't experience the problem. I might create a new site in IIS and point that to it to see if it helps, any suggestions are welcome.
As always, thanks for your time.

A: If it's only occurring when you update files, it could be because of the recompilation that takes place when you do that. It might be particularly true if it's a large site. I've had similar issue that occur with a site of my own.
As to why it only occurs in certain places, I'm afraid I have no answer.


text:
Q: Find a inverse of polynomial in quotient ring in $\mathbb{Z}_p$ Let $f=x^3+x+1$, I want to find a inverse of $g=x^4 +3x^3+x^2+1$ in $A=\mathbb{Z}_5[x]/(f)$.
I do the division between $f$ and $g$ is $q=x+3$ and $r=2x+3$, then I continued with the division between $x^3+x+1$ and $r$ and then I have rest $=1$.
Now I don't know how to move in order to find the inverse.
Thanks for the attention.

A: Represent the gcd of the two polynomials as a linear combination of these polynomials using the extended euclidean algorithm (Bezout's thm):
$1 = a\cdot f + b\cdot g$ for some polynomials $a,b$.
Then $b\cdot g\equiv 1 \mod f$ and so $b\cdot g =1$ in $\Bbb Z_5[x]/\langle f\rangle$.


text:
Q: Remove that ugly skype banner How can I remove that ugly banner in Skype? It showed up in the latest version but I think it is pretty annoying.
I know I can go back to the latest version but I would rather keep my software up to date (you know, viruses and malware and stuff) so I'm looking for something that can fix this problem in the current version of skype (and possibly newer ones)

A: Put
127.0.0.1 rad.msn.com
127.0.0.1 apps.skype.com

in your HOSTS file. Done.

A: Luckily, there is a way:

*

*Start Internet Explorer and click on the cog icon (or press ALT+X)

*Go to Internet Options > Security

*Click Restricted Sites and click on the Sites button

*Enter https://apps.skype.com/ in the textbox and click Add.

*Click Close and OK

(see here)

A: Can you please try this
http://www.cnet.com/how-to/how-to-disable-ads-in-skype/
It not only removes the ad but it removes the whole bar.
Overview of the steps listed in the link

*

*Add  https://apps.skype.com in restricted sites

*Open config file of skype. You can find the config.xml in directory similar to the below example
C:\users[your user name]\App Data\Roaming\Skype[your Skype username]

*Search for AdvertPlaceholder tag and remove the line

*Then make the config.xml readonly to restrict skype from adding it automatically again.

Thanks

A: I am using the Linux Skype client and there is no ads at all on it, so I am not sure my advice would help you.
You can use a network sniffer (like Wireshark) to see the IP the software is trying to load ads from. If it is always the same (it should first retrieve the list of ads, I guess), you can try to block it in your hosts file (by assigning 127.0.0.1 as a alias of this IP, so every request to get ads are redirected to your PC and then fail).
But if Skype is retrieving the ads from the same server as it uses to connect yourself to the Skype services (for communicating with your contacts) it may just break everything...

A: I've written a tool that automatically removes the entire Skype advertising. http://www.mediafire.com/download/3s1903x5vc0cfvn/Skype_Werbung_weg.exe
Therefore you have to enter your username, because the settings are at %AppData%\Skype and then in a folder with the Skype name. But it will not be given to me or third,this shows the fact, that it easily works without Internet.
The Tool is Written in German, because I´am from Germany. If you can read in it "Bitte Skype Kontonamen (der nicht aenderbare) eingeben.
(Klicke in Skype auf deinen Namen [Oben links]
und dann siehst du ihn oben recht unter "Konten"):" It means, that you have to enter your Skype Account name. You can find it, in Skype with an click to your username (at the top right corner) and than you can see it under "Accounts" (At the top right) Tipp: if you have linked with Microsoft, it´s not your Microsoft email Address.
If you are interested: This tool is a packed batch with an extra tool to easily add things to hosts file. You can simply unpack with WinRar or 7Zip for example and in the batch I still have some notes for operation made.
Is recognized scanners at VirusTotal of about 3 of 50 viruses, because it´s changing the hosts file...
The Notes in the Batch script are also in German.
Hopefully you could understand my bad English.


text:
Q: Is there a word/phrase for when you hate a nickname but if one person says it you secretly like it? Say you hate being called a specific nickname or pet name, but there's one person who calls you it and you secretly like it? I've tried finding a word, but I don't know if there is one. Maybe there's a phrase?

A: One expression is to have a soft spot for someone. Farlex has

a soft spot
A particular fondness or affection for someone or something, often for reasons that [are] hard to understand or articulate.

So you could say:

I hate being called diddykins but secretly like it when X calls me that. I have a soft spot for her/him.


text:
Q: How to create animation with delay when dismiss view swiftui I used the following example ( iOS SwiftUI: pop or dismiss view programmatically ) in my code, but I don't know how to create an animation just like flipping a page and put several seconds delay when [Button] tapped.Does anyone know a solution?
struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: {

                //withAnimation(.linear(duration: 5).delay(5))// Error occurred in dalay.(Type of expression is ambiguous without more context)
                withAnimation(.linear(duration: 5)) // not work
                {
                    self.presentationMode.wrappedValue.dismiss()
                }
        }
        )
    }
}

struct RootView: View {
    var body: some View {
        VStack {
            NavigationLink(destination: DetailView())
            { Text("I am Root. Tap for Detail View.")
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            RootView()
        }
    }
}

A: This would be one way to do it. Without the NavigationLink you have full control over all animations and transitions.
struct DetailView: View {
    @Binding var showDetail:Bool

    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: {
                withAnimation(Animation.linear.delay(2)){
                    self.showDetail = false
                }
            }
        ).frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.yellow)
    }
}

struct RootView: View {
    @State var showDetail = false

    var body: some View {
        VStack {
            if showDetail{
                DetailView(showDetail:self.$showDetail).transition(.move(edge: .trailing))
            }else{
                Button("I am Root. Tap for Detail View."){
                    withAnimation(.linear){
                        self.showDetail = true
                    }
                }
            }
        }.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.red)
    }
}

A: You can dispatchQueue delay?
    Button(
        "Here is Detail View. Tap to go back.",
        action: {
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                self.presentationMode.wrappedValue.dismiss()

            }})


text:
Q: How to style successful input fields in Thymeleaf I would like to use Bootstrap's has-success and has-failure classes with Thymeleaf.
So far I have

This displays the failure style correctly, when the form is posted and the field is invalid.
However if I change the second part of the ternary to 'form-group has-success', then on the initial form GET request, then, of course, it styles it as a success, even though the form hasn't been posted yet.
My question: is there a way in Thymeleaf to handle the following

*

*Displays a form without any styling on GET.

*On POST apply has-error or has-success classes.

A: I think you'll need to add attributes to your Model in the back-end for this.
In you GET request, change nothing. In your POST request, add an attribute: ["hasErrors", true] if the form data you send via the post is incorrect, false otherwise.
Now in your html you can add the following:

You check if the hasErrors model attribute isn't null, if it is, it means you're in the GET method and you should display a simple form-group. If the hasErrors is not null, you can create the ternary expression based on the boolean value hasErrors. The th:block is non-html. You can replace it with a div, but then you neen an extra div just to check a boolean.

A: I'm not going into GET/POST problem but I think that this can help you:
New th:errorclass for adding CSS class to form fields in error
Until now, whenever we wanted to apply a specific CSS class to an input field in a form when there were errors for that field, we needed to use the th:class or th:classappend attributes.
In Thymeleaf 2.1, in order to simplify this structure, a new th:errorclass attribute processor has been introduced. This processor will read the name of the field from the name or th:field attribute in the same tag, and apply the specified class if such field has errors.
Note the 'error' literal is in fact a token, so no single quotes are really needed.
The result is much more concise. Note also that th:errorclass works like th:classappend, not th:class. So the specified class will in fact be appended to any existing ones.
http://www.thymeleaf.org/whatsnew21.html#errcl

A: I found that Thymeleaf as a hasAnyErrors function.

This now works.

*

*When the user GETs the form, hasAnyErrors is false, so the empty string is appended and the input and label receive the default style.

*When the user POSTs the form, if there are any errors then the first part of the ternary is evaluated. This adds the has-error or has-success styles.

This was inspired by Roel Strolenberg's answer below.


text:
Q: Link that takes to a specific view controller from html source (example: instagram links) I am looking for a way to create a link in a HTML blog that takes the user to my iOS application, and specifically to a view controller that will show the requested info. How would I would I go about generating the link and have the app recognise which link the user pressed on to take to the view controller.
The example that comes to mind, is when you find an instagram link in a website that takes the user to the instagram app then to the picture associated with the link.

A: You need to define a custom url scheme within the plist of your app. Once installed, every app (and of course Safari can) open your app by requesting such an url.
If you embed this in your blog, your app will be launched and the parameter given via didFinishLaunvhingWithOptions:
Well documented at Apple:
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html#//apple_ref/doc/uid/TP40007072-CH6-SW1
Edit: if you want to see an example what these schemes look like and how they are used, Instagram defined their url scheme here http://instagram.com/developer/mobile-sharing/iphone-hooks/


text:
Q: How to stop e-mail from sending to wrong recipient I am using Lotus Notes 8.5 version.
My question, how can I stop e-mail if I accidentally sent to wrong recipient. If yes, how many minutes after I sent to ensure that the recipient will not receive my e-mail.
Thank you very much.

A: This action is detailed in the help topic "Recalling a message".
In the sent view:
1. Select the message
2. Above the message list, click "Recall Message" (If this button does not display, your administrator has disabled it)
3. If the message was sent to more than one recipient, select the recipient to recall it from.
4. Optional, to recall the message from a recipient who has already read it, select "Recall the message even if it has been read"
5. Make sure that "Send me a status report for each recipient" is checked so you get confirmation.


text:
Q: Autocommit with PDO The rollback of my transaction doesn't work.
How do I set autocommit to false (or 0) in the php script using PDO (I have InnoDB 5.7.18) ?
Here is my code:
     global $bdd;  //defined with PDO

       try {
            $bdd->beginTransaction();
            /* my requests */
            $bdd->commit();
        } catch (Exception $e) {
            $bdd->rollBack();
            return $e->getMessage();
        }

        return true;
    }

A: I solved my problem myself: a few of my tables were in MyISAM (whereas the majority are in InnoDB -> I work with an old database system...); so the rollback didn't work for these tables. Once I changed them into InnoDB, it worked.
Thanks to everybody for the help !

A:  $db = new PDO('mysql:dbname=employee');
 $db->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
 var_dump($db->query('SELECT @@autocommit')->fetchAll());

A: Try setting the following attribute:
$bdd->setAttribute(PDO::ATTR_AUTOCOMMIT,0);


text:
Q: What is the ontological status of Faddeev Popov ghosts? We all know Faddeev-Popov ghosts are needed in manifestly Lorentz covariant nonabelian quantum gauge theories. We also all know they decouple from the rest of matter asymptotically, although they "superficially" interact over finite time periods.

*

*So, what is their ontological status?

*If they don't really exist, can we just formulate a local theory without them?

*OK, we can using spin foams?

*So are they not really needed?

*If they do "exist" out there, then say a state with an electron and no ghosts is "actually" different in "reality" from the state with same electron with the same momentum, but with a ghost added?

*According to the formalism, they are different states. But observationally, we can never tell the difference. Both states will always give the same observable results for any physical observation. So are they the same state or not?

*Do we just take the partial trace over the ghost sector?

*But that's not gauge invariant except asymptotically, is it?

A: 1,3&4. If you fixed a gauge and got rid of unphysical degrees of freedom (sacrificing manifest gauge invariance), you would not have to muck around with ghosts. You need to come up with them in order to get rid of the unphysical modes and still preserve manifest gauge invariance. You take a call on what that means ontologically; as far as physics is concerned, that doesn't matter.
5&6. As @RonMaimon says, ghosts are gauge dependent. It doesn't make sense to compare a state in one gauge (without ghost) to the same state in another gauge (with ghost). Remember, a gauge is kind of like the setup in which you "measure" the gauge field. And no physical observable will depend on your gauge choice.
7&8. We don't need to take any partial trace. The ghosts decouple honest-to-god. So you might as well not bother with them. If they did not decouple completely, qft would start behaving very weirdly, to put it mildly.
q2. Huh! Where did spin foams enter this discussion?

A: I'd say BRST ghosts have more elements of reality compared to longitudinal gauge bosons which are pure gauge. Look at the inner product structure. Physical states belong to the BRST cohomology of BRST-closed modulo BRST-exact. pure gauge longitudinal gauge bosons are BRST-exact and have zero inner product with any other BRST-closed state. BRST ghosts have nonzero inner products with themselves and other BRST-closed states. BRST ghost states are merely BRST-closed. BRST-closed states with different ghost numbers have zero inner product between themselves, even while having nonzero norms.
The BRST ghost structure is independent of the choice of gauge-fixing. Different choices of gauge fixings correspond to different extended Hamiltonians but these Hamiltonians can only differ by BRST-exact quantities. So, different gauges only differ by BRST-exact differences to be quotiented over.


text:
Q: Django form validation fails (on update) I'm fighting with the Django form validation for a while now. I'm using pretty basic code. Returning the form data using an ajax request is the only special thing but I don't think its the cause auf my problems here.
I'm trying to update an user entry. I create an instance of the user and I feed that instance into the CreateForm() but I still get the duplicate username error.
here is a part of the view:
def user_update(request):
    if request.is_ajax():
        print request.POST
        user = User.objects.get(pk=int(request.POST['pk']))
        print user
        form = UserCreateForm(request.POST, instance=user)
        print form
        if form.is_valid():
            form_cleaned = form.cleaned_data
        else:
            print '### form is invalid ###'
            print form.error_messages

The output for request.POST is:
<QueryDict: {u'username': [u'testuser'], u'password1': [u'test'], u'password2': [u'test'], u'pk': [u'27'], u'csrfmiddlewaretoken': [u'wyBoaBAlxLTO952BzWSxR7HMK6W7nsAM'], u'email': [u'soso@soso.so']}>

The output for print user is:
testuser

In print form I always get the duplicate username error, hence the form is always invalid.
Please give me a hint. Many thanks in advance.

A: For form validation, you have used UserCreateForm.
Apart from the regular regex validation of fields, the UserCreateForm also checks if a given username is available or not. And any existing user will fail this check.
You should use an appropriate form like UserChangeForm or if your application only updates a particular field like password, then choose from the built in forms.

A: With reference to UserCreationForm in django, it has clean_username() validation method that checks if user with given username already exists, if so raises the validation error that you are getting.
You should better use UserChangeForm if you want to update user fields.

A: The UserCreationForm's clean_username() has the following code:
User._default_manager.get(username=username)

If this is successful, you get your error. Since your user (admin) already exists, you'll always get the error. As suggested by @sudipta, you're better off with the UserChangeForm.
IMHO, you could define your own custom form either with your own behaviour rather than using a stock one and deviate from its original purpose.


text:
Q: map[Task]int64 where Task is an interface Let's say I define the following interface in a Go library:
type Task interface {
    Do() error
}

func Register(task Task) { ... }

func GetId(task Task) int64 { ... }

In Register(), the library associates a unique int64 with each task instance. GetId() must return the identifier for the given task.
My initial idea was to store the association as a map[Task]int64. This seems to work fine, but I was told that it would break if an object implementing Task was not equality-comparable (for example, a struct containing a map). I still need to check if this is true.
I was going to try and use a slice of struct { task Task; id int64 } instead and just iterate over it, but that would still require equality comparable Task instances. And AFAIU there is no identity comparison in Go.
How can I have a robust mapping from Task instances to their ID?
EDIT: Both solutions proposed so far work, but they have the disadvantage that every Task implementation has to include some repetitive code to handle the IDs. I could provide that code in a TaskBase struct that could be embedded, but ideally I would prefer a solution that doesn't require implementations to even know about the IDs (they are internal to the library and have no meaning outside of it).

A: A more complete example:  http://play.golang.org/p/1RzDiw7F9t
package main

import (
    "fmt"
    "math/rand"
)

type Task interface {
    Do() error
    ID() int64
}

type XTask struct {
    id int64
    // other stuff
}

func NewXTask( /*task parameters...*/) *XTask {
    t := &XTask{ /*initialize members*/}
    t.id = Register(t)
    // possibly more initialization...
    return t
}

func (t *XTask) Do() error  { return nil }  // stub
func (t *XTask) ID() int64  { return t.id }

var taskRegistry = map[int64]Task{}

func Register(t Task) int64 {
    var id int64
    for {
        id = rand.Int63()
        if _, exists := taskRegistry[id]; !exists {
            break
        }
    }
    taskRegistry[id] = t
    return id
}

func main() {
    t1 := NewXTask()
    t2 := NewXTask()
    fmt.Printf("%x\n", t1.ID())
    fmt.Printf("%x\n", t2.ID())
}

I used an ID method as Daniel suggested, and I turned the map backwards from the way you had it.  This is because the Task objects know their own ID, so a map from Task to ID is not needed.  A map from ID to task however, is useful for guaranteeing uniqueness.  It might come in handy some other time if you find yourself with only an ID and you need the corresponding Task object.
Also note this example is not goroutine-safe.  If you need that you will have to add synchronization.


text:
Q: $_SERVER['SERVER_NAME'] is not working with console application in Yii framework When i am trying to run my photoResizer command  like this /var/www/myProject/proted/yiic photoResizer
i am getting this error.
PHP Error[8]: Undefined index: SERVER_NAME
in file /var/www/myProject/protected/components/UploadHandler.php at line 190
#0 /var/www/myProject/protected/components/UploadHandler.php(45):
UploadHandler->get_full_url()
#1 /var/www/myProject/protected/commands/PhotoResizerCommand.php(37):
UploadHandler->__construct()
#2 /var/www/myProject/framework/console/CConsoleCommandRunner.php(71):
PhotoResizerCommand->run()
#3 /var/www/myProject/framework/console/CConsoleApplication.php(92):
CConsoleCommandRunner->run()
#4 /var/www/myProject/framework/base/CApplication.php(180):
CConsoleApplication->processRequest()
#5 /var/www/myProject/framework/yiic.php(33): CConsoleApplication->run()
#6 /var/www/myProject/protected/yiic.php(7): require_once()
#7 /var/www/myProject/protected/yiic(4): require_once()

I need to solve this problem or any alternative to run a php script via command line in yii framework.
Thanks.

A: Quite obviously there's no "server" when running an app from the command line, so you cannot use that variable for anything. Apparently UploadHandler is hard coded to expect to be executed in the context of a web request to handle files uploaded within the request (which, you know, makes sense). Since you're not in a web request context, it fails.

A: You can add in config/console.php in components array
'request' => array(
    'hostInfo' => 'http://localhost',
    'baseUrl' => '',
    'scriptUrl' => '',
),

and also add urlManager
'urlManager' => array(
    'urlFormat' => 'path',
    'showScriptName' => false,
    'rules' => array(
        '<controller:\w+>' => '<controller>/index',
        '<controller:\w+>/<id:\d+>' => '<controller>/view',
        '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
        '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),
),