Q: JsDoc group multiple @typedef into one configuration file I have a project where I have to define multiple jsDoc's @typedef for describing multiple custom object types required by functions in the project.
I'm wondering if I could group all these @typedef together into a single module/configuration file and reference them project-wide?
Otherwise I would have to write these custom @typedef into multiple modules, and given that most of these have many properties this could create very big comment blocks that makes the modules ugly and difficult to read.


Q: How to run multiple methods parallely and get outputs from each of them in java I want to run three different methods in parallel to improve the performance in Java. Also I need to get the outputs from all the three of them. Below is the sample which I have tried. here, I'm not sure how to retrieve the returned string values. Please help me to add(concatenate all the three strings to total).
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test {

    public static void main(String[] args) {
        String total = "";

        Callable<String> callable1 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t1 = "";
                t1 = method1();
                return t1;
            }
        };

        Callable<String> callable2 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t2 = method2();
                return t2;
            }
        };

        Callable<String> callable3 = new Callable<String>()
        {
            @Override
            public String call() throws Exception
            {
                String t3 = method3();
                return t3;
            }
        };

        List<Callable<String>> taskList = new ArrayList<Callable<String>>();
        taskList.add(callable1);
        taskList.add(callable2);
        taskList.add(callable3);

        ExecutorService executor = Executors.newFixedThreadPool(3);

        try
        {
            executor.invokeAll(taskList);
            //total = ;(want to concatenate all the strings here).

            System.out.println(total);
        }
        catch (InterruptedException ie)
        {
            //do something if you care about interruption;
        }

    }
    public static String method1()
    {
        System.out.println("method1");
        return "1";

    }

    private static String method2()
    {
        System.out.println("method2");
        return "2";
    }

    private static String method3()
    {
        System.out.println("method3");
        return "3";
    }

}

A: As taskList is a List<Callable<String>>, executor.invokeAll(taskList) returns a List<Future<String>> containing a Future<String> corresponding to each task in taskList.  You need to save that List<Future<String>> so that you can later get at the results of your tasks.  Something like this:
List<Future<String>> futureList = executor.invokeAll(tasklist);
String result = futureList.get(0).get() +
                futureList.get(1).get() +
                futureList.get(2).get();

In addition to InterruptedException, Future.get() can also throw CancellationException and ExecutionException so you need to be prepared to deal with these in your try block.

A: As you have very few number of task, you can create 3 CompletableFutures and stream over it and join it.
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> method1());
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> method2());
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> method3());

String concate = Stream.of(task1, task2, task3)
        .map(CompletableFuture::join)
        .reduce("", (s1, s2) -> s1 + s2);
System.out.println(concate);

A: Adding on top of @Govinda answer -
You can create Stream of CompletableFutures by using the supplyAsync factory method and complete them by calling CompletableFuture::join and concat by calling Collectors.joining().
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(Test::method1);
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(Test::method2);
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(Test::method3);

String concat =
    Stream.of(task1, task2, task3).map(CompletableFuture::join).collect(Collectors.joining());

System.out.println(concat);


Q: Prove that there exist a regular covering of the 8 figure of degree at most $n!$
Let $\phi : Y \rightarrow X$ be a $n$-sheet covering of the 8 figure. Prove that there exist $\psi : Z \rightarrow X$ an at most $n!$- sheet regular covering such that the diagram commutes (where $\mu$ is a covering).
$\require{AMScd}$
\begin{CD}
Z @>\mu>> Y\\
@V \psi V V @VV \phi V\\
X @>>Id> X
\end{CD}

(Sorry, but I don't know how to draw diagonal arrows with this code. It should have an arrow $\psi$ from $Z$ to $X$)
I have been thinking of doing this by induction. Assuming the statement true for $(n-1)$-sheeted coverings. We enumerate the $n$ vertices of $Y$.
I want to apply the statement to $Y_1',\ldots, Y_n'$, where $Y_j'$ is $Y$ without the vertex $j$. Here I glue the corresponding arrows arriving and leaving (from the viewpoint of the vertex $j$, $a^{-1}$ continues as $a$ and the same with $b$, where $a$ and $b$ are the arrows that project to each loop in figure 8. If there is any loop in $j$, I simply ignore it).
Each time I will obtain an at most (n-1)!-sheeted regular covering $Z_j$ satisfying the conditions. But I don't see how to glue them to obtain the at most $n\times (n-1)!$-sheeted regular covering.
This idea comes to me just by the numbers involved.
Maybe I should proceed in a different way. Any advice? Thanks


Q: How do i add fabricjs-canvas objects in json format to a indexed array in php? I'm trying to make a database system to handle the saved fabricjs canvases. For every thing to work i need the canvas objects
json=canvas.toDatalessJSON; // in javascript

...to be saved in php as .json file in a indexed array system that allows me to load and add more canvas objects or delete objects.
The thing troubling me is how to actually structuring this. What i'm trying here is something like:
... The json structure i'm considering ...
["1"]{Object:.....}
["2"]{Object:.....}
["4"]{Object:.....} (["3"] deleted in this case)

... Trying to create in php ...
$i="1";
$A=[];
$A[$i]=[];
array_push($A[$i],json_decode($json));
$newjson=json_encode($A);

But this is obviously not the way to make it. Any ideas ?
EDIT 1
Thank's for your answer @Michael. I ended up not using exactly what you propose. But i accept it as the answer that let my to a solution. In my solution i'm adding the index to the object, and unset the index when i'm going to use the object.
Create:
$dataA=array();
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);

Add:
$data0=file_get_contents($filename.'.json');
$dataA=json_decode($data0,true);
$dataB=json_decode($data,true);
$dataB["index"]= $ThumbIndex;
$dataA[]=&$dataB;
$data=json_encode($dataA);
file_put_contents($filename.'.json',$data);

A: Assuming you are trying to overwrite element "1" in your json object using php, try this:
$newjson = json_decode($json, true);
$newjson["1"] = Array();
$newjson = json_encode($newjson);

If you want to add an element:
$newjson = json_decode($json, true);
$newjson[] = Array();
$newjson = json_encode($newjson);


Q: Removing tuples that have the same pair of values from a list I want to remove all the tuples that have the same pair of values, e.g. [(1,1), (2,3), (2,2), (3,4)] I want [(2, 3), (3, 4)]. I am working in Haskell. This is what I tried:
unique [] = []
unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[]

And the output was:
[(2,3)]

I am confused on why (3, 4) did not appear.

A: Because your else case says:
unique [] = []
unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[]
It thus says if fst x is not equal to snd x, then we return x : [] (or shorter [x]), and we are done. So it does not perform recursion on the rest of the list.
We can solve this by adding recursion on the rest of the list, like:
unique [] = []
unique (x:xs) = if fst x == snd x then unique xs else x : unique xs
That being said, we can use a filter here, like:
unique :: Eq a => [(a, a)] -> [(a, a)]
unique = filter (\(x, y) -> x /= y)
or even shorter:
unique :: Eq a => [(a, a)] -> [(a, a)]
unique = filter (uncurry (/=))
We thus retain all elements for which the first element x is not equal to the second element y.


Q: not a valid identifier - bash script error while execution I'm getting following error while I try to capture process ids in my shell script.....
$bash ./restartjbossserver.sh
./restartjbossserver.sh: line 10: `i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}')': not a valid identifier

And this is my script....
for i=$(ps -ef | grep "jboss" | grep -v "grep" | awk '{print $2}')
do
echo $i
if [ $i != NULL ]
then
echo "Killing JBos Process.."
kill -9 $i
echo "Killed Joss Process..."
fi
done

sleep 10s

echo "Deleting JBoss Cache..."

rm -rf /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/domain/tmp/*
echo " Deleted JBoss Cache..."

sleep 10s

nohup /home/cbsmsblapp/opt/EAP-6.3.0/jboss-eap-6.3/bin/domain.sh  & >nohup.out

A: The syntax for iterating over a list is
for i in $( ...

not
for i=$( ...

A: Have a look at the pkill and pgrep commands.  You could just pkill jboss.


Q: Two function in a event on React-Native How to put two function in a event like onValueChange?
I tried with
  onValueChange={(selected) => this.setState({selected}),this.state.eventOnChange}>

A: What about:
onValueChange={(selected) => {
    this.setState({selected});
    this.state.eventOnChange();
}}

A: Component.setState() is asynchronous and may be locked on the second call while it is still doing the first.
Do the second call in a callback like this:
onValueChange=
    { (selected) => {
        this.setState(
            {category:selected},() => {this.filter();} // Add Functions That's you want to call.
        )
    }
}

A: Resolved with the following code:
<TextInput
      style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1, }}

      onChangeText={(text) => this.setState({
        text
      }, () => {
        this._onChangeText();
      })
      }
      autoCorrect={false}
      underlineColorAndroid='rgba(0,0,0,0)'
      value={this.state.text}
    />

Thanks to @pinewood.

A: onValueChange={(itemValue, itemIndex) =>  this.setState({id: itemValue}),this.getOtherFunction }


Q: why shell for expression cannot parse xargs parameter correctly I have a black list to save tag id list, e.g. 1-3,7-9, actually it represents 1,2,3,7,8,9. And  could expand it by below shell
for i in {1..3,7..9}; do for j in {$i}; do echo -n "$j,"; done; done
1,2,3,7,8,9

but first I should convert - to ..
echo -n "1-3,7-9" | sed 's/-/../g'
1..3,7..9

then put it into for expression as a parameter
echo -n "1-3,7-9" | sed 's/-/../g'  | xargs -I @ for i in {@}; do for j in {$i}; do echo -n "$j,"; done; done
zsh: parse error near `do'

echo -n "1-3,7-9" | sed 's/-/../g'  | xargs -I @ echo @
1..3,7..9

but for expression cannot parse it correctly, why is so?

A: Because you didn't do anything to stop the outermost shell from picking up the special keywords and characters ( do, for, $, etc ) that you mean to be run by xargs.
xargs isn't a shell built-in; it gets the command line you want it to run for each element on stdin, from its arguments.  just like any other program, if you want ; or any other sequence special to be bash in an argument, you need to somehow escape it.
It seems like what you really want here, in my mind, is to invoke in a subshell a command ( your nested for loops ) for each input element.
I've come up with this; it seems to to the job:
echo -n "1-3,7-9" \
| sed 's/-/../g'  \
| xargs -I @  \
bash -c "for i in {@}; do for j in {\$i}; do echo -n \"\$j,\"; done; done;"

which gives:
{1..3},{7..9},

A: Could use below shell to achieve this
# Mac newline need special treatment
echo "1-3,7-9" | sed -e 's/-/../g' -e $'s/,/\\\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash
1,2,3,7,8,9,%

#Linux
echo "1-3,7-9" | sed -e 's/-/../g' -e 's/,/\n/g' | xargs -I@ echo 'for i in {@}; do echo -n "$i,"; done' | bash
1,2,3,7,8,9,

but use this way is a little complicated maybe awk is more intuitive
# awk
echo "1-3,7-9,11,13-17" | awk '{n=split($0,a,","); for(i=1;i<=n;i++){m=split(a[i],a2,"-");for(j=a2[1];j<=a2[m];j++){print j}}}' | tr '\n' ','
1,2,3,7,8,9,11,13,14,15,16,17,%

A: echo -n "1-3,7-9" | perl -ne 's/-/../g;$,=",";print eval $_'


Q: Exclude .csproj from VisualStudio 2012 .sln when using Mono Compiler I want to build my VisualStudio 2012 solution (.sln) with Mono, but it cannot compile projects that rely on VisualStudio-specific assemblies.  E.g.
xbuild ServerResource.sln
...
HypervResourceControllerTest.cs(18,17): error CS0234: The type or namespace name `VisualStudio' does not exist in the namespace `Microsoft'. Are you missing an assembly reference?

In this case, HypervResourceControllerTest.cs(18,17) is a reference to Visual Studio test tools:
using Microsoft.VisualStudio.TestTools.UnitTesting;

Since I don't need the testing environment to compile, can I tell the Mono compiler to bypass a specific project in a .sln?

A: Create a new configuration, tell xbuild to use it:

*

*In Visual Studio, create a new configuration that excludes the projects you're not interested in. -(Build -> Configuration Manager..., select  on the Active solution platform: drop down list)

*Using the Configuration Manager, remove unwanted solutions from the configuration.

*Next, close VisualStudio, which will save changes to the .sln and .csproj  The .sln will record which projects are associated with the configuration.  The .csproj will record the settings of the configuration, such as whether TRACE or DEBUG is defined.

*Finally, when calling xbuild assign your configuration's name to the Configuration property.
E.g.
xbuild /p:Configuration="NoUnitTests" ServerResource.sln

The above will build the projects associated with the NoUnitTests configuration.


Q: What is -c and nrow doing in this function? What is the purpose of -c and nrow in this function?
bdf <- by(bdf, bdf$Serial_number, function(SN, k) {
                     SN[-c(1:k, (nrow(SN)-k+1):nrow(SN)),]
                     }, k = 10)

by() splits the data frame bdf by the second argument Serial_number and applys the function function(SN, k) in the third argument. I don't understand the body of the function.

A: c() creates a vector. - makes the numbers in the vector negative. The vector is in the "row" position of [, so it is omitting the rows from 1 to k, and from nrow(SN) - k + 1 to the end of the data frame. So it's chopping off the first k and last k - 1 rows of the data frame.


Q: How to create a dijit/Dialog for a specific HTML Div and use Div's elements as its content? Learning from http://dojotoolkit.org/reference-guide/1.9/dijit/Dialog.html, I know how to create dijit/Dialog widget programmatically and dynamically. But now I need to update the implementation of a form within our application which has many inputs. I want to create a dijit/Dialog for the specific DIV, and hope its div elements will be this dialog's elements. How is it possible?

A: Please try the following code. This code, will remove your div node from it's parent. div will be moved into body tag.
dojo.require("dijit.Dialog");

var myDialog=new dijit.Dialog(
    {
        title:"Dialog Title",
        content:dojo.byId("divNodeID")
    }
);

myDialog.show();

Hope this helps you. Thanks!

A: If you surround your  with the HTML that will create a Dialog, it should work.
For example, if your code is:
<form>
   ... some HTML ...
</form>

then consider coding:
<div data-dojo-type="dijit/Dialog" data-dojo-id="myDialog" title="MyTitle">
   <form>
      ... some HTML ...
   </form>
</div>


Q: Is there a Rails gem for management of a "multi-visit pass" scenario? I'm a Rails noob. I'm looking to implement an application where users can purchase a multi-visit pass, then spend the credits week-by-week.
For example, register and login, then purchase 10 visits at a gym - the system should list 10 remaining visits. Sign up to a class and 9 remaining visits are listed. When the credits are low, remind the user to top them up with another 10-visit pass, etc.
I know I can use Devise and CanCan to manage the authentication and authorisation aspects.
My question is whether there's already a gem to handle the management of the user's credits, or whether I'd need to write this from scratch.
I've searched https://rubygems.org/gems/rails with no luck, but it's entirely possible I'm missing something obvious.

A: I don't think there is a gem to do that, but it should be pretty simple to code:

*

*Add remaining_visits to your User model and table.

*Do current_user.update(remaining_visits: current_user.remaining_visits+10) when a ticket is purchased.

*Copy Devise sessions controller into app/controllers/devise/sessions_controller.rb.

*Inside this controller, add this kind of code to create (where the user logs in): current_user.update(remaining_visits: current_user.remaining_visits-1).

Note: Instead of copying Devise sessions controller you can just overwrite the create action.


Q: Migrating from "MSSQL Server" To Another SQL Server I have an application that requires this older version of "MSSQL Server".
Is there any chance I could seamlessly upgrade the DBMS to another (preferably free) product?
It's having alot of "Out of hard drive space" messages and the application that uses it is crashing more and more.
Thanks for the advice!

A: Besides the comment from GregD, it maybe the host that is out of space.
You could update your question with the following information:

*

*SQL Server Version?

*Host HDD Partitioning and drive space?

*Size of the SQL Server data files and log files?

*Maintenance plans that you have?

It may just be that you need to truncate your log file if you are using a simple recovery method.
As for moving to a more modern SQL version, you will need to setup a test lab first then try the application against SQL Expr 2005 or 2008. I would also put the database into compatibility mode to ensure even more compatibility.
You may be in a position where you cant put the app against another version as it may be using stored procedures or views that only exist in the MSSQL Server version that it is linked to.
If you can't upgrade the database and you are indeed having resource issues you would need to investigate the following:

*

*Upgrade the system by adding more HDD space

*Add a small SAN to the site and attach to the system. Move the SQL Database to the SAN for improved performance

*Upgrade the system by replacing the metal that it runs on

*Consider consolidating the service by thinking about Virtualisation if excessive IO/Memory is not required

After you have done analysis and have some factual data in front of you can you then start making recommendations to the appropriate persons on how best to move forward and ensure this resource is available for the foreseeable future.

A: So, if you never back up an SQL Server it uses space endlessly as the transaction logs grow and grow.  Have you tried backing it up?  A backup causes a checkpoint, which lets SQL server know it doesn't need to keep certain transaction log files.
You might need to back it up to a remote system if the drive is too full.  Remember, the backup will be written by the Windows account that SQL is running as, not your user account - so that user needs to have access to the network share you are attempting to back up to.
For your reference:
http://technet.microsoft.com/en-us/library/ms189085.aspx
There are other reasons for MSSQL file growth, of course, including insertion of data. ;)  If that's not it however, you can look at things like transactions that aren't ever committed.
The answer to your stated question about changing from MSSQL to some other platform is that it depends.  If you are referring to an app that already supports multiple DB back ends, then it can be as easy as dumping your data to some universal format, then importing it in to the db platform you prefer, then switching your app to use your preferred DB - but in most cases it is not this simple.  In most cases, the application is tightly coupled to the RDBMS platform and it's not as simple to "change back ends" without re-writing significant parts of the code.

A: Depending on the complexity of your app, you could update it to use SQL Server 2008 Express, which is free.

A: You could probably use SQuirreL  java SQL client to do a export of the db and then import it into another db.   Its a little bit of a learning curve to do that though...  i'd say the transaction log/backup idea is much better...


Q: Evaluate Matlab symbolic function I have a problem with symbolic functions. I am creating function of my own whose first argument is a string. Then I am converting that string to symbolic function:
f =  syms(func)

Lets say my string is sin(x). So now I want to calculate it using subs.
a = subs(f, 1)

The result is sin(1) instead of number.
For 0 it works and calculates correctly. What should I do to get the actual result, not only sin(1) or sin(2), etc.?

A: You can use also use eval() to evaluate the function that you get by subs() function
f=sin(x);
a=eval(subs(f,1));
disp(a);
a =

    0.8415

A: syms x
f = sin(x) ;

then if you want to assign a value to x , e.g. pi/2 you can do the following:
subs(f,x,pi/2)
ans =

1

A: You can evaluate functions efficiently by using matlabFunction.
syms s t
x =[ 2 - 5*t - 2*s, 9*s + 12*t - 5, 7*s + 2*t - 1];
x=matlabFunction(x);
then you can type x in the command window and make sure that the following  appears:

x

x =
@(s,t)[s.*-2.0-t.*5.0+2.0,s.*9.0+t.*1.2e1-5.0,s.*7.0+t.*2.0-1.0]

you can see that your function is now defined by s and t. You can call this function by writing x(1,2) where s=1 and t=1. It should generate a value for you.
Here are some things to consider: I don't know which is more accurate between this method and subs. The precision of different methods can vary. I don't know which would run faster if you were trying to generate enormous matrices. If you are not doing serious research or coding for speed then these things probably do not matter.


Q: Check if feature class exists using FME After reviewing this article: https://knowledge.safe.com/answers/50003/view.html
It is still unclear how to check to see if a feature class exists using FME. I was able to successfully read in the schema of the GDB, but what transformer is best applied to check the schema for a specific feature class name? How would the logic go?

A: First add the Schema (Any Format) Reader.

Next add a Tester Transformer. Connect inspectors to the outputports of the tester, this way the result will popup in a dataviewer called the Inspector.

Configure the Tester Transformer by hitting the cogwheel. Using a GDB as dataformat, fme_feature_type_name represents the Feature Class Name. Enter the Feature Class Name you want to check in the field "Right Value"

Now run the Workspace.

You could also use the AttributeFilter / TestFilter or other Transformers to process the Schema Reader output.


Q: Pyspark: how to read CSV file with additional lines so I am having the following CSV file. It has some additional strings between the valid rows. Excel seems to do a good job when reading those(and just ignores the additional ones).

However, the story with spark is a bit different.

I have set it as spark.read.csv(path, header=True, multiLine=True, sep='|')
Is there some simple way to handle it?


Q: Is there a correct resistance value for I2C pull-up resistors? The datasheet of the 24LC256 EEPROM states that:

The SDA bus requires a pull-up resistor to VCC (typical 10 kΩ for 100 kHz, 2 kΩ for 400 kHz and 1 MHz).

I thought that any resistor with a kΩ value would do the job (and it seems that my EEPROM works fine at different frequencies with a 10 kΩ resistor).
My questions are:

*

*is there a correct value for pull-up resistors ?

*is there a law/rule to determine this value ?

*how do different resistance values affect the I²C data bus ?

A: The correct pullup resistance for the I2C bus depends on the total capacitance on the bus
and the frequency you want to operate the bus at.
The formula from the ATmega168 datasheet (which I believe comes from the official I2C spec) is --
$$\text{Freq}<100\text{kHz} \implies R_{\text{min}}=\frac{V_{cc}-0.4\text{V}}{3\text{mA}}, R_{\text{max}}=\frac{1000\text{ns}}{C_{\text{bus}}}$$
$$\text{Freq}>100\text{kHz} \implies R_{\text{min}}=\frac{V_{cc}-0.4\text{V}}{3\text{mA}}, R_{\text{max}}=\frac{300\text{ns}}{C_{\text{bus}}}$$
The Microchip 24LC256 specifies a maximum pin capacitance of 10pF (which is fairly
typical). Count up the number of devices you have in parallel on the bus and
use the formula above to calculate a range of values that will work.
If you are powering off of batteries I would use values that are at the high
end of the range. If there are no power limits on the power source or
power dissipation issues in the ICs I would use values on the lower end
of the range.
I sell some kits with an I2C RTC (DS1337). I include 4K7 resistors in the kit which
seems like a reasonable compromise for most users.

A: For low frequencies the value doesn't really matter, but for high frequencies it can have a filtering effect on the signal, in combination with other capacitances in the circuit, which is why they recommend different values for different speeds.

A: Minimal resistor value depends on driving capabilities of two sides of the bus. For example they drive 10 mA, so your resistor value should be greater than \$\frac{V_{bus}}{10~mA}\$. It is not exact resistor value, it depends on your bus capacitance. You can check your resistor value whether it is correct or not, by measuring rising time and falling time of bus pulses. You can find these time values in below link:
http://www.cypress.com/knowledge-base-article/rise-and-fall-time-specifications-scl-and-sda-lines-i2c

A: It makes sense that higher frequencies require lower resistance pull-ups: a lower resistance will charge/discharge the cable's capacitance faster, which results in steeper edges. With the wider pulses of lower frequencies a less steep edge won't influence the pulse's shape as much.
Therefore the I2C specification gives maximum values for the pull-up resistors as a function of bus capacitance for three speed classes:

The minimum values are defined in function of the bus voltage, and should limit the current through the drivers.

A: Assuming you want to maximize the speed while keeping the current consumption at minimum. It's pretty easy to calculate the maximum and the minimum resistor values. This is explained in this datasheet.
Bus capacitance
First, we need to know the bus capacitance. It is true that you can make a rough estimate it by adding the pin capacitance of the drivers. However, if you are developing a product, you can assemble a prototype with whatever test resistance and calculate a more accurate value.
In the referred datasheet, the following equation is derived:
$$t_r = t_{0.7V_{CC}} - t_{0.3V_{CC}} = 0.8473 \times R_{P} \times C_b$$
You can measure the rise time on your test set up and plug the highest in to the equation:
$$C_b = \frac {t_{r{Max}}}{ 0.8473 \times R_{P_{test}}}$$
With this value, you can also validate if your system meets the maximum bus capacitance allowed by the specification.
Maximum resistance
After you get the capacitance, you can plug the capacitance back in the equation to get the maximum resistor values for your system:
For standard mode:
$$R_p(max) = \frac {1000ns}{ 0.8473 \times C_b}$$
For fast mode:
$$R_p(max) = \frac {300ns}{ 0.8473 \times C_b}$$
For fast mode plus:
$$R_p(max) = \frac {120ns}{ 0.8473 \times C_b}$$
Minimum resistance
This is the easiest calculation, just divide the maximum bus voltage drop by your maximum target current:
$$R_P(min) = \frac{V_{CC}-V_{OL}(min)}{I_{OL}}$$
Note: In the datasheet they specify VOL(max). I believe it is a typo. In any case, this answer provides a safe quick calculation.

A: There is a correct range of values, however it is difficult to describe exactly what that range is.  Generally, 10k works.
Digital outputs have a specified ability to source or sink current.  If your output could sink 5 mA and the output was connected through a pull-up to 5 V and then set to 0, you would need a minimum of 1k resistance.  If you use less than 1k, the output will not be able to sink enough current to pull the pin all the way down to 0V.  If you use a bigger value, like 10k, then the pin only has to sink 0.5 mA, which is much less than it's rating.
Digital inputs have a specified leakage current.  This is kinda like the amount of current it takes to "maintain" a 0 or 1 at an input.  If your pull-up resistor is too large, then it won't be able to overcome the leakage current.  If it just barely overcomes the leakage current, then any noise in the circuit could be enough to change the input.
When using digital outputs that can sink and source current ("totem pole driver", "push-pull driver"), you might be tempted to not use pull-up or pull-down resistors.  However, it is very important that CMOS inputs not be allowed to float or they can pull excessive current...and it's very easy to forget that bidirectional MCU pins usually come up as inputs!

I2C and other protocols like it use "open drain" (or "open collector") outputs.  Instead of having outputs that can pull up and down, and open drain outputs can only pull down.  That is why the external pull-up resistor is required.  There are now additional restrictions on the range of pull-up resistors; the pull-up value will form an RC circuit with the bus capacitance.  Too small of a value will once again prevent the output drivers from sinking enough current to pull the pin all the way down to 0.  However, too large a value will take too long to charge the bus capacitance up.
If there are setup/hold times that you are not allowed to violate, those will help you determine an RC time constant.  The bus capacitance is largely determined by PCB layout, so you can then pick an R value that combines with the C to provide a value that is comfortably within the setup/hold time for your digital input.

A: Low pull-up values (lower resistance) can improve the edges of the signal transitions but can sometimes be too stiff - if the devices on the bus cannot sink the pull-up current you get logic 'low' which isn't really that low, which can cause communication errors (and much pain.)
I would go with the highest pull-up resistance that gives you reliable communications.

A: if you ask me the best thing is to look at each project with oscilloscope if you think it is critical. You can do the math, but... it is better to measure it :) because impedance (length of lines and so on) have a big factor.
There is a gif animation of effect of different values on my website:
https://small-roar.com/i2c-inter-integrated-circuit/
As you can see too small value results in not detecting of signal - with older MCUS like Atmega it is not a problem because they have high values for "logic low/high" + if you want low power application its not the best way to go.

A: An issue I haven't seen mentioned yet is power consumption.  If one is using a 3.3 volt supply, a 3.3K resistor to ground will waste 1mA of current (3.3mW of power) whenever an output is low.  Using a 10K resistor would reduce both current and power by a factor of three.  If there will be a lot of communication on the I2C bus, that power consumption may end up being a significant portion of overall power drain especially if the bus may sit low for extended periods of time.  For example, if one is reading 100 bytes/second but after reading each byte the bus is left with the device outputting the first bit of the next byte, and most of those bytes are have the MSB clear, the bus may spend 90% of the time with SCL and SDA low.  Depending upon what else the system is doing, that could massively increase power draw.
To save power, it may be helpful to have a "pull-up" resistor connected to an I/O pin rather than to VDD.  While I haven't seen hardware I2C implementations offer support for this, having the master output data on a separate I/O pin that's connected to the bus via resistor rather than using an open-collector driver and a fixed pull-up resistor will avoid wasting current when the master wants to output a "0".  In addition, if the master is going to leave SCK low for awhile without caring about what's on SDA, the master may disable the pull-up until it's ready for some more communication.  If none of the devices need to use clock stretching, the master can simply use a direct output for SCK and not bother with any pull-up on that wire.
If one is using software bit-banging with a fast processor, and one wants to get good performance despite high bus capacitance, the above approach can be combined with the use of a processor's built-in weak pull-ups.  When reading data, turn on a very strong pull-up, briefly, immediately after each falling edge of SCK, and then switch to a weak pull-up.  The strong pull-up will pull the line high despite the capacitance, and once the line is pulled high the weak pull-up will be able to keep it high.  Even if a device would have trouble pulling the line low against the strong pull-up, it would be able to do so once the strong pull-up is switched off.

A: Regarding the first two questions I believe they were aduately answered.
Regarding the third:
As others mentioned, pull-up values along with cable capacitance play a big role both in whether your devices are recognized and the speed you are able to achieve as they effectively form a low-pass filter.
For a recent project I had to drop the pull-up resistors value very low (510Ohms) to run a 50m I2C bus over plain old flat telephone cable at 5v. This is well out of I2C specs (min ~1,5KOhms pull-ups for 5V at 3mA) but it works.

A: According to the I2C bus specification The I2C pull up resistor value mainly depends on the I2C mode (Standard / Fast / Fast Plus / HS), VDD and the bus capacitive load.
It's minimum value is calculated using the following equation:
Rpmin = (VDD – VOLmax) / IOL
Where:

*

*VDD: Power supply voltage

*VOLmax: Maximum LOW-level output voltage

*IOL: LOW-level output current

While, it's maximum value is calculated using the following equation:
Rpmax = tr / 0.8473 x Cb
Where:

*

*tr: Maximum rise time of signal ( SDA / SCL / SDAH / SCLH)

*Cb: Maximum capacitive load for bus line

I have built an online tool for sizing the pull up resistor at different bus modes. You can access it here.


Q: How to test redirect to created instance in Flask Having following function in  views.py:
def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

How can I get an id of created model to put it in assertion?
def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

I'm using Flask, Flask-SQLAlchemy, Flask-Testing

A: Query the created question object. As a side effect, you can test that the question was created.
...
q = Question.query.filter_by(title='What about somestuff in Flask?').first()
self.assertRedirects(response, '/questions/%d/' % q.id)


Q: uniform convergence sequence The sequence of function $\{f_n\}$ defined on $\mathbb{R}$, every  function is decreasing function (if $x \geq y$ then  $f_1(x)\geq f_1(y)$, $f_2(x)\geq f_2(y)$,.......) and sequences of function is decreasing function  ($f_n\geq f_{n+1}$) and $\{f_n \}$ converges point wise.
Then  $f_n$ converges to $f$  uniformly.
Example :
$f_n(x)=x+\frac{1}{n}$  , $n=1,2,3$..... defined on $(-\infty , 0]$. This sequence of function is uniformly convergence
My assumption is correct.

A: Perhaps one should first recall that one cannot prove that a statement holds simply exhibiting a case where it holds. Here, to exhibit a sequence $(f_n)$ such that all the hypotheses hold and such that $f_n\to f$ uniformly proves nothing about the validity of the general statement.
...Which happens to be false, as a single counterexample is enough to prove. Such as the following one.
Assume that $f_n(x)=1$ if $x\leqslant0$, $f_n(x)=1-nx$ if $0\leqslant x\leqslant\frac1n$ and $f_n(x)=0$ if $x\geqslant\frac1n$. Then, as desired, each function $f_n$ is nonincreasing, the sequence $(f_n(x))$ is nonincreasing for every fixed $x$, and $f_n\to f$ pointwise with $f(x)=1$ if $x\leqslant0$ and $f(x)=0$ if $x\gt0$.
But the convergence $f_n\to f$ is not uniform since $f_n(\frac1{n^2})=1-\frac1n$ and $f(\frac1{n^2})=0$ hence the difference $f_n(\frac1{n^2})-f(\frac1{n^2})$ does not converge to $0$.


Q: Determining the cardinality from set builder notation I am currently struggling with the following question :
Let S be defined as the following:
    S = {(A,B)| A ⊆ {1,2,....,n}, B ⊆ {1,2,....,n}, |A ∩ B| >= 1}
What is the cardinality of S? Justify your answer.

I am by no means looking for someone to give me the answer, rather I am looking for hints on how to even begin dissecting this question. For starters a translation of the definition of S in terms of english. I believe it says S is defined as a tuple of set A and B s.t A is a subset of positive integers 1 to n and the same with set B? Any hints would be greatly appreciated.

A: *

*How many choices are there for $A$ (if we ignore the other conditions)?

*How many for $B$?

*So how many choices for $(A,B)$ if we ignore the intersection condition?

Now the tricky idea:

*

*How many $(A,B)$ with $A,B\subseteq \{1,2,\ldots,n\}$ with $|A\cap B|=\emptyset$ are there?

Use these results to deduce the cardinality of $S$.
Hint for the "trick" part: consider maps $\{1,2,\ldots,n\}\to \{1,2,3\}$.

A: Assume that you have chosen a set $A\subset[n]$. This $A$ will have $r\in[0..n]$ elements. How many allowed choices are there for $B$?
Write $B$ in the form $B=B'\cup B''$ with $B':=B\cap A$ and $B'':=B\cap\complement A$. Then $B'$ and $B''$ can be chosen independently, and the number of choices only depends on $r$ and $n$.


Q: how to generate dynamic menu and components in angular based on API response I want to (propably) dynamically generate some number of menu positions and components reffering to these menu positions based on API response. Response to c# backend would be made on application start in app.component.ts. Those menu positions would be statuses of proceesing items (for example "finished", "in progress" etc.) and html in every component should look almost identically (just table with positions from sql database, only difference between them was sql query made to database with different "where" clause). Now it is two statuses, but in future it could be 7 more, so I don't want to create a new component in angular every time I add new status in backend. So what I should be looking for? And after receiving response from api where should I store this answer? (In order to have those components all time, I don't want them to dissapear after page reload or anything else).

A: When displaying data fetched from an API it's good practice to implement a model controller view pattern where the date is downloaded by the controller (a service), saved in the model which is marked with the @Injectable() decortator and is injected in the view component you're displaying the data. So your fetched data is stored in the model and can be accessed everywhere you need it.
The controller can look something like that:
@Injectable({
    providedIn: 'root'
})
export class StatusService{
    constructor(private http : HttpClient)
    { }

    public getStatus() : Observable<any>
    {
        return this.http.get('http://myapi.com/getstatus');
    }
}

The model is just storing this data:
export class Status
{
    public id : number;
    public type: string;
}

@Injectable()
export class StatusModel
{
    public statuses: Status[];

    constructor(private statusService : StatusService)
    { }

    public getStatus() : Observable<Status[]>
    {
        return this.statusService.getstatus().pipe(map((status: Status[]) =>
        {
            this.statuses = data;
            return this.statuses ;
        }));
    }
}

In you component (view) you're injecting the StatusModel in the constructor and make the API request:
@Component({
    selector: 'app-status',
    templateUrl: './status.component.html',
    styleUrls: ['./status.component.scss'],
})
export class StatusComponent implements OnInit {
    constructor(public statusModel : StatusModel)
    {
        this.getStatus();
    }

public getStatus() : void
    {
        this.statusModel.getStatus().subscribe(
            (data) =>
            {
                console.log(data);
            },
            (error) =>
            {
                console.log(error);
            }
        );
    }
}

In your HTML you can dispay these statuses stored in statusModel.statuses using *ngFor like that:

{{status.id}

{{status.type}}

You can also use *ngIf to display different statuses differently or ngClass to set specific style classes for specific statuses.


Q: Wrong output in printing values using for loop in C I wrote a simple C program to print all the multiples of 3 but there is some error during runtime my code is:
#include <stdio.h>

void main(void) {
    int i, x;
    for(i = 1; i < 1000; i++) {
        x = i % 3;
        if(x == 0) {
            printf("%d\n", i);
        }
     }
}

the problem is that if I enter numbers greater than 891 till 1000 in the loop the output is starting from 6 instead of 3 and if i write the code as above than the output is starting from 114. for the values less than or equal to 891 it is showing the correct output.

A: Make sure you can view all output:
reuts@reuts-K53SD:~/ccccc$ cat mmph.c && gcc mmph.c
#include<stdio.h>
main(){

    int i,x;
    for(i=1;i<1000;i++)
    {
        x=i%3;

        if(x==0){
            printf("%d\n",i);

        }
    }
}
reuts@reuts-K53SD:~/ccccc$ ./a.out | egrep "^3$|999"
3
999

As you can see, this works. Your output is probably truncated.


Q: Is there a symbols level option/solution for SLD? Is it possible to have an sld blend the symbology in the lines together just as QGIS and ArcGIS allow using symbol levels?
In QGIS I can use symbol levels on the line layer and have this appearance:

currently in sld it has this appearance:

I was hoping to have the appearance of the individual lines blending together as one. The intent is to apply the sld to a geoserver layer. Currently I am only using rules like the one listed below.
    <Rule>
      <MinScaleDenominator>2500</MinScaleDenominator>
      <MaxScaleDenominator>12500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#ffe14c</CssParameter>
          <CssParameter name="stroke-width">3</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>

A: When stacked symbols are only separated by the <Rule> tags, the order in which they appear on the map is random. You need to separate them using <FeatureTypeStyle> tags. Symbols at the top of the SLD will be drawn first, so for your road example you should put the road casing first followed by the road fill. E.g.
<FeatureTypeStyle>
 <Rule>
 <Name>Road casing</Name>
  <MinScaleDenominator>2500</MinScaleDenominator>
  <MaxScaleDenominator>12500</MaxScaleDenominator>
  <LineSymbolizer>
    <Stroke>
      <CssParameter name="stroke">#000000</CssParameter>
      <CssParameter name="stroke-width">5</CssParameter>
      <CssParameter name="stroke-linejoin">round</CssParameter>
      <CssParameter name="stroke-linecap">round</CssParameter>
    </Stroke>
  </LineSymbolizer>
 </Rule>
</FeatureTypeStyle>

<FeatureTypeStyle>
 <Rule>
 <Name>Road fill</Name>
  <MinScaleDenominator>2500</MinScaleDenominator>
  <MaxScaleDenominator>12500</MaxScaleDenominator>
  <LineSymbolizer>
    <Stroke>
      <CssParameter name="stroke">#ffe14c</CssParameter>
      <CssParameter name="stroke-width">3</CssParameter>
      <CssParameter name="stroke-linejoin">round</CssParameter>
      <CssParameter name="stroke-linecap">round</CssParameter>
    </Stroke>
  </LineSymbolizer>
 </Rule>
</FeatureTypeStyle>

Check out our Ordnance Survey SLD's for some examples
They can get quite long and complex with multiple rules!

A: Well that was easy...My issue was I had my line and casing grouped in the FeatureTypeStyle.
The fix was to group the rules for the road in one FeatureTypeStyle and the casing in another. See below:
  <FeatureTypeStyle>
    <Rule>
      <MinScaleDenominator>50000</MinScaleDenominator>
      <MaxScaleDenominator>140000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#000000</CssParameter>
          <CssParameter name="stroke-width">6</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>12500</MinScaleDenominator>
      <MaxScaleDenominator>50000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#000000</CssParameter>
          <CssParameter name="stroke-width">8</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>5000</MinScaleDenominator>
      <MaxScaleDenominator>12500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#000000</CssParameter>
          <CssParameter name="stroke-width">11</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MaxScaleDenominator>5000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#000000</CssParameter>
          <CssParameter name="stroke-width">14</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
  </FeatureTypeStyle>
  <!-- end of motorway casing -->
  <!-- start of motorway -->
  <FeatureTypeStyle>
    <Rule>
      <MinScaleDenominator>6500000</MinScaleDenominator>
      <MaxScaleDenominator>25000000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#73452e</CssParameter>
          <CssParameter name="stroke-width">1</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>3000000</MinScaleDenominator>
      <MaxScaleDenominator>6500000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#d96d6d</CssParameter>
          <CssParameter name="stroke-width">1</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>1500000</MinScaleDenominator>
      <MaxScaleDenominator>3000000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#d94c4c</CssParameter>
          <CssParameter name="stroke-width">4</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>750000</MinScaleDenominator>
      <MaxScaleDenominator>1500000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#d94c4c</CssParameter>
          <CssParameter name="stroke-width">5</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>50000</MinScaleDenominator>
      <MaxScaleDenominator>750000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#e55050</CssParameter>
          <CssParameter name="stroke-width">4</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>12500</MinScaleDenominator>
      <MaxScaleDenominator>50000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#e55050</CssParameter>
          <CssParameter name="stroke-width">5</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>2500</MinScaleDenominator>
      <MaxScaleDenominator>12500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#e55050</CssParameter>
          <CssParameter name="stroke-width">7</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MaxScaleDenominator>2500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#e55050</CssParameter>
          <CssParameter name="stroke-width">10</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
  </FeatureTypeStyle>
    <!-- end of motorway -->
    <!-- start of motorway centerline -->
  <FeatureTypeStyle>
    <Rule>
      <MinScaleDenominator>1500000</MinScaleDenominator>
      <MaxScaleDenominator>3000000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#fae57d</CssParameter>
          <CssParameter name="stroke-width">1</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>750000</MinScaleDenominator>
      <MaxScaleDenominator>1500000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#fae57d</CssParameter>
          <CssParameter name="stroke-width">1.5</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>50000</MinScaleDenominator>
      <MaxScaleDenominator>750000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#ffe14c</CssParameter>
          <CssParameter name="stroke-width">1</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>12500</MinScaleDenominator>
      <MaxScaleDenominator>50000</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#ffe14c</CssParameter>
          <CssParameter name="stroke-width">2</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MinScaleDenominator>2500</MinScaleDenominator>
      <MaxScaleDenominator>12500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#ffe14c</CssParameter>
          <CssParameter name="stroke-width">3</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
    <Rule>
      <MaxScaleDenominator>2500</MaxScaleDenominator>
      <LineSymbolizer>
        <Stroke>
          <CssParameter name="stroke">#ffe14c</CssParameter>
          <CssParameter name="stroke-width">4</CssParameter>
          <CssParameter name="stroke-linejoin">round</CssParameter>
          <CssParameter name="stroke-linecap">round</CssParameter>
        </Stroke>
      </LineSymbolizer>
    </Rule>
  </FeatureTypeStyle>
  <!-- end of motorway -->

A: Just change the 'strike-linecap' of casing lines to 'butt' in order to disappear them at the start and end of line segments as follow:
<FeatureTypeStyle>
 <Rule>
 <Name>Casing</Name>
  <MinScaleDenominator>2500</MinScaleDenominator>
  <MaxScaleDenominator>12500</MaxScaleDenominator>
  <LineSymbolizer>
    <Stroke>
      <CssParameter name="stroke">#000000</CssParameter>
      <CssParameter name="stroke-width">5</CssParameter>
      <CssParameter name="stroke-linejoin">round</CssParameter>
      <CssParameter name="stroke-linecap">butt</CssParameter>
    </Stroke>
  </LineSymbolizer>
 </Rule>
</FeatureTypeStyle>

<FeatureTypeStyle>
 <Rule>
 <Name>Fill</Name>
  <MinScaleDenominator>2500</MinScaleDenominator>
  <MaxScaleDenominator>12500</MaxScaleDenominator>
  <LineSymbolizer>
    <Stroke>
      <CssParameter name="stroke">#ffe14c</CssParameter>
      <CssParameter name="stroke-width">3</CssParameter>
      <CssParameter name="stroke-linejoin">round</CssParameter>
      <CssParameter name="stroke-linecap">round</CssParameter>
    </Stroke>
  </LineSymbolizer>
 </Rule>
</FeatureTypeStyle>


Q: (Karate) How to intercept the XHR request response code? I am testing a login functionality on a 3rd party website. I have this url example.com/login . When I copy and paste this into the browser (chrome), page sometimes load, but sometime does not (empty blank white page).
The problem is that I have to run a script on this page to click one of the elements (all the elements are embedded inside #shadow-root). If the page loads, no problem, script is evaluated successfully. But page sometimes does not load and it returns a 404 in response to an XHR request, and as a result, my * eval(scrip("script") step returns "js eval failed...".
So I found the solution to refresh the page, and to do that, I am considering to capture the xhr request response. If the status code is 404, then refresh the page. If not, continue with the following steps.

Now, I think this may work, but I do not know how to implement karate's Intercepting HTTP Requests. And firstly, is that something doable?
I have looked into documentation here, but could not understand the examples.
https://github.com/karatelabs/karate/tree/master/karate-netty
Meanwhile, if there is another way of refreshing the page conditionally, I will be more than happy to hear about it. Thanks anyone in advance.

A: First, using JavaScript you should be able to handle shadow roots: https://stackoverflow.com/a/60618233/143475
And the above answer links to advanced examples of executing JS in the context of the current page. I suggest you do some research into that, try to take the help of someone who knows JS, the DOM and HTML well - and you should be find a way to know if the XHR has been made successfully or not - for e.g. based on whether some element on the page has changed etc.
Finally here is how you can do interception: https://stackoverflow.com/a/61372471/143475


Q: ms-access queries I never really did ms access queries, but today I need one. I have 2 tables, models and orders. From first table one 2 fields are of interest here: number and color, from second only number which can only be equal to values of number from table "models" . What I need is to select most frequent color. In mysql that would be something like
    SELECT models.color, orders.number  FROM  models
    INNER JOIN orders ON (orders.number =models.number)
    group by color
    order by count(color) desc limit 1

But in ms-access that doesn't seem to work
How do you write query to do same thing in ms-access?

A: try this:
SELECT TOP 1 models.color, COUNT(orders.number)  FROM  models
INNER JOIN orders ON (orders.number=models.number)
GROUP BY models.color
ORDER BY 2 desc

A: All you need is to get rid of limit and use Top 1 instead:
SELECT Top 1 models.color  FROM  models
INNER JOIN orders ON (orders.number =models.number)
group by color
order by count(color) Desc

However, there is a caveat for Top n, in MS Access, Top n will return matches, so if several items have the same count, all will be returned. If this does not suit, you can work around this by ordering by a unique id as well:
order by count(color) desc, OrderID

Note also that number is a reserved word.


Q: Job for docker.service failed because the control process exited with error code while trying to start docker service in Manjaro[Arch] Getting this error while running docker pull manjarolinux/base:
Using default tag: latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

List of the previous commands that I've run:
sudo groupadd docker
sudo usermod -aG docker $(whoami)
sudo chown $(whoami) /var/run/docker.sock

Output of sudo dockerd --debug which had warnings or errors:
WARN[0000] containerd config version `1` has been deprecated and will be removed in containerd v2.0, please switch to version `2`, see https://github.com/containerd/containerd/blob/main/docs/PLUGINS.md#version-header
#and
WARN[2022-11-18T14:38:01.266464955+05:30] failed to load plugin io.containerd.snapshotter.v1.devmapper  error="devmapper not configured"
#and
WARN[2022-11-18T14:38:01.266829045+05:30] could not use snapshotter devmapper in metadata plugin  error="devmapper not configured"
#and
ERRO[2022-11-18T14:38:01.267936333+05:30] failed to initialize a tracing processor "otlp"  error="no OpenTelemetry endpoint: skip plugin"
#and
ERRO[2022-11-18T14:38:01.279926226+05:30] failed to mount overlay: no such device       storage-driver=overlay2


Q: Jquery button toggle show hide div I have these two divs on a page with two buttons beneath them to control hiding and showing them respectively.

Im Blue

Im Red

Blue

Red

I am using this javascript at the moment on the onclick of link.
function toggle_visibility(id) {

    var e = document.getElementById(id);

    console.log(e);
    if(e.style.display == 'none') {
        e.style.display = 'block';
    } else {
        e.style.display = 'none';
    }
}

It works however how do I make it so that clicking one button will disable the other. So clicking blue will show the blue div and hide the red div, then disable the button and enable the other button so the same can be donw but in reverse.
I have made a fiddle with the code i am using on my page which works, but on the fiddle its not? not sure why, ill post it anyway.
EDIT _ Fiddle Now Working. Thanks.
JSFIDDLE

A: You can't execute your js method before the elements get loaded.  so wrap your code in head/body
check this fiddle

A: Here is a possible solution (no jQuery) : http://jsfiddle.net/wared/A6w5e/.
As you might have noticed, links are not "disabled", I simply save the id of the DIV which is currently displayed in order to check the requested id before toggling : if (current !== id).
Another thing to note is that toggle_visibility is overwritten (only once) inside itself. It might look weird, but it's just a way to create a closure in order to enclose the variable named current inside a private context. The goal is to avoid polluting the parent scope.
Lastly, I've modified the original code to hide all divs except the one targeted by id.
function toggle_visibility(id) {
    var current = 'Blue';
    (toggle_visibility = function (id) {
        var div, l, i;
        if (current !== id) {
            current = id;
            div = document.getElementsByClassName('toggle360');
            l = div.length;
            i = 0;
            for (; i < l; i++) {
                div[i].style.display = div[i].id === id ? 'block' : 'none';
            }
        }
    })(id);
}

A: Wrap your code in head or body.
You are executing your code before DOM is created
Fiddle Demo

A: A couple people have commented why it doesn't work in fiddle. To answer the question....
It easy to toggle visibility using jquery if there are only two divs:
$(document).delegate('.flashlinks a', 'click', function () {
  $('.toggle360').toggle();
});

I would use a css class to disable the links. Then I would select what to do with the click based on if the class was present:
$(document).delegate('.flashlinks a:not(".disabled")', 'click', function () {
  $('.toggle360').toggle();
  $('.flashlinks a').toggleClass("disabled");
});

$(document).delegate('.flashlinks a.disabled', 'click', function () {
  e.preventDefault();
});

and in my css I would have something like
.disabled {
    color: black;
    text-decoration:none;
}

jsfiddle


Q: g++ __FUNCTION__ replace time Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work
#include <whatsneeded>
#define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__

int main(int argc, char* argv)
{
  printf(DBG_WHEREAMI "\n"); //*
}

since after preprocessing using
g++ -E test.cc

the source looks like
[...]

int main(int argc, char* argv)
{
  printf(__FUNCTION__ "test.cc" "6" "\n"); //*
}

and now the compiler rightly throws up because the *ed line is incorrect.
Is there any way to force that replacement with a string to an earlier step so that the line is correct?
Is __FUNCTION__ really replaced with a string after all? Or is it a variable in the compiled code?

A: You are using __FUNCTION__ like a preprocessor macro, but it's a variable (please read http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html).
Try printf("%s", __FUNCTION__) just for testing and it will print the function name.

A: __FUNCTION__ is not standard. Use __func__. As the documentation says, it's as if:
<ret-type> function_name( <args> )
{
    static const char __func__[] = "function-name";
    ...

A: In C/C++, the preprocessor will turn "my " "name " "is " "Bob" into the string literal "my name is Bob"; since __FILE__ and __LINE__ are preprocessor instructions, "We are on line " __LINE__ will pass "We are on line 27" to the compiler.
__FUNCTION__ is normally a synonym for __func__. __func__ can be thought of as a pseudo-function that returns the name of the function in which it is called. This can only be done by the compiler and not by the preprocessor. Because __func__ is not evaluated by the preprocessor, you do not get automatic concatenation. So if you are using printf it must be done by printf("the function name is %s", __func__);

A:
Is there any way to force that replacement with a string to an earlier step so that the line is correct?

No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor construct because the preprocessor has no knowledge of the C++ language. When a source file is being preprocessed, the preprocessor has absolutely no idea about which function it is looking at because it doesn't even have a concept of functions.
On the other hand, the preprocessor does know which file it is working on, and it also knows which line of the file it is looking at, so it is able to handle __FILE__ and __LINE__.
This is why __func__ is defined as being equivalent to a static local variable (i.e. a compiler construct); only the compiler can provide this functionality.

A: Is this what you want?
#include <stdio.h>

#define DBG_WHEREAMI(X) printf("%s %s(%d): %s\n",__func__,__FILE__,__LINE__,X)

int main(int argc, char* argv)
{
  DBG_WHEREAMI("Starting");
}

Note: Since you marked this as C++ you should probably be using the iostreams to make sure it's type safe.

A: printf("%s" __FILE__ __LINE__ "\n", __FUNCTION__);

Yeah, I know that's not really the same.

A: Note that if you create a class, you can build a message from any number of types as you'd like which means you have a similar effect to the << operator or the format in a printf(3C). Something like this:
// make sure log remains copyable
class log
{
public:
  log(const char *function, const char *filename, int line)
  {
    f_message << function << ":" << filename << ":" << line << ": ";
  }
  ~log()
  {
    //printf("%s\n", f_message.str().c_str()); -- printf?!
    std::cerr << f_message.str() << std::endl;
  }

  log& operator () (const char *value)
  {
    f_message << value;
  }
  log& operator () (int value)
  {
    f_message << value;
  }
  // repeat with all the types you want to support in the base class
  // (should be all the basic types at least)
private:
  sstream f_message;
};

// start the magic here
log log_error(const char *func, const char *file, int line)
{
  log l(func, file, line);
  return l;
}

// NOTE: No ';' at the end here!
#define LOG_DEBUG  log_error(__func__, __FILE__, __LINE__)

// usage sample:
LOG_DEBUG("found ")(count)(" items");

Note that you could declare the << operators instead of the (). In that case the resulting usage would be something like this:
LOG_DEBUG << "found " << count << " items";

Depends which you prefer to use. I kind of like () because it protects your expressions automatically. i.e. if you want to output "count << 3" then you'd have to write:
LOG_DEBUG << "found " << (count << 3) << " items";


Q: Не могу понять в чем проблема БОТ ДИСКОРДА discord.py python Traceback (most recent call last):
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\nsbm\Desktop\pipka", line 16, in <module>
    client.run('token')
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 723, in run
    return future.result()
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\nsbm\AppData\Roaming\Python\Python310\site-packages\discord\http.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001D02529A290>
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 750, in call_soon
    self._check_closed()
  File "C:\Program Files\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
[Finished in 823ms]

CODE
import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        # don't respond to ourselves
        if message.author == self.user:
            return

        if message.content == 'ping':
            await message.channel.send('pong')

client = MyClient()
client.run('token')

A: raise LoginFailure('Improper token has been passed.') from exc
Данная ошибка говорит о том, что у вас ошибка в токене, проверьте его.


Q: show ruby date as a RFC 3339 timestamp Does anyone know how I can convert a ruby time class instance into a RFC 3339 timestamp?
The output should be something like this:

"2013-10-13T13:34:52.000+02:00"

A: require 'date'
Time.now.to_datetime.rfc3339


Q: Using class properties in angular templates I am trying to use a property from a template in angular. It doesn't work and I can't figure out why. I've set up an example here:
https://github.com/Fulkerson/angular-property
It is the example from the Tour of Heroes. My commit adds the property propname which simply returns name and uses it in the dashboard (main page).
Basically what I want to do is add multiple properties that process a field in different ways. But why is it I cannot use the properties from templates, and how can accomplish what I want to do in another way?

A: The data returned by the heroService.getHeroes method is plain JSON object (without the getter you defined in the Hero class). If you want to use the getter defined in the class you have to return an Array of real Hero instance.
1/ We add a constructor for the Hero class in app/hero.ts for convenience
  constructor ({id,name} = {id: undefined, name: undefined}) {
    this.id = id;
    this.name = name;
  }

2/ Instead of returning plain js data from heroService we map to obtain an array of Hero instance in dashboard.component.ts
getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes =>
        this.heroes = heroes
        .slice(1, 5)
        .map(hero => new Hero(hero))
      );
  }

And Tadaa !
Here is the stackblitz created upon your github repo

A: Well, your problem is that, though you're adding a new getter to the Hero class, in the dashboard you're listing the heroes coming from the service. The problem is that the service is mocking data, and that data is, in truth, a simple array of objects (defined in in-memory-data.service.ts):
const heroes = [
      { id: 11, name: 'Mr. Nice' },
      { id: 12, name: 'Narco' },
      { id: 13, name: 'Bombasto' },
      { id: 14, name: 'Celeritas' },
      { id: 15, name: 'Magneta' },
      { id: 16, name: 'RubberMan' },
      { id: 17, name: 'Dynama' },
      { id: 18, name: 'Dr IQ' },
      { id: 19, name: 'Magma' },
      { id: 20, name: 'Tornado' }
    ];

In the original example this does not matter as the Hero class is used there basically as an interface or type annotation. You, however, are giving that class methods, but those methods do not exist in the array.
So, basically, your template is trying to access a propname property from the items of this array. That property, as you see, is undefined. As a result, you don't see the name in the page. To avoid this, just change the definition of the array:
const heroes = [
      Object.assign(new Hero(), { id: 11, name: 'Mr. Nice' }),
      ...
    ];

(you can also give Hero a constructor with parameters and use it instead of Object.assign). This way you'll get an array of true Hero objects.


Q: How do debug Bot code accessed via DirectLine API? We are developing a bot that will primarily be accessed using the DirectLine API. As the bot and the client app are still in development, the development is made difficult by the fact that we cannot Debug both the client app and bot on one box since DirectLine API can't connect back to the local box.
What's the story there? Any recommendations on best way to do this?

A: Take a look at ngrok.  The basic version is free.

ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.


Q: javascript delete not working rails i have a partial am rendering which works well when am creating through javascript but deleting it via javascript is not working , maybe there is something am doing wrong but ma code is thus ...
the partial rendering
 <ul id="<%= dom_id(feed) %>">
        <%= render :partial => feed.talks %>

the partial

        <%= link_to image_tag(talk.user.image.url(:tiny)),talk.user,:style=> "width: 7%; padding-right: 0px;", :class=> "pull-left img_client"%>

          <%= link_to talk.user.username, talk.user %>: <%= talk.details %>

          <%="#{time_ago_in_words(talk.created_at)} ago "%>

          <% if current_user.id == talk.user_id %>
          <%= link_to "x", talk, method: :delete, data: { confirm: "You sure?" },remote: true, class: 'pull-right' %>

          <% end %>

create.js.erb   which works fine
$('.feed #<%= dom_id(@feed) %>').html("<%= j render(@feed.talks) %>");
$("#new_talk")[0].reset();

destroy.js.erb which doesnt delete unless a full page relod
$('.unstyled custumer_say_<%= @talk.id %>').remove();

seems there is something am not doing right

A: $('.unstyled custumer_say_<%= @talk.id %>').remove();

You're calling something that doesn't exist as far as I can see
Change your ul to this:
<ul id="unstyled custumer_say_<%= @talk.id %>" class="unstyled custumer_say" style="list-style: none;">

And the destroy.js.erb to
$("#unstyled custumer_say_<%= @talk.id %>").remove();

Notice the double quotes


Q: Android Events: When implementing interfaces is it better to use the outer class or anonymous classes This is an example of using outer class
public class MyActivity extends Activity implements OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);
        findViewById(R.id.myid).setOnClickListener(this));
    }
    public void onClick(View v){...}
}

This is an example of anonymous classes
public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);
        findViewById(R.id.myid).setOnClickListener(new OnClickListener() {
            public void onClick(View v){...}
        }));
    }
}

A: Performance and efficiency are slightly a  more important consideration in Android. Something considered to be half baked optimization effort, sometimes makes sense in android.(like we should not use enum but java int enum pattern). So to the answer to your question is.
If you have to register multiple onClick listeners, Implement interface and use switch case within it.
If you have to register only one on click listener, use anonymous class. (Android developers prefers anonymous class, whenever possible. Limiting the scope ;))


Q: Start application when file is received via Bluetooth My application should start when any file is received via Bluetooth.
Please tell me, which intent is fired when a file is received via Bluetooth?

A: There's no such specific intent action which tells that a file is downloaded. However, you should listen for the following broadcast to detect that a phone is disconnected and then check programatically if a file is downloaded.
<intent-filter>
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
</intent-filter>


Q: Just scaling a rectangle I'm trying to start with processing.
Now I'm just trying to scale a rectangle. I have found this example:
float a = 0.0;
float s = 0.0;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
}

void draw()
{

  s = s + 0.04;

  translate(width/2, height/2);
  scale(s);
  rect(0, 0, 50, 50);

}

It scales smoothly the rectangle but I'm a bit surprise because for resizing a rectangle I expected the sizing parameters (3rd and 4th) of rect() were modified, something like this way:
float r = 1;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
}

void draw(){

    rect(width/2, height/2, r, r);

    r += 1;

}

but this way doesn't scale the rectangle smoothly. So, should I use the first approach instead of the second one even if I find it the second one more natural? Any comment will be wellcome.
Regards
Javier

A: The first solution is quite complex, you are not actually scaling the rectangle, but rather the projection matrix. The projection matrix is the series of mathematical operations that are applied before something is drawn to the screen. You can think of it as a camera, but it is far more complex than that.
I actually put the code side by side and didn't notice that much difference in the smoothness. I also added a few tweaks, so that may have helped :)
float r = 1;
float s = 0.0;

void setup()
{
  size(200,200);
  rectMode(CENTER);
  frameRate(30);
  smooth();
}

void draw(){
   rect(width/4, height/2, r, r);
   r += 1.4;
   translate(width/2, height/2);
   scale(s);
   translate(-width/2, -height/2);
   rect(width/2, height/2, 50, 50);
   s += 0.04;
}

The main change that I made was to turn on smooth. I think that because you didn't have it on, the top square drawing was jumping to each pixel, but with the tranlation / scale operation, it would smooth those over. The other thing I did, was to translate back to the top left after doing the scale operation. This is important to do so that things draw where you expect them to. You will notice that the scaling rect now scale out from the center.


Q: Angularjs ui-grid export functionality, Display dynamic data in the exporterPdfHeader Using Angularjs,ui-grid and uiGridExporterService exporting the data in the grid view. I'm using this export option in report functionality so when I export (PDF) need to display the filtered inputs in the PDF view.
$scope.gridOptions2 = {
    enableSorting: true,
    enableColumnMenus: false,
      columnDefs: [
      // { field: 'id', width: '60', displayName: 'S.No', cellTemplate: ''},
      // { field: 'id',   displayName: 'S.No', visible: false},
      { field: 'reg_id',  width: '130',   displayName: 'Id', enableSorting: false},
      { field: 'name', width: '160', displayName: 'Username', enableSorting: false}
      ],
      exporterMenuCsv: false, // ADD THIS

      exporterPdfDefaultStyle: {fontSize: 11},
      exporterPdfTableStyle: {margin: [10, 30, 30, 30]},
      exporterPdfTableHeaderStyle: {fontSize: 11, bold: true, italics: false, color: 'blue' },

      exporterPdfHeader: {
        margin: 20,
        columns: [{
          text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle',
          text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle',
          width: 150
        }]
    },
      exporterFieldCallback : function ( grid, row, col, value ) {
        if ( col.name === 'status' ) {
          value = decodeStatus( value );
        }
        return value;
      },
      exporterPdfFooter: function ( currentPage, pageCount ) {
        return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' };
      },
      exporterPdfCustomFormatter: function ( docDefinition ) {
        docDefinition.styles.headerStyle = { fontSize: 22, bold: true };
        docDefinition.styles.footerStyle = { fontSize: 10, bold: true };
        return docDefinition;
      },

      exporterPdfOrientation: 'landscape',
      exporterPdfPageSize:'A4',  // exporterPdfMaxGridWidth = Defaults to 720 (for A4 landscape), use 670 for LETTER
      exporterPdfMaxGridWidth: 600,    // bug, for A4, default is 720, set to 600 solve my problem.
      exporterExcelFilename: 'myFile.xlsx',
      exporterExcelSheetName: 'Sheet1',
      onRegisterApi: function (gridApi) {
        $scope.grid2Api = gridApi;
    }
  };

Need to pass the selected inputs  into the $scope.monthVal.
exporterPdfHeader: {
        margin: 20,
        columns: [{
          text: "Employee Salary Detail", alignment: 'center', style: 'defaultStyle',
          text: "Month : "+ $scope.monthVal, alignment: 'right', style: 'defaultStyle',
          width: 150
        }]
    },


Q: Creating a custom Authorize attribute with specific rules I'm trying to create a custom Authorize attribute to do the following:

*

*If the user has a role of "Regular user" - he is redirected to /index/subscribe

*All other users(Administrator,Subscriber) gets access to /Search/Index

This is when the user tries to open up the Search controller. I made the custom Authorize attribute like this:
public class DenyRegularUser : System.Web.Mvc.AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/User/Logon");
                return;
            }

            if (filterContext.HttpContext.User.IsInRole("Regular user"))
            {
                filterContext.Result = new RedirectResult("~/Index/Subscribe");
            }
        }
    }

And this is my Search controller:
namespace WebApplication2.Controllers
{
    [DenyRegularUser(Roles ="Regular user")]
    public class SearchController : Controller
    {
        // GET: Search
        public ActionResult Index()
        {
            return View();
        }
    }
}

But for some reason, even when I update the user's role from Regular user to Administrator or Subscriber, I get redirected to login page: /user/login...
This shouldn't happen as the login functionality works perfectly and I get the role of the user...
What am I missing out here??

A: This may help.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DenyRegularUser  : AuthorizeAttribute
{
    public DenyRegularUser() :
        base()
    {

    }

    protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (AuthorizeRequest(actionContext))
        {
            return true;
        }
        return false;
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Code to handle unauthorized request
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect);
        actionContext.Response.Headers.Add("Location", "~/Index/Subscribe");
    }

    private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        //Write your code here to perform authorization
    }
}

I believe the IsAuthorized method is the correct way to override the AuthorizeAttribute.


Q: Two Python instances, same libraries I currently have both Python 2.6 and 2.7 running on my Linux machine.
Now, from Python 2.7, I can't access the libraries that I installed through package manager for Python 2.6.
I tried uninstalling the library and installing it back with Python 2.7 installed as my default runtime. No luck.
How can I share libraries between two Python instances? Is there a more correct way to do this than just copying them?
If useful: my Linux distro is Debian, and my package manager is apt.

A: You should be able to install the files to an external location and define the environment variable PYTHONPATH to point to the directory that contains the modules.

A: You should have now both a /usr/lib/python2.6 folder and a /usr/lib/python2.7. Try creating links inside the 2.7 folders to the required files or folders inside the 2.6 folder.


Q: Convert an RDD to a DataFrame in Spark using Scala I have textRDD: org.apache.spark.rdd.RDD[(String, String)]
I would like to convert it to a DataFrame. The columns correspond to the title and content of each page(row).

A: Use toDF(), provide the column names if you have them.
val textDF = textRDD.toDF("title": String, "content": String)
textDF: org.apache.spark.sql.DataFrame = [title: string, content: string]

or
val textDF = textRDD.toDF()
textDF: org.apache.spark.sql.DataFrame = [_1: string, _2: string]

The shell auto-imports (I am using version 1.5), but you may need import sqlContext.implicits._ in an application.

A: I usually do this like the following:
Create a case class like this:
case class DataFrameRecord(property1: String, property2: String)

Then you can use map to convert into the new structure using the case class:
rdd.map(p => DataFrameRecord(prop1, prop2)).toDF()


Q: make cells mandatory to fill in google sheets with javascript I am new to programming. Is there a way of making a cell mandatory to be filled in google sheets or microsoft excel using javascript, where by a message pops up to remind users to fill in the cells.


Q: sum calculation for position in intervals in pandas dataframe I have a pandas dataframe with intervals (define by start and stop) :
df = pd.DataFrame(
    {
        'start': [1,1,1,2,2,2,2,3,3,3,3,3,3,3],
        'stop': [9,9,10,10,10,11,11,11,11,12,11,12,11,11],
        'percent' : [0.51,0.29,0.92,0.60,0.10,0.12,0.60,0.30,0.10,0.42,0.51,0.51,0.51,0.10],
        'order':[3,80,3,3,4,8,89,2,3,4,5,64,82,68]

    }
    )

Which look like :
start   stop    percent order
1   9   0.51    3
1   9   0.29    80
1   10  0.92    3
2   10  0.60    3
2   10  0.10    4
2   11  0.12    8
2   11  0.60    89
3   11  0.30    2
3   11  0.10    3
3   12  0.42    4
3   11  0.51    5
3   12  0.51    64
3   11  0.51    82
3   11  0.10    68

I want to calculate, for each position (by splitting intervals): total count, sum of value, sum of order
NB : original dataframe is not coordinate sorted in the example.
I want to end up with a dataframe :
pos count   sum_percent sum_order
1   3   1.72    86
2   7   3.14    190
3   14  5.59    418
4   14  5.59    418
5   14  5.59    418
6   14  5.59    418
7   14  5.59    418
8   14  5.59    418
9   14  5.59    418
10  12  4.79    335
11  9   3.17    325
12  2   0.93    68

I managed to have the result that i want for the count column like this :
max_pos=df[['start', 'stop']].values.max()
pos_range=np.arange(1, max_pos+1)
counts = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values)).sum(axis=0)
o = pd.DataFrame({'pos': pos_range, "counts": counts})

But for the sum of column, i didn't manage to do it.
Any help ?
Thanks in advance

A: Use the boolean variable used to count as an index:
import numpy as np
import pandas as pd
names=["start","stop","percent","order"]
vals=np.array([
  [1,9,0.51, 3],
  [1,9,0.29,80],
  [1,10,0.92, 3],
  [2,10,0.60, 3],
  [2,10,0.10, 4],
  [2,11,0.12, 8],
  [2,11,0.60,89],
  [3,11,0.30, 2],
  [3,11,0.10, 3],
  [3,12,0.42, 4],
  [3,11,0.51, 5],
  [3,12,0.51,64],
  [3,11,0.51,82],
  [3,11,0.10,68]
  ])

df = pd.DataFrame(vals, columns=names)
df
max_pos=df[['start', 'stop']].values.max()
pos_range=np.arange(1, max_pos+1)

_ix = ((df[['start']].values <= pos_range) & (pos_range <= df[['stop']].values))
counts = _ix.sum(axis=0)
sum_percent=[]
for i in _ix.T:
    sum_percent.append(df["percent"].values[i].sum())
sum_order = []
for i in _ix.T:
    sum_order.append(df["order"].values[i].sum())

o = pd.DataFrame({'pos': pos_range, "counts": counts, "sum_percent":sum_percent, "sum_order":sum_order})


Q: Annotate datatime calculations How could I cast datetime to seconds and perform calculation on that or directly perform calculation on datetime?
for example:
User.objects.annotate(min=Min('created'), max=Max('created'), perc=F('created') - min/(max - min))

User model
class User(AbstractUser):
    ...
    created = models.DateTimeField(auto_now_add=True)

How to get the value of perc for each user(I'm using postgres)?


Q: Help with jQuery's .live() method I have a function that dynamically creates links for a photo gallery. The function also produces a larger image as a background image of a div when and thumbnail is clicked on. What I want to do is have a third event, where if the user clicks the enlarged image in the div, the jQuery Fancybox loads an even bigger version of the image being displayed in the div. The problem is that the link for the anchor tag I'm using is created dynamically, and I know that Fancybox parses the HTML when the DOM is ready...unfortunately my function changes the DOM by appending the anchor tag for the full sized image. The help I need is using the Fancybox's options to specify the href attribute for the plugin. I'm sorry that was so long-winded...here's the code.
jQuery:
function gallery(picid, picnum){
var ext = 'jpg';
var fullSize = 'imgs/'+picid+'_full.'+ext;
$('#photolarge').css("background", 'url(imgs/'+picid+'_large.'+ext+') no-repeat');
$('#photolarge a').attr(
    {   href: fullSize
        //rel: 'lightbox',
    }
    );

$("#lightboxlink").click(function(){
    $('#lightboxlink').fancybox({
        'autoDimensions' : false,
        'width' : 'auto',
        'height' : 'auto',
        'href' : fullSize
        });

    });

return false;
}

HTML Snippet

CSS:
#photolarge {
width: 590px;
height: 400px;
margin-left: 7px;
border: 2px solid;
background: none;}

#phototable {
width: 590px;
height: 300px;
border: 2px solid;
margin: 10px 0 0 7px;}

#phototable img {
cursor: pointer;}

#phototable ul {
list-style: none;
display: inline;}

#phototable li {
padding-left: 10px;}

#lightboxlink {
display: block;
height: 100%;
width: 100%;}

Any help would be greatly appreciated!!!

A: Try this and see if it works,this is just fancy box bit though,the rest of your code seems fine
$("#lightboxlink").live('click', function(){

    $.fancybox({
        'autoDimensions'  : false,
        'width'           : 'auto',
        'height'          : 'auto',
        'href'            : $(this).attr('href')
    });
    return false;
});


Q: Inverse Cosine in Python Apologies if this is straight forward, but I have not found any help in the python manual or google.
I am trying to find the inverse cosine for a value using python.
i.e. cos⁻¹(x)
Does anyone know how to do this?
Thanks

A: To augment the correct answers to use math.acos, it is also worth knowing that there are math functions suitable for complex numbers in cmath:
>>> import cmath
>>> cmath.acos(1j)
(1.5707963267948966-0.88137358701954294j)

Stick with math.acos if you're only interested in real numbers,

A: The result of math.acos() is in radians. So you need to convert that to degrees.
Here is how you can do:
import math
res = math.degrees (math.acos (value))

A: We have the acos function, which returns the angle in radians.
>>> import math
>>> math.acos(0)
1.5707963267948966
>>> _ * 2 - math.pi
0.0

A: In response to using inverse cosine to find return angles via math.acos,  it's all fine and dandy so long as the angle is <=90*  once you go past that, python will have no way of differentiating which angle you wanted.
Observe.
>>> math.cos(5)
0.28366218546322625

Above, I asked python to fetch me the cosine of a 5 radian angle, and it gave me .28~ Great, below I'll ask python to give me the radian which has a .28~ cosine. Should be 5, right? It literally just told me it was.
>>> math.acos(0.28366218546322625)
1.2831853071795865

Wrong! Python returns 1.28~ radians. The reason is obvious when plotted visually, 1.28rad has the same cosine as 5rad, they're inverse angles. Every angle shares the same sine with another angle (and -sine with two others).
i.e. 5/175* share an equivalent sine. They share inversely proportional cosines .99~/-.99 respectively.  Their -sine cousins would be 185 and 355.  The relationship meme here is that all these angles share the same angular deflection from the horizontal axis. 5*.
The reason python returns 1.28 and not 5 is that all computers/calculators are based on an abacus-like data table of an angle/radian, its sine, cos, tan etc etc.  So when i math.acos(x), python asks the kernal to look through that data table for whichever angle has a cosine of x, and when it finds it, it returns the first entry it appears with. and then python gives that angle to me.
Due to this shared, proportional symmetry, sin/cos ratios repeat frequently. And you are likely to see the same figure, multiple times. There's no way for python, or the OS, to determine the difference of which of the two angles you actually require without doing additional logic that takes into account the -/+ value of the angle's sine.  Or, the angle's tangent.
1.28 Rad has  x cosine, y sine, z tan  (72*)
1.88 Rad has -x cosine, y sine, -z tan (108*)
4.39 Rad has -x cosine, -y sine, z tan (252*)
   5 Rad has  x cosine, -y sine, -z tan (288*)

or, viewed Cartesianly,
                       negX,posY | posX,posY
                            -----+-----
                       negX,negY |  posX,negY

1.88 Rad has -x cosine, y sine (108) | 1.28 Rad has  x cosine, y sine (72*)
                                -----+-----
4.39 Rad has -x cosine, -y sine (252)|    5 Rad has  x cosine, -y sine (288)

So if, for whatever reason, i need 5 radians to be chosen (say for a vector drawing or game to determine the various vectors enemies are from the player), i would have to do some type of if/then logic comparing the sines/tangents.

A: You're looking for the math.acos() function.

A: You may also use arccos from the module numpy
>>> import numpy
>>> numpy.arccos(0.5)
1.0471975511965979

WARNING: For scalars the numpy.arccos() function is much slower (~ 10x) than math.acos.  See post here
Nevertheless, the numpy.arccos() is suitable for sequences, while math.acos is not. :)
>>> numpy.arccos([0.5, 0.3])
array([ 1.04719755,  1.26610367])

but
>>> math.acos([0.5, 0.3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

A: or just write a function of your own for the taylor expansion of cos^{-1}
this would be more time consuming (and maybe slower to run) but is the more general approach


Q: "He knows his counterparts in each branch" Can I use the word counterpart this way:

He knows his counterparts in each branch.

The context is that he works as the marketing manager in one of the company branches. And the counterparts refer to those who work as the marketing manager in other branches. Or should add something in front of the "counterpart"?

A: One of the meanings of counterpart is ‘A person or thing not exactly similar to another, but serving as its equivalent in a different context’ (OED). That would make the plural, counterparts, a suitable word to use in the way in which it is used in your example. An alternative, slightly less formal, is opposite numbers.

A: Counterpart is the right word, as shown with Barrie's research in the OED:

A person or thing not exactly similar to another, but serving as its equivalent in a different context.

There is a question about number, though.
Each branch is treated as singular, or at least considered individually, and if there is only one marketing manager in each branch, your sentence should be

He knows his counterpart in each branch.

An equivalent when considering plural branches, and therefore more than one manager, is

He knows his counterparts in other branches.

If there is more than manager per branch, then counterparts in each branch is fine.


Q: How to use @HiltAndroidApp annotation but there's no Application class in the project? As Android documentation said:

All apps that use Hilt must contain an Application class that is annotated with @HiltAndroidApp

When I create an Android project from template (Tabs template of Android Studio) it seems not to provide any Application class but class MainActivity : AppCompatActivity() instead. So how can I use Hilt in this project?
I have tried this:
@HiltAndroidApp
class MainActivity : AppCompatActivity() {
    ...
}

But it didn't work :<

A: Your MainActivity is not the Application class.
For activities use the @AndroidEntryPoint. See more on https://dagger.dev/hilt/android-entry-point
The annotation @HiltAndroidApp is for the Application class. See more on https://dagger.dev/hilt/application


Q: How do I exclude multiple terms in Kibana 4 How can I exclude multiple search terms in Kibana 4? If I type in only one term, it excludes it...but how can I have more than one excluded term. For example, the term "not yet classified"

A: If I understand your question properly, you're trying to use the "Exclude Pattern" to exclude certain values from populating in the chart.
The "Exclude Pattern" and "Include Pattern" fields are for Regular Expressions and are documented here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html.
If you want to exclude multiple fields, you could do something like this:
term1|term2|term3

A: The query field in Kibana uses Lucene syntax which has some info at http://www.lucenetutorial.com/lucene-query-syntax.html.
To exclude a term containing specific text, use

-field: "text"

to exclude different texts, I use

-field: ("text1" or "text2")

If it's two separate fields, try

-field1: "text1" -field2: "text2"

A: in newer version of kibana if you want to exclude some term use this:
not field : "text"

if you want to exclude a phrase use this:
not field : "some text phrase"

you can use other logical operation with not:
field: "should have phrase" and not field: "excluded phrase"

A: https://www.elastic.co/guide/en/kibana/master/kuery-query.html
To match documents where response is 200 but extension is not php or css.
response:200 and not (extension:php or extension:css)

A: So in the query above the visualization, you can use Lucene syntax to exclude the hits, once saved this will perform the same as an attempt of using regex or Lucene syntax in the Exclude Field of the Buckets advanced options.