text:
Q: Can I change my Windows desktop wallpaper programmatically in Java/Groovy? Is there a way I can use Java (or Groovy) to change my desktop wallpaper in Windows XP?  I have a program that creates a new image every day (or whenever) and I would like a way to automatically update my desktop.
I've seem some questions on this site about C++ or .NET, but I did not see anything specific to Java.

A: You can do it easier:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinDef.PVOID;
import com.sun.jna.win32.W32APIOptions;
public class Wallpaper {
 public static interface User32 extends Library {
     User32 INSTANCE = (User32) Native.loadLibrary("user32",User32.class,W32APIOptions.DEFAULT_OPTIONS);
     boolean SystemParametersInfo (int one, int two, String s ,int three);
 }
public static void main(String[] args) {
   User32.INSTANCE.SystemParametersInfo(0x0014, 0, "C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg" , 1);
   }
 }

A: You can write a batch file to change the wall-paper, and execute that batch file using,
Runtime.getRuntime.exec()

A: Sorry I'm a bit behind @ataylor's answer because I was preparing a snippet to do it.  Yes, JNA is a correct approach.  Here you go:
import java.util.HashMap;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.UINT_PTR;
import com.sun.jna.win32.*;

public class WallpaperChanger {
   public static void main(String[] args) {
      //supply your own path instead of using this one
      String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg";

      SPI.INSTANCE.SystemParametersInfo(
          new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
          new UINT_PTR(0),
          path,
          new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
   }

   public interface SPI extends StdCallLibrary {

      //from MSDN article
      long SPI_SETDESKWALLPAPER = 20;
      long SPIF_UPDATEINIFILE = 0x01;
      long SPIF_SENDWININICHANGE = 0x02;

      SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
         {
            put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
            put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
         }
      });

      boolean SystemParametersInfo(
          UINT_PTR uiAction,
          UINT_PTR uiParam,
          String pvParam,
          UINT_PTR fWinIni
        );
  }
}

You need to have the JNA libraries on the classpath for this to work.  This was tested in Windows 7, there might be some nuances in XP but I think it should work.  That API is presumably stable.
References

*

*Setting Wallpaper - Coding4Fun

*How to determine if a screensaver is running in Java?

*W32API.java
Edit (2010/01/20):
I had previously omitted the options SPIF_UPDATEINIFILE and SPIF_SENDWININICHANGE.  These are now being used as they were suggested in the Coding4Fun MSDN article.

A: The JNA java library allows you to easily call Win32 API calls.  In particular, to change the desktop background, you need to call the SystemParametersInfo  function.
Take a look at this article for an introduction to JNA: http://today.java.net/article/2009/11/11/simplify-native-code-access-jna

A: Here is a Pure Java implementation which uses Project Panama to make the native callbacks into Windows USER32.DLL. Note that the API is incubating so has changed between JDK16, 17 and later builds. These samples use the versions of Panama that are in the current JDK16/17 release, some changes may be required if you switch to the latest Panama Early Access builds.
import java.lang.invoke.*;
import java.nio.file.Path;
import jdk.incubator.foreign.*;

/**
 %JDK16%\bin\java -Dforeign.restricted=permit --add-modules jdk.incubator.foreign SetWallpaper.java A.JPG
 */
public class SetWallpaper {
    static final int SPI_SETDESKWALLPAPER  = 0x0014;
    static final int SPIF_UPDATEINIFILE    = 0x01;
    static final int SPIF_SENDCHANGE       = 0x02;
    public static void main(String[] args) throws Throwable {
        LibraryLookup user32 = LibraryLookup.ofLibrary("user32");
        MethodHandle spi = CLinker.getInstance().downcallHandle(user32.lookup("SystemParametersInfoA").get()
            // BOOL SystemParametersInfoA         (UINT uiAction,  UINT uiParam,   PVOID pvParam,       UINT fWinIni);
            , MethodType.methodType(int.class,     int.class,      int.class,      MemoryAddress.class, int.class)
            , FunctionDescriptor.of(CLinker.C_LONG,CLinker.C_LONG, CLinker.C_LONG, CLinker.C_POINTER,   CLinker.C_LONG));

        Path path = Path.of(args[0]).toRealPath();

        try (NativeScope scope = NativeScope.unboundedScope()) {
            MemorySegment img = CLinker.toCString(path.toString(), scope);
            int status = (int)spi.invokeExact(SPI_SETDESKWALLPAPER, 0, img.address(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
            System.out.println("Changed wallpaper to "+path+" rc="+status+(status == 0 ? " *** ERROR ***": " OK"));
        }
    }
}

Small changes needed for JDK17:
/**
%JAVA_HOME%\bin\java --enable-native-access=ALL-UNNAMED --add-modules jdk.incubator.foreign SetWallpaper.java A.JPG
*/
public static void main(String[] args) throws Throwable {
    System.loadLibrary("user32");
    // BOOL SystemParametersInfoA(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni);
    MemoryAddress symbol = SymbolLookup.loaderLookup().lookup("SystemParametersInfoW").get();
    MethodHandle SystemParametersInfoW = CLinker.getInstance().downcallHandle(symbol
        , MethodType.methodType(int.class,     int.class,      int.class,      MemoryAddress.class, int.class)
        , FunctionDescriptor.of(CLinker.C_LONG,CLinker.C_LONG, CLinker.C_LONG, CLinker.C_POINTER,   CLinker.C_LONG));

    Path path = Path.of(args[0]).toRealPath();

    try(ResourceScope scope = ResourceScope.newConfinedScope()) {
        SegmentAllocator allocator = SegmentAllocator.arenaAllocator(scope);
        // toCString as WIDE string
        Addressable wide = allocator.allocateArray(CLinker.C_CHAR, (path+"\0").getBytes(StandardCharsets.UTF_16LE));
        int status = (int)SystemParametersInfoW.invokeExact(SPI_SETDESKWALLPAPER, 0, wide.address(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
        System.out.println("Changed wallpaper to "+path+" rc="+status+(status == 0 ? " *** ERROR ***": " OK"));
    }
}

A: Expanding on the answer from @DuncG, here's an updated solution which uses Project Panama from JDK 18.
import jdk.incubator.foreign.*;

import java.lang.invoke.MethodHandle;
import java.nio.file.Path;

import static jdk.incubator.foreign.ValueLayout.*;

public class WindowsOperatingSystem {
    private static final int SPI_SETDESKWALLPAPER  = 0x0014;
    private static final int SPIF_UPDATEINIFILE    = 0x01;
    private static final int SPIF_SENDCHANGE       = 0x02;

    private static final MethodHandle systemParametersInfoAFunction;

    static {
        System.loadLibrary("user32");
        // BOOL SystemParametersInfoA(UINT uiAction, UINT uiParam, PVOID pvParam, UINT fWinIni);
        systemParametersInfoAFunction = CLinker.systemCLinker().downcallHandle(
                SymbolLookup.loaderLookup().lookup("SystemParametersInfoA").get(),
                FunctionDescriptor.of(JAVA_BOOLEAN, JAVA_INT, JAVA_INT, ADDRESS, JAVA_INT)
        );
    }

    public static void setWallpaper(Path file) {
        try (ResourceScope scope = ResourceScope.newConfinedScope()) {
            SegmentAllocator allocator = SegmentAllocator.nativeAllocator(scope);
            Addressable nativeFilePath = allocator.allocateUtf8String(file.toString());
            var result = (boolean)systemParametersInfoAFunction.invokeExact(
                    SPI_SETDESKWALLPAPER,
                    0,
                    nativeFilePath,
                    SPIF_UPDATEINIFILE | SPIF_SENDCHANGE
            );
            if (!result) {
                throw new IllegalStateException();
            }
        } catch (Error | RuntimeException t) {
            throw t;
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }
}


text:
Q: SQL Select id and output of exists in single SQL query I have 2 tables with primary key(A.Id), foreign key(EquipmentKey) reference between 2 tables A and B. Now I want result like A.Id, Whether it exists in B or not.
This is the query I am trying. Can it be achieved easily in single query?
Below query doesnt work. I get error T.Id can not be found.
select
    A.Id,
    ExistsInB = CASE
                    WHEN EXISTS(SELECT 1 FROM B WHERE EquipmentKey = A.Id) THEN 1
                    ELSE 0
                END
from A

A: SELECT A.Id, (B.EquipmentKey IS NOT NULL) AS ExistsInB
FROM A LEFT OUTER JOIN B ON (A.Id = B.EquipmentKey)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to access the phone call state in flutter? I want to know whether the call is disconnected or continued, and based on that I want to perform an action in the application.
Can anyone tell me how to check if the phone call is disconnected or not?
along with that I also want to know if it is received by the end-user or not
any kind of help will be appreciated.
thank you

A: I think you should take the steps I list below:

*

*One line of code can make a phone call

*Wait for any in-flight phone

*Calls Watch everything that happens on the phone during a single Call or all
calls.

*Keep track of the length of calls, errors, and
call drops.

Now let's start
Install the plugin
Flutter_phone_state: ^0.5.8
Initiate a call
It is best to make calls from your app whenever you can. This is the best way to find where the call came from.
final phoneCall = FlutterPhoneState.makePhoneCall("480-555-1234");
The truth about a call comes from a PhoneCall object.
showCallInfo(PhoneCall phoneCall) {
    print(phoneCall.status);
    print(phoneCall.isComplete);
    print(phoneCall.events);
}

PhoneCall.events can be read as a stream, and when the call is over, the plugin will gracefully close the stream. The plugin keeps an eye on all calls in progress and will eventually force any call to time out.
watchEvents(PhoneCall phoneCall) {
  phoneCall.eventStream.forEach((PhoneCallEvent event) {
    print("Event $event");
  });
  print("Call is complete");
}

You could also just wait until the call is over.
waitForCompletion(PhoneCall phoneCall) async {
  await phoneCall.done;
  print("Call is completed");
}

Accessing in-flight calls
In-flight calls can be accessed like this:
final `activeCalls = FutterPhoneState.activeCalls;`

Note that activeCalls is a copy of the calls at the time you called it. This copy cannot be changed. It won't be updated on its own.
Watching all events
You can watch all the events instead of just focusing on one call. We recommend using "FlutterPhoneState.phoneCallEventStream" because it includes our own tracking logic, call timeouts, failures, etc.
watchAllPhoneCallEvents() {
  FlutterPhoneState.phoneCallEvents.forEach((PhoneCallEvent event) {
    final phoneCall = event.call;
    print("Got an event $event");
  });
  print("That loop ^^ won't end");
}

You can sign up to get the raw events if you want to. Keep in mind that there are only so many of these events.
watchAllRawEvents() {
  FlutterPhoneState.rawPhoneEvent.forEach((RawPhoneEvent event) {
    final phoneCall = event.call;
    print("Got an event $event");
  });
  print("That loop ^^ won't end");


text:
Q: RStudio and R 2.14.0, installing sp and rgdal In the process of installing and getting the packages sp and rgdal running in my RStudio Version 0.98.501 on my Mac OS X 10_7_5, I get this error message:
Error: This is R 2.11.1, package 'rgdal' needs >= 2.14.0

However if I look at on the RStudio website the version 0.98.501 is the latest and should be up to date with R 2.14. Do I need to de-install any old versions? How would I do that?


text:
Q: MATCH/DELETE requests stopped working after adding Spring Security dependency(some time after) In Spring application (java) all controllers worked fine (take \ add \ modify \ delete, i.e. GET \ POST \ PATCH \ DELETE requests), however after adding the Spring Security dependency at some point the DELETE and PATCH methods stopped working ... In this case, the GET \ POST methods work properly for all controllers. When trying to access the PATCH \ DELETE methods in the console, it gives the following error
WARN 15516 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
At the same time, on the web link for this (any PATCH/DELETE) request, it gives the following result
Web view of error
If it is important I can send the code of the rewritten configure method (HttpSecurity http). Also, perhaps importantly, controllers are implemented using @Controller annotations and not @RestController. Can you please tell me what could be the problem?

A: I found what was the problem, the thing is that i was running app with @SpringBootApplication annotation like this
@SpringBootApplication
public class RunningApplication {
    public static void main(String[] args) {
        SpringApplication.run(RunningApplication.class, args);
    }
}

So basically, before I was running app with Tomcat server, and got other config with missing thing, that was hiddenHttpMethodFilter , so now i've added this bean (to my running app class - RunningApplication), and after that all methods worked properly
@Bean
    HiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new HiddenHttpMethodFilter();
    }


text:
Q: Python For Loop giving RANDOM errors on each run, IndexError or ValueError I'm new to python. I put together this code to pull daily Options data from yfinance for multiple stock symbols for all possible expiration dates for each stock symbol (each symbol can have different expirations dates). So I created two For Loops, first loop picks the stock, second loop picks the expiration date for that selected symbol. The code looks like this
pip install yfinance --upgrade --no-cache-dir
import yfinance as yf
import pandas as pd

# List of tickers
tickers = ["AAPL","ABBV","ABT","ACN","ADBE","ADI","ADP","AEP","AGG","ALL","AMAT","AMD","AMGN","AMT","AMZN","APD","ARKF","ARKG","ARKK","ARKQ","ARKW","ARKX","XOP"]

# Loop to call put and call values for all expirations for all tickers in the list

put_call_combined = []

for X in tickers:
    ticker = X
    DateArray = yf.Ticker(ticker).options
    for Y in DateArray:
        strikeChoice = Y
        opt = yf.Ticker(ticker).option_chain(strikeChoice)
        calls = opt.calls
        puts = opt.puts
        put_call_combined.append([calls.lastTradeDate.max().date(),ticker,strikeChoice,puts['openInterest'].sum(),puts['volume'].sum(),calls['openInterest'].sum(),calls['volume'].sum()])
        ArrayStore = None

#Final Output
df = pd.DataFrame(data=put_call_combined, columns=["dataset_day","ticker", "expiry","putOI","putVolume","callOI","callVolume"])
df

My problem is; on every run I'm getting random errors, when I look at the final DF, I can see the loop was broken at different symbols. Sometimes it fails due to an IndexError
IndexError                                Traceback (most recent call last)
<ipython-input-26-de7016fd3a37> in <module>
      6
      7     ticker = X
----> 8     DateArray = yf.Ticker(ticker).options
      9
     10     for X in DateArray:

~\anaconda3\lib\site-packages\yfinance\ticker.py in options(self)
    193     def options(self):
    194         if not self._expirations:
--> 195             self._download_options()
    196         return tuple(self._expirations.keys())

~\anaconda3\lib\site-packages\yfinance\ticker.py in _download_options(self, date, proxy)
     59                 self._expirations[_datetime.datetime.utcfromtimestamp(
     60                     exp).strftime('%Y-%m-%d')] = exp
---> 61             return r['optionChain']['result'][0]['options'][0]
     62         return {}
     63

IndexError: list index out of range

And sometime it's a ValueError;
ValueError                                Traceback (most recent call last)
<ipython-input-25-0a07edf80d9a> in <module>
      9     for x in DateArray:
     10         strikeChoice = x
---> 11         opt = yf.Ticker(ticker).option_chain(strikeChoice)
     12         calls = opt.calls
     13         puts = opt.puts

~\anaconda3\lib\site-packages\yfinance\ticker.py in option_chain(self, date, proxy, tz)
     92                 self._download_options()
     93             if date not in self._expirations:
---> 94                 raise ValueError(
     95                     "Expiration `%s` cannot be found. "
     96                     "Available expiration are: [%s]" % (

ValueError: Expiration `2021-10-15` cannot be found. Available expiration are: [2021-09-17, 2022-01-21, 2023-01-20]

If I reduce the number of symbols, for instance 4 or 5 symbols at a time, I can get the output for all of these symbols, but when the list becomes too many, then the errors start kicking in RANDOMLY. Anyone has any idea why this might be happening? Am I pushing the limits of Yahoo Finance API?
Thanks
MT

A: I'm getting a similar issue when I try to download a large number (100 or more) of historical stock prices using yf.download. I thought I might try using a for loop with yf.Ticker to get the prices one at a time, and put a try-except block inside the for loop to deal with exceptions. Hopefully that will at least allow the for loop to complete and I'll get the rest of the data.


text:
Q: Count occurrence of words in cell in Excel I am using Microsoft Excel 2013.
I have a entire sentence in one of the cell in my Excel spreadsheet.
I want to count instance of several words in that cell.
Example: Say the sentence "He is not doing very well. His scores have been dropping consistently over the last few months. I spoke to him about his scores. I have also recommended several actions." exists in cell A2.
I want to count the instances of words "he","his","I","him" in the sentence.
So the cell B2 would have a count of 6.
How do I do this?

A: Per XOR LX's suggestion of replacing all punctuation marks, the formula in cell B2 would look like this:
=SUMPRODUCT((LEN(" "&A2&" ")-LEN(SUBSTITUTE(" "&LOWER(A2)&" "," "&{"he","his","i","him"}&" ","")))/LEN(" "&{"he","his","i","him"}&" "))


text:
Q: How is the author's application of the law of total expectation consistent with the definition? I have the following solution:

Let $$Y_j = \begin{cases} 1, & \text{if $j$th toss is a head} \\ 0, & \text{if $j$th toss is a tail} \end{cases}$$
Let $X$ denote the waiting time to $HH$. First, we note that, if any toss is a tail, then the experiment regenerates. In particular, if $Y_1 = 0$, then the experiment regenerates. Therefore, we have that
$$E[X \vert Y_1 = 0] = E[X] + 1.$$
On the other hand, for the case where the first toss is a head, the law of total expectation -- with extra conditioning on $Y_1 = 1$ -- gives us that
$$\begin{align} E[X \vert Y_1 = 1] &= \sum_{y = 0}^1 E[X \vert Y_2 = y, Y_1 = 1] P(Y_2 = y \vert Y_1 = 1) \\ &= E[X \vert Y_2 = 0, Y_1 = 1] P(Y_2 = 0) + E[X \vert Y_2 = 1, Y_1 = 1] P(Y_2 = 1) \end{align}$$

Wikipedia gives the law of total expectation as follows:

If ${\displaystyle {\left\{A_{i}\right\}}_{i}}$ is a finite or countable partition of the sample space, then
$${\displaystyle \operatorname {E} (X)=\sum _{i}{\operatorname {E} (X\mid A_{i})\operatorname {P} (A_{i})}.}$$

How is the author's application of the law of total expectation consistent with the definition?
I would greatly appreciate it if people would please take the time to explain this.

A: To answer "How is the author's application of the law of total expectation consistent with the definition?"
I think the Tower Property can explain it better. Tower property:
For sub-σ-algebras $\mathcal H_1\subset \mathcal H_2\subset \mathcal F$ we have $$ E(E(X\mid \mathcal H_2) \mid \mathcal H_1)= E(E(X\mid \mathcal H_1)\mid \mathcal H_2)=E(X\mid \mathcal H_1)$$

Define $\mathcal H_1=\sigma(Y_1)$ and $\mathcal H_2=\sigma(Y_1,Y_2)$ so $\mathcal H_1 \subset \mathcal H_2\subset \mathcal F$
$$\begin{align} \mathbb E[X \vert Y_1 ] &\overset{\text{Tower property}}{=} \mathbb E\left( \mathbb E[X \vert Y_1 ] \mid Y_1,Y_2\right)
\\ &\overset{\text{Tower property}}{=} \mathbb E\left( E[X \vert Y_1 ,Y_2 ] \mid Y_1\right)
\\ &= \mathbb E\left( g(Y_1 ,Y_2 ) \mid Y_1\right)
\\ &= \sum_{y}  g(Y_1 ,Y_2=y )\mathbb  P(Y_2 = y \vert Y_1 )
\\ &= \sum_{y } \mathbb E[X \vert Y_2 = y, Y_1] \mathbb P(Y_2 = y \vert Y_1 )= \cdots \end{align}$$


text:
Q: Proof that all real numbers have a rational Cauchy sequence? I saw in an article that for every real number, there exists a Cauchy sequence of rational numbers that converges to that real number. This was stated without proof, so I'm guessing it is a well-known theorem in analysis, but I have never seen this proof. So could someone give a proof (preferably with a source) for this fact? It can use other theorems from analysis, as long as they aren't too obscure.

A: Let $\alpha$ be any real number.
Define
$$a_n = \frac{\lfloor n \alpha \rfloor}{n}$$
where $\lfloor , \rfloor $ denotes the floor function.
Then $a_n \in \mathbb Q$. Moreover we have
$$\frac{n \alpha -1}{n} \leq a_n \leq \alpha$$
and hence $a_n \to \alpha$.

A: Based on the context gathered from your question and your comments it is clear that you are concerned about the equivalence of construction of reals as Dedekind cuts of rationals and as equivalence classes of Cauchy sequences of rationals.
We can do this in the following manner. First we show that corresponding to a given Dedekind cut of rationals there exists a Cauchy sequence of rationals. To do so in proper manner it is best to explicitly state the definition of a Dedekind cut of rationals.
A Dedekind cut of rationals is a set $A\subseteq\mathbb{Q} $ with the following properties:

*

*$\emptyset\neq A\neq \mathbb{Q} $.

*If $p\in A$ and $q\in\mathbb{Q} $ with $q<p$ then $q\in A$.

*If $p\in A$ then there exists a $q\in A$ with $p<q$.

The above definition is one provided by Rudin in his Principles of Mathematical Analysis. But the true picture of a Dedekind cut is revealed when one considers not only the set $A$ but also its complement $B=\mathbb{Q} - A$ as done by Dedekind himself.
It is easy to prove that given any positive rational number $\epsilon$ one can find rationals $p, q$ such that $p\in A, q\in B$ such that $0<q-p<\epsilon $. Thus for every positive integer $n$ we can find rationals $a_n, b_n$ such that $a_n\in A, b_n\in B, 0<b_n-a_n<1/n$ and further we can ensure that $b_{n} \geq b_{n+1},a_{n}<a_{n+1}$. Now we can show that $\{a_n\} $ is a Cauchy sequence of rationals. This is how one can find a Cauchy sequence of rationals corresponding to a given Dedekind cut of rationals. Note that the sequence $b_n$ can also be considered here instead of $a_n$.
To do the reverse let us consider a Cauchy sequence of rationals $\{a_n\} $ and we then need to find a Dedekind cut corresponding to it. Consider a rational number $r$. If there is a positive integer $m$ such that $a_n>r$ for all $n\geq m$ then we say that that $r$ is inferior to the sequence $\{a_n\} $. Consider the set $$A=\{p\mid p\in\mathbb {Q}, \exists q\in\mathbb{Q}, q>p, q\text{ is inferior to sequence }\{a_n\} \} $$ Since a Cauchy sequence is bounded it is clear that the set $A$ and its complement $B=\mathbb{Q} - A$ are both non-empty. Also if $p\in A$ then there is some $r\in\mathbb{Q} $ such that $r>p$ and $r$ is inferior to $\{a_n\} $. And if we take a rational $q$ with $q<p$ then $q<r$ and hence $q\in A$. Moreover we also have $(p+r) /2<r$ so that $p<(p+r) /2\in A$. Thus $A$ satisfies all the properties of a Dedekind cut. This is how one finds a Dedekind cut of rationals corresponding to a given Cauchy sequence of rationals.
We still need to show that if $\{b_n\} $ is another Cauchy sequence of rationals which is equivalent to $\{a_n\} $ (ie $a_n-b_n\to 0$) and if we apply the above mentioned procedure to find a Dedekind cut $A'$ corresponding to the sequence $\{b_n\} $ then $A'=A$. This is not difficult to prove and you should try it yourself.

The full equivalence of the construction of reals via Dedekind cuts and via Cauchy sequences of rationals can be done by proving that the correspondence between these approaches described above is an isomorphism which preserves arithmetic as well as order relationship. But carrying out such a proof is boring and lengthy.

A: Note that  the set of real numbers is a complete set that is every Cauchy sequence of real numbers is convergent also every convergent sequence is a Cauchy sequence. Therefore once you have a rational sequence converging to a real number the same sequence is a  rational Cauchy sequence converging to the same real number.

A: One way to define the real numbers is as equivalence classes of Cauchy sequences (see exercise 3.24 in Princples of Mathematical Analysis by Walter Rudin for the details of the (actually, a more general) construction). Under this construction, it is obvious that every real number has such a Cauchy sequence, since every real number literally is a (set of) Cauchy sequence(s). Once you've done this, it is an easy exercise to prove that $\mathbb{R}$ is the only complete ordered field up to isomorphism, so it doesn't matter which construction you use for $\mathbb{R}$, the Cauchy construction guarantees it.

A: Let $x \in \mathbb R$.
Let $q_i \in \mathbb Q$ so that $x - \frac 1i < q_i < x$.
Claim 1: Such a sequence $\{q_i\}$ exists (because the rationals are dense in the reals)
Claim 2: $q_i \to x$ (by the very definition of limits)
Claim 3: $\{q_i\}$ is cauchy.  (For $n > \frac 2\epsilon; i,j > n$ then $|q_i - x| < \frac 1n < \frac \epsilon 2$ and $|q_i - q_j| < |q_i - x| + |q_j - x| < \epsilon$.)
Basically this is the FUNDAMENTAL principal of the meaning of real numbers.
Real numbers are such that every bounded above sequence has a least upper bound.  That is the fundamental claim of the nature of real numbers.  The means that any sequence in which all the terms get "close together" must have an existent real limit.
A Cauchy sequence is just such a sequence.  To be informal, a Cauchy sequence is a sequence that "ought to" converge although the actual limit point need need be specified (or even be specifiable).
Another way, perhaps without choice is, by the Archmedian principal there exists a unique integer $k_1$ so that $k_1 \le x < k_1 + 1$ and for every integer $n$ there is a unique $k_n$ so that $k_n \le x*n < k_n + 1$ or $\frac {k_n}n \le x < \frac {k_n}n+ \frac 1n$.  Let $q_n = \frac {k_n}n$.  That is a cauchy sequence converging to $x$.
In fact, if $k_n$ is the unique integer so that $k_n \le x*10^n \le k_n +1$ then the sequence $q_n = \frac {k_n}{10^n}$ is nothing more or less then the sequence of $n$th place decimal expansions.  (If $x = \pi$ then $\{q_n\} = \{3, \frac {31}{10}, \frac {314}{100}, \frac {3141}{1000}, ....\}$ etc.)
It is precisely because all reals have cauchy sequences of rationals converging to them, that the concept of decimal numbers even works.


text:
Q: Angular change in select causing strange behavior in $scope variables Here's the code in my view...
<label for="restaurant-type-select" class="control-label">
    Type
</label>
<select class="form-control" id="restaurant-type-select" ng-model="restaurant.type" ng-change="restaurantTypeChanged()">
    <option value="Franchise">Franchise</option>
    <option value="Corporate">Corporate</option>
    <option value="Individual">Individual</option>
</select>
<div ng-if="restaurant.type == 'Franchise' || restaurant.type == 'Corporate'">
    <label for="restaurant-group-select" class="control-label">
        Restaurant Group
    </label>
    <select class="form-control" id="restaurant-group-select" ng-model="restaurant.restaurant_group" ng-options="restaurant_group.name for restaurant_group in restaurant_groups.items track by restaurant_group.id">
    </select>
</div>

Here's the relevant controller code...
$scope.restaurantTypeChanged = function() {
    if ($scope.restaurant.type == "Individual") {
        $scope.restaurant.restaurant_group = {};
    }
    console.log($scope.restaurant.restaurant_group);
};

The purpose of this code is pretty simple.  If the restaurant.type is "Individual" there should be no restaurant_group set.  Otherwise, the restaurant_group should be visible and setable.  The problem is that the restaurant_group doesn't seem to stay set.
For example... My starting conditions are restaurant.type = "Corporate" and the restaurant.restaurant_group = { "id": 1, "name": "Something" }.  both select boxes show this correctly.  When I select "Individual" for the restaurant type, the restaurant group select box disappears and the console logs...

{}

This is what I expect.  However, when I change the restaurant type back to "Corporate" the restaurant group select box reappears with the "Something" option already selected.  The console log immediately displays...

{"id": 1, "name": "Something"}

This is not what I would expect.  I would expect the restaurant group to remain an empty object until I set it again with the restaurant group select box.  I'm obviously missing something that is going on here.

A: I expect this is happening because restaurant.restaurant_group is bound to the restaurant-group-select inside your div with ng-if="restaurant.type == 'Franchise' || restaurant.type == 'Corporate'".
So when you select a new restaurant type, the ng-if is resolving to true and restaurant.restaurant_group is picking up the default value from restaurant-group-select (usually the top one in the list).

A: Can you share Plnkr for this?
Its working for me. Please check.
Plunkrhttp://plnkr.co/edit/GUAJHc6n324zNdTTkbqL?p=preview

A: I think the problem is due to ng-if..Try using ng-show in place ng-if

A: Thanks guys.  The problem ended up being something besides my Angular code. We're using REST services on the backend.  The Angular code is changing the restaurant_group to an empty object.  Then it is updating the data and refreshing. I expected the backend to remove the restaurant_group if it was set to null or an empty object.  Instead it is simply ignoring that property.  So, on refresh the backend is repopulating the scope data.
Sorry if I wasted your time looking at this. Turns out that the Angular side of things is working just like it should.


text:
Q: Does the Medialink Wireless-N AP support transparent LAN bridging? I would like to set up my new Medialink Wireless-N Router as a "transparent bridge" to my LAN such that wireless clients appear to be on the same network as the wired.
Does this AP support such a configuration, and if so how do I enable it?

A: Yes, it always bridges between its LAN ports and wireless. So turn its DHCP server off and plug one of its LAN ports into your existing Ethernet LAN (e.g. one of the LAN ports of your upstream router), and it'll do what you need.
I RTFM'd for you and the User Manual tells you how to do this step by step under the heading "Router to router configuration".


text:
Q: How to grab value using XDocument I have this xml from which I am trying to grab the value in the node <ErrorCode> after investigating, i found it easier to use XDocument because it cleans any unwanted \r\n that the response from an api was giving me.. but now I am not sure how to retrieve that value using XDocument
<PlatformResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://platform.intuit.com/api/v1">
  <ErrorMessage>OAuth Token rejected</ErrorMessage>
  <ErrorCode>270</ErrorCode>
  <ServerTime>2012-06-19T03:53:34.4558857Z</ServerTime>
</PlatformResponse>

I want to be able to take advantage of this call to get the value
 XDocument xmlResponse = XDocument.Parse(response);

I can't use XmlDocument because it does not clean the XML as it is doing it XDocument
Thank you

A: Since you have defined the Namespace, try the following code:
    XDocument xmlResponse = XDocument.Load("yourfile.xml");
    //Or you can use XDocument xmlResponse = XDocument.Parse(response)
    XNamespace ns= "http://platform.intuit.com/api/v1";
    var test = xmlResponse.Descendants(ns+ "ErrorCode").FirstOrDefault().Value;

Or if you don't want to use Namespace then:
    var test3 = xmlResponse.Descendants()
                .Where(a => a.Name.LocalName == "ErrorCode")
                .FirstOrDefault().Value;

A: you can use xpath structure to get the value somethink like this
string errorcode= xmlResponse.SelectSingleNode("PlatformResponse/ErrorCode").InnerText

or this
string result = xmlResponse.Descendants("ErrorCode").Single().Value;

A: XDocument doc = XDocument.Load("YouXMLPath");

var query = from d in doc.Root.Descendants()
            where d.Name.LocalName == "ErrorCode"
            select d.Value;


text:
Q: Is there a way to chain navigation in React Navigation V5? Suppose I have screens A, B, C. Is it possible to write code in screen A to navigate from A to B then immediately to C?

A: use dispatch with Custom action creators
import { CommonActions } from '@react-navigation/native';

 const goToC = () => {
    navigation.dispatch((state) => {
      //update navigation state as you want.
      const routes = [
        //current state
        ...state.routes,
        //add 2 new route to state.
        { name: 'b', params: {id : 100} }, //you can also add params
        {name: 'c' }
      ];

      return CommonActions.reset({
        ...state,
        routes,
        index: routes.length - 1,
      });
    });
  }

full code try snack here.
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { CommonActions } from '@react-navigation/native';

const containerStyle = { flex: 1, alignItems: 'center', justifyContent: 'center' };

function ScreenA({ navigation }) {

  const goToC = () => {
    navigation.dispatch((state) => {
      const routes = [
        ...state.routes,
        { name: 'b', params: {id : 100} },
        {name: 'c' }
      ];

      return CommonActions.reset({
        ...state,
        routes,
        index: routes.length - 1,
      });
    });
  }

  return (
    <View style={containerStyle}>
      <Text>ScreenA</Text>
      <Button
        onPress={goToC}
        title="Go to C"
      />
    </View>
  );
}

function ScreenB({ navigation, route }) {
  return  (
    <View style={containerStyle}>
        <Text>{JSON.stringify(route.params)}</Text>
        <Text>ScreenB</Text>
    </View>
  )
}

function ScreenC({ navigation }) {
  return  <View style={containerStyle}><Text>ScreenC</Text></View>
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="a" component={ScreenA} />
        <Stack.Screen name="b" component={ScreenB} />
        <Stack.Screen name="c" component={ScreenC} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

the result


text:
Q: Cannot initialize the data source object of OLE DB provider Getting the following error in SQL Server 2008 when trying to select data from an Excel (xls) file:
Msg 7303, Level 16, State 1, Line 43
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server

The SQL is as follows:
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;HDR=YES;Database=c:\\Temp\\Book1.xls;', 'SELECT * FROM [Sheet1$]')

Steps taken:

*

*Installed the Access Database Engine. 'Microsoft.ACE.OLEDB.12.0' does show up in Server Objects > Linked Servers > Providers

*Made sure 'Dynamic parameters' and 'Allow inprocess' is selected

*Made sure the Excel file was closed

*Made sure 'ad hoc distributed queries' was enabled (1)

*Made sure the user running the SQL service has permissions to the c:\temp\ folder

My theory:
Running on my dev box works fine as my SQL service is running as 'LocalSystem'. The target server I'm trying to get running has a specific network user it's running on. This cannot be changed.
From what I know/have read about OPENROWSET and OPENQUERY (also tried with linked server) it needs to create a temporary file in C:\Windows\ServiceProfiles\\AppData\Local\Temp. I've manually tried to create a folder structure for this user in service profiles but that doesn't work either.
:: UPDATE ::
In the end I abandoned this idea and instead created an package in integration services. As this process needs to run as part of a job this works well enough for my needs.
If anyone is interested. Creating the package in IS is as easy as following the import data wizard and at the end you choose 'Create Integrated Services Package'. This can then be called from your job.
Ta


text:
Q: Ubuntu 18.04 Touchpad randomly jumps I have a Dell Inspiron 15 (3558). Ever since I upgraded to Ubuntu, there have been problems where the touch-pad randomly jumps when using it. For example I could be scrolling up and the cursor would instantly jump to the top at the slightest touch. I lowered sensitivity in settings but that doesn't seem to help. I read a solution online where the touch-pad sensitivity seems to be fixed but the tap-and-click function doesn't work. I don't want to sacrifice the tap-click function for sensitivity. Here are the results of xinput:

A: I observe the behavior persists only when my laptop is plugged in. Found that one when I was looking through this link.
One temporary hack is by placing your hand on the keyboard or any
metal part of your laptop to ground it.


text:
Q: Is there any event when an application enter into full screen mode and quit full screen mode in Windows? My app should know when does an application enter into full screen mode and quit full screen mode? I have found this question Detecting full screen mode in Windows. But the solutions need my app to detect the state in periods. I want to know is there any event to notify my app? Thank you!

A: Yes, there is an event called "fullscreenchange", this will trigger when you toggle between full screen mode (enter/exit full screen mode).


text:
Q: Automatically mirror a git repository One of the side-effects of using an external Subversion repository was getting automatic offsite backups on every commit.
I'd like to achieve the same using Git.
i.e. every commit to my local repository automatically commits to an external one so the two repositories are always in sync.
I imagine that a post-commit hook would be the way to go. Does anyone have any specific examples of this?

A: I wrote a post-commit hook for just this purpose. The hook itself is simple; just add a file named post-commit to your .git/hooks/ directory with the following contents:
git push my_remote

The post-commit file should be executable. Also make sure that you add a suitable remote repository with the name my_remote for this this hook to work.
I also made a symlink named post-merge that points to post-commit. This is optional. If you do this you'll auto-sync after merges as well.
UPDATE: If you want to ensure that your server, and your mirror do not get out of sync, and ensure that all branches are also backed up, your post-commit hook can use:
git push my_remote -f --mirror

A: I just wanted to add that I had a similar issue, but in my case I needed every push to a remote repository to automatically mirror to another remote as a backup. My local machine also couldn't directly connect to the mirrored repo, so it had to be pushed from the server-side.
For that, I had to create a post-receive hook on the remote repo (under the hooks/ directory). And then, as Manoj's answer suggested, I simply added the following command to the post-receive file:
git push --mirror my_remote

Hopefully that will help others who, like me, stumbled upon this question from Google.

A: GitBitLabHub allows you automatically mirror repositories between Bitbucket / Gitlab / Github using simple webhooks.
Under the hood it does the following:
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch --prune
git remote set-head origin -d
git branch -a || 'true'
git push --prune dest +refs/remotes/origin/*:refs/heads/* +refs/tags/*:refs/tags/*

All you need is to set up deploy keys and webhooks:

*

*Generate an ssh key for source and destination repositories:

ssh-keygen -t rsa -f ~/.ssh/project_id_rsa

*

*It will generate 2 keys, the PRIVATE key to ~/.ssh/project_id_rsa and the PUBLIC key to ~/.ssh/project_id_rsa.pub.

*The PUBLIC key is used as Deploy Key while the PRIVATE key should be used in SRC_DEPLOY_KEY and DEST_DEPLOY_KEY env variables.

*Add this PUBLIC key as a Deploy Key for the source and destination repositories.
Depending on the platform it's called Deploy Key or Access key.
See how to add Deploy/Access Key to bitbucket, bitbucket access keys,
gitlab, github.

*

*Add the PUBLIC key to the source repo with read-only access.

*Add the PUBLIC key to the destination repo with write access.

*Create the webhook in the source repository. Using default settings should be enough.
See how to create a webhook in bitbucket,
gitlab, github.


text:
Q: How to get the clicked link's href with jquery? Does anyone know how can I get the clicked link's href with jquery? I have the link as following:
    Test1.

    Test2.

    Test3.

I wrote a code as following to get the href value from the link I clicked on. But somehow this is always return me the 1st link's href (ID=1) even though I clicked on Test2 or Test3. Does anyone know what is it going on here? and how can I solve this issue?
    $(".testClick").click(function () {
        var value = $(".testClick").attr("href");
        alert(value );
    });

A: Suppose we have three anchor tags like ,
Test1.

Test2.

Test3.

now in script
$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

A: this in your callback function refers to the clicked element.
   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

A: You're looking for $(this).attr("href");

A: $(".testClick").click(function () {
         var value = $(this).attr("href");
         alert(value );
});

When you use $(".className") you are getting the set of all elements that have that class. Then when you call attr it simply returns the value of the first item in the collection.


text:
Q: how to check array contains value I need to check "Drinks" is already exist in this array if it exists I need to replace the new value instead of the "Drinks:Focus"
["Drinks:Focus", "Baked:No", "Addons:320"]

my angular version
@angular-devkit/architect         0.803.19 (cli-only)
@angular-devkit/build-optimizer   0.0.35
@angular-devkit/core              8.3.19 (cli-only)
@angular-devkit/schematics        8.3.19 (cli-only)
@schematics/angular               8.3.19 (cli-only)
@schematics/update                0.803.19 (cli-only)
rxjs                              5.5.6
typescript                        2.4.2
webpack                           3.12.0

A: You can use Array.map() and String.includes() to achieve this, as followings:

let arr = ["Drinks:Focus", "Baked:No", "Addons:320"]

arr = arr.map(item => item.includes('Drinks') ? item.replace('Drinks','Beverage') : item)

console.log(arr)


text:
Q: How to open a pdf file in android emulator from sdcard hi i am new to android development. i manually kept a pdf file in emulator sdcard through ddms, and i also installed "adobe reader" in emulator when i tried to read the pdf file in emulator
with the following code
File file =
new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/iTunes Connect.pdf");
        Uri path = Uri.fromFile(file);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setDataAndType(path,"application/pdf");
        try
        {
            startActivity(intent);
        }
        catch (ActivityNotFoundException e)
        {
            Toast.makeText(xv.this,
                getString(R.string.app_name),
                Toast.LENGTH_SHORT).show();
        }

i am getting the file path is not valid error.
can any one help me in this.

A: use %20(for white space) in between iTunes and 20Connect.pdf.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/iTunes%20Connect.pdf");

I think this will solve your problem

A: try out this path
File file=new File("/sdcard/iTunes Connect.pdf");

I think this will work for u

A: I think you should not use hard coded file paths.
The framework will give you the base path of the area you want to save files to.
For SD card you should, use Environment.getExternalStorageDirectory()
local files you should, use Context.getFilesDir() (or Context.openFileOutput(String name, int mode), etc)
local cache you should, use Context.getCacheDir()
For emulator you can try File file=new File("mnt/sdcard/iTunes Connect.pdf");

A: I think that your emulator have  not adob reader install please check first it is install or not
 File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
    Intent target = new Intent(Intent.ACTION_VIEW);
    target.setDataAndType(Uri.fromFile(file),"application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    Intent intent = Intent.createChooser(target, "Open File");
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        // Instruct the user to install a PDF reader here, or something
    }   `enter code here`


text:
Q: Linearity and Homogeneity of Re() and Im() In chat, I was informed that $\operatorname{Im}()$ and $\operatorname{Re}()$ are homogeneous functions of degree $1$, as well as linear.
The issue I'm having is moving imaginary constants in and out of these functions.  For example, $3i\operatorname{Im}(e^{ti}) = 3i\sin(t)$, while $\operatorname{Im}(3ie^{ti}) = 3\cos(t)$, but $3i\operatorname{Im}(e^{ti})$ and $\operatorname{Im}(3ie^{ti})$ should be equal by homogeneity and linearity.
Are these functions really homogeneous and linear?  Do such notions work abnormally when scaling by imaginary factors?  Otherwise, what else is going wrong here?

A: There are a few different definitions of "linear".
The functions $\Re$ and $\Im$ are "$\mathbb{R}$-linear"—that is, $\Re{(kx)} = k\Re{(x)}$, and $\Im{(kx)} = k\Im{(x)}$, for any $k \in \mathbb{R}$.
However, they are not "$\mathbb{C}$-linear"—that is, those equations don't necessarily hold for $k \in \mathbb{C}$.
Notably, these definitions don't require $x$ and $k$ to belong to the same space. This part of linearity is all about $k$, the factor that you can "pull out", and what sort of thing $x$ is doesn't matter. In particular, linearity is often used in vector spaces, where $x$ is a vector, but $k$ is a scalar. And if not otherwise specified, scalars are generally assumed to be reals.
(For the sake of completeness, as you probably already know, linearity also requires $\Re{(x+y)} = \Re{(x)} + \Re{(y)}$. But that doesn't have anything to do with scalars and isn't affected by what scalar field you choose.)


text:
Q: Не могу открыть ссылку в PHP Господа, доброго дня!
У меня есть ссылка поста в Телеграм:
https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg)Dratuti_!

Но я никак не могу открыть ии из ПХП автоматом.
Ни так:
fopen( "https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg)Dratuti_!" );

Ни так:
header( "Location: https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg)Dratuti_!" );

Ни так:
$homepage = file_get_contents('https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg)Dratuti_!');
echo $homepage;

Подскажите, пожалуйста, в чем проблема ? Всю голову сломал.

A: А ссылка точно верная, https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg)Dratuti_! Сервер ответ код ошибки 400 Bad Request. Если обрабатывать надо еще ошибки то лучше использовать curl.
А если изменить ссылку на https://api.telegram.org/bot386180823:AAE2ITnRmCWRYRuT3cMGO7MZ7zE2hieGQW8/sendMessage?chat_id=@rech_append&parse_mode=Markdown&text=[%7F](https://rechtsanwalt-gmbh.ru/images/logo_uae.jpg Я получаю статус 200
Дока по curl http://php.net/manual/ru/ref.curl.php


text:
Q: Unable to get equal spaced margins on a webpage I have three boxes/containers on a single row of my webpage.
The first box, the blue box is 2px away from the browser edge on the left, while the last box, the purple box is 2px when I inspect element.
image of boxes
However it does not look like this on the web page and looks uneven:
http://jamesbsite-com.stackstaging.com/
I have read all about the box-model but I am still unable to get equal spacing even though I have set a 2px margin on both the left and right.
Please advise as to what is causing this?
The .call-outs-container is the parent container and the .call-out is the child
and they are being applied to these divs:

#

amendment
complete code below

#

<!doctype html>

        <title>James' page!</title>

        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

Feature1

 hello

Feature2

Nanking

new tab

Feature3

            I am interested in history.

James's page!

A few facts about me

I like web desigm.

A:

div{
text-align:center;}
<!DOCTYPE html>

Welcome Page

Welcome Page2

A: I would recommend using flexbox in this situation. It will make controlling things much easier. No need for float.

*

*First, you need to add display: flex to .call-outs-container.

*Next, specify that the items will fill the axis evenly by adding flex: 1 1 0 to .call-out

.call-outs-container {
  display: flex;
}

.call-out {
  padding: 5px;
  margin-right: 2px;
  flex: 1 1 0;
  /* margin-left: 2px;
  margin-top: 40px;
  margin-bottom: -5px;
  width: 30%;
  float: left; */
}

.call-out:nth-child(1) {
  background-color: #c0dbe2;
}

.call-out:nth-child(2) {
  background-color: #cdf1c3;
}

.call-out:nth-child(3) {
  background-color: #ccb9da;
}

Feature1

 hello

Nanking

    new tab

Feature3

    I am interested in history.


text:
Q: Validation rules using value from another control I'm trying to do something that I previously assumed would be quite easy: use the value from one control in the validation rule of another. My application has a variety of parameters that the user can enter, the specific parameters in question here define the start and end points of a range, and the user sets the values through a textbox.
The two controls in question are the start and end textboxes, and the following conditions should be checked in validation:

*

*Start value must be greater than or equal to some arbitrary value

*End value must be less than or equal to some arbitrary value

*Start value must be less than or equal to end value

The first two conditions I have already accomplished. The third is far more difficult to implement, because I cannot access the end textbox's value from the validator. Even if I could, there are five different ranges (each with their own start and end textbox) I'm trying to validate, and there must be some solution more elegant than creating a validation rule for each one.
Here is the relevant XAML code:
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:validators="clr-namespace:CustomValidators"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBox Name="textboxStart" Grid.Row="0">
        <TextBox.Text>
            <Binding Path="Start" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <validators:MeasurementRangeRule Min="1513" Max="1583"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

    <TextBox Name="textboxEnd" Grid.Row="1">
        <TextBox.Text>
            <Binding Path="End" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <validators:MeasurementRangeRule Min="1513" Max="1583"/>
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>
</Grid>

And here is the relevant C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Globalization;

namespace WpfApplication1 {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow () {
            InitializeComponent();
        }

        private decimal _start;
        private decimal _end;
        public event PropertyChangedEventHandler PropertyChanged;

        public decimal Start {
            get { return _start; }
            set {
                _start = value;
                RaisePropertyChanged();
            }
        }

        public decimal End {
            get { return _end; }
            set {
                _end = value;
                RaisePropertyChanged();
            }
        }

        private void RaisePropertyChanged ([CallerMemberName] string propertyName = "") {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

namespace CustomValidators {

    public class MeasurementRangeRule : ValidationRule {
        private decimal _min;
        private decimal _max;

        public decimal Min {
            get { return _min; }
            set { _min = value; }
        }

        public decimal Max {
            get { return _max; }
            set { _max = value; }
        }

        public override ValidationResult Validate (object value, CultureInfo cultureInfo) {
            decimal measurementParameter = 0;

            try {
                if (((string) value).Length > 0)
                    measurementParameter = Decimal.Parse((String) value);
            } catch (Exception e) {
                return new ValidationResult(false, "Illegal characters or " + e.Message);
            }

            if ((measurementParameter < Min) || (measurementParameter > Max)) {
                return new ValidationResult(false,
                  "Out of range. Enter a parameter in the range: " + Min + " - " + Max + ".");
            } else {
                return new ValidationResult(true, null);
            }
        }
    }
}

The question linked here seems to be relevant, but I cannot understand the answers provided.
Thanks...

A: For any who might face this problem, it is far easier to implement IDataErrorInfo to validate errors in general, and to accomplish validation against other controls in some logical grouping. I encapsulated the relevant properties (start, end, min and max) in a single class, bound the controls to those properties, and then used the IDataErrorInfo interface for validation. Relevant code is below...
XAML:

    <TextBox Name="textboxStart" Grid.Row="0" Text="{Binding Path=Start, ValidatesOnDataErrors=True}" Margin="5"/>
    <TextBox Name="textboxEnd" Grid.Row="1" Text="{Binding Path=End, ValidatesOnDataErrors=True}" Margin="5"/>
</Grid>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Runtime.CompilerServices;
using System.ComponentModel;

namespace WpfApplication1 {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow () {
            InitializeComponent();

            Parameter testParameter = new Parameter(0, 10);
            testGrid.DataContext = testParameter;
        }
    }

    public class Parameter: INotifyPropertyChanged, IDataErrorInfo {
        private decimal _start, _end, _min, _max;
        public event PropertyChangedEventHandler PropertyChanged;

        public Parameter () { }

        public Parameter (decimal min, decimal max) {
            this.Min = min;
            this.Max = max;
        }

        public decimal Start {
            get { return _start; }
            set {
                _start = value;
                //RaisePropertyChanged for both Start and End, because one may need to be marked as invalid because of the other's current setting.
                //e.g. Start > End, in which case both properties are now invalid according to the established conditions, but only the most recently changed property will be validated
                RaisePropertyChanged();
                RaisePropertyChanged("End");
            }
        }

        public decimal End {
            get { return _end; }
            set {
                _end = value;
                //RaisePropertyChanged for both Start and End, because one may need to be marked as invalid because of the other's current setting.
                //e.g. Start > End, in which case both properties are now invalid according to the established conditions, but only the most recently changed property will be validated
                RaisePropertyChanged();
                RaisePropertyChanged("Start");
            }
        }

        public decimal Min {
            get { return _min; }
            set { _min = value; }
        }

        public decimal Max {
            get { return _max; }
            set { _max = value; }
        }

        private void RaisePropertyChanged ([CallerMemberName] string propertyName = "") {
            if (PropertyChanged != null) {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string Error {
            get { return string.Empty; }
        }

        public string this[string columnName] {
            get {
                string result = string.Empty;

                switch (columnName) {
                    case "Start":
                        if (Start < Min || Start > Max || Start > End) {
                            result = "Out of range. Enter a value in the range: " + Min + " - " + End + ".";
                        }
                        break;
                    case "End":
                        if (End < Min || End > Max || End < Start) {
                            result = "Out of range. Enter a value in the range: " + Start + " - " + Max + ".";
                        }
                        break;
                };

                return result;
            }
        }
    }
}


text:
Q: Is it possible to receive duplicate IDs with Firebase .doc()? As specified in the Firebase documentation, .doc() creates a unique ID.
I create new documents for Firestore the following way (note that session.docId should be equal to the actual document ID and I am using AngularFire syntax):
const id = db.createId();
const session = { docId: id, name: "test" };
this.db.collection("sessions").doc(id).set(session);

Does .doc() guarantee that the above workflow will always work (meaning that id will always be unique)?
Let's assume I have an array full of sessions (e.g. 10000 items) - I iterate over this array and create a session document for each item the way I specified it above. Considering the asynchronous nature of Javascript, I am very sceptical if this might produce a duplicate ID at some point (although very unlikely due to the length etc. of the docId). Or does .doc() "reserve" the ID for a limited amount of time?
I am aware that I could also create a new document via .add() and update the docId afterwards via .set(), but this method would need 2 write operations and would also be way slower.

A: doc() always generates a DocumentReference with random ID immediately on the client app (not asynchronously) that is virtually guaranteed to be unique.  The chance of collision between two IDs is astronomically low.  It's effectively the same thing as calling add(), except it is not actually creating the document at the same time.
Note that doc() doesn't return the string ID directly - it returns a DocumentReference that contains the ID.
See also:

*

*Firestore: Are ids unique in the collection or globally?
If for some reason you do not trust this method of generating IDs, you are free to generate them yourself somehow.  It's just a string.


text:
Q: Updating 'pip' after configuring 'pip' to point to Homebrew's pip3 causes errors After installing Python 3 using Homebrew and putting the Homebrew aliases (e.g. pip -> pip3) on my path
export PATH=/usr/local/opt/python/libexec/bin:$PATH

and then updating pip with
pip3 install -U pip

I get errors whenever I run pip:

pkg_resources.VersionConflict: (pip 19.1 (/usr/local/lib/python3.7/site-packages), Requirement.parse('pip==19.0.3'))

How do I configure my Homebrew Python 3 correctly with pip3 so that updates to pip (and other packages) work when the aliases provided with Homebrew's Python 3 are on my path?


text:
Q: What is the meaning of scrollLeftOffset jqgrid setting? I am using jqGrid in virtual mode (i.e. paging is being done via a scrollbar). Firstly I had a problem that sometimes when scrolling by large distance (for example, from the start to the middle) no requests  to server were sent and no new data appeared in the grid. But when scrolling by small distance requests were sent and data appeared in the grid. I noticed that the problem can be solved by playing with scrollLeftOffset property, but the problem is I don't actually understand how this property works. I would like to know how to caluculate this property properly, knowing total count of records and page size.

A: Basically scrollLeftOffset  controll dynamically the appearance of the scroll dialog information when virtual scrolling is enabled and scrollPopUp is set to true
As from the Guriddo documentation it has the following meaning:

Determines the left offset of the box which appear when virtual scroll
  is enabled and scrollPopUp parameter is set to true. The information
  does appear when we use the mouse to scroll through the pages. The
  value of 0% set the box to appear at upper left corner of the grid.
  See scrollPopUp and scrollTopOffset parameters. Default value : 100%

It is available only in Guriddo jqGrid from version 4.8


text:
Q: Transform rotation to movement direction in 2D space I am trying to rotate my GameObject to be facing in the direction that it is moving. I am not using Rigidbody.Velocity, I am just using transform.position to move the object. Here is my code:
public GameObject player;

void Update ()
{
    Vector3 _origPos = new Vector3(player.transform.position.x,player.transform.position.y, player.transform.position.z);

    if (Input.touchCount > 0)
    {
        // The screen has been touched so store the touch
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) {
            // If the finger is on the screen, move the object smoothly to the touch position
            Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
            transform.position = Vector3.Lerp(transform.position, touchPosition, Time.deltaTime);
            //transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,0), Vector3.up);
            Vector3 moveDirection = gameObject.transform.position - _origPos;

        }
    }
}

Any suggestions on how to implement rotation? I am completely stumped

A: You do it using Trigonometry. You will need 3 points of reference, luckily you already have two of those.
Points needed:

*

*A) Where you are going to move.

*B) Current position at center of mass.

*C) The tip of your object, the front.

Calculate the distance from B to C, call it x. Then calculate the distance from B to A, call it y.
Now use inverse tangent to find the angle.
angle = arctan(y/x)

Then apply it to your object's rotation.
Use world coordinates instead of local.
If you use Mathf for inverse tangent, remember it uses radians.

A: I would assume that you'd use Quaternion.LookRotation to orient your transform.
Something like:
Quaternion rotation = Quaternion.LookRotation(moveDirection);
player.transform.rotation = rotation;

Did a quick test with your code and that works, assuming the player GameObject forward facing direction is Z.

A: This got the desired effect for me in my 2D game.
 transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,transform.position.z), Vector3.up);

I used the objects own position.z instead of the touchPosition.z so that it stayed on it's 2D axis


text:
Q: Retrieve uploaded relativePath file on server side I'm using fileUpload from Primefaces (JSF framework) based on jQuery-File-Upload. I'm trying to make this component supporting drag&drop folder thanks to new File API of Firefox or Chrome. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory#Example So far, I've been able to make it happen thanks to passthrough attribute.
One of the interesting feature is "webkitRelativePath" allowing to know the relative path of an uploaded file.
I'm wondering how I could retrieve this info on server side, so I can create an object with this new info.
Thanks for your help.

A: Well I just read his from fileupload.js:
_initXHRData: function (options) {
     ...
     formData.append(
     ($.type(options.paramName) === 'array' &&
          options.paramName[index]) || paramName,
          file,
          file.uploadName || file.name
     );
     ...
}

(file containing webKitRelativePath)
So I guess the info is already pass to the server, don't you think? Since i'm using Servlet 3.0, I should be able to retrieve it from Part object, finger crossed...


text:
Q: Search for cells missing specified text and then add it I have an Excel spreadsheet with alphanumeric entries in Column A.  All entries should have the same six digit ending but some don't.  I found a macro that adds specific text to the end of each cell in a column but it adds it to ALL cells. The macro I'm trying to adjust is:
Sub AppendToExistingOnRight()
 Dim c As Range
 For Each c In Selection
 If c.Value <> "" Then c.Value = c.Value & "-368341"
 Next
 End Sub

I need an IF statement to say,
if c.Value **does not contain** "-368341" Then c.Value = c.Value & "-368341"

I just don't know what terminology to use.  I know this is probably simple but I've searched for a while and can't find a simple solution.  Please help!

A: Please try:
If c.Value <> "" And InStr(c, "-368341") = 0 Then c.Value = c.Value & "-368341"

instead of your If statement.


text:
Q: c# - programmatically form fill and submit login Using C# and ASP.NET I want to programmatically fill in values for a web form and then 'POST' those values.
I've seen examples of others using webclient and other classes in posts such as:
How do you programmatically fill in a form and 'POST' a web page?
I am looking to carry out similar functionality - where I automatically post data to a form. In my case I am looking to submit data to simulate a login. I have a couple of questions:
1) Using the Post code in this thread, how can you determine if the Post was a success? We cant really presume a 200 response is a success.  It wouldn't necessarily be correct to presume a 302 redirect signifies success either.  Is there any sure fire way to determine we are logged on successfully after the post?
2) Do some sites block requests that do not originate from their own domain?

A: yes some sites block request. but you can check the login with auth cookie. Use HttpWebRequest/HttpWebResponse
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));

byte[] data = Encoding.Default.GetBytes("item1=11111&item2=22222&Item3=33333");
request.Method = "POST";
request.ContentLength = data.Length;

Stream sout = request.GetRequestStream();
sout.Write(data, 0, data.Length);
sout.Flush();
sout.Close();

request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

now check response.Cookies for auth cookie


text:
Q: how do i get only values from var dump array? Is it possible to escape array(1) { [0]=> string(12)} from var_dump($variable) because I want to show only values from var_dump and except array string?
Testing Code
 <?php
 $array = array(
 "foo" => "bar",
 "bar" => "foo",
 100   => -100,
-100  => 100,
 );
 var_dump($array);
 ?>

now results will be like this
array(4) {
["foo"]=>
string(3) "bar"
["bar"]=>
string(3) "foo"
[100]=>
int(-100)
[-100]=>
int(100)
}

But I want to get only bar and foo values except string(3) and array(4)?

A: Right here:
foreach ($array as $key => $value){
    echo $key.'=>'.$value."\n";
}

For each key-value pair, this will echo the items as desired.

A: <?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100
);

print_r($array);

$newArray = array_filter($array, function($v) {
    return (gettype($v) != 'string');
});

print_r($newArray);
?>

Outputs:
Array
(
    [foo] => bar
    [bar] => foo
    [100] => -100
    [-100] => 100
)
Array
(
    [100] => -100
    [-100] => 100
)

$newArray contains all values except strings. (you can change != to == to get only the string values)
After your edit I think you may want this (accessing individual items in an associative array):
echo $array['bar'];
echo $array['foo'];

Outputs:
foo
bar

A: http://php.net/manual/en/function.array-values.php
$array = array(
    "a" => "bar",
    "b" => "foo",
);

var_dump($array);
//bar
//foo

A: Try
<?php
  $array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
  );

  echo '<pre>';
  print_r($array);
  echo '</pre>';
?>

A: You could do:
call_user_func_array('var_dump', $array);

That is using var_dump() on each value of the $array instead of the whole array:
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);

call_user_func_array('var_dump', $array);

echo implode(', ', $array); # for comparison

Output:
string(3) "bar"
string(3) "foo"
int(-100)
int(100)
bar, foo, -100, 100


text:
Q: Fatal error: Call to a member function bind_param() on a non-object in C:\wamp\www\k24Electronics\admin\Supplier\import.php on line 13 Call Stack function add_product( $product_name, $product_brand, $product_type,
                      $product_description,$product_price, $number,
                      $reservefee, $status,$image,$supplier_id )

{
     global $data,$sth;
     $con = new mysqli("localhost","root","","eeee");
     $sth = $con->prepare( "INSERT INTO products
                                (product_name,product_brand,product_type,
                                product_description,product_price,number,reservefee,
                                status,image,supplier_id)
                            VALUES(0,?,?,?,?,?,?,?,?,?,?)" );

     $sth->bind_param('ssssiiisbi', $product_name, $product_brand, $product_type,$product_description,$product_price, $number, $reservefee, $status,$image,$supplier_id);

    $sth->execute();

    $data []= array(
    'product_name' => $product_name,
    'product_brand' => $product_brand,
    'product_type' => $product_type,
    'product_description' => $product_description,
    'product_price' => $product_price,
    'number' => $number,
    'reservefee' => $reservefee,
    'status' => $status,
    'image' => $image,
    'supplier_id' => $supplier_id
    );
}

A: You have an error in $con->prepare, so it has returned false therfore the  bind_param has failed as it is not working on a mysqli_statement object.
Try deleting one of ? from your VALUES clause in the prepare, because you are telling mysql to insert 11 parameters into 10 column names.


text:
Q: Need scalable database solution for very big automated data entry database I've been working on MySQL database in simple web applications for a long time and i now have a project which should maintain about 1,000 up to 10,000 query per minute (it is some logging database system) and a lot of theme are Insert statement.
First thing worried me is i don't think MySQL could handle that much query per second,I know i should buy stronger Server but i don't know if MySQL can be good solution for that.Is there any way to calculate that ability before buying servers?
Second important thing is that the database will grow too fast and it will be use all server resources like hard disk or CPU usage sooner or later and i should have an expanding solution,my question in this part from experienced database admins is :
"Is MySQL suitable for distributing or cluster databases ?"
or
"Is there any easy to use database which support clustering and distributing systems?" (I know MySQL have a cluster version but i don't know if it is appropriate in my project).
Edit:
The project is about logging users(by their RF-ID tags) as they pass throw the antenna range or rf-id readers or Electronic gates and read their permission to enter or leave the area which specified in database for that tag ID, and record there activity in database.The operator should access all these data and be able to manipulate theme.
P.S:
I know there are very professional servers with large capacity of hard disk like SAN or NAS(Network-attached storage),but as it is not national or very big company project i need easy to distribute database to distribute it over normal servers.

A:
"Is MySQL suitable for distributing or cluster databases ?"

While you certainly can do manually sharding, the truth is that the most common MySQL cluster technologies are focused in high availability. NDB Cluster is based mainly on a memory database with lots of throughput, but not necessarily low-latency and large datasets. Galera does not support autosharding (only does read scaling).

"Is there any easy to use database which support clustering and distributing systems?" (I know MySQL have a cluster version but i don't know if it is appropriate in my project).

Other people may give you better advice about other databases, but beware:

*

*Many vendors that criticize the relational and transactional database model sometimes forget to tell you ideas like "eventually consistent" or the possibility of data loss in exchange for better performance (I look at you, NoSQL).

*Can you use a non-distributed database? There are datawarehousing/highly compressed solutions for MySQL (InfiniDB, TokuDB). Even InnoDB has a memcached interface (allowing you even 1M Querys Per Second), which may help in reducing latency for the SQL (although not memory requirements and disk space).

If you tell us more about how you are going to use your logs (statistics, historic data?), we may be able to tell you if a relational database is better for you, or you have to go for other paradigm like column-based databases, or map-reduce, etc. Even then, you should try any product for yourself.


text:
Q: Ajax jQuery redirect like GitHub or Neowin I'm building a website using pure HTML tags. When I use an hyperlink tag like xx I want to redirect to yy. It works, but I want a smooth Ajax redirect like those used in GitHub.
In https://github.com/jquery/plugins.jquery.com, if you click any of those links below plugins.jquery.com, you can see a smooth Ajax redirect.
In Neowin you can see those smooth redirects if you click on any of those page buttons at the bottom.
How can I do a Ajax redirect from this little HTML page using jQuery or something similar?
<!DOCTYPE HTML>

        <meta charset="utf-8">
        <title>Page 1</title>

        Page 2

From the code above I want the a href to be Ajax redirected. I don't care about fancy effects for now, but I want that smoothness.

A: I'd say this is a specialized function especially on GitHub. You will have to do several things:

*

*Check for click event on every link on the page or in a certain container (see http://api.jquery.com/on/)

*Then you do the real AJAX request (see http://api.jquery.com/get/)

*You will get the whole HTML page as a response, which you can filter and only update the parts of the page that actually change - or if you want to replace the whole page, do so (see http://api.jquery.com/html/)

If you can elaborate a bit more on what you tried so far, we can help you much better.


text:
Q: animating constraints out of screen on all devices I'm animating constraints so that view goes out of screen. I set the constraints like this:
        upperLeadingConstraint.constant = -344
        upperTrailingConstraint.constant = 356

upperLeadingConstraint sets the distance to left edge of the screen, upperTrailingConstraint sets the distance to right edge of the screen.
Is this working on universal displays like iphone6+ ? Or should I make the constants a little bigger just to be safe? Thanks for help

A: It depends on how you set these constraints, I mean to what elements. To get the answer on your question you must provide more details or you can calculate the position of the element on other devices by your own.


text:
Q: MariaDB Sort Order COLLATE problem with characters I can not  find information on how to sort by name if it contains special characters.
Database stores Željko Arambašić name as Željko ArambaÅ¡ić (latin1_swedish_ci) and when sorted by name it comes of first because of starting Å in DB, but is of course presented right in UTF-8, just in wrong order place.
I found solution of MySQL that uses COLLATE inside query but my MariaDB is reporting an error on that part.
I can not find anywhere a replacement for that. Please advise.
SELECT * FROM STRANKE ORDER BY str_naziv COLLATE xxx;


text:
Q: randomly remove portions of a sequence to create shorter sequence I am new to programming and would appreciate your help!
I have a file with ~20K sequences with the following format:
>sequence_1
MAADTPGKPSASPMAGAPASASRTPDKPRSAAEHRKSSKPVMEKRRRARINESLAQLKTLILDALRKESSRHSKLEKADILEMTVRHLRSLRRVQVTAALSADPAVLGKYRAGFHECLAEVNRFLAGCEGVPADVRSRLLGHLAACLRQLGPSRRPASLSPAAPAEAPAPEVYAGRPLLPSLGGPFPLLAPPLLPGLTRALPAAPRAGPQGPGGPWRPWLR

>sequence_2
MGWDLTVKMLAGNEFQVSLSSSMSVSELKAQITQKIGVHAFQQRLAVHPSGVALQDRVPLASQGLGPGSTVLLVVDKCDEPLSILVRNNKGRSSTYEVRLTQTVAHLKQQVSGLEGVQDDLFWLTFEGKPLEDQLPLGEYGLKPLSTVFMNLRLRGGGTEPGGRS

I want to create random fragments of these sequences of lengths ~ 50-100 characters. I need to keep the original order intact (so I am not randomizing the characters).
Examples of sequences I could make from >sequence_1 would be:
MAADTPGKPSASPMAGAPASASRTPDKPRSAAEHRKSSKPVMEKRRRARINESLAQLKTLILDALR

or
MTVRHLRSLRRVQVTAALSADPAVLGKYRAGFHECLAEVNRFLAGCEGVPADVRSRLLGHLAACLRQLGPSRRPASLSPAAPAEAPAPEVYAGRPLLPSLGGPFPLLAPPLLPGLTRALPAAPRAGPQGPGGPW

The best analogy I can think of is randomly cutting these sequences into smaller lengths. I'm really unsure how to even go about this, or if it is possible with a script. I'd also appreciate any explanation for responses so I can learn.

A: Use a randomly generated start for a slice:
from random import *

def fifty_slice(sequence):
    i = randrange(0, len(sequence) - 50)
    return sequence[i:i+50]

A: I think you are after implementing a tree data structure in python.
Each line of your 20 K sequences each are parent nodes, and then you can create code that creates children for each of the random sub sequences. Each of the children can also become parents if needed, though I don't think the problem you described requires this.
see https://github.com/caesar0301/treelib


text:
Q: Meaning of Levels of Diagnostic tests in Star Trek Often in Star Trek (almost all variations of it) they talk about "level N" diagnostics.
Is there an actual description of what the diagnostic levels mean?

A: I have not come across one in Star Trek but I run a software consultancy and have a similar protocal for software that my company produces.
Warning - SPECULATION (although it is supported by good engineering princples):
The higher (or lower depending on how you do it) number means that you get more detailed information.  Some people ask why you would not put it on the highest level at all times, the reason you do not and you try to pick your level carefully is that you risk too much information being spewed out and causing you to miss something important or to have to spend a lot of time sifting through information to find what you need.
Also, more output means more time spent producing output - not much of a consideration normally but on a real time machine (like a nuclear power plant monitor) a couple of microseconds writing output and not monitoring the systems can be serious.  There is also the fact that more diagnostics means bigger log files which can cause an issue on some systems where users do not delete them and you end up with, literally, years of log files eating disk space up!

A: According to the tech manuals diagnostic levels indicate how much of a disruption on the system the diagnostic will take, where level 5 is run a self check usually taking a few minutes, all the way to level 1 shut it down, physically check, and carefully reinitialize.  The details of each diagnostic level and time taken change depending on the system being diagnosed.  Level 4 diagnostic on a navigational thruster probably takes less time and involves different measures than a Level 4 diagnostic on the warp core.  Here are some generalizations of the measures at different diagnostic levels.

*

*Take system out of service, full shutdown, manual inspection, observed re-initialization, manual testing.

*Take system out of service, limited manual inspection, crew monitored automated tests.

*Take system out of service, minimal manual inspection, automated tests.

*Take system out of service, automated tests.

*Automated tests.


text:
Q: Removing hyphens from a cell in Excel I am looking to take the hyphen or dash out of a birthdate.
01/01/01
01-01-01
I need to combine the birthdate with other fields and it can't have the seperator in it.
I am sure there is a better way. I can get the month and year out, using left & right however I can't figure out how to get the middle out. Below is what I have so far and I know that I can combine them using "&"...if someone can help me with the middle or give me a better equation I would appreciate it.
LEFT(A1,2)
RIGHT(A1,2)
Solution:
=LEFT(F2,2)&MID(F2,4,2)&RIGHT(F2,4)

A: if it is a string, (not formated as a date) then you can use
MID(A1,4,2)

otherwise i just use the MONTH(A1) DAY(A1) YEAR(A1) functions

A: I'm not sure what an excel formula is so this answer might be irrelevant...
VBA has a Mid function that would do what you want I believe. This page has good explanations for that and the other similar functions: http://www.vbtutor.net/VBA/vba9.htm

A: Change the number format of the date to something line "mmddyy". To combine it with other text in another cell, use a formula like:
="The date is "&TEXT(A1,"mmddyy")

where the date is in cell A1.

A: You could also do a Find and Replace to replace the "-" with nothing.
Ctrl + H will bring up the Replace dialog box.


text:
Q: Handling empty arrays in pySpark (optional binary element (UTF8) is not a group) I have a json-like structure in spark which looks as follows:
>>> df = spark.read.parquet(good_partition_path)
id: string
some-array: array
    element: struct
        array-field-1: string
        array-field-2: string

depending on the partition, some-array might be an empty array for all id's. When this happend spark infers the following schema:
>>> df = spark.read.parquet(bad_partition_path)
id: string
some-array: array
    element: string

Of course that's a problem if I want to read multiple partitions because spark cannot merge schemas. I have tried to define manually the schema so there should be no problem
>>> df = spark.read.schema(good_schema).parquet(bad_partition_path)
id: string
some-array: array
    element: struct
        array-field-1: string
        array-field-2: string

So far so good, but when I try to actually collect the data I get an error:
>>> df.head(5)
# Long error message
Caused by: java.lang.ClassCastException: optional binary element (UTF8) is not a group

I don't understand why this fails. There should be no incompatibility cause by the schema. In case you wonder, collecting the data without specifying the schema works.
>>> df = spark.read.parquet(bad_partition_path)
id: string
some-array: array
    element: string   # infers wrong schema
>>> df.head(5)
[Row(...)] # actually works

Edit
Here there's a reproducible example in python
from pyspark.sql.types import *

myschema = StructType([
   StructField('id', StringType())
 , StructField( 'some-array'
              , ArrayType(StructType([
                  StructField('array-field-1', StringType())
                , StructField('array-field-2', StringType())
                ])
              ))
  ])

path_writeKO = "path/to/parquet"
jsonKO = '{"id": "OK", "some-array": []}'
dfKO = sc.parallelize([jsonKO])
dfKO = spark.read.json(dfKO)
dfKO.write.parquet(path_writeKO) # write without schema

read_error = spark.read.schema(myschema).parquet(path_writeKO) # read with schema
read_error.collect() # Fails!!

A: The solution I've found is setting the option dropFieldIfAllNull to True when reading the json file. This causes field with empty array to disapear, making merging schema easier.
>>> jsonKO = '{"id": "OK", "some-array": []}'
>>> dfKO = sc.parallelize([jsonKO])
>>> dfKO = spark.read.option('dropFieldIfAllNull', True).json(dfKO)
id:string

Now, undesired type inference won't apply and when reading multiple partitions of the same file the option mergeSchema will be able to read all files without colision.

A:
Of course that's a problem if I want to read multiple partitions
  because spark cannot merge schemas. I have tried to define manually
  the schema so there should be no problem

I am afraid that there is no such a schema which can parse simultaneously these two cases. The data {"id": "OK", "some-array": [{"array-field-1":"f1", "array-field-2":"f2"}]} can be parsed only with:
good_schema = StructType([
  StructField('id', StringType()),
  StructField( 'some-array',
              ArrayType(StructType([
                StructField('array-field-1', StringType()),
                StructField('array-field-2', StringType())
              ])
          ))
  ])

when {"id": "OK", "some-array": []} with:
bad_schema = StructType([
  StructField('id', StringType()),
  StructField('some-array', ArrayType(StringType()))
])

Therefore one option is to read these two directories with different schemas.

I don't understand why this fails. There should be no incompatibility
  cause by the schema.

As explained above the data is incompatible with the schema.

In case you wonder, collecting the data without
  specifying the schema works.

This is the expected behaviour since when there is no explicit schema specified Spark will try to discover it.
Suggested solution
The only solution that I can think of is to treat some-array field as a string. I don't know if this feasible in your system although you could implement it by casting the some-array into string for both schemas/partitions.
This conversion can be done with at least two options given:
good_data_df = spark.read.schema(good_schema).parquet(...)
bad_data_df = spark.read.schema(bad_schema).parquet(...)

*

*Read both datasets and convert the some-array field to string then save the results under one common directory with:

good_data_df = good_data_df.withColumn("some-array", col("some-array").cast("string"))
bad_data_df = bad_data_df.withColumn("some-array", col("some-array").cast("string"))

good_data_df.union(bad_data_df).write.mode("overwrite").parquet("parquet_path")

*Execute the above conversion in runtime skipping the re-write step.

Finally you can load some-array as a string and then convert it to array_schema using from_json function:
from pyspark.sql.types import *
from pyspark.sql.functions import from_json

array_schema = ArrayType(StructType([
                StructField('array-field-1', StringType()),
                StructField('array-field-2', StringType())]))

# we will use this for both partitions
generic_schema = StructType([
  StructField('id', StringType()),
  StructField('some-array', StringType())
])

parquet_path = "/tmp/60297547/parquet"
good_data = "{'id': 'OK', 'some-array': \"[{'array-field-1':'f1a','array-field-2':'f2a'},{'array-field-1':'f1b','array-field-2':'f2b'}]\"}"
bad_data = "{'id': 'OK', 'some-array': '[]'}"

# putting bad and good partitions into the same dataset where some-array is string
rdd = sc.parallelize([bad_data, good_data])
df = spark.read.json(rdd)
df.write.mode("overwrite").parquet(parquet_path)

final_df = spark.read.schema(generic_schema).parquet(parquet_path)
final_df = final_df.withColumn("some-array", from_json(final_df["some-array"], array_schema))

final_df.show(10, False)

# +---+------------------------+
# |id |some-array              |
# +---+------------------------+
# |OK |[[f1a, f2a], [f1b, f2b]]|
# |OK |[]                      |
# +---+------------------------+

final_df.printSchema()
# root
#  |-- id: string (nullable = true)
#  |-- some-array: array (nullable = true)
#  |    |-- element: struct (containsNull = true)
#  |    |    |-- array-field-1: string (nullable = true)
#  |    |    |-- array-field-2: string (nullable = true)


text:
Q: XCOPY still asking (F = file, D = directory) confirmation My batch script xcopy is still asking F = file, D = directory confirmation even though I have added /F in the script, the log is showing as below.
Please help on how to avoid asking confirmation.
Script:
net use p: /delete
net use p: "\\200clan\F_Drive" /USER:adm /PERSISTENT:NO-1111
set source=%1
set target=p:/%2

echo %source% %target%

xcopy /S /I /Q /Y /F "%source%" "%target%"

Log:

C:\test\foldera>xcopy /S /I /Q /Y /F "C:/test/folder1/folder2/logs/154/compareReport_177.html" "p:/Services/WSDLCompare/177_20151116/compareReport_177.html"
Does P:\Services\WSDLCompare\177_20151116\UIReport_177.html specify a file name
or directory name on the target
(F = file, D = directory)?

A: Put a \ behind the target to suppress the question and specify it as a folder:
xcopy src dest\

Put a * behind the target to suppress the question and specify it as a file:
xcopy src dest*

Note: The second command is a hack that relies on wildcard matching (will match any item starting with "dest") so use it at your own risk!

A: xcopy doesn't know the target is a directory. You clarify this by putting a backslash at the end:
xcopy /S /I /Q /Y /F "%source%" "%target%\"

A: The /I switch (not /F as you mentioned in your question) prevents xcopy from asking whether the destination is a file or a directory only if multiple source files are given, so if the source is a directory, or if wildcards ? or * are used. If the destination already exists, such prompt does never appear.
There are the following scenarios (depending on the provided values of %source% and %target%):

*

*a single source file, the destination is a file:
the /I switch is useless, so you need to pipe F into the xcopy command line:
echo F|xcopy /S /Q /Y /F "%source%" "%target%"

provided that the /Y switch is given (to force overwriting), you could also create the target file in advance (empty file):
>> "%target%" rem/
xcopy /S /Q /Y /F "%source%" "%target%"

*a single source file, the destination is a directory:
the /I switch is useless too; you can pipe D into the xcopy command line:
echo D|xcopy /S /Q /Y /F "%source%" "%target%"

or you can simply append a \ to the destination:
xcopy /S /Q /Y /F "%source%" "%target%\"

although this causes trouble when %target% specifies the current directory of a drive like D: for instance, because D: means the current directory of this drive whereas D:\ means the root directory of it;
or you create the destination directory in advance:
2> nul mkdir "%target%"
xcopy /S /Q /Y /F "%source%" "%target%"

the 2> nul portion suppresses the error message in case the directory already exists;

*multiple source files, the destination is a file:
this is usually a senseless situation, because you tell xcopy to copy each source file to the same destination file, thus attempting to overwrite it;

*multiple source files, the destination is a directory:
the /I switch makes sense here:
xcopy /S /I /Q /Y /F "%source%" "%target%"

the pipe option also works here:
echo D|xcopy /S /Q /Y /F "%source%" "%target%"

so does appending a \ to the destination (regarding the limitation as mentioned above):
xcopy /S /Q /Y /F "%source%" "%target%\"

or you create the destination directory in advance:
2> nul mkdir "%target%"
xcopy /S /Q /Y /F "%source%" "%target%"

Conclusion
The most flexible and secure solution is to pipe the desired selection (F or D) into the xcopy command line. (Note that the query is locale-dependent.)

Supplement
There are some minor issues in your code fragment I want to mention here:

*

*you should generally use the \ as a path separator as this is the Windows standard character for that purpose (although / works too in most cases);

*there is -1111 appended to your second net use command line; if this constitutes the password for the resource, it should be moved before the /USER option; otherwise just remove it;

*your set command lines introduce problems with some special characters (like &, ^, (, )); to avoid such, state set "source=%~1" and set "target=p:/%~2"; the ~ removes potential surrounding "" from the arguments (which are required if they contain SPACE, ,, ;, =);

Here is the code with the all of the above things reworked:
net use P: /DELETE
rem supposing `-1111` constitutes the password for the resource:
net use P: "\\200clan\F_Drive" -1111 /USER:adm /PERSISTENT:NO

set "source=%~1"
set "target=P:\%~2"

echo "%source%" "%target%"

rem supposing the destination is a directory:
echo D|xcopy /S /I /Q /Y /F "%source%" "%target%"

rem actually you do not need any interim variables:
REM echo D|xcopy /S /I /Q /Y /F "%~1" "P:\%~2"

A: When copying a single file with XCOPY, there is no option to indicate if the destination is a filename or a directory (with the filename defaulting to that of the source file).
In such cases XCOPY will prompt with a (locale specific) message like:
C:> xcopy foo.txt bar.txt
it prompts
Does foo.txt specify a file name or directory name on the target (F = file, D = directory)?
Adding a wildcard (*) to the end of the destination will suppress this prompt and default to copying as a file:
C:> xcopy foo.txt bar.txt*
1 File(s) copied
This requires the source and target file extensions to be the same length, typically 3 characters.
for more information: https://ss64.com/nt/xcopy.html

A: Removing the destination filename will suppress the message. This works for me!

A: I use:
xcopy /S /I /Q /Y /F "%source%" "%target%"

It works.

A: Try:
echo F>xcopy_answer.tmp
xcopy xcopy /Q/Y "%source%" "%target%"<xcopy_answer.tmp


text:
Q: Cannot find media query rules in CSS file opened by python cssutils package I need to modify the CSS rendering style for several similar web pages, so I'd intend to open each css file and modify their rules.
I tried to modify an element in web page, making it not disappear along with the change of screen size, the origin css rule is:
@media screen and (max-width: 768px):
.base-header .group-list.nav {
display: none; }

I want to disable the display: none settings to make the element remain appearing.
Now I'd parse the first css file via cssutils:
import csutils

stylesheet = cssutils.parseFile('global.css')

In stylesheet.cssRules, I couldn't find the display: none rule setting under @media screen . However I could find other rule settings that is not under media query.
If I open the css file by open(), I could see the media query settings, but the file return by open() is more messy and seems hard to edit to me.
How could I find the rules under media query in css files?
Or is there better way to solve my problem, without using parsing method in cssutils?
Thank you for every advice!

A: I found that I'm able to edit the file via traditional open() then edit file method.
If I use Visual Studio Code to open the css file then auto-format it, I could open the resulting file then edit it line-by-line.
However, for the css file I need to first format it to read the file line by line, otherwise the css file is too messy to parse. I still haven't find a way to solve this, BeatifulSoup seems not helping for CSS parsing problem.


text: Q: Page title of biliography In a paper I created, the name of the last section is also the page heading for the biliography at the end. How can I change this so that on the pages with references the page title is "Bibliography"?


text:
Q: Prove that if $F: A \rightarrow B$ and $F^{-1}$ is a function, then $F$ is one-to-one Prove that if $F: A \rightarrow B$ and $F^{-1}$ is a function, then $F$ is one-to-one
Proof: Suppose $F$ is not one-to-one. Then there exist $x_{1}, x_{2} \in A$ such that $F(x_{1}) = F(x_{2})$ where $x_{1} \neq x_{2}$. Now, at this point I'm stuck as to how I can arrive at a contradiction. Could someone help?

A: A function cannot be one-many. It is impossible that $x_1=x_2$ and $f(x_1)\neq f(x_2)$.

A: Suppose $F(x_1) = F(x_2)$. Now apply $F^{-1}$ to both sides to get $F^{-1}(F(x_1)) = x_1 = F^{-1}(F(x_2)) = x_2$. Hence $F$ is injective.

A: Suppose $f:A\to B$ and $f^{-1}$ is a function $\Rightarrow f^{-1}(f(x_1))=f^{-1}(f(x_2))$ $\Rightarrow x_1=x_2$ as desired.