text:
Q: layoutAnimation works only one time I have a LinearLayout with layoutAnimation property that is used for a customize ExpandableListView. like this :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layoutAnimation="@drawable/list_layout_controller"
    android:orientation="vertical" >

When I click on the list, the animation will be displayed. But it works only once and it will not animate the list in the next click. Why?
Please let me know, If you need more description.
Thank you

A: First u want to declare
Animation  listanimation = AnimationUtils.loadAnimation(mainActivity.this, R.anim.list_layout_controller);

and everytime clearAnimation first.
In clickevent of LinearLayout
 linearLayout.clearAnimation();
 linearLayout.startAnimation(listanimation);

A: call
listView.scheduleLayoutAnimation();
before all changes in the list

A: Layout Animations are run when views are added to the layout. So you will have to manually add/remove the views on every expand/collapse for the layout animation to work.
For this, you can maintain a Map of views with the list index as the key.
Every time you get click, just pick the corresponding items from the map and add to your layout. The animation will run on that view and your problem is fixed.
You can also try by changing the visibility of views in onClick(). But not sure about this.
Try and let me know.
Hope that helps.

A: Try to restart animation on each item click:
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      view.getAnimation().start();
      //your custom logic
}
});

A: Just use
public void startLayoutAnimation ()

http://developer.android.com/reference/android/view/ViewGroup.html#startLayoutAnimation()


text:
Q: Do I need to have Excel installed to query spreadsheets using an OleDB Provider? I am working on some software that uses an OleDB to open a .xls file, query some data, and fill a dataset with the results.  I am now looking at using this software on systems that do not have Excel.  Will my software still be able to read the spreadsheets?
This xls file contains 1000s of configuration settings that my software uses.  If this setup won't work on computers without Excel, I'm guessing my next best move is to convert the xls file to an XML file and read it in using XML Services.

A: You need either the full Office or the Office Data Connectivity Components installed on the client computers.

A: You don't have to have office or the office data connectivity installed, you can use the Jet for OleDB engine which is installed on pretty much every windows machine in existence.  However it's very old technology and is limited to 32 bit.
http://msdn.microsoft.com/en-us/library/ms175866.aspx
If you want to avoid this mess entirely then switch over to an app.config file or a properties file and you can get the pure .net solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sort dictionary high to low and alphabetically I have tried to sort my array from high to low however using advice from this website i could only sort it from low to high and couldn't sort alphabetically.
My code:
x={"luiz":2,"adrian":8,"guv":10,"homer":3,"jane":6}

y={"gus":3,"gump":7,"harry":7,"elliot":9}

z={"elizabeth":10,"micheal":2,"david":7}

sorted_x = sorted(x.items() , key operator.itemgetter(1))

sorted_y = sorted(x.items() , key operator.itemgetter(1))

sorted_z = sorted(x.items() , key operator.itemgetter(1))

my program needs to output the name and values from highest score to lowest and then output the dictionarys alphabetically

A: To reverse the sort, simply add reverse=True:
sorted(x.items(), key=operator.itemgetter(1), reverse=True)

Presumably you wanted to sort the keys alphabetically, rather than sort by score from lowest to highest; in that case just omit the key:
sorted(x.items())

because the key-vale tuples produced by dict.items() are already going to be sorted by the key first.

A: Thanks this is my program now
import operator

x={"luiz":2,"adrian":8,"guv":10,"homer":3,"jane":6}

sorted(x.items(), key=operator.itemgetter(1), reverse=True)

sorted(x.items())
y={"gus":3,"gump":7,"harry":7,"elliot":9}

sorted(y.items(), key=operator.itemgetter(1), reverse=True)

sorted(y.items())

z={"elizabeth":10,"micheal":2,"david":7}

sorted(z.items(), key=operator.itemgetter(1), reverse=True)

sorted(z.items())


text:
Q: Bison: where is the last $$ value stored in pure-push parser? I wrote a parser definition, which interfaces with python as an extension. I declared the following options, so that Bison generates a reentrant push parser:
%define api.pure full
%define api.push-pull push

In order to pass semantic values to python through it's C API, I declared the YYSTYPE to be PyObject* as follows:
%define api.value.type {PyObject*}

Now, the last ("accepting") rule has the following action:
full :  declarations data
  { $$ = Py_BuildValue("(s, O, O)", "full", $1, $2); }
;

The Py_BuildValue function here will create a tuple object containing a string and two other objects of an arbitrary type, and return a PyObject* pointer to it.
Given that I call the parser in the following way:
token_index = 0;
yypstate* ps = yypstate_new();

do{
    token_id = get_token_id(token_index);
    semval = semvals[token_index];
    state = yypush_parse(ps, token_id, &semval);
    token_index += 1;
} while (state == YYPUSH_MORE);

... how can I access the value generated by the full rule (i.e. its $$)?
I tried yylval and yyval, and it seems like they are not defined.
I suspected that the pointer to the value may be stored somewhere in ps structure, but I can't find any documentation on it.

A: The stack is deallocated at the end of the parse, so whatever was pushed as $$ will vanish. If you want to return a value you should provide an extra argument to the push parser which points to the place to store the result, rather than assigning it to $$.


text:
Q: Selenium Grid With Page Object Model Page Factory How would I initialize the browser if I want to test on multiple browsers using Page Object Model Page Factory?
Currently I have iniatialized the browsers in my Base Class like this.
// initialise driver/browser

 public void initDriver() throws MalformedURLException{
   if(CONFIG.getProperty("browser").equals("firefox")){
       cap = DesiredCapabilities.firefox();
       cap.setBrowserName("firefox"); // chrome,iexplore
       cap.setPlatform(Platform.ANY);
   }else if (CONFIG.getProperty("browser").equals("chrome")){
       cap = DesiredCapabilities.chrome(); // no need path of chrome exe
       cap.setBrowserName("chrome");
       cap.setPlatform(Platform.ANY);
   }else if (CONFIG.getProperty("browser").equals("iexplore")){
       cap = DesiredCapabilities.internetExplorer(); // no need path of chrome exe
       cap.setBrowserName("iexplore");
       cap.setPlatform(Platform.WINDOWS);
   }
   if(driver == null){
       driver=new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),cap);
   }
   String waitTime=CONFIG.getProperty("default_implicitWait");
   driver.manage().timeouts().implicitlyWait(Long.parseLong(waitTime), TimeUnit.SECONDS);
   }

This however only runs my test my test only on one of the browsers.
This is my testng.xml file
<suite name="Selenium Grid with webdriver" >
<listeners>
    <listener class-name="Codes.listener.TestsListenerAdapter" />
</listeners>
<test name="Login test">
    <classes>
        <class name="Codes.testCases.LoginTest" ></class>
    </classes>
</test>
</suite>

A: Your browser initialization seems ok but I am wondering , why cap is not initialized when driver == null You should improve your testng.xml in following way:
To Run the test methods parallely:
<suite name="Selenium Grid with webdriver" parallel="methods" thread-count="5" >
    <listeners>
        <listener class-name="Codes.listener.TestsListenerAdapter" />
    </listeners>
    <test name="Login test">
        <classes>
            <class name="Codes.testCases.LoginTest" ></class>
        </classes>
    </test>
</suite>

Similarly you can define parallel = "classes" or parallel = "tests" to choose the parallel execution level.

A: As @Priyanshu mentioned, you need to change your testng.xml. I believe that you have updated your testng.xml but as per your above testng.xml file you have only one <class> in <test>, so in your cases parallel="methods" (I assume you wanna execute different test scripts in parallel and not different methods of same test script) or parallel="classes" will not work. Change it to parallel="tests" and then try running it like this :-
<suite name="Selenium Grid with webdriver" parallel="tests" thread-count="5" >
    <listeners>
        <listener class-name="Codes.listener.TestsListenerAdapter" />
    </listeners>
    <test name="Login test">
        <classes>
            <class name="Codes.testCases.LoginTest" ></class>
        </classes>
    </test>

    <test name="Login test2">
        <classes>
            <class name="Codes.testCases.LoginTest2" ></class>
        </classes>
    </test>

   <test name="Login test3">

   <!-- class etc.. etc.. -->

   </test>

</suite>


text:
Q: How to split file in two by segments of 4 lines in unix I'm searching for a way how to split my file in two, haven't found an answer here. I have a large file (with millions of lines) and would like to split it in two files, always by four lines, i.e. the first four lines (1,2,3,4) go in the first output file, the second four lines (5,6,7,8) go in the second output file, then the third four lines (9,10,11,12) go again to the first output file, etc. I'm sure there will be a way - possibly using awk (?) but I can't get it right... Thanks a lot!

A: All you need is
awk 'NR%4==1{c=!c} {print > ("out"c)}'

Look:
$ seq 10 | awk 'NR%4==1{c=!c} {print $0 " > " ("out"c)}'
1 > out1
2 > out1
3 > out1
4 > out1
5 > out0
6 > out0
7 > out0
8 > out0
9 > out1
10 > out1

A: another awk
awk '{print > "out_"((NR-1)%8>3)}' file


text:
Q: How to solve no method error in ruby on rails? I defined my route and controller actions correctly. Still I'm getting a no method error.
Here is my code:
Route:
 get "/restaurants", to: "restaurants#index"

Controller action:
def index
  resto = Restaurant.all
  render json: resto,status: :ok
end

here is my error in the browser:
NoMethodError in RestaurantsController#index
undefined method `type' for #<Restaurant:0x00007fb711a07628>
Extracted source (around line #4):

    def index
     resto=Restaurant.all
    ( render json: resto,status: :ok) # this is the line throwing error

    end
end

And here is the problem in the console
Use Ctrl-C to stop
Started GET "/restaurants" for ::1 at 2022-08-16 22:26:25 +0530
   (0.7ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by RestaurantsController#index as HTML
  Restaurant Load (1.2ms)  SELECT "restaurants".* FROM "restaurants"
  ↳ app/controllers/restaurants_controller.rb:4:in `index'
[active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (12.1ms)
Completed 500 Internal Server Error in 38ms (ActiveRecord: 7.5ms | Allocations: 17269)


text:
Q: Delete RegistryKey Win64/32 I am trying to delete a Windows key using Delphi , however unsuccessfully , follows the code I'm using
Function DeleteKeyAPI(hRoot: HKEY; sPath: String; IsReg64: BOOL): BOOL;
Var
  iRet: Integer;
Begin
  If IsReg64 Then
    iRet := RegDeleteKeyEx(hRoot, PChar(sPath), KEY_WOW64_64KEY, 0)
  Else
    iRet := RegDeleteKeyEx(hRoot, PChar(sPath), KEY_WOW64_32KEY, 0);

  If iRet = ERROR_SUCCESS Then
    Result := True
  Else
    Result := False;
End;

in some keys I can delete more than one has in own Regedit me of an access denied error
how can I fix this problem ?
Edited -----------------------
I tried to do as follows , but without success
function SHDeleteKey(key: HKEY; pszSubKey: LPCTSTR): DWORD; stdcall;

implementation

{$R *.dfm}

function SHDeleteKey; external 'shlwapi.dll' name 'SHDeleteKeyA';

procedure TForm1.FormCreate(Sender: TObject);
begin
  SHDeleteKey(HKEY_LOCAL_MACHINE, 'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run\AdobeCS6ServiceManager');
end;

A: You should inspect the value of iRet to learn more. This is a Win32 error code that will give more details of the reason for failure.
From the documentation:

The subkey to be deleted must not have subkeys. To delete a key and all its subkeys, you need to enumerate the subkeys and delete them individually. To delete keys recursively, use the RegDeleteTree or SHDeleteKey function.

This is one common failure mode, namely that the subkey you are attempting to delete has subkeys itself. I'm not sure what error code is, perhaps ERROR_DIR_NOT_EMPTY.
Another common failure mode is that the named subkey does not exist. That would lead to error code ERROR_PATH_NOT_FOUND or perhaps ERROR_FILE_NOT_FOUND.
Finally, and what I guess is the real problem, you cannot obtain delete rights to the key. Since you are using alternate registry flags, I suspect you are trying to delete a subkey under HKLM. Your process needs sufficient rights to be able to do this. Typically that means running as an elevated admin user. You will get ERROR_ACCESS_DENIED if you have insufficient rights.

Regarding your edit, AdobeCS6ServiceManager is a value rather than a key. The function you need is RegDeleteValue. Read about the registry to learn what these terms mean: https://msdn.microsoft.com/en-us/library/windows/desktop/ms724182.aspx
Furthermore, it is disappointing that you ask a question about RegDeleteKeyEx and then edit to show code that calls SHDeleteKey. Please try to stick to the original question.


text:
Q: Match a line not ending in digit (with possible trailing white spaces) I want to match a line which doesn't end in a digit (with possibly trailing white spaces. I am using Emacs Regex (and I am open to use other Regex flavors).

*

*What are some good regexs to accomplish that?

*Can we use Possessive Quantifiers. (suppose Possessive Quantifiers work in Emacs Regex)

*Here are two attempt of mine.
[^[:digit:]] *^J

where ^J is the new line character, typed by C-q C-j, will match
concepts of logic 1

But
[^[:digit:]] *$

doesn't match
concepts of logic 1

I wonder why there is the difference?
Thanks.

A: So you want to match either a line that does not end in any char (i.e., is empty) or a line that ends in a character that is not a digit and not a newline char?
Interactively, you would type the regexp to C-M-s, this way:
\(^$\|[^C-qC-j[:digit:]]\)$

Where typing C-q C-j inserts a newline char (C-j) interactively.  It looks like this in Isearch, where the ^J is a single (newline) char:
\(^$\|[^^J[:digit:]]\)$

From Lisp, you would double the backslashes and use \n to represent the newline char:
\\(^$\\|[^\n[:digit:]]\\)$

If you want to allow trailing whitespace, then add [ \t]* before the $.  For example, interatively:
\(^$\|[^C-qC-j[:digit:]]\)[ \t]*$


text:
Q: How to find where Tomcat is install/running from when it is not installed as a service I'm trying to determine the Tomcat install directory when it is started from startup.bat in Windows.
It is easy enough to determine where tomcat7.exe is running when Tomcat is running as a service, but I'm not sure how to do it when it's started with the script.  I know java is running when Tomcat is started from the script, but the executable path is for the java jre.  Is there something I can do to find where catalina is running based on java?

A: Assuming you know the location of startup.bat, then just go two folders above and you're done.
Assuming you only have a shortcut to this file, then you would need to retrieve a list of processes explaining the application and the location of the files they're using, similar like ps aux command from Unix based OSes. Fortunately, Windows have such thing as well. From this great Q/A: Is there a command in Windows like ps -aux in UNIX?, more specifically, this answer, the way to find the location of tomcat in Windows is to execute the wmic application (through CMD if you want) and write process command, this will provide a list of the current applications running and their parameters. For example, I initialized Tomcat from startup.bat file and got this result using the commands above (single line):
java.exe                     "C:\Program Files\Java\jdk1.7.0_40\bin\java"   -Djava.util.logging.config.file="<TOMCAT_HOME>\conf\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager   -Djava.endorsed.dirs="<TOMCAT_HOME>\endorsed" -classpath "<TOMCAT_HOME>\bin\bootstrap.jar;<TOMCAT_HOME>\bin\tomcat-juli.jar" -Dcatalina.base="<TOMCAT_HOME>" -Dcatalina.home="<TOMCAT_HOME>" -Djava.io.tmpdir="<TOMCAT_HOME>\temp" org.apache.catalina.startup.Bootstrap  start

Here's the same result but splitted in several lines to ease readability:
java.exe "C:\Program Files\Java\jdk1.7.0_40\bin\java"
    -Djava.util.logging.config.file="<TOMCAT_HOME>\conf\logging.properties"
    -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
    -Djava.endorsed.dirs="<TOMCAT_HOME>\endorsed"
    -classpath "<TOMCAT_HOME>\bin\bootstrap.jar;<TOMCAT_HOME>\bin\tomcat-juli.jar"
    -Dcatalina.base="<TOMCAT_HOME>"
    -Dcatalina.home="<TOMCAT_HOME>"
    -Djava.io.tmpdir="<TOMCAT_HOME>\temp"
    org.apache.catalina.startup.Bootstrap  start

Note: I've replaced the real path by <TOMCAT_HOME> in the results from above.

TL;DR do this:

*

*Open cmd

*Execute wmic

*Execute process

*Wait few secs and search java.exe and the arguments containing Tomcat jars.

A: Since you explicitly mentioned *.bat and Windows here is your answer.
1.Most tomcat application comes as a zip instead as msi/exe . The place where you extract is actually its locations . You start the application by clicking startup.bat file
2.Open the bat file with notepad . You will also find the relative path of the application.
3.Look for the  path variables .
Hope this information helps


text:
Q: It would be possible to define an uniform distribution on $\Bbb N$ using infinitesimals? In standard analysis it is clear that it is impossible to define an uniform probability distribution on $\Bbb N$ because there is no constant $c\in\Bbb R$ such that $\sum_{k=1}^\infty c=1$.
Using Robinson's hypernaturals it doesn't seem feasible either because $\Bbb N$ is an external set and so there is no way that $\Bbb N$ appear as a set in an internal formula.
Another way to do this could be to try to define an external function of the kind $f:\{1,\ldots, N\}\to\Bbb N$ here $N$ is an unlimited hypernatural and $f$ is surjective and linear. However again this doesn't seem feasible because the structure of the hyperfinite set $\{1,\ldots, N\}$ seems very different that the structure of $\Bbb N$.
Someone knows some attempt like this, maybe using a different kind of infinitesimals different than those of Robinson's theory?

Another way to say the same: someone knows some attempt to extend the field of reals such that there is some constant $c\neq 0$ such that $\sum_{k=1}^\infty c\in\Bbb R\setminus\{0\}$?

A: Of course we need to specify what properties the  extension should have.
The answer is no  under fairly  weak  assumptions:

If $F$ is a field with a topology such  that addition is separately continuous and infinite sums  are defined as limits of partial sums then $\sum c$ diverges for every non-zero $c\in F$.

Say $s=\sum  c$ and let $s_n$ be the $n$th partial sum. Then $s_{n+1}=s_n+c$, so continuity of addition shows that $s=s+c$, hence $c=0$.

A: I don't disagree with the answer, but I thought I would pose a different semi-answer - an answer to a slightly different question, but that someone might be thinking of when they look at this question, as other similar questions have arisen.  Instead of requiring that it be specifically $\mathbb{N}$, let's say that we just want to define a uniform distribution on the set of numbers from $1$ to some hyperinteger $\omega$.
As the questioner implies, for any probability distribution on the set $\Omega$, $\sum\limits_{n=1}^{\omega}\text{Pr}[x=n] = 1$.  If the probability is uniform, then $\text{Pr[x = n]}$ is a constant ($c$) for the whole distribution.  So what is this $c$?  Well, for any $k$, $\sum\limits_{n=1}^{k} c = c\cdot k$.  Therefore, for a hyperfinite $\omega$ this will also be true.  This means that, for a uniform distribution:
$$
\sum\limits_{n=1}^{\omega}\text{Pr}[x=n] = c\cdot \omega = 1 \\
c = \frac{1}{\omega}
$$
Likewise, we can also figure out other features such as the expected value of this distribution.  The expected value is given by:
$$
\mathbb{E}[x] = \sum_{n=1}^\omega Pr[x=n]\cdot n
$$
Since the probability is the constant $c$, it can replace the probability and be moved outside of the summation:
$$
\mathbb{E}[x] = c \sum_{n=1}^\omega n
$$
$\sum\limits_{n=1}^\omega n$ is just an arithmetic series.  Therefore, we can determine its value using the standard arithmetic series formula as $\frac{\omega}{2}(1 + \omega) = \frac{\omega^2 + \omega}{2}$.  Since $c = \frac{1}{\omega}$, this becomes:
$$
\mathbb{E}[x] = \frac{1}{\omega} \frac{\omega^2 + \omega}{2} = \frac{\omega}{2} + \frac{1}{2}
$$
So, using hyperreals, although we may not be able to mimic $\mathbb{N}$ precisely, there are similar questions that can be asked and answered using the system. This answers the question as you posed it at the end of your post, but not necessarily as you posed it in the beginning.


text:
Q: Secure file server Introduction
I want to create a Java web application for storing and backing up user files, similar to Dropbox. One of the interesting Dropbox feature is that it can detect whether a certain file already exists on server. For example, if one user upload a file onto server, another user who tries to  upload the same file will not need to upload the same file content. Server will only need mark that he has the same file. This helps to save the bandwidth/space and increases the speed in many ways.
The most basic solution to this problem is to use a file hash string, e.g. sha1, md5, etc., to identify the file. The client software check whether a certain hash exists on server or not. If it exists, then it can skip the uploading process and mark that user has the same file.
Problem
The web application is implemented based on REST architecture so that user can easily write their own client software to upload their files. For security reasons, the SSL is enabled for all transactions. But my most security concern is about users faking that they have a file without actually owning it if I use sha1 or any other standard hash alogorithms. This cannot be prevented by SSL or encryption. If a user manage to get the hash string, e.g. md5 and sha1 of many files can be found by googling, he can mark that he has the file using REST service on the web application.
So one of the possible solution is that the server requests a set of certain random bytes from the file as well as the hash of the whole file. Here is example steps:

*

*Client checks whether a certain hash exists on server or not. Then, server returns the required positions of random bytes if the file already exists.

*Client sends random bytes as per request if the server has the file. Client software will not be able to response to it without having the actual file.

In this way, it can save the bandwidth as well as ensure that user owns the file they want to upload.
Question
I am no expert in Security over the web so I have no idea whether this is a good idea or not. I have read some articles about implementing their own fancy process might lead to the reduction in security strength because the security cannot be tested and the extra information may provide a cracking method.
Does anyone has any comment on the process?
Will it reduce the sucurity?
Does anyone have an idea to solve this problem differently?
I understand that there might not be an exactly answer to this question but I would like to hear if anyone has encounter the same problem and has any good solution to it.

A: Rather than asking the client to upload some random bytes of the file's contents, it may be better to ask the client to upload the hash of a random region the file.  That way you can use a wider range of sizes that you ask the client to verify.
Better yet, though, may be to send the client a random number and require the client to compute an HMAC of the entire file's contents using that number as the key.  This is more computationally-expensive since the server must compute the HMAC too, but it verifies that the client has the entire file, not just a small portion of it.

A: One unavoidable side effect of this hash feature, even with a verification scheme, is that it reveals that a copy of the file already exists somewhere on the server.  That by itself may be sensitive information.
For the most stringent privacy protection, you should forego this feature and make each user upload their own copy of the file.  You can use hash comparison on the server to avoid storing multiple copies of the file, transparently to the clients.


text:
Q: How should I fix this git mistake?
*

*I made some code changes(updates to added files)

*Then I mistakenly removed the project level build.gradle using Git Bash:
rm -f build.gradle
git commit -m "removing project level build.gradle"
git push origin master
My whole project directory is under git control(git init'ed), but for some reason my code changes weren't pushed to the master branch.  My build.gradle was removed though--Why?
I want to do the following now:

*

*push the code changes I made from my local repo to the remote repo.

*undelete the build.gradle

*remove build.gradle from source control, since different people are using different gradle versions.

Thanks

A: *

*I need to ADD ANY CHANGED FILES, even if they were already added.  This was new to me because I relied on Android Studio to do this before, where it was implicit with a commit.

*git checkout SHA_OF_COMMIT build.gradle

*"git rm --cached build.gradle";
build.gradle was already in my repo, so adding *.gradle to my gitignore would not have had any effect.  Executing the above command removes the file from git's control.  Other collaborators should run this command too to stop tracking from their local repos.


text:
Q: What is the measure, in degrees, of $\angle BFC$? In triangle ABC, $\angle CAB = 18$ and $ \angle BCA = 24$ .$ E $ is a point on $CA $ such that $\angle CEB=60$ and $F $is a point on $AB $ such that $\angle AEF=60$.What is the
  measure, in degrees, of $\angle BFC$?
Taken from the 2014 IMC
Ive solved similar problems but im not sure how to solve this
I worked out $\angle BAC= 18$ , $\angle EBC =96$ , $\angle FEB = 42$, and $\angle BEC = \angle FEB = \angle AEF=60$.

A: Let $D$ be placed on the line $BC$ such that $B$ is placed between $D$ and $C$.
Thus, since $$\measuredangle DBA=42^{\circ}=\measuredangle ABE,$$ we see that $BA$ is a bisector of $\angle DBE$ and since $EF$ is a bisector of $\angle AEB$, we obtain that
$CF$ is a bisector of $\angle BCA.$
Id est, $$\measuredangle BFC=12^{\circ}+18^{\circ}=30^{\circ}.$$


text:
Q: How to access the search text in a TCRDBGrid component? Is there a way to access the text entered in a Devart (Core Lab) TCRDBGrid search bar?
I tried implementing the OnKeyDown event but the event didn't happen during entry in the search fields, only when the grid itself was selected. There are no other events that look relevant.
The text appears to go into a TEdit which is part of a TCRGridTitleEdit, which is part of TCRDBGrid but is private.
Is there a way to get the search text?
Example TCFGBGrid:
+---------+------------+
| UserId  |  UserName  | <- Column titles
+---------+------------+
|[987654] | [        ] | <- Search bar (searching for UserId 987654)
+---------+------------+
| 123456  |  Wile Cau  | <- Data
+---------+------------+
|   ...   |    ...     | <- More data

If UserId 987654 doesn't exist, I want to prompt something like "Create new user 987654?" and potentially create a new record with UserId set to 987654.

A: TCRDBGrid  is distributed with source code. You can modify source code:
declare the event type:
  TOnTextChanged = procedure (Sender: TObject; Text: string) of object;

add event declaration in the TCRGridTitleEdit class:
private
    FOnFilterChanged: TOnTextChanged;
    FOnSearchChanged: TOnTextChanged;

public
    property OnFilterChanged: TOnTextChanged read FOnFilterChanged write FOnFilterChanged;
    property OnSearchChanged: TOnTextChanged read FOnSearchChanged write FOnSearchChanged;

call this event in the ProcessEdit procedure:
procedure TCRGridTitleEdit.ProcessEdit;
begin
  if (FActiveColumn = nil) or (CRDBGrid = nil) or not FEdit.Modified then
    Exit;

  if FAsFilter then
    with CRDBGrid do begin
      try
        TCRColumn(FActiveColumn).GetFilterExpression(FEdit.Text);
        FFilterExpressions[FActiveColumn.Index] := FEdit.Text;
        Self.Caption := FFilterExpressions[FActiveColumn.Index];
        if Assigned(FOnFilterChanged) then
          FOnFilterChanged(self, FEdit.Text);
      except
        on EConvertError do begin
          FEdit.SelectAll;
          raise;
        end;
      end;
    end
  else
    try
      with FActiveColumn.Field do
        DataSet.Locate(FieldName, {$IFDEF CLR}Variant{$ENDIF}(FEdit.Text), [loCaseInsensitive,loPartialKey]);
      if Assigned(FOnSearchChanged) then
        FOnSearchChanged(self, FEdit.Text);
    except
      on EConvertError do
        Exit;
    end;
end;

and add event declaration in the TCRDBGrid class:
private
  function GetOnFilterChanged: TOnTextChanged;
  procedure SetOnFilterChanged(Value: TOnTextChanged);
  function GetOnSearchChanged: TOnTextChanged;
  procedure SetOnSearchChanged(Value: TOnTextChanged);

published
  property OnFilterChanged: TOnTextChanged read GetOnFilterChanged write SetOnFilterChanged;
  property OnSearchChanged: TOnTextChanged read GetOnSearchChanged write SetOnSearchChanged;

implementation
function TCRDBGrid.GetOnFilterChanged: TOnTextChanged;
begin
  Result := CRGridTitleEdit.OnFilterChanged;
end;

procedure TCRDBGrid.SetOnFilterChanged(Value: TOnTextChanged);
begin
  CRGridTitleEdit.OnFilterChanged := Value;
end;

function TCRDBGrid.GetOnSearchChanged: TOnTextChanged;
begin
  Result := CRGridTitleEdit.OnSearchChanged;
end;

procedure TCRDBGrid.SetOnSearchChanged(Value: TOnTextChanged);
begin
  CRGridTitleEdit.OnSearchChanged := Value;
end;


text:
Q: A locally injection is an injection? Let $X$ be a (path-)connected space, and $f:X \rightarrow Y$ is a continuous mapping, if for any $x\in X$, there exist a neighbourhood $U$ of $x$, such that $f$ is an injection on $U$, then $f$ is an injection (on $X$).
Is this right?
Or we need strength the conditon of $X$?
Thanks a lot.

A: No. Consider $f:\Bbb R^2\to \Bbb R^2$ defined by $(x,y)\to e^x(\cos(y),\sin(y))$. Its jacobian never vanishes, so $f$ is a local diffeomorphism (in particular, it's locally injective), but it's not globally injective.


text:
Q: How to group array based on multiple keys conditionally? I have a simple issue grouping conditionally.
const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

I want to group the array by day & code BUT if there is both A & B for one day then only B stays

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

// I want to group the array above by day & code BUT if there is both A & B then only B stays

const aOutput = [
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"}]

A: You could do something like this using reduce:
Create an accumulator with each date as key. If the accumulator doesn't have the current date in context or if the current object has the preferred code, then add the object as value.
(Added an additional A code object to demonstrate)

const aInput = [
 {"date":"2018/9/10", "code":"A"},
 {"date":"2018/9/10", "code":"B"},
 {"date":"2018/9/11", "code":"B"},
 {"date":"2018/9/11", "code":"B"},
 {"date":"2018/9/12", "code":"A"}]

const preferredCode = "B";

const merged = aInput.reduce((r,{date, code}) =>{
  if(!r[date] || code === preferredCode)
      r[date] = {date, code};

  return r;
},{})

const final = Object.values(merged)

console.log(final)

The above code assumes that there are only 2 codes. If you have more than 2 codes and you want to get all the unique codes per day unless there is a B, then you can do the following using reduce and some

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/12", "code":"A"},
{"date":"2018/9/12", "code":"C"}]

const preferredCode = "B";

const merged = aInput.reduce((r,{date, code}) =>{
  r[date] =  r[date] || [];

  if(code === preferredCode)
    r[date] = [{date, code}]
  else if(!r[date].some(e => e.code === preferredCode || e.code === code))
    r[date].push({date, code})

  return r;
},{})

const final = [].concat.apply([],Object.values(merged))

console.log(final)

A: You can group by code in this array by using .reduce

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

const result = aInput.reduce((r, a) => {
  r[a.code] = [...r[a.code] || [], a];
  return r;
}, {});

console.log(result)


text:
Q: yargs doesn't receive any arguments I am trying to write a subcommand using yargs that takes in an argument, and following the documentation to the letter. However, the command itself acts like it doesn't receive any arguments, instead just using the default.
main.js:
require('yargs')()
    .commandDir(path.join(core.ROOT, 'cmds'), { extensions: ['cmd.js'], recurse: true })
    .wrap(null)
    .help()
    .alias('help', 'h')
    .version(false)
    .parse();

command.cmd.js:
module.exports = {
    command: 'my-command',
    desc: `Does something`,
    builder: {
        date: { type: 'string', alias: 'd', default: '' },
        start: { type: 'string', alias: 's', default: '' },
        end: { type: 'string', alias: 'e', default: '' },
    },
    async handler(argv) {
        console.log(require('util').inspect(argv, { depth: null }));
        ...
    }

The output for argv is:
  _: [ 'my-command', '2021-01-01', '2021-12-31' ],
  env: 'dev',
  date: '',
  d: '',
  start: '',
  s: '',
  end: '',
  e: '',
  '$0': 'src/main.js'
}

A: In your code you aren't providing the user arguments,
require('yargs')()

.parse();

You probably want to provide process.argv.slice(2). like so:
require('yargs')(process.argv.slice(2))
...
.parse();

Not sure how you were able to verify the argv though, with the code you provided, it should always only give:
{ _: [], '$0': 'some_string' }

So maybe you did provide the arguments, and just forgot to show it in your example code.

The argv output had the dates as positional arguments:
{ _: [ 'my-command', '2021-01-01', '2021-12-31' ], ... }
It seems like you are trying to make those positional arguments as values for argv.start and argv.end. But you aren't telling yargs how to interpret positional arguments.
It should look something like this:
module.exports = {
    command: 'my-command [start] [end]',
    desc: `Does something`,
    builder: y => {
    return y.positional("start", {
        type: "string",
        alias: "s",
        default: ""
    });
    },
    async handler(argv) {
        console.log(require('util').inspect(argv, { depth: null }));
    }
}


text:
Q: Update entity via table view Is it possible to update a value in the entity from the configure cell function?
I want to change the value of an entries attribute if a number is greater than the other. This is what i have so far but it crashes the app with an error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason:
'[<Outgoing 0x7fbcf3141890> setValue:forUndefinedKey:]: the entity Outgoing
is not key value coding-compliant for the key "goingover".'

MY configurecell method:
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    Outgoing *outgoing = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = outgoing.costDescription;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f",[outgoing.amount floatValue]];

    if (self.incomingTotal > self.outgoingTotal) {

        [outgoing setValue:@"no" forKey:@"goingover"];

    }

    if ([outgoing.goingOver isEqualToString:@"yes"]) {
        cell.backgroundColor = [UIColor redColor];
    }else{

        cell.backgroundColor = [UIColor lightGrayColor];

    }

}

A: I presume that in your Outgoing class, which should be a subclass of NSManagedObject, you have not properly defined the attribute goingover with this exact name and type NSString.
Besides, it is a bad idea to update a core data entity in the configureCell method. You should separate your views (cell) and your data (managed object). This method is for configuring the cell, not the data. Instead, before loading any cell, make sure the data is correct (according to the rule you have defined in your if statement.
Finally, it not advisable to store a boolean (true or false) in a string. You should modify your data model to use a boolean. Also, such as simple condition probably does not need to be persisted at all. Just use the if clause to color your cell.


text:
Q: Three-way Mixed ANOVA (BBW) - sig vs no sig interactions, what now? I'm desperately trying to have an answer for this, but no luck so far.
My RQ:

*

*Do students experience increased anxiety prior to their first laboratory (yes)

*Can a short intervention reduce this initial anxiety

*Is there a difference between gender (males vs females) or laboratory experience (Short vs Long)

n ≈ 300 /year.65% females, 35% males.70% attend long laboratory, 30% attend short laboratory
Study design: Anxiety Measure 1 (continuous variable) ---> Intervention ---> Anxiety Measure 2 (same survey) ---> Attend first lab --> Anxiety measure 3 (same survey, post lab)
I figured Three-way mixed ANOVA BBW.

*

*The dependent variable is anxiety score.

*The 1st between subjects factor is gender (two groups: male and female).

*The 2nd between subject factor is lab experience (Two groups, long and short).

*The within-subject factor is time (which has three time points, T1, T2, and T3).

Problem (when I follow Laerd Statistics)

*

*Step 1: Do you have a statistically significant three-way interaction?  -→ No

*Step 2: Do you have any statistically significant two-way interactions? -→ No

*Laerd: If no – you do not have any statistically significant simple two-way interactions – end analysis and write up.

If I listen to Laerd, there is nothing to write. However, by looking for significant simple main effects, however: I found that males reported lower anxiety levels when compared to females at T1 (p = 0.015).
By further looking into simple simple main effects, I found that at T1, males in the longer lab show higher anxiety than females in the longer labs.
And .... at T2, males in the longer lab show higher anxiety than females in the longer labs.
Of course, the most important aspect is overall anxiety (Regardless of gender or laboratory experience) significantly decreased across all three time points (suggesting the intervention works (T2 - T1), and initial heightened anxiety was present (T3 - T1).
My confusion is, if I follow Laerd's stats, I only talk about not having three way interactions and two way interactions... However, as you can see, I have quite a bit of findings.
I am facing this issue across another cohort as well (dif year), where another intervention showed no three way interaction, but a two way interaction. However, according to Laerd, I can't look at simple simple comparisons for some reason.


text:
Q: Automatically Scroll to rendered element after setState in React.js Suppose i have some setState declarations on list items on top of page as follows:
<DropdownMenu >
    <DropdownItem className="channel-setting__btn"
      onClick={() => this.setState({ facebookFields: true, youtubeFields: true })}>All</DropdownItem>

    <DropdownItem
      className="channel-setting__btn"
      onClick={() => this.setState({ facebookFields: true, youtubeFields: false })}>Facebook
    </DropdownItem>

    <DropdownItem
      className="channel-setting__btn"
      onClick={() => this.setState({ facebookFields: false, youtubeFields: true })}>Youtube
    </DropdownItem>

</DropdownMenu>

Is there any way that when ever i click on DropDownItem then whatever the DOM Element has rendered the page automatically scrolls smoothly to that section or wherevever the element has rendered on page, in this cas the Elements are Different forms for facebook and youtube which will render at the very end and far too close to the end of page.

A: You can use scrollIntoView function after componentDidUpdate which is called immediately after render.
Here is a version using ID of the element to be scrolled to. You can also store the refs of the element and do it the react recommended way. (You are not modifying the DOM in anyway)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      media: ''
    }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({
      media: event.target.value
    });
  }
  componentDidUpdate() {
    const element = document.getElementById(this.state.media);

    element.scrollIntoView({behavior: 'smooth'});
  }
  render() {
    return (

        <select value={this.state.media} onChange={this.handleChange}>
          <option value="facebook">Facebook</option>
          <option value="youtube">Youtube</option>
        </select>

Facebook

Youtube

    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
.social-media {
  height: 100vh;
}

#facebook {
  margin-top: 100vh;
}

You might want to check the browser support of scrollIntoView and include a polyfill.

A: There are couple of ways to do this:
One of the way is to listen to the change of state in componentWillReceiveProps lifecycle event as:
componentWillReceiveProps(nextProp, nextState){
   //considering only first case here
   if (nextState.facebookFields== true && youtubeFields ==true){
      setTimeout(function(){
         let objControl=document.getElementById("theIdOfTheElementToBeRendered");
         objControl.scrollIntoView();
      },500)
   }
}

As you see above, I have used setTimeout, because at this time the element is not rendered. The callback function will be called back once the rendering will happen (I assumed a 500ms delay; you can decide yourself).
I have used plain old JS to scroll to the element. Make sure the element has a unique id.
Hope this answer helps you. I am open for discussion. Regards.


text:
Q: How Can I Draw an Arc in Android XML? I want to draw an arc as an Android XML object. I need it to be an xml, not a Drawable I can code programmatically (that'd be too easy!) because I need it for a notification icon.
I know how to code circles and rings, and I can use radius on rectangles to get quarter/half circles fine. However, I can't figure out how to code just any arc (e.g. 30 degrees) in an xml. Is it possible?

A: that XML is still a Drawable resource, while SVG is being called vector & path in there. you can use whatever tool to create vector paths, which then can be used as the pathData. the correct location for such files is src/main/res/drawable-nodpi, here's one example path (and one can put several of them into such a vector):
<?xml version="1.0" encoding="utf-8"?>
<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="500.0"
    android:viewportHeight="500.0"
    android:width="50dp"
    android:height="50dp">

    <path
        android:fillColor="@color/colorAccent"
        android:pathData="M 250 250 A 100 100 0 0 0 450 250 Z"/>

</vector>

the actual know "how to draw an arc" (with the values of the above path):

meanwhile Android Studio even has a "Preview" tab for that:

A: Arc is just like a quarter-circle. So, you need to draw rectangle shape to form an arc.
Below code is to draw an arc using rectangle shape :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size android:height="15dp" android:width="15dp"/>
<solid android:color="@color/darkGray"/>
<corners android:topRightRadius="0dp" android:bottomRightRadius="15dp"/>
</shape>

A: For me, the solution was quite simple. I had to use Figma to create the Arc.
Note: It does not matter whether or not you have prior experience with using Figma or any design tool for that matter. It is a very simple and straightforward process and it takes less than 5 minutes to achieve.

Now, let's get to the good part...

*

*The first step is to download the Figma Desktop app and draw an arc. This short video pretty much summarizes how to draw an arc.

*The second step is to export your arc as an SVG file. Again, this is a straightforward process, this 51-second video summarizes this process.

*The last step is to add the SVG file to Android studio. To do that, go to File > New >Vector Asset and then select Local File in the menu that pops up. All in all, you should see a menu like the one below. Note that the name of my SVG local file is arc.svg.


text:
Q: Setting multiple object attributes at once Is there a way to set multiple attributes of the same object on a single line, similarly to the way one assigns values to multiple variables?
If I can write
a,b,c=1,2,3

I would like to have something like
someObject.(a,b,c)=1,2,3

Having the same effect as
someObject.a=1
someObject.b=2
someObject.c=3

A: First of all you can do the same with object attributes as with other variables:
someObject.a, someObject.b, someObject.c = 1,2,3

Not sure if that is already what you have in mind. If you want to update arbitrary attributes (e.g. in a function) then you could exploit the fact that Python objects store their attributes in a dict, which supports the update() method:
someObject.__dict__.update({"a":1, "b":2, "c":3})

However, this should only be done with care! If one would offer this in a function any attribute of someObject can be changed with that function and even new attributes can be inserted!

A: You can use map to update the attributes of an object with a dictionary of attributes and values.
attrs = {'a': 1, 'b': 2, 'c': 3}

map(lambda item: setattr(someObject, *item), attrs.iteritems())

In Python 3, you need to surround the map call with a list and convert iteritems to items like so.
list(map(lambda item: setattr(someObject, *item), attrs.items()))

A: def setattrs(_self, **kwargs):
    for k,v in kwargs.items():
        setattr(_self, k, v)

Use this function like this:
setattrs(obj,
    a = 1,
    b = 2,
    #...
)

You can also define this function on class, but that would be less generic (i.e. apply only to that class instances).
Another answer mentions __dict__.update and it can be rewritten to get rid of quotes: obj.__dict__.update(a=1, b=2), however i would not recommend using this method: it doesn't work with properties and it might be hard to notice if you migrate from simple attributes to properties. Basically, __dict__ is "hidden" attribute, implementation detail, which you shouldn't use unless you really want to change implementation in some way.

A: attributes = ['a', 'b', 'c']
values = [1, 2, 3]
for attr, val in zip(attributes, values):
    setattr(obj, attr, val)


text:
Q: Multiple \if condition using etoolbox First: I've found "Checking if two conditionals are met" but I don't know how to change it do suit my needs.
Wanted: I have eight different predefined values and I want different definitions of a constant dependnig on the eight values.

\documentclass{article}

\usepackage{etoolbox}
\usepackage{verbatim}

\begin{document}

\noindent Define the following:
\begin{verbatim}
\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}
\end{verbatim}
What I want:
\begin{verbatim}
\cumuA > 75         : \def\quartileC{0}
\cumuA < 75 < \cumuB: \def\quartileC{1}
\cumuB < 75 < \cumuC: \def\quartileC{2}
\cumuC < 75 < \cumuD: \def\quartileC{3}
\cumuD < 75 < \cumuE: \def\quartileC{4}
\cumuE < 75 < \cumuF: \def\quartileC{5}
\cumuF < 75 < \cumuG: \def\quartileC{6}
\cumuG < 75 < \cumuH: \def\quartileC{7}
\end{verbatim}
This should then result in
\begin{verbatim}
\def\quartileC{3}
\end{verbatim}

\end{document}

I guess that etoolbox is the way to go here but (as said before) I don't know how use it properly for this task.

A: In this update I add a second simple no package method. As in the other answers naturally I use \ifdim because I need to compare fixed point numbers.
Let me first point out that your conditions should read \cumuA >= 75,  then \cumuA<75<=\cumuB then \cumuB<75<=\cumuC etc... (i.e. not only strict inequalities).
Notice that TeX has no direct proviso for testing >= or <= : the programmer is suppose to negate the result of testing, respectively < or > thanks to the \else. Or there is \unless from e-TeX (not used in my answer).
In both approaches I arrange things to test only one inequality at each step. First approach, the most simple minded:
\documentclass{article}

\begin{document}

\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}

\def\quartileC{7}%
\ifdim 75pt>\cumuG pt\else\def\quartileC{6}\fi
\ifdim 75pt>\cumuF pt\else\def\quartileC{5}\fi
\ifdim 75pt>\cumuE pt\else\def\quartileC{4}\fi
\ifdim 75pt>\cumuD pt\else\def\quartileC{3}\fi
\ifdim 75pt>\cumuC pt\else\def\quartileC{2}\fi
\ifdim 75pt>\cumuB pt\else\def\quartileC{1}\fi
\ifdim 75pt>\cumuA pt\else\def\quartileC{0}\fi

quartileC: \quartileC
\end{document}

The second approach uses some delimited macros borrowed from code of xint.
\long\def\DOTHIS #1#2\ORTHAT #3{\fi #1}%
\makeatletter
\let\ORTHAT\@firstofone
\makeatother

The advantage of the second approach is to allow also, if desired, the easy definition of an expandable one-parameter macro \mypercentile which will be used as
\edef\quartileC {\mypercentile{75}}

for example. This is added at bottom.

*

*for this I needed to add spaces after each pt from the first posted version, as TeX inserts a non expandable \relax token if not. (This changed nothing to the original functioning, but has to be done if one wants the \mypercentile thing).

*the expandability is in the strongest sense (\romannumeral-`0 will fully expand \mypercentile).
The code:
\documentclass{article}

\usepackage{verbatim}

% MACROS TAKEN WITH NEW NAMES FROM XINT CODE BY JFBU
\long\def\DOTHIS #1#2\ORTHAT #3{\fi #1}%
\makeatletter
\let\ORTHAT\@firstofone
\makeatother

\begin{document}
\noindent Define the following:
\begin{verbatim}
\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}
\end{verbatim}
\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}

What I want:
\begin{verbatim}
\cumuA > 75         : \def\quartileC{0}% I meant \cumuA>=75 here
\cumuA < 75 < \cumuB: \def\quartileC{1}% I want  \cumuA < 75 <= \cumuB
\cumuB < 75 < \cumuC: \def\quartileC{2}% rather: \cumuB < 75 <= \cumuC
\cumuC < 75 < \cumuD: \def\quartileC{3}
\cumuD < 75 < \cumuE: \def\quartileC{4}
\cumuE < 75 < \cumuF: \def\quartileC{5}
\cumuF < 75 < \cumuG: \def\quartileC{6}
\cumuG < 75 < \cumuH: \def\quartileC{7}
\end{verbatim}
This should then result in
\begin{verbatim}
\def\quartileC{3}
\end{verbatim}

I do:
\begin{verbatim}
\ifdim 75pt>\cumuA pt \else\DOTHIS{\def\quartileC{0}}\fi
\ifdim 75pt>\cumuB pt \else\DOTHIS{\def\quartileC{1}}\fi
\ifdim 75pt>\cumuC pt \else\DOTHIS{\def\quartileC{2}}\fi
\ifdim 75pt>\cumuD pt \else\DOTHIS{\def\quartileC{3}}\fi
\ifdim 75pt>\cumuE pt \else\DOTHIS{\def\quartileC{4}}\fi
\ifdim 75pt>\cumuF pt \else\DOTHIS{\def\quartileC{5}}\fi
\ifdim 75pt>\cumuG pt \else\DOTHIS{\def\quartileC{6}}\fi
\ORTHAT{\def\quartileC{7}}%
\end{verbatim}

(The spaces after ``pt'' were added in an edit; they do not matter here but
are useful for expandable wrapper \string\mypercentile).
% EDIT ADDS SPACE AFTER pt TO AVOID TEX INSERTION OF \relax
% (which does not matter here but does in the expanable wrapper
% \mypercentile next)

\ifdim 75pt>\cumuA pt \else\DOTHIS{\def\quartileC{0}}\fi
\ifdim 75pt>\cumuB pt \else\DOTHIS{\def\quartileC{1}}\fi
\ifdim 75pt>\cumuC pt \else\DOTHIS{\def\quartileC{2}}\fi
\ifdim 75pt>\cumuD pt \else\DOTHIS{\def\quartileC{3}}\fi
\ifdim 75pt>\cumuE pt \else\DOTHIS{\def\quartileC{4}}\fi
\ifdim 75pt>\cumuF pt \else\DOTHIS{\def\quartileC{5}}\fi
\ifdim 75pt>\cumuG pt \else\DOTHIS{\def\quartileC{6}}\fi
\ORTHAT{\def\quartileC{7}}%

and I obtain that \texttt{\string\quartileC} has meaning
\texttt{\meaning\quartileC}.

\clearpage

\def\mypercentile #1{%
\ifdim #1pt>\cumuA pt \else\DOTHIS{0}\fi
\ifdim #1pt>\cumuB pt \else\DOTHIS{1}\fi
\ifdim #1pt>\cumuC pt \else\DOTHIS{2}\fi
\ifdim #1pt>\cumuD pt \else\DOTHIS{3}\fi
\ifdim #1pt>\cumuE pt \else\DOTHIS{4}\fi
\ifdim #1pt>\cumuF pt \else\DOTHIS{5}\fi
\ifdim #1pt>\cumuG pt \else\DOTHIS{6}\fi
\ORTHAT{7}%
}

\edef\quartileC{\mypercentile{75}}
\edef\quartileB{\mypercentile{50}}
\edef\quartileA{\mypercentile{25}}

\ttfamily

\string\quartileC{} has meaning \meaning\quartileC.

\string\quartileB{} has meaning \meaning\quartileB.

\string\quartileA{} has meaning \meaning\quartileA.

\end{document}

\def\mypercentile #1{%
\ifdim #1pt>\cumuA pt \else\DOTHIS{0}\fi
\ifdim #1pt>\cumuB pt \else\DOTHIS{1}\fi
\ifdim #1pt>\cumuC pt \else\DOTHIS{2}\fi
\ifdim #1pt>\cumuD pt \else\DOTHIS{3}\fi
\ifdim #1pt>\cumuE pt \else\DOTHIS{4}\fi
\ifdim #1pt>\cumuF pt \else\DOTHIS{5}\fi
\ifdim #1pt>\cumuG pt \else\DOTHIS{6}\fi
\ORTHAT{7}%
}

\edef\quartileC{\mypercentile{75}}
\edef\quartileB{\mypercentile{50}}
\edef\quartileA{\mypercentile{25}}

A: The following is an etoolbox implimentation using
\ifdimcomp{<dimA>}{<relation>}{<dimB>}{<true>}{<false>}

quartileC: 3

\documentclass{article}
\usepackage{etoolbox}
\begin{document}

\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}

% \ifdimcomp{<dimA>}{<relation>}{<dimB>}{<true>}{<false>}
\ifdimcomp{\cumuA pt}>{75pt}{\def\quartileC{0}}{}
\ifdimcomp{\cumuA pt}<{75pt}{\ifdimcomp{\cumuB pt}>{75pt}{\def\quartileC{1}}{}}{}
\ifdimcomp{\cumuB pt}<{75pt}{\ifdimcomp{\cumuC pt}>{75pt}{\def\quartileC{2}}{}}{}
\ifdimcomp{\cumuC pt}<{75pt}{\ifdimcomp{\cumuD pt}>{75pt}{\def\quartileC{3}}{}}{}
\ifdimcomp{\cumuD pt}<{75pt}{\ifdimcomp{\cumuE pt}>{75pt}{\def\quartileC{4}}{}}{}
\ifdimcomp{\cumuE pt}<{75pt}{\ifdimcomp{\cumuF pt}>{75pt}{\def\quartileC{5}}{}}{}
\ifdimcomp{\cumuF pt}<{75pt}{\ifdimcomp{\cumuG pt}>{75pt}{\def\quartileC{6}}{}}{}
\ifdimcomp{\cumuG pt}<{75pt}{\ifdimcomp{\cumuH pt}>{75pt}{\def\quartileC{7}}{}}{}

quartileC: \quartileC

\end{document}

Nested conditions allow for an and-like boolean operation.

A: An alteration to Ahmed's answer in Checking if two conditionals are met for numbers to make it work with this case and using "dimensions":

quartileC: 3

\documentclass{article}
\usepackage{catoptions}
\makeatletter
\def\dimtest#1and#2#{%
  \ifdim\dimexpr\cpt@dimlt\cpt@dimgt\cpt@dimeq#1%
    \cpt@removetonnil<=>\cpt@nnil\relax
    \ifdim\dimexpr\cpt@dimlt\cpt@dimgt\cpt@dimeq#2%
      \cpt@removetonnil<=>\cpt@nnil\relax
      \expandafter\expandafter\expandafter\@firstoftwo
    \else
      \expandafter\expandafter\expandafter\@secondoftwo
    \fi
  \else
    \expandafter\@secondoftwo
  \fi
}
\makeatother

\begin{document}

\def\cumuA{33.3}
\def\cumuB{59.5}
\def\cumuC{73.8}
\def\cumuD{83.3}
\def\cumuE{88.1}
\def\cumuF{90.5}
\def\cumuG{97.6}
\def\cumuH{100}

\dimtest \cumuA pt>75pt and 0pt=0pt {\def\quartileC{0}}{}
\dimtest \cumuA pt<75pt and 75pt<\cumuB pt{\def\quartileC{1}}{}
\dimtest \cumuB pt<75pt and 75pt<\cumuC pt{\def\quartileC{2}}{}
\dimtest \cumuC pt<75pt and 75pt<\cumuD pt{\def\quartileC{3}}{}
\dimtest \cumuD pt<75pt and 75pt<\cumuE pt{\def\quartileC{4}}{}
\dimtest \cumuE pt<75pt and 75pt<\cumuF pt{\def\quartileC{5}}{}
\dimtest \cumuF pt<75pt and 75pt<\cumuG pt{\def\quartileC{6}}{}
\dimtest \cumuG pt<75pt and 75pt<\cumuH pt{\def\quartileC{7}}{}

quartileC: \quartileC

\end{document}


text:
Q: Date values from SQL cannot be filtered in EXCEL I created a VIEW in SQL which contains a date column.
The date column is defined as datetime ,I had to use CONVERT (nvarchar.mydate,103) so I can get the following format : dd/mm/yyyy.
Now when I connect from EXCEL to get this data view,I am getting the date as follow :

I want them to be displayed as years so I have to use the Text to columns option and convert them.

The problem that I need to do this every time after I refresh the sheet. Is there a way that I can get the date automatically to be filtered by years.

A: Get the date from SQL without converting it and apply the proper format in Excel.
Otherwise you will have to convert it back from text to number in Excel.


text:
Q: C++ - Pointer to a class method I have to set up a pointer to a library function (IHTMLDocument2::write) which is a method of the class IHTMLDocument2. (for the curious: i have to hook that function with Detours)
I can't do this directly, because of type mismatch, neither can I use a cast (reinterpret_cast<> which is the "right one" afaik doesn't work)
Here's what I am doing:
HRESULT (WINAPI *Real_IHTMLDocument2_write)(SAFEARRAY *) = &IHTMLDocument2::write

Thanks for your help!

A: The pointer to function has the following type:
HRESULT (WINAPI IHTMLDocument2::*)(SAFEARRAY*)

As you can see, it's qualified with it's class name. It requires an instance of a class to call on (because it is not a static function):
typedef HRESULT (WINAPI IHTMLDocument2::*DocumentWriter)(SAFEARRAY*);

DocumentWriter writeFunction = &IHTMLDocument2::write;

IHTMLDocument2 someDocument = /* Get an instance */;
IHTMLDocument2 *someDocumentPointer = /* Get an instance */;

(someDocument.*writefunction)(/* blah */);
(someDocumentPointer->*writefunction)(/* blah */);

A: You need to use a member function pointer.  A normal function pointer won't work, because when you call a (non-static) class member function there is an implicit this pointer referring to an instance of the class.


text:
Q: build substrate pallet get the following fault, how to resolve it? error[E0282]: type annotations needed
--> /Users/apple/.cargo/registry/src/github.com-1ecc6299db9ec823/sp-arithmetic-2.0.0/src/fixed_point.rs:541:9
|
541  |                   let accuracy = P::ACCURACY.saturated_into();
|                       ^^^^^^^^ consider giving accuracy a type

A: The latest Rust nightly is broken for MacOS.
To solve this for Substrate, run the following:
rustup toolchain install nightly-2020-08-23
rustup target add wasm32-unknown-unknown --toolchain nightly-2020-08-23

Then make sure to compile your node with:
cargo +nightly-2020-08-23 build --release


text:
Q: javax.el.PropertyNotFoundException: Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean Do you have any idea why my app throws me this exception:
WARNING: /myProfile.xhtml @71,27 target="#{profileBean.selectedUser}": Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean
javax.el.PropertyNotFoundException: /myProfile.xhtml @71,27 target="#{profileBean.selectedUser}": Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean
---
Caused by: javax.el.PropertyNotFoundException: Property 'selectedUser' not found on type bg.fmi.master.thesis.beans.ProfileBean

When i have this property in my bean:
@ManagedBean(name = "profileBean")
public class ProfileBean implements Serializable {
    private TUser selectedUser = new TUser();

    public TUser getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(TUser selectedUser) {
        this.selectedUser = selectedUser;
    }

The .xhtml code is this:
      <p:dataGrid var="user" value="#{profileBean.userList}">
                            <p:panelGrid columns="2">
        ....
        <p:commandButton id="submit" value="Save changes" actionListener="#{profileBean.editUser()}" >
           <f:setPropertyActionListener target="#{profileBean.selectedUser}" value="#{user}" />
        </p:commandButton>
  </p:dataGrid>

Thanks in advance!

A: I have made a simple project based on your sample code.
<h:form>
    <p:commandButton id="submit" value="Save changes" actionListener="#{profileBean.editUser()}" >
       <f:setPropertyActionListener target="#{profileBean.selectedUser}" value="#{user}" />
    </p:commandButton>
</h:form>

There was no such error as described. Your problem comes from other place. Remove unnecessary bits and try to isolate the problem. You could change the name of the property and see if the error reflects the new name. Make sure you don't have another bean with the same name.


text:
Q: Is it possible to include arguments in slash commands (Discord.js) I am currently trying to build a discord.js bot that links to an NBA api in order to output statistics when requested. I am able to connect to the api and output my results eg. /seasons will output all seasons on record.
What i am now trying to achieve is a command such as /player-stats [player name] which will then output the stats of the requested player but i am unable to find a way to register the argument (players name) along with the command (/player-stats).
Any help would be greatly appreciated.

A: It is possible to add arguments in interaction commands.
If you are new you can use a gui for making slash commands also
https://slash-commands-gui.androz2091.fr/
You can get help from here also
https://www.youtube.com/watch?v=pXehoXnFxPM


text:
Q: SEO for CSS Content and Background URL Images Wondering if search engines will have any issues with pages where all the images are set as background images, and if it will correctly find and index the 'captions' under each picture (ie. the CSS content tag).  I don't really care if search engines find the background images, but I would like to have them index the captions.

A: There is no reason to expect search engines to index any strings in style sheets, whether in content attribute values or elsewhere. So the code snippet in the question will look completely empty to a search engine.
There is no law against processing and interpreting style sheets in search engines, and rumors say that they are doing that to some extent to detect attempts at fooling them (e.g. with text hidden from users with CSS). But there does not seem to be any conceivable motivation for them to extract strings that are used for CSS-generated content.


text:
Q: Better way to break out of while loop? C I need to create a singly linked list based on user input which adds to the front of the list and is based upon user input.  I have completed the program, but I am, for some reason, running a blank on one smaller part with the user input here:
    while(numInput != -1)
{
    cout << "Enter a number: ";
    cin >> numInput;
    if(numInput != -1)
    {
        theList->addToHead(numInput);
    }
}

I know there is a better way to write this even though it does the correct thing.  If I don't have the IF statement within the while loop, it will add "-1" to the list and I don't want that.  So this code works, but I feel it should be written differently.  I messed around with different loops but cannot think of it right now.  Thanks in advance.

A: Could use comma operator, it will be neat.
while(cout << "Enter a number: ", cin >> numInput && numInput != -1)
{
    theList->addToHead(numInput);
}

A: break;

Is that what you are looking for?

A: I think what you meant was:
std::cout << "Enter a number: ";
while (std::cin >> numInput && numInput != -1) {
    theList->addToHead(numInput);
    std::cout << "Enter a number: ";
}


text:
Q: So is it best to use try/catch? When is it best to use try and catch?  I've gotten angry responses when I answered questions using try and catch (some even -1 me...) I Googled it and found this article and also this stackoverflow question.
I give some examples:

*

*I have a drop down list with time zone IDs, when the user selects his time zone I'm updating the database. In other application i'm pulling this the value from the DB and recalculate the user current time and date. There is an option that the data in the DB is misspelled (hardcoded change in the DB or bug). In the conversion method of the date time of the user I'm using try and catch, which some people told me it is wrong!. I could check the value from the DB using for loop but it is costing more for each time I'm converting the date time...

*I have to declare if an XML file is well formatted using this code:
protected bool IsValidXML(string xmlFile)
{
    try
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlFile);
    }
    catch(XmlException ex)
    {
        ///write to logger
        return false;
    }
    return true;
}

I can't see any other way to check the xml file.

*Sometime I have a part on my application I'm writing to a file. writing to a file can cause exeprtion for many reasons , some other process is using this file while writing or other. so usually I'm using this code:
 using (StreamWriter w = new StreamWriter(fs))
 {
     try
     {
         w.Write("** (Line) " + someValue + " **" + Environment.NewLine);
         w.Flush();
     }
     catch(IOExeption ex){}
     finally
     {
         w.Close();
     }
 }

In conclusion I see some ways to use try and catch and ways to not use. The one sentence in the article I saw said If an exception happens, you need to know about it. , but when dealing with a generic application most of the times I know that an exception will happened but most of the times I can't really know why it happened so I can't catch it before (like the examples I wrote) , So when is best to use the try and catch
In the same level in ASP.NET the page has an Error event that you can catch like so:
this.Error += new EventHandler(Page_Error); //this = instance of System.Web.UI.Page

Is the event is the same as try catch problem??

A: How you handle an exception depends on the nature of the exception, and on the context in which it occurs.
Smart people have written excellent articles about the subject, and I certainly can recommend:

*

*How to Design Exception Hierarchies by Krzysztof Cwalina

*Vexing exceptions by Eric Lippert

*API Design Myth: Exceptions are for "Exceptional Errors" by Krzysztof Cwalina

About your examples:
In case 1 you might indeed want to be defensive. But then make sure that you do something sensible in that catch block.
Case 2 looks reasonable, but you're reading the XML document only to throw it away. Would it no make more sense to also process it?
In Case 3 you are using try finally, which is definitely not the same thing as try catch. In your specific example you don't even need it, as the using statment is already making sure the file will be closed.

A: From a personal perspective I've always assumed that whatever can go wrong, will go wrong and write my exception handling strategy accordingly.  One of my major bugbears with others code is when you get an unhandled exception that could easily have been trapped - it looks messy an if it is production code then it shows a complete lack of knowledge of how your program works and the things that might go wrong.
My approach might be overkill, but if something you are doing can throw an error then it should be trapped.  I'm not a huge fan of letting exceptions cascade through the stack and being caught at the top level - I'd prefer to trap them at source, log them and then, if the application allows it continue, or at worst fail gracefully and leave the user (or other developers) understanding what has gone wrong or why.
With web applications we use a slightly different approach.  The error (stack trace etc) is logged, so that authorised people can see it and the user is given a cut-down version of the error which tells them something has gone wrong but not the specifics.
Thats my two pence anyway.  I'm not sure if the approach is right or wrong, but it works for us and helps us to produce more robust code.

A: The criticisms of your use of try/catch in this answer were not against using try/catch in general, but against that particular way of using it.

*

*You should capture the exception object (i.e. use catch(SomethingHappenedException e) so you get the available information about what went wrong.

*You should catch specific exceptions rather than everything. In the DateTime example, I would try to find what exceptions might be thrown by each of my calls. I would then try and figure out if there was some way of trapping these errors without using exceptions - one of the exceptions that might be caught in that code is a ArgumentNullException. That's an exception, but I should be able to handle that within the flow by first checking that I'm not passing a null zone id.
Finally, if it's not possible to handle those cases within the normal flow of the program, I catch specific exceptions that might plausibly occur, and as closely to the source of the exception as possible.
It might seem a bit more effort but it does save you on debugging time down the road!

A: For example 1, it would be helpful to see code. It's hard to comment without a more concrete idea of what you're doing.
For example 2, the problem with that code is that it completely hides any error condition. Sure, we'll find out if an xml file is good or bad... but why is the xml good or bad? We can't know. It's not that try/catch is bad: it's that the whole thing is being written at the wrong level. Just write code to read the xml file, and have your error handling around that code.
For example 3, you are again swallowing any helpful exception information, and in fact not doing anything with your try/catch at all. The .Close() call in your finally blocks is completely unecessary, because closing your stream is entirely handled when the stream is disposed by the using block.
In summary, I think what you need to learn here is not that try/catch blocks are bad. It's that swallowing exception information is bad.

A: I think I can sum up the issues people have had in the past with your questions on try...catch, as well as provide some clarity that should help you in the future.
Your first two examples are caused by data validation errors. The data should be checked for known validation errors before being passed to the conversion function (example 1) or trying to write an XML file (example 2).
There is significant overhead in exception handling, so it should only occur when absolutely necessary. The try...catch pattern is designed for handling unexpected (exceptional) errors, not standard data validation.
Example 3 is almost proper usage. It is a situation where there are unexpected things that may occur that you cannot be prepared for, like an IOException. Catching a specific exception is considered bad form as it can lead to multiple catch blocks or missed handling. Catching the generic Exception object is better, and the exception handling code can determine and deal with the exact type of exception.
Your try...catch block should encapsulate the streamwriter as well, since it is best practice to only have one try...catch per method. If you use try...catch, it must always contain exception handling code. Empty catch blocks or empty finalize blocks are bad form and are not helping the code or anyone who is trying to maintain it after you.
    try
    {
       using (StreamWriter w = new StreamWriter(fs))
       {

           w.Write("** (Line) " + someValue + " **" + Environment.NewLine);
           w.Flush();
       }
    }
    catch(Exception ex)
    {
        //exception handling code here
    }
    finally
    {
       //any clean up code here. The using statement makes it unnecessary for the streamwriter
    }

Hope all of this helps answer some questions and bring some clarity to the issue.

A: In my experience, any external operations (such as interacting with a db or file system, or using 3rd party components) should have a try catch block around it. In my own code, I always try to put in guard clauses to methods to limit the number of exceptions my own code produces, if for example you know that the database won't accept a null First name on a person object, add a guard clause should be added to the top of any save method.
In short, don't rely on exceptions to tell you where your code is going wrong, rather try to cut down the likelyhood of an exception first


text:
Q: Upload Image from front-end and get its url hi i am upload file from front-end but now code get only image attachment id i want get image url.
   function agp_process_woofile($file, $post_id){

     if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attachment_id = media_handle_upload($file, $post_id);

  add_post_meta($post_id, '_file_paths', $attachment_id);

  $attachment_data = array(
    'ID' => $attachment_id,
    'post_excerpt' => $caption
  );

  wp_update_post($attachment_data);

  return $attachment_id;

}

See attachment_id i want get url from this function and update that url to "_file_paths" post meta

A: For upload image in frontend just create simple post form
<form method="post" enctype="multipart/form-data">
<input type="file" name="imagefile" />
<input type="submit" name="Submit" value="Submit" />
</form>
After submit form upload image as attachment in wordpress media as below.
if($_POST){
if (!function_exists('wp_generate_attachment_metadata')){
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if($_FILES)
{
    foreach ($_FILES as $file => $array)
    {
        if($_FILES[$file]['error'] !== UPLOAD_ERR_OK){return "upload error : " . $_FILES[$file]['error'];}//If upload error
        $attach_id = media_handle_upload($file,$new_post);
        echo wp_get_attachment_url($attach_id);//upload file URL
    }
}
}

A: hi found solution so sharig with you guys :)
function agp_process_woofile($files, $post_id, $caption){

  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attachment_id = media_handle_upload($files, $post_id);

 $attachment_url = wp_get_attachment_url($attachment_id);
  add_post_meta($post_id, '_file_paths', $attachment_url);

    $attachment_data = array(
    'ID' => $attachment_id,
    'post_excerpt' => $caption
  );

  wp_update_post($attachment_data);

  return $attachment_id;

}

A: Use the default wordpress function wp_handle_upload please refer
http://codex.wordpress.org/Function_Reference/wp_handle_upload
here my example code :
upload.html
<form action="" enctype="multipart/form-data" id="form" method="post" name="form">

<input id="file" name="file" type="file">

<input id="submit" name="submit" type="submit" value="Upload">
</form>

<img id="deleteimg"    src="<?php echo plugins_url( '/images/remove.png'__FILE__);?>">

<?php include "Function /upload.php";?>

upload.php
<?php
include_once ABSPATH . 'wp-admin/includes/media.php';
include_once ABSPATH . 'wp-admin/includes/file.php';
include_once ABSPATH . 'wp-admin/includes/image.php';
require_once (ABSPATH . 'wp-includes/pluggable.php');
if (isset ( $_POST ['submit'] )) {
    if (! function_exists ( 'wp_handle_upload' ))
        require_once (ABSPATH . 'wp-admin/includes/file.php');
    $uploadedfile = $_FILES ['file'];
    if (! empty ( $uploadedfile ['name'] )) {
        $upload_overrides = array (
            'test_form' => false
        );
        $movefile = wp_handle_upload ( $uploadedfile, $upload_overrides );
        if ($movefile) {
            echo "File is valid, and was successfully uploaded.\n";
        } else {
            echo "Possible file upload attack!\n";
        }
    } else {
        echo "Please select the image to upload";
    }
}
?>

upload.js `
 jQuery(document).ready(function() {
     // Function for Preview Image.
     jQuery(function() {
         jQuery(":file").change(function() {

             if (this.files && this.files[0]) {
                 var reader = new FileReader();
                 reader.onload = imageIsLoaded;
                 reader.readAsDataURL(this.files[0]);
             }
         });
     });
     function imageIsLoaded(e) {
         jQuery('#message').css("display", "none");
         jQuery('#preview').css("display", "block");
         jQuery('#previewimg').attr('src', e.target.result);
     };
     // Function for Deleting Preview Image.
     jQuery("#deleteimg").click(function() {
         jQuery('#preview').css("display", "none");
         jQuery('#file').val("");
     });
     // Function for Displaying Details of Uploaded Image.
     jQuery("#submit").click(function() {
         jQuery('#preview').css("display", "none");
         jQuery('#message').css("display", "block");
     });
 });`


text:
Q: I'm writing a book and am wondering what punctuation is invalid for such "statement"? I can't give you the details of the book because I'm currently writing it and it's not something I'd like to discuss. But I'll give you the paragraph here.

ONE moment. That's all it takes for everything to change forever.
  That's all it took to change me forever. After all, isn't that what
  we're all after? Time? We want time, so that we can write our wrongs.
  We want time so that we could turn it all around and make things right
  again, in our lives, or in the lives of those we love. We want time,
  because it's the only thing that tells us the truth. We want time
  because it has the ability to heal us from the damage one moment has
  caused us.

I feel like the commas and some other punctuation are either too much or missing. Is my paragraph missing anything? Is there too much of one thing? Lack of punctuation? How would I properly write that with the correct punctuation?

A: Punctuation can help us read something as if we were hearing it spoken. From that point of view your prose reads well. It sometimes pauses me for a moment's reflection; it sometimes rushes ahead with an appropriate urgency; and it does not unnaturally stop me in the wrong places. Stay with it and trust yourself.


text:
Q: Keyup event fire multipletime Currently, I am working on Angular 4 app. In my component Html, I have one textbox. Whenever user first type anything I want to make an API call to get some data.
The issue is if User type 'A' then it is working fine and calling API. But when user type "ABC" it is making API call 3 times. Instead of making API call for every letter, only one call should be made.
Please suggest any solution.
Component's HTML :
<input id="inputbox" (keyup)="keyUp($event)"/>

Component :
data: string[]

keyUp(event: any) {
this.loadDataApiCall();
}

loadDataApiCall() {
// calling api to load data.
 //fill data into
}

Can I solve this issue with help of RXjs in angular 4

A:  Observable.fromEvent(yourDomElement, 'keyup').auditTime(100).subscribe(()=>{
      doSomething();
    });

A: You should probably add a timeout to your call and clear it every time it is triggered so only the last call is called.
data: string[]

keyUp(event: any) {
    window.clearTimeout(window.apiCallTimeout);
    window.apiCallTimeout = window.setTimeout(this.loadDataApiCall, 100);
}

loadDataApiCall() {
// calling api to load data.
 //fill data into
}

This means of course that the call will be done 100ms after the user stops typing. Also if he types "a" and after a while he types "bc", then two calls will be made. Of course you can increase the delay to meet your requirements.

A: If you only want one API call you can use the blur event, which is emitted when the control loses focus:
<input id="inputbox" (blur)="keyUp($event)"/>

A: Try this:
keyUp(event: any) {
this.loadDataApiCall();
event.stopImmediatePropagation();
}

A: the right way to implement this is by registering the event and calling the API after sometime while saving the latest value and checking that the last registered value matches the latest registered value
so in your keyup
keyUp(event: any) {
  this.latestValue = event.target.value;
  this.registerApiCall(event.target.value);
}

register func
 registerApiCall(value){
      setTimeout(this.loadDataApiCall.bind(this), 500, value)
    }

api call
loadDataApiCall(value) {
  if (this.latestValue == value ){
    // calling api to load data.
    //fill data into
  }
}

see working example in this plnk
EDIT:

Observable.fromEvent(yourDomElement, 'keyup').auditTime(100).subscribe(()=>{
        doSomething();
      });

by 陈杨华 is the RxJs implementation that looks much better, and here is a working plnkr

A: If you're willing to change your form to Reactive Forms this would be extremely easy
this.form.get("input").valueChanges.debounceTime(1000).subscribe((value) => {});

Reactive Forms gives you access to observables of value changes and status changes. We're basically subscribing to that observable which emits the value any time it changes and we add a delay of one second so that if the user is still typing and changing the value then it will not execute the code in our subscribe.

A: @Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="text" (keyup)='keyUp.next($event)'>
    </div>
  ,
})
export class App {
  name:string;

  public keyUp = new Subject<string>();

  constructor() {
    const subscription = this.keyUp
      .map(event => event.target.value)
      .debounceTime(1000)
      .distinctUntilChanged()
      .flatMap(search => Observable.of(search).delay(500))
      .subscribe(console.log);
  }
}


text:
Q: Dropwizard to Micrometer migration (MetricRegistry & ConsoleReporter) I had an old project I am trying to migrate to micrometer that I previously set with Dropwizard metrics which essentially followed this getting started tutorial https://metrics.dropwizard.io/4.2.0/getting-started.html
Naturally Everything else in my code has moved perfectly, all my other classes were similar, but it seemed two classes, MetricRegistry and ConsoleReporter are not part of the Micrometer family... And the code is identical to that tutorial link I just shared.
Any advice or links to make the migration to micrometer for these two classes? I'd like to change as little as possible in the process of course. Just two classes and the MetricRegistry meter function of Dropwizard https://javadoc.io/doc/io.dropwizard.metrics/metrics-core/4.1.0-rc2/com/codahale/metrics/MetricRegistry.html#meter-java.lang.String-com.codahale.metrics.MetricRegistry.MetricSupplier- as you can see in use for the tutorial too

A: I'm not 100% sure what you are doing but Micrometer has a MeterRegistry but you might be already aware of that.
I don't recommend writing metrics to logs but you can take a look at LoggingMeterRegistry if you really want to.


text:
Q: How to define in an API, since which version a path/parameter is supported We have an growing swagger API/openAPI and for documenting changes we like to document on a path or parameter (and perhaps definition) since which version of the API it is available.
The swagger specification knows the info.version field, but on paths or parameters I could not find something refering to this version.
Perhaps vendor extensions beginning with a x-... like x-since might be helpful. At least validation does not fail using them.
But is there perhaps any existing implementation for this use case?

A: I'm not aware of any existing attribute in OpenAPI/Swagger 2.0 spec to meet your need so you should go with vendor extensions (x-since, x-created-on, x-created-by, etc)


text:
Q: Field authenticationManager in service.SecurityServiceImpl required a bean of type 'org.springframework.security.authentication.AuthenticationManager' I am new to Spring Boot and trying to implement whatever I've learned from this link:
login-registration-feature.
My aim is to build a user login and registration feature but i'm stuck with this error:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field authenticationManager in com.x.assignment.auth.service.SecurityServiceImpl required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.

My folder structure, code is same as the one mentioned in the link. But couldn't figure out why @AutoWired is not working. Please help me. Thank you.

A: In the configuration class WebSecurityConfig add bean directly:
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}


text:
Q: How can I create a loop for these if statements? This is what I have achieved without a loop, which is ugly. I'm sure this can be done with a loop without having the repetitive statements:
def my_function(my_list_of_words):
    _digits = re.compile('\d')
    to_return = []

    for i, p in enumerate(my_list_of_words):
        new_list= []
        if 'start' in p:
            if bool(_digits.search(my_list_of_words[i+1])):
                new_list.append(p)
                new_list.append(my_list_of_words[i+1])
                if bool(_digits.search(my_list_of_words[i+2])):
                    new_list.append(my_list_of_words[i+2])
                    if bool(_digits.search(my_list_of_words[i+3])):
                        new_list.append(my_list_of_words[i+3])
                to_return.append(" ".join(new_list))

    return to_return

This works fine, but I don't know how many strings with numbers there will be after "start".
I want a loop that will continue looking for numbers in the list of strings, until the next index doesn't have a number.
I tried this:
def my_function(my_list_of_words):
    _digits = re.compile('\d')
    to_return = []

    for i, p in enumerate(my_list_of_words):
        new_list= []
        count = 1
        if 'start' in p:
            new_list.append(p)
            while bool(_digits.search(my_list_of_words[i+count])):
                new_list.append(my_list_of_words[i+count])
                ++count
            to_return.append(" ".join(new_list))

    return to_return

This doesn't work for some reason, it seems to loop for ever. I have also tried:
while True:
  if bool(_digits.search(my_list_of_words[i+count])):
    //doo things
    ++count
  else:
    break

This doesn't work for me either, it loops for ever.
Representation of what I'm trying to achieve:
['foo','foo','foo','start', '23', 'a32bc', '43', '332', 'foo', 'start', '23', 'a32bc']

would produce
['start 23 a32bc 43 332', 'start 23 a32bc']

Let's say we have the above list, when we reach 'start', I want to check whether the next has a number, in our case 23, if yes, then check the next for number (contains 32 so true again), keep doing this until the next doesn't have a number.
How can I achieve this with a loop?

A: The Pythonic version of a while True: count++ loop is an iterator, combined with next() function to advance to the next element. When the iterator is exhausted, a StopIteration exception is raised.
Create an iterator for your list (with the iter() function, then use nested loops to advance the iterator as you match:
def my_function(my_list_of_words, _digits=re.compile('\d').search):
    word_iter = iter(my_list_of_words)
    digit_words = None
    results = []
    try:
        curr = next(word_iter)
        while True:
            # scan to the next 'start' value
            while 'start' not in curr:
                curr = next(word_iter)

            # collect digits; curr == start so we advance to the next
            digit_words = [curr]
            while True:
                curr = next(word_iter)
                if not _digits(curr):
                    break
                digit_words.append(curr)
            results.append(' '.join(digit_words))
            digit_words = []

    except StopIteration:
        # out of words, append remaining digit_words if there are any.
        if digit_words:
            results.append(' '.join(digit_words))

    return results

So this skips elements until 'start' is found, then collects entries that have digits, then switches back to finding 'start', etc. until StopIteration is raised by the next() call.
Demo:
>>> my_function(['foo','foo','foo','start', '23', 'a32bc', '43', '332', 'foo', 'start', '23', 'a32bc'])
['start 23 a32bc 43 332', 'start 23 a32bc']

You could replace all the results.append() calls with yield to make this a generator.
Note that I'm assuming there won't be any overlapping sequences; e.g. 'start' will never appear in a word with digits in a contiguous digits section.

A: import re

def my_function(my_list_of_words):
    _digits = re.compile('\d')
    to_return = []

    for i, p in enumerate(my_list_of_words):
        new_list= []
        if 'start' in p and i+1 < len(my_list_of_words):
            if bool(_digits.search(my_list_of_words[i+1])):
                new_list.append(p)
                for j in xrange(1,len(my_list_of_words)-i):
                    if bool(_digits.search(my_list_of_words[i+j])):
                        new_list.append(my_list_of_words[i+j])
                    else:
                        break
                to_return.append(" ".join(new_list))

    return to_return

print my_function(['foo','foo','foo','start', '23', 'a32bc', '43', '332', 'foo', "donotmatch66", 'start', '23', 'a32bc', 'start'])

will return
['start 23 a32bc 43 332', 'start 23 a32bc']

A: Here, a simple program to find prime numbers in python which should cover your for loop in  if condition :
def getPrime(X):
    print("The entered number is ",str(X))
    x=int(X)
    if x==1:
        print("1 is treated as speacial charater")
        return False
    for i in range(2,x):
        if x%i==0:
            print("{} is eual to {}x{}".format(x,i,x//i))
            return False
        else:
            print(x, "is a Prime Number")
            return True

print("Please enter number greater than 1 ")
M =input()
m=int(M)
for i in range(2,m):
    getPrime(i)


text:
Q: Android: Able to send/receive files through Socket.IO (AndroidAsync)? Is it possible to send/receive files through a Socket.IO connection using koush's AndroidAsync client?
If there isn't a direct way, any workarounds?
Thanks in advance!


text:
Q: How to make Visual Studio 2010 warn about unused variables? #include <string>

using namespace std;

int main()
{
    string s; // no warning
    int i;    // warning C4101

    return 0;
}

*

*Why does Visual Studio warn me about the unused variable i but not about s in the example?

*I assume that the compiler is not sure about side effects of the string constructor. Is this the reason for not showing a warning?

*Can I somehow enable warnings about unused string variables?

My warning level is set to 4.

A: I hypothesize that compilers only warn about unused variables for trivially constructible/destructible types.
template<typename>
struct Empty
{

};

template<typename T>
struct Trivial : Empty<T>
{
    int* p;
    int i;
};

template<typename>
struct NonTrivial
{
    NonTrivial() {}
};

template<typename>
struct TrivialE
{
    TrivialE& operator=(const TrivialE&) {}
};

struct NonTrivial2
{
    NonTrivial2() {}
};

struct NonTrivialD
{
    ~NonTrivialD() {}
};

int main()
{
    Empty<int> e;      // warning
    Trivial<int> t;    // warning
    NonTrivial<int> n; // OK
    TrivialE<int> te;  // warning
    NonTrivial2 n2;    // OK
    NonTrivialD nd;    // OK
}

Comparison of compilers' treatment
As can be observed, they are consistent.
Since std::string cannot possibly be trivially destructible, the compilers won't warn about it.
So to answer your question: you can't.

A: There is no warning because actually there is no unused variable s. s is an instance of the string class and this class has a constructor which is called upon the declaration string s;, therefore s is used by it's constructor.

A: std::string is not a primitive type, while int is. Non-primitive types have constructors and destructors, which may perform some useful functions: memory management, output to screen and so on, therefore declaration of a non-primitive type does not necessarily mean that the variable is not used. string does not do anything like this, of course, but probably they supress warnings for known types also having in mind that you may come up with the idea of redifining the string behavior (and you can do this by editing some header files since string is based on a template class).


text:
Q: R Run chunk while folded/hidden in Rmarkdown RNotebook I'm struggling to find anything like this on forums or manuals, but I would like to find this feature.
Is there a way to run a chunk in Rstudio while keeping it hidden like below?

This feature would be great when writing documentation/write-up within the same file and testing and updating the code.
As far as I can see, whichever way I run it, it unfolds/shows the chunk contents like below.

Thanks!

A: I found that when setting chunk output in console in settings, then running the chunks via ctrl+alt+R or ctrl+shift+enter or mouse click on the run button keeps them folded while running.
Only setting chunk output inline unfolds the chunks obligatorily it seems.


text:
Q: INI file reverse engineering I am maintaining a legacy application which prints product labels on packaging. The format of the label is stored in a INI file. I wanted to know if anyone has any hints about the meaning of this format. I have pasted a snippet here.
{D1531,1000,1501|}
{C|}
{U2;0130|}
{D1531,1000,1501|}
{AX;+000,+000,+00|}
{AY;+05,0|}
{PC000;0922,0555,15,15,H,11,B|}
{RC00;<FE/>LABELTITLE</FE>|}
{PC001;0865,0555,15,15,H,11,B|}
{RC01;<FE/>CURRENT</FE>|}
{PC002;0796,0040,10,10,H,11,B|}

A: Use the source code. :-)   That will get you somewhere faster than reading the input to a program and trying to deduce the content of the code from the input to that code.

A: This is printer commands for Century Eagle barcode label printer.
jai Ho!


text:
Q: Why can't I connect to localhost port 5000, why does it get refused? I'm trying to build a docker image, but whenever I run the app my connection to localhost gets refused.
The problem does not only occur with port 5000, but also with every else. I'm running the Docker Toolbox on Windows.
My command is :
docker run 5000:80 azure-text

When I curl or just do a docker run, the error message says "Failed to connect to localhost port 5000: Connection refused"
My Dockerfile:
FROM python:2.7-slim

WORKDIR /app_

COPY . /app_

RUN pip install --trusted-host pypi.python.og -r requirements.txt

EXPOSE 80

ENV NAME World

CMD ["python", "app.py"]

Would be happy about advice!

A: If you're using Docker Toolbox you need an additional port forward to connect to localhost. You can the reach docker in another IP. Run this command to see which host is running your docker host:
docker-machine ls

For example, if your docker machine is running on 192.168.99.100, you can access your running service on http://192.168.99.100:5000