text:
Q: Creating Variables in Advance to Use in Loops (?) Which one of these two is more 'efficient':
for (int i = 0; i < 10; i++) {
    int x = i * 2;
}

or -
int x;
for (int i = 0; i < 10; i++) {
    x = i * 2;
}

(Just an example)
I understand they are different in essence - so please do not address the difference in their use.
In a case where both would prove to do the same thing - will creating the x variable multiple times be a less efficient method rather than just creating it once and simply reassigning its value?

A: No, in this case, with the way compilers are, there is no performance difference.
I prefer the first approach from a readability point of view, but that's something to be discussed elsewhere.
However, as a bonus section to this answer:
for (int x = 0; x < calculateUserCountFromDatabaseOrSomething(); x++) {
   //Do stuff
}

In the above case, this will be a performance issue since the calculateUserCountFromDatabaseOrSomething() method is going to be called on every iteration of the loop.  This is something that definitely needs to be considered when writing software.

A: The efficiency should be the same - I'd expect the byte code to be exactly the same.
However, what you should really care about is the readability and maintainability of the code, which is better in the first approach, as it limits the scope of x more - making it clearer where it will be used.
You should almost always care about readability over performance until you have evidence that not only is the less-readable alternative faster, but that the most readable solution is not fast enough.

A: If you want a definitive answer check this:
http://livingtao.blogspot.com/2007/05/myth-defining-loop-variables-inside.html
This conducts a byte code comparison of the results of compilation.
The answer is no difference by the way.

A: Depends on the type of the objects. For example if X is String it will make little difference. If for example X is some sort of Map, you can initialize it once, and clear it every time in the end of iteration. In the case X is int, it really does not matter, in terms of efficiency. Mind the scope of the variable, declaring it outside the loop suggests an intention, that it will be used after that.

A: Since you're allocating space for only one int instead of ten ints, in the second scenario, it should be faster. However, in reality the java compiler will almost certainly optimize this heavily to the point where microbenchmarks would say they took the same time.

A: The variable is not created multiple times:
for ( A; B; C ) {
    D;
}

the execution is this:
A - (B - D - C) ... (B - D - C) until B became false

A: No performance benefits, both are same,  but ,its better practice to declare your variables in as narrow a scope as possible, so as to make it more readable and clear.
Variables should only exist within the scope that they are used


text:
Q: Create onDragEnter custom event I was experimenting with the onDragEnter event and realized it only works in IE. How can I recreate this event using jQuery, so that I can get information about what is being dragged, etc.?
For example, I'm trying to drag some random text over a box that can recognize what the text is, etc. I also need to be able to drag some random image and have the same box recognize what the image is, etc.
Any help would be greatly appreciated.
Regards,
David

A: I imagine someone has wrapped this into a nice event model already, but I don't know of it, so here's one option:
During drag (after dragstart and before dragstop) you should be able to attach an event handler to onmousemove. That will fire pretty much continuously as the element is being dragged, and you can run basic dimensional math to detect whether the mouse or the dragged element(s) have intersected with any of your potential target elements, and fire your own event then.

redpajama_set_name: RedPajamaStackExchange


text:
Q: React navigation not working on button press I am working through a react native tutorial and I am trying to learn react native. I am using react-navigation@4.1.1 and its not working. I've installed the correct dependencies to get the project to run. Here is my code...
app.js
import React, {useState} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Font from 'expo-font';
import { AppLoading } from 'expo';
import MealsNavigator from './assets/navigation/MealsNavigator';

//const fetchFonts = ()=>{
  //return Font.loadAsync({
    //'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
   // 'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
 // });
//};

export default function App() {
 // const [fondLoaded, setFontLoaded] = useState(false);
  //if (!fondLoaded){
    //return ( <AppLoading
    //startAsync= {fetchFonts}
   // onFinish= {()=> setFontLoaded}
    ///>
    //);
  //}
  return (
    <MealsNavigator/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

mealsnavigoter.js that holds navigation
import {createStackNavigator} from 'react-navigation-stack';
import { createAppContainer} from 'react-navigation';
import CategoriesScreen from '../../screens/CategoriesScreen';
import CategoryMealScreen from '../../screens/CategoryMealScreen';
import MealDetailScreen from '../../screens/MealDetailScreen';

const MealsNavigator = createStackNavigator({
    Categories: CategoriesScreen,
    CategoriesMeals: {
        screen: CategoryMealScreen
    },
    MealDetal: MealDetailScreen
});

export default createAppContainer(MealsNavigator);

categories screen that has the button when pressed is supposed to navigate to the categories meal screen
import React from 'react';
import {View, Text,Button, StyleSheet} from 'react-native';

const CategoriesScreen = props =>{
    return(
        <View style={styles.screen}>
            <Text>The Categories Screen!</Text>
            <Button title="Go to Meals" onPress={()=>{props.navigation.navigate('CategoryMeals');}} />
        </View>
    );

};

const styles = StyleSheet.create({
    screen:{
        flex:1,
        justifyContent:'center',
        alignItems: 'center'
    }
});

export default CategoriesScreen;

categoryMeals screen that i want to navigate to
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';

const CategoryMealScreen = props =>{
    return(
        <View style={styles.screen}>
            <Text>The Category Meal Screen!</Text>
        </View>
    );

};

const styles = StyleSheet.create({
    screen:{
        flex:1,
        justifyContent:'center',
        alignItems: 'center'
    }
});

export default CategoryMealScreen;

A: Simple spelling mistake. Change your
<Button title="Go to Meals" onPress={()=>{props.navigation.navigate('CategoryMeals');}} />

to
<Button title="Go to Meals" onPress={()=>{props.navigation.navigate('CategoriesMeals');}} />


text:
Q: How to redirect Dtrace output when using the -c flag? How can I redirect only Dtrace's output when running a script with the -C flag?
like in this case:
dscript.d -s myscript.d -c date

Note: I found the answer to my question before posting it, but I'm putting it here so it's part of SO.

A: One solution with pipes is:
dtrace -o /dev/fd/3 -s dscript.d -c date 3>&1 1>out 2>err

which says:

*

*dtrace's stdout goes to fd 3, which is dup'd from the current stdout

*dtrace's stderr goes to 'err'

*date's stdout is modified to 'out'

*date's stderr is modified to 'err'

Or the more simpler method is to do:
dtrace -o log.txt -s dscript.d -c date


text:
Q: The image of a completely reducible group is itself completely reducible. This is part of Exercise 3.3.12 of Robinson's "A Course in the Theory of Groups (Second Edition)". According to Approach0 and this search, it is new to MSE. I am not familiar with representation theory nor is that topic covered in the book so far.
The Details:
Since definitions vary, on page 15, ibid., paraphrased, it states that

A subgroup $N$ of $G$ is normal in $G$ if one of the following equivalent statements is satisfied:
(i) $xN=Nx$ for all $x\in G$.
(ii) $x^{-1}Nx=N$ for all $x\in G$.
(iii) $x^{-1}nx\in N$ for all $x\in G, n\in N$.

We call a group simple if $G\neq 1$ and $1$ and $G$ are the only normal subgroups of $G$. This definition is equivalent to the one found on page 16.
Robinson defines completely reducible in terms of $\Omega$-groups on page 85; however, for $\Omega=\varnothing$, the definition is equivalent to saying

a group is completely reducible if it is a direct product of a possibly infinite family of simple groups.

The Question:

Prove that the image of a completely reducible group is completely reducible.

I assume here that "image" refers to "homomorphic image".
Thoughts:
I start out by supposing, for a group $G$, that
$$G=\varphi \left(\underset{i\in\mathcal{I}}{{\rm Dr}}\, G_i\right),\tag{1}$$
where $\varphi$ is a group homomorphism, each $G_j$ is a simple group, and $\mathcal{I}$ is a (potentially infinite) index set. Let $H=\underset{i\in\mathcal{I}}{{\rm Dr}}\, G_i$.
I suspect, from experience and $(1)$, that I should aim for
$$G\cong\underset{i\in\mathcal{I}}{{\rm Dr}}\, \left(\varphi\rvert_{G_i} (G_i)\right),\tag{2}$$
where $\varphi\rvert_{G_j}$ the restriction of $\varphi$ to $G_j$.
I suppose there are two stages:

*

*Go from $(1)$ to $(2)$. I think this follows from the fact that both $\varphi$ and each $\varphi\rvert_{G_j}$ are homomorphims.

*Show that each $\varphi\rvert_{G_j} (G_j)$ is simple. I think that follows from the first homomorphism theorem, since the kernel of $\varphi\rvert_{G_j}$ is normal in $G_j$.
I think I could solve this on own if I could follow steps like this. My confidence is low, however, because Robinson defines the direct product on pages 20 to 21, ibid., like so:

Let $\{G_\lambda\mid \lambda\in\Lambda\}$ be a given set of groups. The cartesian (or unrestricted direct) product,
$$C=\underset{\lambda\in\Lambda}{{\rm Cr}}\, G_\lambda,$$
is the group whose underlying set is the set product of the $G_\lambda$s [. . .] and whose group operation is multiplication of components: thus
$$(g_\lambda)(h_\lambda)=(g_\lambda h_\lambda),$$
$g_\lambda, h_\lambda\in G_\lambda$. [. . .]
The subset of all $(g_\lambda)$ such that $g_\lambda=1_\lambda$ for almost all $\lambda$ [. . .] is called the external direct product,
$$D=\underset{\lambda\in\Lambda}{{\rm Dr}}\, G_\lambda,$$
[. . .] In case $\Lambda=\{\lambda_1,\dots,\lambda_n\}$, a finite set, we write
$$D=G_{\lambda_1}\times\dots\times G_{\lambda_n}.$$
Of course $C=D$ in this case.

I'm not used to it.
Moreover, I want to move on to the rest of the book. I've given this problem a couple of days and I reckon that's enough for half an exercise.
The kind of answer I'm looking for is a full solution or, if not, a list of strong hints.
Please help :)


text:
Q: preg_match to find number of elements starting with id Can you please tell me how to use preg_match in php to find the number of elements in an html starting with a particular id.

find the number of elements starting with id="test_". So in the above example I should get 3
Also get the second parameter in the form of an array
So
    Arr[0] = 1;
    Arr[1] = 2;
    Arr[2] = 3;
Can anyone please tell me how the above can be done.

A: Here is the simplest way:
$regex = '~id="test_\K[^"]~';
$number_of_matches = preg_match_all($regex, $yourstring, $matches);
if ($number_of_matches) print_r($matches[0]);

Results

*

*$number_of_matches is 3

*$matches[0] is an array with the three matches: (1,2,3), i.e. $matches[0][0] is 1, $matches[0][1] is 2, $matches[0][2] is 3.

A: $str = '

';
if ( preg_match_all( '/test_([0-9]+)/', $str, $matches ) )
{
    print_r($matches[1]);
}

Output:
Array
(
  [0] => 1
  [1] => 2
  [2] => 3
)


text:
Q: std::function inside template class giving object creation error Getting below error for the code given below. Trying to have 3 std::function inside an template class and then initialize them with different functions from different classes.
Why is this error happening? What's wrong with below code?

template <typename T>
class CFuntion {
public:
    std::function<void()> callback_1;
    std::function<void()> callback_2;
    std::function<void()> callback_3;

    template <typename A, typename B, typename C>
    CFuntion(A cb1, B cb2, C cb3)
        : callback_1(cb1), callback_2(cb2), callback_3(cb3)
    { }
};

class Impl1 {
public:
    void do_something1() {
        cout << "Inside Impl1 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl1 do_something2" << endl;
    }
};

class Impl2 {
public:
    void do_something1() {
        cout << "Inside Impl2 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl2 do_something2" << endl;
    }
};

class Impl3 {
public:
    void do_something1() {
        cout << "Inside Impl3 do_something1" << endl;
    }

    void do_something2() {
        cout << "Inside Impl3 do_something2" << endl;
    }
};

int main()
{
    unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1, &Impl2::do_something1,
                                        &Impl3::do_something2));
    ptr1->callback_1();
    ptr1->callback_2();
    ptr1->callback_3();

    system("pause");
    return 0;
}

A: Look at this part:
unique_ptr<CFuntion<void>> ptr1 = make_unique<CFuntion<void>(std::bind(&Impl1::do_something1, &Impl2::do_something1, &Impl3::do_something2));
//                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here, you pass only one object to your CFunction<void>'s constructor. What you needed might be this:
// You need to pass temporary objects to 'std::bind()' to bind non-static member functions
Impl1 obj1;
Impl2 obj2;
Impl3 obj3;
std::unique_ptr<CFuntion<void>> ptr1 = std::make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1, obj1), std::bind(&Impl2::do_something1, obj2), std::bind(&Impl3::do_something2, obj3));

Or, by looking at your Impl1, Impl2 and Impl3 classes it seems you could just make their member methods static (As none of those three classes seem to need any sort of distinction between their objects or have any instance variables to access/modify.):
class Impl1 {
public:
    static void do_something1() {
        cout << "Inside Impl1 do_something1" << endl;
    }

    static void do_something2() {
        cout << "Inside Impl1 do_something2" << endl;
    }
};

class Impl2 {
public:
    static void do_something1() {
        cout << "Inside Impl2 do_something1" << endl;
    }

    static void do_something2() {
        cout << "Inside Impl2 do_something2" << endl;
    }
};

class Impl3 {
public:
    static void do_something1() {
        cout << "Inside Impl3 do_something1" << endl;
    }

    static void do_something2() {
        cout << "Inside Impl3 do_something2" << endl;
    }
};

That way, you just need to do this, which appears to be what you want to do:
std::unique_ptr<CFuntion<void>> ptr1 = std::make_unique<CFuntion<void>>(std::bind(&Impl1::do_something1), std::bind(&Impl2::do_something1), std::bind(&Impl3::do_something2));


text:
Q: Show that every solution of the following differential equation has an analytic continuation along any path that avoids its singularities . The problem states as follows. Let $f(z)$ be  a meromorphic function on an open set $\Omega$. Consider a differential equation
\begin{align}
 y''+f(z)y=0.  \hspace{1cm}(1)
\end{align}
Show that every solution of $(1)$ has an analytic continuation along any path $\gamma$ on $\Omega$, such that  $\gamma$ avoids the poles of $f(z)$.


text:
Q: Parse GML to use in map creation so I posted a question on OpenData and after advancing me a bit further in my quest to create maps from real cartographic information, I was advised to post my follow up questions on this website.
So after this intro, here is the original question:
I'm creating a 2D realistic RTS (Real time strategy game) and I wanted to be able to use real locations as the scenarios for the games.
The game will be developed via unreal engine which uses c++. The idea is for the engine to read an file and convert into a grid (coordinate point) where each square has type of terrain associated, like in this image of a scenario editor.

The file resulting from the other website is a GML (Geographic Markup Language) of a given location in the globe. GML is a XML extension.
The problem I'm facing is converting that GML for a given location into data that can be used by my game, like an location array or something like that.
Any sugestions?

A: There are many possibilities into doing this but the general guidelines or concepts should be as follows:

*

*Know the data structure used by your engine

*Open the incoming file and being able to parse and extract the needed data

*Populate your structures or classes

*Use your custom structures or classes to create game content (map data).

The first suggestion that I can give would be to read up on any and all documentation on the GML file format to know how the tags of the marked up language works then from there look to see if you can find any libraries that make it easy to read in a GML or XML file type and to generate C++ classes or structures, otherwise you will have to write both the file loader and gml(xml)parser with schema manually. Then from those structures being able to extract the data that you need and to pass them or store them into your engine's custom data structures. Then finally you should be able to use the stored data in your engine to generate the content that you want.
References

*

*www.opengeospatial.org

*www.w3.org

*www.ogcnetwork.net

*www.gdal.org

*www.svgopen.org
Books

*

*Geo-Informatics... 200+ page preview of almost 1,000 pages
Whitepapers

*

*ResearchGate
Tools - Some Free Some Not

*

*Google Search - GML File Converter

*GoLoader by Snowflake Software

*Various Sources by OGCNetwork

*Open Source software from opengeospatial

*GML Reader by tsusiatsoftware
Libraries

*

*Question found on Stack Exchange

*Various Libraries & Frameworks for Different Formats and Languages

*gmXML Parser by YOYO games - *This Might be for the GameMaker Language

*Java Code Examples for org.geotools.xml.Parser from programcreek

*GML API for C/C++ Documentation

*GML - The Geometric Modelling Library - API & GUI

*Open Source - CityGML
The information needed is out there; it just takes time and effort; good research and the ability to apply what you have read into an actual code base.


text:
Q: Is it correct to say "Cut the rope with a knife with your mouth"? I know that both "with" and "by" can be used to say how something is done. After "with", we use an object and after "by" we use a method.
For example, "I cut the cake with a knife" and "I cut the cake by using a knife"
If we don't have a knife, we might say "I cut the cake with my hand" and "I cut the cake by hand".
Now, a man's hands and legs got tied together but his mouth was free. There was a knife next to him and he had to use his mouth to take hold of the knife to cut the rope.
So, there were 3 things involved: the rope, the knife and the mouth.
I can say lengthily like this "Hold the knife with your mouth and then cut the rope with the knife".
Can we make that sentence shorter by saying  "Cut the rope with a knife with your mouth"?

A: No, with a knife with your mouth doesn't make any sense.  If someone said that, I would say, "Huh?  Do you want me to use a knife, or do you want me to use my mouth?"  It really just doesn't make any sense because the man is not cutting the rope with his mouth.

A: You can express what you are trying to express but you would not express it as you have.  Since putting a knife in your mouth and using that knife to cut a rope is not a common situation, you will need to provide a bit more information in your statement to prevent your reader from getting lost and confused.  You would say something like,

Use your mouth to cut the rope with the knife.

Saying, Use your mouth, immediately clarifies what you are requesting.  In the situation you describe, context will help clear up any ambiguity in the above statement.


text:
Q: Set PATH to use the current TeX Live bin directory I run Ubuntu 16.04. I want to run update-tlmgr-latest.sh on my machine (cf. The underlying problem farther down for details about that), but before I do this, https://www.tug.org/texlive/tlmgr.html says under "Disaster recovery" that I should

be sure your PATH is set to use the current TeX Live bin directory; the recovery archives use kpsewhich from PATH to figure out where to unpack themselves.

The problem, in short: I am definitely not "sure" about anything related to any of this, since my ubuntu capabilities are strictly limited to a minimum.
I tried the following:

sudo apt-get purge texlive

produces
Package 'texlive' is not installed, so not removed

apt-get does not recognize my texlive installation, although it's installed, since I use it to compile my LaTeX documents.

which install-tl

has no output

which tlmgr

and
sudo su
which tlmgr

both produce
/usr/bin/tlmgr

so root and the user account recognize the same directory for tlmgr (I think this might be important, but I don't really know why)

The underlying problem
I am trying to
tlmgr update --self

but all of
tlmgr update --all
tlmgr update --list
tlmgr update --self

gives me (this is taken from a similar question, but only the checksum and the last line number are different, the rest is the same):
(running on Debian, switching to user mode!) Unknown directive
...containerchecksum
c59200574a316416a23695c258edf3a32531fbda43ccdc09360ee105c3f07f9fb77df17c4ba4c2ea4f3a5ea6667e064b51e3d8c2fe6c984ba3e71b4e32716955... ,
please fix it! at
/usr/share/texlive/tlpkg/TeXLive/TLPOBJ.pm line 210, line 5579.

and
sudo su
tlmgr update --self

outputs
(running on Debian, switching to user mode!)
cannot setup TLPDB in /root/texmf at /usr/bin/tlmgr line 5604.

I guess I am running Debian TL, since it's switching to user mode.

sudo apt-get install texlive

results in a double installation, cluttering the system.
The steps described in this post are a bit overwhelming, but if you think this would be the absolute best thing to do, I will.


text:
Q: Initialise a database with SpatiaLite 4.3 I am starting to work with SpatiaLite 4.3 in an empty database. SpatiaLite requires a number of meta-data tables, where it stores information about geometry fields. For previous versions there are SQL scripts that create and initialise these tables; for instance, the release page for version 2.3 lists a script named init_spatialite-2.3.sql.
I have not been able to find a similar script for version 4.3. Is the database initialised differently in this version?

A: With current SpatiaLite versions the spatial metadata tables are created with SQL function InitSpatialMetadata(). The usage is documented in http://www.gaia-gis.it/gaia-sins/spatialite-sql-latest.html

Creates the geometry_columns and spatial_ref_sys metadata tables the
  return type is Integer, with a return value of 1 for TRUE or 0 for
  FALSE

*

*if the optional argument transaction is set to TRUE the whole operation will be handled as a single Transaction (faster): the >
  default setting is transaction=FALSE (slower, but safer).

*if the optional argument mode is not specified then any possible ESPG SRID definition will be inserted into the spatial_ref_sys table.

*if the mode arg 'WGS84' (alias 'WGS84_ONLY') is specified, then only WGS84-related EPSG SRIDs will be inserted

*if the mode arg 'NONE' (alias 'EMPTY') is specified, no EPSG SRID will be inserted at all

Single transaction is much faster, about 1 second vs. one minute.
select InitSpatialMetadata(1);

If the size of the database is critical then using mode WGS84 or NONE will save about 5 megabytes but then you may need to insert the SRID definitions that you need later with InsertEpsgSrid.


text:
Q: Raspberry Pi PWM accuracy, Python I have a simple Python program running on a Pi 2. I can't seem to figure out why the output frequency is way off.  I have it programmed for 2000hz.  I measure the output two ways and both yield 1530 Hz.
Since I use pin 18, I believe I should be using the hardware PWM.  Any suggestions, what am I missing.
Here's the code
 import time
import sys
import datetime
import RPi.GPIO as GPIO

def tonet(hz,s):
    pt = GPIO.PWM(tone,hz)
    pt.start(50)        # duty cycle
    time.sleep(s)
    pt.stop
    GPIO.output(tone, GPIO.LOW)  # good house keeping
    return

# Pin Definitons:
tone = 18 #

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(tone, GPIO.OUT) #  pin set as output
GPIO.output(tone, GPIO.HIGH)
pause = raw_input('high   press a key')
GPIO.output(tone, GPIO.LOW)
pause = raw_input('low  press a key....')

print 'start pwm'

tonet(2000, 20)

GPIO.cleanup()

A: I think the pins 12 and 24 (BOARD numberingscheme) are hardware PWM capable, hence more accurate.

A: Broadcom pin #18 is a PWM hardware pin on Raspberry Pi 2 and 3. However the question is how does the interface library you are using support the PWM hardware on the Pi 2.
Reading this Raspberry Pi StackExchange posting's answer, it appears that the RPIO library may have some PWM inaccuracy, at least at the time of the answer in 2012.
Can I use the GPIO for pulse width modulation (PWM)?

As suggested by Alex Chamberlain, the WiringPi library appears to
  support both hardware PWM output on one GPIO pin and software PWM on
  any of the other GPIO pins. Meanwhile the RPIO.PWM library does PWM by
  DMA on any GPIO pin. Effectively this is a halfway house between
  hardware and software PWM, providing a 1 µs timing resolution compared
  to 100 µs with WiringPi's Software PWM[1].
Which of these is suitable for your applications depends on how many
  PWM outputs you need and what performance you want out of those
  outputs.
If your application is tolerant of low-timing resolution and high
  jitter then you could use a software or DMA assisted timing loop. If
  you want higher precision / lower jitter PWM then you may need
  hardware assistance.

Also see this Raspberrypi.org forum discussion from 2013.
RPIO.PWM: Precise PWM via DMA for servos and more (1µs res)
Also I seem to remember that the headphone jack audio can interfere with PWM usage as the circuitry is shared between the two. This should only be a problem if you are using the jack.


text:
Q: Tkinter ScrolledText widget not appearing I'm trying to add the ScrolledText widget to a Tkinter window. The program reads it perfectly as in it accepts the INSERT method for it with no errors but it's not showing up. The problem came up when I added Notebook Tabs. I've attached the code snippet. I used the place() method because I need the rest of my buttons and labels arranged in a specific pattern.
import tkinter
from tkinter import *
from tkinter import scrolledtext
from tkinter import messagebox
from tkinter import ttk
import os
import datetime

# Variables
window = Tk()
window.title("Vesnica Pomenire")
window.geometry('1500x1000')
var = IntVar()
var.set(1)

txt = scrolledtext.ScrolledText(window,width=40,height=10)
txt.place(x=50, y=50)

A: You're missing the mainloop()
import tkinter
from tkinter import *
from tkinter import scrolledtext
from tkinter import messagebox
from tkinter import ttk
import os
import datetime

# Variables
window = Tk()
window.title("Vesnica Pomenire")
window.geometry('1500x1000')
var = IntVar()
var.set(1)

txt = scrolledtext.ScrolledText(window,width=40,height=10)
txt.place(x=50, y=50)

window.mainloop() #You are missing this

You can read more about mainloop() here

A: You really missed mainloop command
window.mainloop()

add this at the bottom of your code and it will do the thing


text:
Q: What changes when you declare "val" in a class constructor? What changes in a class when you declare a constructor value with val? I noticed that it behaves differently below:
scala> :paste
// Entering paste mode (ctrl-D to finish)

class Foo(value: String) extends Bar
class Bar { this: Foo =>
  def go = println(value)
}

// Exiting paste mode, now interpreting.

<console>:9: error: not found: value value
         def go = println(value)
                          ^

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Foo(val value: String) extends Bar
class Bar { this: Foo =>
  def go = println(value)
}

// Exiting paste mode, now interpreting.

defined class Foo
defined class Bar


text:
Q: How to compare two cells against two columns and count when both cells appear in the columns in any order I haven't been able to find something like this. Hoping I can get an answer in Google Sheets! I have a two columns with values pulled from the same list of 5 items. (Each row is an item that has up to two 'types' that come from a 'types list' with 5 values)
For this example:

Types

A

B

C

D

E

Example Column 1
Example Column 2

A
B

B
A

B
C

B

D
E

D
B

I want to create another table like below that will count up how many times a particular combination occurs regardless of order. Results would appear as below:

Type 1
Type 2
Count

A
B
2

B
C
1

B
E
0

D
E
1

I need this formula to count any time both values appear in either column together.
Really hoping I can get this into a simple table format, because I have another table where I will need to do similar that will be more complex so I'm hoping to avoid longer form counting tables if it can be avoided.
Any help would be much appreciated!

A: try:
=ARRAYFORMULA(TRIM(QUERY(IF(A:A<B:B, A:A&" "&B:B, B:B&" "&A:A),
 "select Col1,count(Col1) where Col1 <> ' 'group by Col1
  order by count(Col1) desc label count(Col1)''")))

A: Use this formula
=ArrayFormula(
 { "Type1","Type 2", "Count";
    SPLIT(UNIQUE(FILTER(QUERY({IF(A2:A<B2:B, A2:A&" "&B2:B, B2:B&" "&A2:A)}), LEN(QUERY({IF(A2:A<B2:B, A2:A&" "&B2:B, B2:B&" "&A2:A)}))>2)), " "),
    COUNTIF(QUERY({IF(A2:A<B2:B, A2:A&" "&B2:B, B2:B&" "&A2:A)}), "="&
              UNIQUE(FILTER(QUERY({IF(A2:A<B2:B, A2:A&" "&B2:B, B2:B&" "&A2:A)}), LEN(QUERY({IF(A2:A<B2:B, A2:A&" "&B2:B, B2:B&" "&A2:A)}))>2)))})


text:
Q: Applying filter to a specific widget in the dashboard using sisense js I am very new to sisense I am trying to figure out a way to apply a filter to one specific widget in the dashboard. (I have successfully managed to apply a filter to the whole dashboard)
Use Case:-
I have a dashboard with 4 widgets displaying 4 simple tables.
1st widget - Shows user logins ("user_logins" table has a column "login_date")
2nd widget - Shows user downloads ("user_downloads" table has a column "downloaded_date")
3rd widget - Shows user certifications ("certifications" table has a column "passed_date")
4th widget - Shows user exams ("exams" table has a column "exam_date)
As you can see dates are displayed from different tables and columns. I know how to filter the whole dashboard using "user_id" as all the tables have the column "user_id".
What I am trying to achieve is when I input a daterange from a daterange picker, I want sisense to filter each widget using their respective table column. How can I achieve that?
I have tried the code below.
window.filters['{{ name }}{{ index }}_from'] = {
     disabled: false,
     jaql: {
         title: "{{ subFilter.column }}",
         table: "{{ subFilter.table }}",
         column: "{{ subFilter.column }}",
         dim: "[{{ subFilter.table }}.{{ subFilter.column }}]",
         datatype: "datetime",
         level: "days",
         filter: {
            from: 0
                 }
         }
   };
   dash.$$model.filters.update(window.filters['{{ name }}{{ index }}_from'], { refresh: false, save: true });

       window.filters['{{ name }}{{ index }}_to'] = {
             disabled: false,
             jaql: {
                 title: "{{ subFilter.column }}",
                 table: "{{ subFilter.table }}",
                 column: "{{ subFilter.column }}",
                 dim: "[{{ subFilter.table }}.{{ subFilter.column }}]",
                 datatype: "datetime",
                 level: "days",
                 filter: {
                     to: 0
                     }
               }
       };
  dash.$$model.filters.update(window.filters['{{ name }}{{ index }}_to'], { refresh: false, save: true });

This code does not throw any errors but does not generate any result as well.
Does anyone have any idea how to fix this?


text:
Q: Are these sentences grammatically correct and sound natural? I am not frightened for myself.
I am not scared for myself.
I am not afraid for myself.
I would use them in this contextus:
I am not frightened because of me, I am scared that my grandparents get infected and they will die due to the virus.
Can I use these three sentences replacing the first one?
I am not frightened because of me = I am not frightened for myself. = I am not scared for myself = I am not afraid for myself.
Is it correct grammatically and sound natural? Or is it totally wrong?
(Feel free to correct my any sentences, because a want to learn a lot from my mistakes)

A: Yes, you can use the three expressions you propose, and they are more natural than "because of myself", though that is not wrong.
Some corrections for your post, per your invitation:
"context" is the correct word in English.
"Is it correct grammatically and does it sound natural?"
"Feel free to correct any of my sentences,..."
"...that my grandparents might get infected and die due to the virus.
A final suggestion for your entire sentence:
"I am not afraid for myself, I am afraid that my grandparents might get infected and die due to the virus."

A: All three (scared / frightened / afraid) work fine, just be sure to match them in the sentence.
I am not frightened for myself, I am frightened that my grandparents will get infected and that they will die due to the virus.
I am not afraid for myself, I am afraid that my grandparents will get infected and that they will die due to the virus.
Also note that in the second clause (clauses are the sections separated by the comma) the sections either side of the "and" should match each other structurally - "that [noun]", "will [verb]"  or, like the other comment suggested, just drop them in both parts.
I am not afraid for myself, I am afraid that my grandparents will get infected and that they will die due to the virus.
I am not afraid for myself, I am afraid my grandparents will get infected and will die due to the virus.
although this last one is not as good stylistically, as now the use of "afraid doesn't match in each clause ("afraid for" vs "afraid")
So, finally, my best option:
I am not afraid for myself, I am afraid for my grandparents. They may get infected and die due to the virus.
It's not as strong (may get infected and die vs will get infected and die) but it all matches stylistically.
The best way to determine the style is the context - what is the sentence that this in response to? It would help determine the best structure of the response.


text: Q: Black Screen of Death question on a Dell Inspiron 7348 2-in-1 So, I've been searching for a solution to this issue. I've been scouring forums looking for an answer to my black screen of death problem. I have an Dell Inspiron 7348 2-in-1. Currently this is running 17.04, but have tried various flavors. I know this is driver/hardware related, but not sure how I can fix it permanantly . Unfortunately I'm not sure of how to get additional hardware specs from the grub menu, and this is a single boot system. Here ultimately is the problem. I have loaded various forms of linux onto this system and almost like clockwork after a week running fine after install, I'll shut it down and reboot, and I get a black screen. After instal, for that week it shuts down and starts up with no problems. I've tried nomodeset in the grub menu. If I insert a USB stick in and got through the "try Linux" it comes up just fine. Any help would be appreciated, and if more info is needed, I can try to elaborate more. Thanks in advance!


text:
Q: Incorrect math/rounding? So in the following set of code, I get completely incorrect answers for some reason...
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;

public class Check03B

{
    public static void main(String[] args)
    {
        PrintStream print = new PrintStream(System.out);
        Scanner scan = new Scanner(System.in);
        print.printf("Enter the satellite altitude in km ... ");
        double A = scan.nextDouble();
        double K = 0.00995;
        double R = 6378;
        double z = (K * (A + R));
        double P = Math.pow(z,(3 / 2));
        double x = (P / 3600);
        double y = (P / 60);
        print.printf("Orbital period = " + x + " hours, " + y + " minutes, and " + "%.1f", P).print(" seconds");
    }
}

The answers are suppose to be: 995 hours, 56 minutes, and 21.1 seconds. if the input is 500000
The rounding is not my question, my question is why am I getting:
1.4 hours 83.9 s ... etc.

A: The issue is here,
double P = Math.pow(z,(3 / 2));

More specifically here
(3 / 2)

because that is integer math. You could use
(3 / (double) 2)

or
(1.5)

A: double P = Math.pow(z,(3 / 2));
double x = (P / 3600);
double y = (P / 60);

3/2 = 1 because its integer

you must use float or double in division


text:
Q: How can I automatically reload my output? I had the idea to make a Countup from a Date with days, month and years and I want to show the countup on a small screen with a raspberry pi or something like that. How can I generate a loop etc. to update the numbers on screen (e. g. every hour)?
Here is the code I wrote:
import time

now = time.localtime()
day=now.tm_mday
month=now.tm_mon
year=now.tm_year
hour=now.tm_hour
minute=now.tm_min
summer=now.tm_isdst
print("Tag:", day)
print("Monat:", month)
print("Jahr:", year)

if month<4:
    j=year-2020
elif month==4:
    if day<4:
        j=year-2020
    else:
        j=year-2019
else:
    j=year-2019

if month<4:
    m=month+7
elif month==4:
    if day<7:
        m=month+7
    elif day>=7:
        m=0
    else:
        m=month-4
else:
    m=month-4

if day<7:
    t=day+24
elif day==7:
    t=0
else:
    t=day-7
print(j , ":" , m , ":" , t)

The Timer should work from the 7th of april 2020.

A: This loop works fairly well...
from datetime import datetime                              # for managing dates and times
import time                                                # for sleeping
while True:                                                # Just loop forever
    time.sleep(0.0)                                        # Set this to modify the tick rate
    d = datetime.now()                                     # Update time
    print(d.strftime("%A %d. %B %Y %H:%M:%S.%f"),end="\r") # Print time

If you are confused by the strftime just check out the formatting placeholders here: https://strftime.org/

A: So, I put the code you sent me in my project and it worked perfectly. My next step is to put the numbers (years,month,days) in a window or something like that, to show the counter on a screen with a raspberry pi. So, how can I open a window, which shows the counter and updates every hour without closing the window?
That's my code so far:
import time

now = time.localtime()
hour=now.tm_hour
minute=now.tm_min
summer=now.tm_isdst
#print("Tag:", day)
#print("Monat:", month)
#print("Jahr:", year)

while True:
    time.sleep(3600.0)
    day=7
    month=4
    year=now.tm_year
    if month<4:
        j=year-2020
    elif month==4:
        if day<4:
            j=year-2020
        else:
            j=year-2019
    else:
        j=year-2019

    if month<4:
        m=month+7
    elif month==4:
        if day<7:
            m=month+7
        elif day>=7:
            m=0
        else:
            m=month-4
    else:
        m=month-4

    if day<7:
        t=day+24
    elif day==7:
        t=0
    else:
        t=day-7
    print(j , ":" , m , ":" , t) #vllt noch h und min???


text:
Q: Dynamically blocking excessive HTTP bandwidth use? We were a little surprised to see this on our Cacti graphs for June 4 web traffic:

We ran Log Parser on our IIS logs and it turns out this was a perfect storm of Yahoo and Google bots indexing us.. in that 3 hour period, we saw 287k hits from 3 different Google IPs, plus 104k from Yahoo. Ouch?
While we don't want to block Google or Yahoo, this has come up before. We have access to a Cisco PIX 515E, and we're thinking about putting that in front so we can dynamically deal with bandwidth offenders without touching our web servers directly.
But is that the best solution? I'm wondering if there is any software or hardware that can help us identify and block excessive bandwidth use, ideally in real time? Perhaps some bit of hardware or open-source software we can put in front of our web servers?
We are mostly a Windows shop but we have some Linux skills as well; we're also open to buying hardware if the PIX 515E isn't sufficient. What would you recommend?

A: I'm not sure about yahoo, but you can configure the frequency Google's bot indexes your site. Have a look at Google Webmasters.  I'm not sure if Yahoo has anything similar.  At any that'll reduce your traffic up to 50%.
Alternatively, some web servers can limit traffic per connection so you can try that. I personally would stay away from hardware solutions since it's most likely going to cost more.

A: To reduce the crawling load - This only works with Microsoft and Yahoo. For Google, you'll need to specify a slower crawling speed through their Webmaster Tools (http://www.google.com/webmasters/).
Be VERY careful when implementing this because if you slow down the crawl too much, robots won't be able to get to all of your site, and you may lose pages from the index.
Here are some examples (these go in your robots.txt file):
# Yahoo's Slurp Robot - Please wait 7 seconds in between visits

User-agent: slurp
Crawl-delay: 7

# MSN Robot - Please wait 5 seconds in between visits

User-agent: msnbot
Crawl-delay: 5

Slightly off-topic, but you can also specify a Sitemap or Sitemap index file.
If you'd like to provide search engines with a comprehensive list of your best URLs, you can also provide one or more Sitemap autodiscovery directives.  Please note that user-agent does not apply to this directive, so you cannot use this to specify a sitemap to some but not all search engines.
# Please read my sitemap and index everything!

Sitemap: http://yourdomain.com/sitemap.axd

A: We use a Watchguard firewall (ours is a X1000 which is end-of life now). They have many feautres revolving around blocking domains or ips who are seen time and time again or are using an obsesive amount of bandwidth.
This would need some tweaking because you obvisouly would not want to block Jon Skeet on stackoverflow :)

A: I'd recommend Microsoft ISA Server 2006. Specifically for this requirement, it will limit to 600 HTTP requests/min per IP by default and you can apply an exception for Jon Skeet (sorry, I realise that "joke" has been made already!).
You have the additional benefits of application-level filtering, the ability to load-balance across multiple webservers (instead of NLB on those servers), VPN termination etc. There's a number of commercial extensions available and you can even write your own ISAPI filter if you're feeling brave.
It's obviously not open-source but has benefits to a Windows shop and runs on commodity hardware.

A: If your PIX is running version 7.2 or greater of the OS, or can be upgraded to it, then you can implement QOS policies at the firewall level. In particular this allows you to shape traffic and should allow you to limit the bandwidth used by bots. Cisco have a good gudie to this here.

A: We use Foundry load-balancers (specifically SI850s) to handle this kind of shaping issue, it also handles quite a lot of other 'nastys' like SYN-floods etc. Might be a bit overkill for you guys though.

A: Bluecoat (formerly Packeteer) PacketShaper products can dynamically throttle excessive usage on traffic that it manages.

A: You can even perform rudimentary rate-limiting with any regular Cisco router of any decent capacity/vintage.  Are you using a Cisco router?


text:
Q: $P,Q$ are Hermitian operators with only non-negative eigenvalues, then tr($PQ$) = 0 $\implies$ that $PQ = 0$. So far I can prove:
suppose there is a basis set $\{|i>\}$ that diagonalize $P$ with eigenvalue $p_i$, then tr($PQ$) = $\sum_i<i|PQ|i>$ = $\sum_ip_i<i|Q|i>$.
Since $P, Q$ are Hermitian with non-negative eigenvalues, both $p_i$ and $<i|Q|i>$ is non-negative...
Now there are at least two possibilities to make tr() = $0$.
i) all $p_i$ = $0$, then of course $PQ = 0$
ii) all $<i|Q|i>$ = $0$, then I can't prove $PQ = 0$...
iii) $p_i$, $<i|Q|i>$ alternates to be $0$, $PQ$ = ???
I think they should be a very easy problem... But I am just stuck somehow..

A: Here is a fairly direct argument.
You have
$$
0=\operatorname{tr}(PQ)=\operatorname{tr}(P^{1/2}P^{1/2}Q)=\operatorname{tr}(P^{1/2}QP^{1/2}).
$$
As $Q\geq0$, you have $P^{1/2}QP^{1/2}=P^{1/2}Q(P^{1/2})^*\geq0$. And the trace is faithful, so $P^{1/2}QP^{1/2}=0$. Then
$$
0=P^{1/2}QP^{1/2}=P^{1/2}Q^{1/2}Q^{1/2}P^{1/2}=(Q^{1/2}P^{1/2})^*Q^{1/2}P^{1/2}=0.
$$
So $Q^{1/2}P^{1/2}=0$. Now multiply by $Q^{1/2}$ on the left and by $P^{1/2}$ on the right.


text:
Q: UIButton with title under the imageview I want to creat an UIButton programmatically with the title under the imageView.
Size of the button : 170 * 120
Size of the imge : 50 * 50
Size of the title : depend of the text.
I know I'have to use but I don't know how :
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];
[_button setImageEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f)];

I think I should calculate the size of the title and then Use the EdgeInsets.
Thank you.

A: The ultimate and stable solution is to use frame, not EdgeInset solution like this:
@interface UIButton (UIButtonExt)
(void)centerImageAndTitleEx;
@end

@implementation UIButton (UIButtonExt)

(void)centerImageAndTitleEx
{
CGRect frame = self.imageView.frame;

frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), 10.0f, frame.size.width, frame.size.height);

self.imageView.frame = frame;

frame = self.titleLabel.frame;

frame = CGRectMake(truncf((self.bounds.size.width - frame.size.width) / 2), self.bounds.size.height - frame.size.height - 5.0, frame.size.width, frame.size.height);

self.titleLabel.frame = frame;
}

@end

A: Hope this can help you.
@interface UIButton (UIButtonExt)

- (void)centerImageAndTitle:(float)space;
- (void)centerImageAndTitle;

@end

@implementation UIButton (UIButtonExt)

- (void)centerImageAndTitle:(float)spacing
{
    // get the size of the elements here for readability
    CGSize imageSize = self.imageView.frame.size;
    CGSize titleSize = self.titleLabel.frame.size;

    // get the height they will take up as a unit
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);

    // raise the image and push it right to center it
    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height), 0.0, 0.0, - titleSize.width);

    // lower the text and push it left to center it
    self.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (totalHeight - titleSize.height),0.0);
}

- (void)centerImageAndTitle
{
    const int DEFAULT_SPACING = 6.0f;
    [self centerImageAndTitle:DEFAULT_SPACING];
}

@end


text:
Q: Ошибка авторизации при попытки отправить сообщение от имени сообщества vk Просто пытаюсь отправить сообщение от имени сообщества методом post, но получаю

"error_code":5,"error_msg":"User authorization failed: no access_token passed."

При этом отправка методом get работает успешно!
Пытался отправлять как из кода, так и просто с помощью различных утилит.
var message = new Message()
{
     UserId = 96448509,
     PeerId= 96448509,
     Domain = "kranid",
     RandomId = 2134567654321234,
     Version = 5.92,
     AccessToken = "9746a53ccde445b435a502024c38135201289756d69716f49f973ece422f939447d17d5990b4c68f4e541",
     Text = "hello world!"
};
await  _vkClient.SendMessageAsync(message);

public async Task<string> SendMessageAsync(Message message)
{
     var url = "https://api.vk.com/method/messages.send";
     var response = await _httpClient.PostAsJsonAsync<Message>(url, message);
     return await response.Content.ReadAsStringAsync();
}

Сам запрос получается такой:

VK.VkClient:Information: Method: POST, RequestUri: 'https://api.vk.com/method/messages.send', Version: 2.0, Content: System.Net.Http.ObjectContent`1[VocabularyBot.VK.Message], Headers:
  {
    Accept: application/json
    Content-Type: application/json; charset=utf-8
  }
  VK.VkClient:Information: {"user_id":96448509,"random_id":2134567654321234,"message":"hello world!","access_token":"9746a53ccde445b435a502024c38135201289756d69716f49f973ece422f939447d17d5990b4c68f4e541","v":5.92}

A: В итоге проблема была в том, что я пытался отправить именно JSON, а VK принимает данные, либо в виде обычного url, либо в виде multipart/form-data. То есть относительно конкретно netcore и HttpClient, нельзя использовать метод PostAsJsonAsync, а нужно вызывать PostAsync и передавать ему объект FormUrlEncodedContent, который содержит соответствующие данные, ну или использовать просто get запрос, если ненужно отправлять какие-нибудь файлы.


text:
Q: Objective function Convex proof This is a question from the textbook that I can trying to figure out.
Show that the objective function $$z = c^{T}x  $$ of a linear programming problem is a convex function
I know that $$z = c_{1}x_{1} + .... + c_{n}x_{n}$$ is definition of objective function.
And function f is convex for all $$x, y \in R^{n}$$ $$\lambda \in [0,1]$$ we have $$f (\lambda x + (1 - \lambda)y) \leq \lambda f( x) + (1 - \lambda) f(y) $$
So how do I start this proof...

A: Show that the objective function is linear (a stronger condition than convexity). Can you see how convexity follows?


text:
Q: When I change one GPIO pin output, others also change I implement GPIO via mmap in C. Now I need to use GPIO to simulate I2C, but when I change the output of one pin, the level of the other pin is pulled low. I think I use AND and OR operations to change the value of a pin will not change the value of other pins, what is wrong with my operation? here is my code and pic:
void i2cSDA(u8* map_base, bool isHigh)
{
    (*(volatile u32*)(map_base + GPIO_BASE_OFFSET + rPE_DAT)) = (isHigh) ?
    ((PE_DAT & 0XFFFFEFFF) | 0X00001000):
    ((PE_DAT & 0XFFFFEFFF));
}

void i2cSCL(u8* map_base, bool isHigh)
{
    (*(volatile u32*)(map_base + GPIO_BASE_OFFSET + rPE_DAT)) = (isHigh) ?
    ((PE_DAT & 0XFFFFF7FF) | 0X00000800):
    ((PE_DAT & 0XFFFFF7FF));
}

and in main.c:
int main(int argc, char** argv)
{
    static int dev_fd;
    unsigned char *map_base;

    dev_fd = open("/dev/mem", O_RDWR);

    map_base = (unsigned char *)mmap(NULL, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, dev_fd, GPIO_PAGE_OFFSET);

    i2cInit(map_base);

    i2cSCL(map_base, 1);
    i2cDely();
    i2cSDA(map_base, 1);

    i2cDely();

    i2cSDA(map_base, 0);

    i2cDely();

    i2cSDA(map_base, 1);

    i2cDely();

    close(dev_fd);

    return 0;
}

and PE_DAT is defined as u32 PE_DAT = (*(volatile u32*)(map_base+GPIO_BASE_OFFSET+rPE_DAT));
I use PE12 and PE11, the data register is 32 bits, 0:12 is data for PE0 to PE12, and 13:32 is reserved.

When I try to pull the yellow line to high, the green line get low. Full Code is Here, mainly used I2C.h and GPIO.h.

A: Your funcktions to set/clear bits are wrong:
void i2cSDA(u8* map_base, bool isHigh)
{
    (*(volatile u32*)(map_base + GPIO_BASE_OFFSET + rPE_DAT)) = (isHigh) ?
    ((PE_DAT & 0XFFFFEFFF) | 0X00001000):
    ((PE_DAT & 0XFFFFEFFF));
}

You never update PE_DAT which makes it contain old invalid values.
Also your expressions are too complicated.
This function should looke like this:
void i2cSDA(u8* map_base, bool isHigh)
{
    if (isHigh != 0)
    {
        (*(volatile u32*)(map_base + GPIO_BASE_OFFSET + rPE_DAT)) |= 0X00001000;
    }
    else
    {
        (*(volatile u32*)(map_base + GPIO_BASE_OFFSET + rPE_DAT)) &= 0XFFFFEFFF;
    }
}


text:
Q: How to use a DTO and Messenger with Api-Platform? For one of our resources, we'd like to route the request through a command handler. Creating a new item for this resource has a number of side-effects and prior requirements, so regular REST is not enough.
Since we already have a Messenger handler written for use in different parts of the application, and a simple command object, we thought to use Messenger with an Input Object, as described in the documentation, that says:

Set the messenger attribute to input, and API Platform will automatically dispatch the given Input as a message instead of the Resource. Indeed, it'll add a default DataTransformer (see input/output documentation) that handles the given input

My resource is described thus:
App\Domain\Entity\Bid:
  input: 'App\Application\Command\Lead\BidOnLead'
  messenger: "input"
  itemOperations:
    get: ~
  collectionOperations:
    get: ~
    post: ~

But, when I load the api-docs the schema I'm shown as input is the schema for App\Domain\Entity\Bid, not the schema for App\Application\Command\Lead\BidOnLead, as I would expect.
In case it was only a matter of the documentation being generated incorrectly, I've tried sending a JSON describing the input object (it's a very simple object with a couple of properties), but it fails because it's trying to deserialize into the resource object, not into the input object.
What I'm doing wrong, and how can I implement this?

A: I haven't tested this, but per documentation here:
https://api-platform.com/docs/core/messenger/#symfony-messenger-integration-cqrs-and-async-message-processing
input should be under attributes key:
App\Domain\Entity\Bid:
    attributes:
        input: 'App\Application\Command\Lead\BidOnLead'
        messenger: "input"
    itemOperations:
        get: ~
    collectionOperations:
        get: ~
        post: ~

It may be misleading if you just copying things from annotations to yaml as documentation for yaml is not thorough in ApiPlatform.


text:
Q: Two activities sharing common functionality I have two activities: AddContact and EditContact. They both share a lot of common instance variables and methods that act on that data.
What would be the best way to refactor this code so that there wouldn't be any duplicate code?
Can you recommend any specific design patterns to use? The most obvious of course would be inheritance, but since every activity in android already extends Activity, this is out of the question.
I already thought of making another class that extends Activity, then putting common variables and methods inside this class, and then initializing this class in both AddContact and EditContact. However, if this really is the best way to go, should I make all the methods and instance variables in this shared class static?
Thank you very much for your time.

A: How is Inheritance out of the question?  You could have a base class that extends Activity, then have your two other classes extend that to inherit the shared functionality for example:
public class MainActivity extends Activity {
      //Common functionality and instance methods
}

public class AddContact extends MainActivity {
     //Has all of Main Activity's non private methods/variables
}

public class EditContact extends MainActivity {
    //Has all of MainActivity's non private methods/variables.
}

Also, if you don't want your MainActivity to be used directly, you could just make it abstract to ensure that the subclasses are used instead.  This gives you the perk of reducing redundancy by sharing methods/variables, and also allows you to extend this functionality to make it specific to each subclass, if needed.
The other option is to just use a Singleton to encapsulate common functionality.

A: It depends on that exactly you want to share between two activities. But in my opinion, the best way would be to move common functionality into a Fragment and use it in both activities. If this functionality has visual elements, then it can be visible Fragment with layout. Otherwise it can be invisible fragment with pure logic in it.

A: I wouldn't recommend inheritance, creating a single class common code is really good for reusability however, take on count that each class extending from your base class will be allocating duplicated memory for things with the same purpose, google do not recommend it unless really necessary and the advantages you are getting out of it are really clear, you should take a look at the Singleton design patterns, this seems like a good example of when to implement it, basically you will have 1 single instance that does the job among different components without having to allocate new objects every time, just reusing the one already created.
Hope it helps!
Regards!

A: public class Contact
{
   String name
   //implement the rest of contact's functionality
}

public class AddContact extends Activity
{
    // Create a new instance of Contact
}

public class EditContact extends Activity
{
   // Create a new instance of Contact
}

Only create static methods if it makes sense calling the method if an object has not been created


text:
Q: How to search numbers after decimal point for floating point number in Bash? I am messing around with something on bash (I am very new to it).
I have a floating point number.
I want to to be able to check if there is any digits after the decimal point from 1-9 in order to determine whether it is a whole number - and do it within an if-else statement.
for example
if(*number does have a 1-9 digit after decimal*)
then
    echo 'Number is not a whole number'
else
    echo 'Number is a whole number'
fi

Dabbled with grep and REGEX but don't have a great grasp of it yet

A: With a regex:
x=1.123456789
if [[ "$x" =~ \.[0-9]{1,9}$ ]]; then
  echo 'Number is not a whole number'
else
  echo 'Number is a whole number'
fi

Output:

Number is not a whole number

A: Mac_3.2.57$cat findWhole.bash
#!/bin/bash
for x in 1.123456789 0001230045600.00 1.000000 1 1. 1.. 0002 .00 22.00023400056712300 1.00 .
do
  if [[ "$x" =~ ^[0-9]*\.[0-9]*[1-9][1-9]*[0-9]*$ ]]; then
    echo "$x is not a whole number"
  elif [[ "$x" =~ ^[0-9][0-9]*\.?0*$|^\.00*$ ]]; then
    echo "$x is a whole number"
  else
    echo "$x is not a number"
  fi
done
Mac_3.2.57$./findWhole.bash
1.123456789 is not a whole number
0001230045600.00 is a whole number
1.000000 is a whole number
1 is a whole number
1. is a whole number
1.. is not a number
0002 is a whole number
.00 is a whole number
22.00023400056712300 is not a whole number
1.00 is a whole number
. is not a number
Mac_3.2.57$


text:
Q: Histórico de versões É possível identificar em qual versão de um arquivo (que possui versionamento), está determinado assuntou ou palavra??
Por exemplo, existem 2 versões do documento Teste, onde:

versão 1, possui o texto: "Teste 1, Teste 2 e Teste 3".
versão 2, possui o texto: "Teste 1 e Teste 3".

Ao fazer a busca, queria saber onde encontra-se a palavra "Teste 2".
É na versão 1 ou na versão 2? Que neste caso, encontra-se na versão 1.

A: Olá, Dani.
Com o trecho de código abaixo você conseguirá ler o conteúdo de cada versão de um arquivo dentro de uma biblioteca.
foreach (SPSite tmpSite in tmpRootColl)
            {
                foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                {
                    foreach (SPList tmpList in tmpWeb.Lists)
                    {
                        if (tmpList.BaseType == SPBaseType.DocumentLibrary & tmpList.Title == "Docs")
                        {
                            foreach (SPListItem tmpSPListItem in tmpList.Items)
                            {
                                if (tmpSPListItem.Versions.Count > 0)
                                {
                                    SPListItemVersionCollection tmpVerisionCollection = tmpSPListItem.Versions;

                                    SPFile tmpFile = tmpWeb.GetFile(tmpWeb.Url + "/" + tmpSPListItem.File.Url);

                                    foreach (SPFileVersion tmpSPFileVersion in tmpFile.Versions)
                                    {
                                        StreamReader reader = new StreamReader(tmpSPFileVersion.OpenBinaryStream());
                                        string textoDoc = reader.ReadToEnd();
                                    }
                                }
                            }
                        }
                    }
                }
            }

Faça alguns testes e modifique conforme necessidade.
Creio que pode partir deste código aí.
Abs


text:
Q: Will SCC pattern change if we reverse a graph(using Kosaraju's Algorithm)? Assume we have a digraph, it is not a complete graph and has more than one SCC.
I wonder if the patterns of Strongly Connected Component changes if we transpose the graph and use Kosaraju's Algorithm?
By saying "transpose the graph" I mean flip the direction of edges.
If we try to find SCC in the transposed/reversed graph instead of the original, will the SCC we find be different?
I came up with this question as I misunderstood the algorithm of SCC and runs it on my transposed/reversed graph. What I got is identical SCC to the correct answer/which runs Kosaraju's algorithm. Is it universally true to all graphs?

A: If you look at http://en.wikipedia.org/wiki/Kosaraju%27s_algorithm you will see that:
"the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph."
(A strongly connected component is one where you can get from every vertex to every other vertex in the component, and this will still hold if you reverse all the links). Of course, the links connecting different components will be reversed, so I expect that you will get the components coming out in a different order.

A: No the SCC of the graph will remain the same even when the graph is reversed and that is very important point in kosaraju's algorithm for SCC's. Only the links between SCC's are reversed. Kosaraju's algorithm leverages this fact to evaluate DFS on reversed graph which now gives higher finish time values for SCC's which are closer to the sink SCC. As Sink SCC has no outgoing edge to another SCC hence evaluating DFS on it gives out the SCC as whole connected component and also allows decomposition of graph into a subgraph with similar properties on which we again apply DFS to get another SCC.


text:
Q: Regex-based line deletion script (JS) not working I have an script that reads the file and compares the string by a pattern, if it returns false it will delete the line on the .txt file.
This is my code
const readline = require('readline');
const lineReplace = require('line-replace')
const fs = require('fs');
const inputFileName = './outputfinal.txt';

const readInterface = readline.createInterface({
    input: fs.createReadStream(inputFileName),
});

let testResults = [];
readInterface.on('line', line => {
    testResult = test(line);
    console.log(`Test result (line #${testResults.length+1}): `, testResult);
    testResults.push({ input: line, testResult } );
    if (testResult == false){
        console.log(`Line #${testResults.length} will get deleted from this list`);
        lineReplace({
          file: './outputfinal.txt',
          line: testResults.length,
          text: '',
          addNewLine: false,
          callback: onReplace
        });

        function onReplace({file, line, text, replacedText}) {

        };
    };
});

// You can do whatever with the test results here.
//readInterface.on('close', () => {
//    console.log("Test results:", testResults);
//});

function test(str){

    let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; // email regex

    str = str.split(",");

    // string should be of length 3 with str[1] number of length 7
    if(str && str.length === 3 && Number(str[1]) && str[1] ) {

        let temp = str[0].split("-");

        // check for 85aecb80-ac00-40e3-813c-5ad62ee93f42 separately.
        if(temp && temp.length === 5 &&  /[a-zA-Z\d]{8}/.test(temp[0]) &&  /[a-zA-Z\d]{4}/.test(temp[1]) &&  /[a-zA-Z\d]{4}/.test(temp[2]) &&  /[a-zA-Z\d]{4}/.test(temp[3]) &&  /[a-zA-Z\d]{12}/.test(temp[4])){

            // email regex
            if(regex.test(str[2])) {
                return true;
            } else {
                return false;
            }
        } else {
            return false
        }
    } else {
        return false;
    }
}

But isn't working, returns error no such file or directory, I dont think that is the correct way to do a line remover script

A: First, if the error is "no such file or directory" is because the file doesn't exist. Please check the file exists at first in the same root of your project.
Second, don't use the library "line-replace", if you check the code this create a tmp file and rewrite all the file in a tmp with the replacement. When finish the process the tmp file is renamed to the original.
Third, if you analyze the code the "lineReplace" is async. So there will sometimes to try to open multiple times the file at the same time and consequently write it at same time again. This will create an unsuspected result.
The best recommendation is you must see how File works and Promises (async) in nodejs:

*

*https://nodejs.org/api/fs.html

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

*https://itnext.io/javascript-promises-with-node-js-e8ca827e0ea3
If you see the next code, you will see the next steps:

*

*Create the tmp Route

*Create the tmp File

*Create a promise:

*

*Create a readline interface

*Process each line with a try catch to reject in case of error

*When finish the process replace the tmp file to original file with a try-catch to reject in case of error

*Wait to finish the promise, in case of error delete the tmp file

const fs = require('fs');
const readline = require('readline');

async function replaceLineWithConditional(pathFile, conditional) {
    // tmpFile name
    const tmpFilePath = `${pathFile}.tmp`;

    // Create write stream
    const tmpStream = fs.createWriteStream(tmpFilePath);

    // Process it
    const processFile = new Promise((resolve, reject) => {
        const rl = readline.createInterface({
            input: fs.createReadStream(pathFile),
        });

        // Process line
        rl.on("line", (input) => {
            try {
                if (conditional(input)) {
                    tmpStream.write(input); // input
                    tmpStream.write("\n"); // linejump
                }
            } catch (err) {
                // Reject error
                reject(err);
            }
        });

        // Finish
        rl.on("close", () => {
            try {
                // Move the tmpFile
                tmpStream.close();
                fs.renameSync(tmpFilePath, pathFile);

                // Resolve it
                resolve(true);
            } catch (err) {
                // Reject error
                reject(err);
            }
        });
    });

    try {
        // Await the promise
        return await processFile;
    } catch (err) {
        // Delete the tmp file and throw the error
        tmpStream.close();
        fs.unlinkSync(tmpFilePath);
        throw err;
    }
}

So you could call the function with your conditional function process as a callback. For example, I want to keep it all the lines who have a length more than 3 and not start with "a":
// async/await:
await replaceLineWithConditional("./test.txt", (line) => {
    return line.length > 3 && /^[^a]/.test(line);
});

// then/catch:
replaceLineWithConditional("./test.txt", (line) => {
    return line.length > 3 && /^[^a]/.test(line);
}).then(...).catch(...);

input:
Hi
Hello
abcdef
a
lalalal

output:
Hello
lalalal

If you want the file don't finish with the end line. (take a note: Why should text files end with a newline?) this can be a Quiz problem to test knowledge in the fs library :)


text:
Q: javascript number of days calculation I have the following code
// code set somewhere else on page
var ad = "2012-08-29";
var dd = "2012-09-03";

//my code
var a = new Date(ad+'T00:00:00');
var d = new Date(dd+'T00:00:00');
var nn = Math.ceil( parseInt(  ( d.getTime()-a.getTime() ) / (1000*60*60*24) ) );

dd should always be a date farther in the future than ad.
nn should be the number of nights between ad and dd, so in this example, I should have a value of 5 for nn (and it does, when i test it).
nn is being tracked (put into a GA variable, and also an Omniture variable) but about 50% of the time it is not getting a value.  We have triple checked and 100% ruled out that it is not a problem with the tracking itself (we have checked to make sure the tracking implementation is correct, and the (lack of) numbers are consistent between both GA and Omniture).
We are investigating to make sure ad and dd are always the expected yyyy-mm-dd format, and that dd is always a date farther in the future than ad, but assuming that that is shiny, can anybody think of a reason why this calculation would fail?
edit: to clarify, I don't think this calculation is failing, but I wanted a second (or 3rd!) opinion before ruling it out.

A: You are missing a closing parens in the final line of code. Including the final parens the code runs fine and nn = 5 which I believe to be the desired result.
var nn = Math.ceil( parseInt(  ( d.getTime()-a.getTime() ) / (1000*60*60*24) ) );

Alternatively, you could remove the parseInt as Bergi suggested (it has no impact on the code). Just make sure that the parens match and you will be fine.


text:
Q: Upper bound for tail of binomial expansion Let $P,R,T$ be integer constants with $PR$ much greater than $T$.
Suppose I flip a coin $PR$ times, each time (independent of other times) getting heads with probability $1/P$. The probability that I get at most $T$ heads is
$$\left(1-\dfrac1P\right)^{PR}+\binom{PR}{1}\left(1-\dfrac1P\right)^{PR-1}\left(\dfrac1P\right)+\ldots+\binom{PR}{T}\left(1-\dfrac1P\right)^{PR-T}\left(\dfrac1P\right)^T$$
What upper bound can we find for this?
In particular, it would be nice to get an upper bound that is independent of $P$, something like $$\binom{aT+R}{R}e^{bR+cT}$$ for some constants $a,b,c$.


text:
Q: javax.security.auth.login.LoginException: Login failed I'm trying to run a hadoop job (version 18.3) on my windows machine but I get the following error:
Caused by: javax.security.auth.login.LoginException: Login failed: CreateProcess: bash -c groups error=2
        at org.apache.hadoop.security.UnixUserGroupInformation.login(UnixUserGroupInformation.java:250)
        at org.apache.hadoop.security.UnixUserGroupInformation.login(UnixUserGroupInformation.java:275)
        at org.apache.hadoop.mapred.JobClient.configureCommandLineOptions(JobClient.java:557)
        ... 3 more

The same job works fine in an another windows machine. Do I have may be something wrong in the settings variabls? How can I fix this problem?

A: Maybe bash is not available on your PATH?
Do you have Cygwin installed correctly?
I really like this tutorial by Vlad Korolev to set up Hadoop on Windows.


text:
Q: Why is Eclipse Maven saying dependencies of same version are conflicting? When I have a dependency listed more than once in my dependency tree, even if all versions of that dependency are the same, Eclipse will say (in the Dependency Hierarchy tab of a POM) that all but one are "(omitted for conflict with X.X.X)". The group ID, artifact ID, and version will all be the same.
Here's a simple example with a randomly chosen dependency. Notice maven-model and maven-artifact.

I'm using Eclipse Mars (4.5.0)
This doesn't seem to have any affect on anything, besides the misleading messages in the UI. It's just pretty annoying to see "omitted for conflict..." all over the place, especially if I'm wanting to see the true conflicts.

A: The "Dependency Hierarchy" tab of Eclipse is populated by the M2Eclipse plugin. And, unfortunately, it seems this is hard-coded inside the M2Eclipse plugin source code. Whatever the reason a dependency was omitted (duplicate, version conflict...), the M2Eclipse plugin will add the label "omitted for conflict with".
Note that this is not the case of the tree goal of the maven-dependency-plugin, from which this tab mimics the output. By default, the command mvn dependency:tree will not show dependencies that were omitted. If the verbose flag is set to true, then the output will show every dependency that were omitted for: being a duplicate of another; conflicting with another's version and/or scope; and introducing a cycle into the dependency tree.
I couldn't find a bug for this so you could maybe file an enhancement request, through their Bugzilla, to ask that the plugin adheres more with the output of dependency:tree (for example showing the real reason a dependency was omitted, instead of the current default) and to add an option to switch between verbose and not verbose mode.


text:
Q: Should I Provide Data In Routing Logic or Meteor Template Helper? Example:
I am writing a Meteor app that deals with a list of blog posts. All blog posts are stored in a collection called 'Posts'. I use Iron Router for routing.
I want to show the user a list of all the posts created by a particular author. This list will be displayed using Spacebars. Therefore, I need to provide the data to the template.
Problem:
As far as I know, there are two ways to do this:

*

*Using template helpers

*Using the 'data'-property of my route

Option 1 example:
Template.postList.helpers({
postsToDisplay: function(){
    return Posts.find({author: 'someAuthor'});
}
})

Option 2 example:
//Inside my route
data: function(){
    return {postsToDisplay: Posts.find({author: 'someAuthor'})};
}

Question
Are there any significant differences between those two methods? Is there a reason to prefer one over the  other? Does one deliver better performance?
Thank you very much for your answers!

A:
Are there any significant differences between those two methods? Does one deliver better performance?

Not really, it's just design choices after all.

Is there a reason to prefer one over the other?

I would stick to the iron-router + data method, here is why :

*

*You can use waitOn to actually display the list only when data fetched from the server is ready, using Router.onBeforeAction("loading") and a loadingTemplate improves overall user experience.

*You can design a data agnostic postsList template that you can feed with different contexts.
The last point is particularly interesting, because it allows you to define a reusable template that you could use to display the list of recent posts, the list of posts in a category, the list of posts by a certain author as you want to achieve in the first place, etc...
<template name="postsList">
  {{#each posts}}
    {{> postListItem}}
  {{/each}}
</template>

Here you could define posts as a helper of postsList, but it's better to let the parent template that will call postsList assign posts to whatever it needs to.
template:"postsList",
data:function(){
  return {
    posts:Posts.find({
      "author":this.params.author
    })
  };
}

This design pattern allows us to define a route that provides a data context which represents the list of posts by a given author, but you could also define another route providing a data context which will list posts by category.
So by moving out the data provider role from the template helper to the route definition, we have a much more reusable template, which is nice.


text:
Q: Certbot wildcard with express I created a wildcard for *.example.com, but as expected when someone goes to example.com the ssl certificate is no longer valid.
Should I have created a *example.com wildcard ssl certificate (is that even possible ?), or should I create a seperate example.com ssl certificate and serve that somehow on the fly depending on what address has been used ?
My current setup (app is an express app)
http
    .createServer((req, res) => {
        console.log('Redirecting to: ', `https://${req.headers.host}${req.url}`);
        res
            .writeHead(301, {
                Location: `https://${req.headers.host}${req.url}`,
            })
            .end();
    })
    .listen(8081, () => {
        console.log('http upgrade server online on port 8081');
    });

https
    .createServer(
        {
            key: readFileSync(resolve(cwd(), 'cert', 'privkey.pem')),
            cert: readFileSync(resolve(cwd(), 'cert', 'fullchain.pem')),
        },
        app
    )
    .listen(8080, () => {
        console.log('Secure Server is listening on port 8080');
    });

I have an a record for my domain (example.com) and a cname for the subdomain www


text:
Q: RETURN value to variable from query within stored procedure I have a stored procedure that looks something like this:
CREATE PROCEDURE dbo.Distribute
    -- Add the parameters for the stored procedure here
    DECLARE @COMPANYID VARCHAR(MAX);
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    --Determine who has the large queue
    SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS 'Count', WorkerName
    FROM   TABLE
    WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
    AND COMPANYID = @COMPANYID
    GROUP  BY COMPANYID, WorkerName
    ORDER BY COUNT(COMPANYID) DESC

    RETURN

END
GO

I would like to put the return value into a variable so i can do some more logic in the store procedure further down?
The workerName needs to be returned to a variable which i need to use for something else.

A: This is not a direct answer to your question but if all your stored procedure is supposed to do is retrieve a top row and return one of its columns as an output parameter, you might do better by converting it into an inline table-valued function:
-- of course, you need to DROP PROCEDURE dbo.name
-- prior to creating a function by the same name
CREATE FUNCTION dbo.Distribute
    @COMPANYID VARCHAR(MAX)
RETURNS TABLE
AS
RETURN
    --Determine who has the large queue
    SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS [Count], WorkerName
    FROM   TABLE
    WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
    AND COMPANYID = @COMPANYID
    GROUP  BY COMPANYID, WorkerName
    ORDER BY COUNT(COMPANYID) DESC
;

This will give you much flexibility for various situations. For instance, you could just return the row as is:
SELECT * FROM dbo.Distribute(...);

or insert it into a table:
INSERT INTO dbo.SomeTargetTable (...)
SELECT ... FROM dbo.Distribute(...);

Or, if, as in your present situation, you needed to store the value of WorkName into a variable, you could do this:
SELECT @WorkName = WorkName FROM dbo.Distribute(...);

Moreover, you would be able to return results for a column of arguments (and use them in the same query):
SELECT ...
FROM dbo.SomeTable AS t
CROSS APPLY dbo.Distribute(t.ArgumentColumn) AS d
WHERE d.WorkerName = ...  -- for an example
;

A similar flexibility could be achieved with a stored procedure too, albeit with more coding. You could return the results both as output parameters and as a row. You would still be unable to use the results of the SP in a query directly, same as the results of an equivalent inline TVF.
As a final note, I'd like to emphasise that for the best effect the function should be an inline TVF, not a multi-statement TVF. When "seeing" the former in a complex query, the query planner can (and does) blend the function's body with the rest of the query, which enables the planner to come up with the best execution plan possible.

A: Try this to get it into a variable:
declare @WorkerName as varchar(max)

select
     @WorkerName = WorkerName
from (
   SELECT TOP 1 COMPANYID, COUNT(COMPANYID) AS 'Count', WorkerName
   FROM   TABLE
   WHERE  WorkerName IN ( 'Jimmy', 'Sally' )
   AND COMPANYID = @COMPANYID
   GROUP  BY COMPANYID, WorkerName
   ORDER BY COUNT(COMPANYID) DESC
) _Worker

From here, you can use it in your procedure, change to a function with a return value, or use an output parameter to send it back to the caller.


text:
Q: Google Task API access through Google Apps Script When you query the Tasks Object for all of the Tasks each "Page" will contain the maxResults number of Results (default maxResults=100).
If you have over 100 Tasks in a Specific TaskList or want to use pagination, you need to use pageToken to request subsequent "pages" of Tasks.
This can be done by running list() (TasksCollection Class), then retrieving the nextPageToken(). Subsequently running list() and passing in the nextPageToken, as an optional argument will give you the 2nd page of results.
  var tasksObj = Tasks.Tasks.list(MytaskListId, {maxResults : 20});
  var nextPageToken = tasksObj.getNextPageToken();
  tasksObj = Tasks.Tasks.list(MytaskListId, {maxResults : 20, pageToken: nextPageToken});
  var tasks = tasksObj.getItems();
  //"tasks" will hold the Tasks 20 to 40.

However, I am confused by why the documentation shows a setNextPageToken method
https://developers.google.com/apps-script/class_tasks_v1_schema_tasks#setNextPageToken
What can that be used for?
The below code does not work because subsequent calls to list() without the nextPageToken argument will return the first set (i.e. items 1 to 20).
  var tasksObj = Tasks.Tasks.list(MytaskListId, {maxResults : 20});
  var nextPageToken = tasksObj.getNextPageToken();
  tasksObj.setNextPageToken(nextPageToken);
  tasksObj = Tasks.Tasks.list(MytaskListId, {maxResults : 20});
  var tasks = tasksObj.getItems();
  //"tasks" will hold the Tasks 1 to 20.

Am I missing something....what is the purpose of the setNextPageToken() method?
Thanks.

A: I believe that is a documentation issue. There are two Tasks classes one that exposes behavior and other just exposing schema/properties.
https://developers.google.com/apps-script/class_tasks
https://developers.google.com/apps-script/class_tasks_v1_schema_tasks
Use the 1st one and ignore the 2nd one. We'll look into cleaning this up soon.


text:
Q: How to create a general method for multiple UIActionSheet in Swift I'm setting up a UIViewController with 2 UIButtons.
Each button will have a function which will show an UIAlertController with few options.
It is possible to create a general method to avoid the duplication of code in both functions ?
I already tried to create a function with a parameter of type  UIAlertController but I can't manage to use that parameter.
Here I've created an example to show you what I try to refactor:
func showFirstMenu(){

    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    let optionOne = UIAlertAction(title: "Option 1", style: .default) { action in
        self.performSegue(withIdentifier: "optionOne", sender: self)
    }

    let optionTwo = UIAlertAction(title: "Option 2", style: .default) { action in
        self.performSegue(withIdentifier: "optionTwo", sender: self)
    }

    actionSheet.addAction(optionOne)
    actionSheet.addAction(optionTwo)
    actionSheet.addAction(cancel)

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        actionSheet.popoverPresentationController?.permittedArrowDirections = []
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPad")
    }
    else{
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPhone")
    }
}

func showSecondMenu(){

    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    let optionThree = UIAlertAction(title: "Option 3", style: .default) { action in
        self.performSegue(withIdentifier: "optionThree", sender: self)
    }

    let optionFour = UIAlertAction(title: "Option 4", style: .default) { action in
        self.performSegue(withIdentifier: "optionFour", sender: self)
    }

    actionSheet.addAction(optionThree)
    actionSheet.addAction(optionFour)
    actionSheet.addAction(cancel)

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        actionSheet.popoverPresentationController?.permittedArrowDirections = []
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPad")
    }
    else{
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPhone")
    }
}

It is any way to reduce this amount of code ? Or this is the only way to declare an UIActionSheet ?
Thanks if you read this.

A: Solution 1:
If your AlertViewController's actions will always have segue to perform you can significantly reduce duplication like below using struct and variadic parameters:
struct Option {
    var name: String
    var segueIdentifier: String
}

func configureActionSheet(options: Option...) {
    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    actionSheet.addAction(cancel)

    for option in options {
        let currentOption = UIAlertAction(title: option.name, style: .default) { action in
            self.performSegue(withIdentifier: option.segueIdentifier, sender: self)
        }
        actionSheet.addAction(currentOption)
    }

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        actionSheet.popoverPresentationController?.permittedArrowDirections = []
    }

    self.present(actionSheet, animated: true, completion: nil)
}

func showMenu1() {
    let option1 = Option(name: "Option 1", segueIdentifier: "optionOne")
    let option2 = Option(name: "Option 2", segueIdentifier: "optionTwo")
    self.configureActionSheet(options: option1, option2)
}

Solution 2:
If your AlertViewController's action will always be different then there is not much you can do but still avoid duplication as follows:
func configureActionSheet() -> UIAlertController {
    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    actionSheet.addAction(cancel)

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        actionSheet.popoverPresentationController?.permittedArrowDirections = []
    }

    return actionSheet
}

func showFirstMenu() {
    let optionOne = UIAlertAction(title: "Option 1", style: .default) { action in
        self.performSegue(withIdentifier: "optionOne", sender: self)
    }

    let optionTwo = UIAlertAction(title: "Option 2", style: .default) { action in
        self.performSegue(withIdentifier: "optionTwo", sender: self)
    }

    let actionSheet = configureActionSheet()
    actionSheet.addAction(optionOne)
    actionSheet.addAction(optionTwo)
    self.present(actionSheet, animated: true, completion: nil)
}

A: you can write a function like this
func presentActionsheetWithOptions(title:String, msg: String, options:[String:String], isCancelRequired:Bool) {

    let actionSheet = UIAlertController(title: title, message: msg, preferredStyle: .actionSheet)

    for (header,seg) in options {
        let optionOne = UIAlertAction(title: header, style: .default) { action in
            self.performSegue(withIdentifier: seg, sender: self)
        }
        actionSheet.addAction(optionOne)

    }
    if(isCancelRequired) {
        let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        actionSheet.addAction(cancel)

    }
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        actionSheet.popoverPresentationController?.permittedArrowDirections = []
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPad")
    }
    else{
        self.present(actionSheet, animated: true, completion: nil)
        print("Display on iPhone")
    }
}

Make a function call like
        presentActionsheetWithOptions(title: "test", msg: "testmsg", options: ["option1":"optionone","option2":"optiontwo"], isCancelRequired: true);

decide on variables that should be optional

A: You can set a tag in each UIButton like this:
//For the first button
UIButton.tag = 1

//For the second button
UIButton.tag = 2

Then, you pass this tag in your menu function, create an array of your UIAlertAction titles and identifiers, loop them and add the proper action to the alert by using the switch method:
  func showMenu(sender: UIButton) {
     let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
     let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

     let titles = ["Option 1", "Option 2", "Option 3", "Option 4"]
     let identifiers = ["optionOne","optionTwo","optionThree","optionFour"]
     let tags = [1,1,2,2] //match the button tag with the array index

     for (index, title) in titles.enumerated(){
        if sender.tag == tags[index] {
           let action = self.getAction(title: title, identifier:identifiers[index])
           actionSheet.addAction(action)
        }
      }
      actionSheet.addAction(cancel)
  }

  func getAction(title: String, identifier: String) -> UIAlertAction {
      let action = (title: title, style: .default) { action in
         self.performSegue(withIdentifier: identifier, sender: self)
      }
      return action
  }

Hope this helps!


text:
Q: Why Deployer say storage:link failed when i start using public disk in Laravel? i use php deployer tool (Deployer.org) for deploy my app on Laravel 5.5.
When i start use public disk with symlynk storage -> storage/app/public,
 i have got error on deployng:
In Client.php line 96:

The command "/usr/bin/php /var/www/example.com/releases/1/artisan
storage:link" failed

Exit Code: 1 (General error)

Host Name: production

================

In Filesystem.php line 228:

symlink(): No such file or directory

I saw in  directy on host /releases/1/public broken symlink to my local MacOs folder storage -> /Users/user1/Code/project/storage/app/public
I repeat new installation from scratch Laravel project&Deployer but still gor error.

A: Fixed it. I accidentally pushed up the
Public/Storage folder to git. (


text:
Q: mySQL export to spreadsheet with multiple tabs I have forms inputting to a mySQL backend. Each day I havee a script run that grabs the data from last 24 hours and puts it into a spreadsheet. There are currently 3 tables and 3 spreadsheets created.
I have done this with with:
SELECT *
FROM `transfer-authority`
WHERE Time > DATE_SUB( NOW( ) , INTERVAL 24 HOUR )
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

So it's just a simple CSV. I then use a CRON job to rename this file to the date and email it.
My question is if it is possible to have the results of all three tables made into a spreadsheet with a tab per table? I've searched for this but cannot find anything on it.
Any help or direction is greatly appreciated.

A: Not using a CSV, but there are dozens of PHP libraries that allow you to create real Excel files that do support multiple sheets within a workbook. In addition to PHPExcel, this previous answer on SO lists a good number of libraries capable of doing this

A: It is possible to create a vba script to do this in excel. Check http://www.excelforum.com/excel-programming-vba-macros/543839-combine-csv-files-into-1-excel-workbook-as-sheets.html

A: The easiest way I found to do this was with ssconvert from gnumeric (man page here: http://manpages.ubuntu.com/manpages/lucid/man1/ssconvert.1.html).
It was as simple as this bash script after exporting to 3 CSVs:
#!/bin/sh

DATE="$(date +"%d-%m-%Y")"
ssconvert --merge-to $DATE-chit.xls "file1.csv" "file2.csv" "file3.csv"


text:
Q: Is it possible to use two offsets with lme4 in R? all. I am doing negative binomial linear mixed model using lme4 package in R.
My question is whether or not there is a way to put two offsets in glmer.nb or control one predictor variable of a model to see another predictor's effects.
Using a model, I would like to test whether or not the number of aggression between males increases with the number of male and also with the number of females around them.
My code is like this.
t<- glmer.nb(no.aggression ~ no.males + no.females
           +(1|id_target) + offset(log(hours)), data=x)

The response variable is the number of aggression between males which I observed during a day. Since the daily observation time varied over days, it was put in offset.
The number of males predicted the number of aggression but the number of females did not predict the number of aggression. However, the number of males was positively related with the number of females on the day. So I guess that males might be attracted by the females or something so when there are more females, there are more males. This might result in increase in the number of aggression of a given day. I thought that it will be possible to control the effect of number of males using two offsets or something, though I don't know the way to do that.
Let me know, if you have any tips or if it is not a proper approach.
Best.