text:
Q: If U is a domain and an analytic function f maps U to the unit circle, then f is constant? I'm trying to show that if an analytic function $f$ maps a domain to the unit circle $\{z : |z| = 1\}$ then f must be constant. I want to use the Cauchy-Riemann equations.
What I have so far: Let $f(x+iy) = u(x+iy) + i v(x+iy)$, where $u$ and $v$ are real-valued functions. Since $|f(x+iy)| = 1$ for all $x+iy \in U$, then
$[(u(x+iy))^2 + (v(x+iy))^2]^{1/2} = 1$ so $(u(x+iy))^2 + (v(x+iy))^2 = 1$
So then
$2u(x+iy) u_x(x+iy) + 2v(x+iy) v_x(x+iy) = 0$
and
$2u(x+iy) u_y(x+iy) + 2v(x+iy) v_y(x+iy) = 0$
Since f is analytic we have $u_x(x+iy) = v_y(x+iy)$ and $u_y(x+iy) = -v_x(x+iy)$.
I've tried plugging these into the above system in various ways and just can't seem to get anything meaningful out. I want to show somehow that $u_x = u_y = 0$ and $v_x = v_y = 0$ so that both $u$ and $v$ must be constant.
Thanks for any help!

A: So far so good. Differentiate $u^2 + v^2 = 1$ to get $uu_x + vv_x = 0$ and $uu_y + vv_y= 0$.  You can write these in matrix form as $$\begin{bmatrix} u_x & v_x \\ u_y & v_y \end{bmatrix} \begin{bmatrix} u \\ v \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$
Apply the Cauchy-Riemann equations to find that
$$\begin{bmatrix} u_x & -u_y \\ u_y & u_x \end{bmatrix} \begin{bmatrix} u \\ v \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$ at all points in the domain. Since at least one of $u$ and $v$ must be nonzero (the sum of their squares is one) the matrix is singular and thus has determinant zero. Thus
$$u_x^2 + u_y^2 = 0$$
so that $u_x = u_y = 0$ throughout the domain making $u$ constant. Likewise $v_x = v_y = 0$ throughout the domain making $v$ constant too.


text:
Q: Intellij "cannot resolve symbol" after installing spring boot I've recently installed the plugin "spring boot assistant" into my Intellij. When I was trying to run an old java file that I've completed before, a lot of the symbols were displayed as "cannot resolve symbol".
This is what my file looks like.

I think this might have something to do with maven, but I dont know how to fix it since there's no errors with running the program before installing spring-boot and maven. I've just started learning spring boot so I'm still unfamiliar with the functions. Please help me.

A: Some plugins might mess up with the project settings. First of all, try to invalidate cache: File -> Invalidate Caches / Restart.... Confirm with Invalidate and Restart. It takes a while but is worth a try.
If it doesn't work your SDK is not set: Open File -> Project Structure... and navigate to Project and add a Project SDK and the Project language level you need (you might want to navigate to your SDK saved in the system instead).

It is also worth to try checking up the language levels:

*

*File -> Project Structure... and navigate to Modules.
Check the Language level of each module.

*File -> Settings and navigate to Build, Execution, Deployment -> Java Compiler.
Check the Target bytecode version of each module.

A: It seems to have issues with resolving absolutely basic Java stuff - try going into Project Structure -> Project Settings -> Project and check if you have an SDK defined for your project.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Geom_text not aligned at the top of the bars The geom_text labels are not centered at the top of the bars in the graph below, especially the last two labels (left to right):

Does anyone have any ideas to align them at the top of the bars?
I have tried some code changes, but the best one I got was:
my_df = data.frame(c('2017','2018','2019','2019','2019','2019','2020','2020'),
                   c(96, 91, 20.59, 47.37, 78.12, 10.00, 15.00 ,91),
                   c("No","No", "20%", "20%", "5%", "20%", "20%", "No"))
colnames(my_df) <- c("Year","Threshold","Fee")

colors <- c("No"="seagreen3","5%"="yellow2","20%"="red4")

ggplot(data=my_df,
       aes(x=Year, y=Threshold, label=Threshold, group=Fee)) +
  geom_col(aes(fill = Fee),
           position = position_dodge2(width = 1, preserve = "single")) +
  geom_text(position = position_dodge2(width = 1), vjust=-0.5,size=2) +
  scale_fill_manual(values = cores2)

A: Here is a possible solution by reordering the data frame and adjusting the position_dodge2 elements.
my_df<-my_df[order(my_df$Year, my_df$Fee), ]
ggplot(data=my_df,aes(x=Year, y=Threshold, label=Threshold)) +
  geom_col(aes(fill = Fee), width=1, position = position_dodge2(width = 1, preserve = "single")) +
  geom_text(position = position_dodge2(width = 1, preserve = "single"), vjust=-0.5, size=3)


text:
Q: Get lookup field with xslt I have the following code in XSLT (.aspx page) and I get the Id of "Evaluacion" lookup field with @EvaluacionIDLookup. I need to get the name of "Evaluacion" but the internal name is "EvalCompeEvaluacion" and if I set @EvalCompeEvaluacion intead I get a strange code.

            <xsl:value-of select="@EmpleadoCargoLookup" />
            <xsl:choose>
                <xsl:when test="@RespuestaJSON != ''">

                        <xsl:attribute name="href">
                            <xsl:text>#</xsl:text>
                        </xsl:attribute>
                        <xsl:attribute name="onclick">
                            <xsl:text>javascript:EC.Empleados.ForEvaluation.ViewReport(</xsl:text>
                            <xsl:value-of select="translate(translate(@EmpleadoCedulaLookup,'.',''),',','')"/>,
                            <xsl:value-of select="translate(translate(@EvaluacionIDLookup,'.',''),',','')"/>
                            <xsl:text>);return false;</xsl:text>
                        </xsl:attribute>

                </xsl:when>
                <xsl:otherwise>
                    <xsl:text></xsl:text>
                </xsl:otherwise>
            </xsl:choose>


text:
Q: Use of hyphen between a number and percent Should I use a hyphen between a number and percent? Two examples:

*

*Which is right: fifty percent increase or fifty-percent increase?

*

The population of the city was second highest with 13.5-percent share to the total population of the province.

Is it okay to put a hyphen between 13.5 and percent?

A: The Chicago Manual of Style Online (CMOS 17) has a "Hyphenation Table" that says "number + percent" should always be written open (although if the numbers cover a range, an n-dash would be used between them). The examples given are "50 percent", "a 10 percent raise", and "a 30–40 percent increase". Based on that, it seems like according to CMOS style, you should write "a fifty percent increase" (or "a 50 percent increase": none of their examples shows percentages being spelled out, but I assume that wouldn't make a difference to the hyphenation).
I don't know if other style guides make different choices about this.  The rule is also given in the sixteenth edition of CMOS.
As Wrzlprmft and Barmar mentioned, the second sentence is badly written so it's hard to say how it should be punctuated.


text:
Q: How to turn truth table into smallest possible if / else block How can I take a truth table and turn it into a compacted if block?
For instance, let's say I have this truth table where A and B are conditions and x, y and z are possible actions:
A B | x y z
-------------
0 0 | 0 0 1
0 1 | 0 0 1
1 0 | 0 1 0
1 1 | 1 0 0

This could transform into below if block:
if(A)
{
    if(B)
    {
        do(x)
    }
    else
    {
        do(y)
    }
}
else
{
    do(z)
}

This is an easy sample, but I frequently have several conditions that combined in different ways should produce different outputs and it gets hard to figure out the most compacted and elegant way to represent their logic in an if block.

A: In C#.NET, you can use a Dictionary Class to get the result without any IF ELSE as follows - The nice thing about this is:

*

*It is readable

*New keys will be unique (otherwise, you get an error)

*Sequence does not matter

*Easy to add or remove entries

If you don't have an equivalent of Dictionary Class, you can do the same in a binary look-up/search function.
//A B | x y z
//-------------
//0 0 | 0 0 1
//0 1 | 0 0 1
//1 0 | 0 1 0
//1 1 | 1 0 0
// Create a Dictionary object and populate it
Dictionary<string, string> _decisionTable = new Dictionary<string, string>() {
    { "0,0", "0,0,1" },
    { "0,1", "0,0,1" },
    { "1,0", "0,1,0" },
    { "1,1", "1,0,0"}
};

//usage example: Find the values of X,Y,Z for A=1,B=0
Console.WriteLine(_decisionTable["1,0"]);
Console.Read();

A: Here is your library :)  And you dont need to pass full K-table, only fields that you are interested in :)
It assumes that its AND operator in truth table.
If you want to use more operators, you should be able to rewrite it.
You can have any number of arguments.
Written in python, and tested.
def x():
    print "xxxx"

def y():
    print "yyyyy"

def z(): #this is default function
    print "zzzzz"

def A():
    return 3 == 1

def B():
    return 2 == 2

def insert(statements,function):
    rows.append({ "statements":statements, "function":function })

def execute():
    for row in rows:
        print "==============="
        flag = 1

        for index, val in enumerate(row["statements"]):
            #for first pass of lopp, index is 0, for second its 1....
            #if any function returns result different than one in our row,
            # we wont execute funtion of that row (mark row as not executable)
            if funcs[index]() != val:
                flag = 0

        if flag == 1:
            #we execute function
            row["function"]()
        else: z() #we call default function

funcs = [A,B]  #so we can access functions by index key
rows = []

insert( (0,0), y)
insert( (0,1), y)
insert( (1,0), x)
insert( (1,1), x)
insert( (0,1), x)

execute()

A: What you want is a Rete algorithm. This automatically combs a set of rules and prioritizes them into a tree the way you describe.
There are a number of commercial "rules engine" systems that do this on the very large scale (millions of rules) where execution speed is essential.

A: If you are designing from a Karnaugh map, then the code may as well look that way too:
//                   a      b
def actionMap = [ false: [false: { z() },
                          true:  { z() }],
                  true:  [false: { x() },
                          true:  { y() }]]

actionMap[a][b]()

A: A lookup table containing functions pointers can work well in some situations. In C, for example, you can do something like this:
typedef void(*VoidFunc)(void);

void do(int a, int b)
{
    static VoidFunc myFunctions[4] = {z, z, y, x}; // the lookup table

    VoidFunc theFunction = myFunctions[ a * 2 + b ];
    theFunction();
}

This is a good solution when the number of inputs is relatively small, since the number of entries in the table has to be 2^^n where n is the number of inputs. 7 or 8 inputs might be manageable, 10 or 12 starts to get ugly. If you have that many inputs, try to simplify by other means (such as Karnaugh maps) first.

A: Map the inputs into a single value and then switch on it:
#define X(a, b) (!!(a) * 2 + !!(b))
switch(X(A, B)) {
case X(0, 0):
    ...
    break;
case X(0, 1):
    ...
    break;
case X(1, 0):
    ...
    break;
case X(1, 1):
    ...
    break;
}
#undef X

A: Look at the "Gorgeous Karnaugh" software - it can accept truth tables quite exact as your sample, accept analytic boolean formulas definition, accept Lua scripting to build truth tables. Next, "Gorgeous Karnaugh" software draws the K-Maps for taken input, which you can minimize manually or using "Espresso" logic minimizer, and produces output for C/C++ and some hardware languages. Look to the summary features page for "Gorgeous Karnaugh" - http://purefractalsolutions.com/show.php?a=xgk/gkm


text:
Q: Is there a simple way to prove the Four Colour Theorem? The four colour theorem says that:

Given any separation of a plane into contiguous regions, producing a figure called a map, no more than four colours are required to colour the map so that no two adjacent regions have the same colour.
From http://en.wikipedia.org/wiki/Four_colour_theorem

The theorem has been proved using computers. But I am wondering, is there a more simple proof than using computers to do it? I feel that using brute force to prove something is like the last resort. So, is there a simple proof of the Four Colour Theorem, or is it yet to be proved?

A: A completely computer-free proof has yet to exist. However there are easy proofs for the five(and up) color theorems.

A: no, there isn't. This has been proved using a computer which took hundreds of hours as you have to go through every proof separately.

A: The four colour theorem was supposedly proved by 'Appel and Haken' by using a computer as a tool. They used the tool to supposedly go through every example possible. However there is no 'proof' that the proof actually happened and exists.  I guess it can be proved by hand but it would take you years.. So the answer is no there is no simple proof of the four colour theorem.


text:
Q: How to get current location using googleapiClient then put marker I do want to get current location with GoogleApiClient with this code below,
@Override
public void onConnected(@Nullable Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if(mLastLocation != null)
    {
        currentLat = mLastLocation.getLatitude();
        currentLon = mLastLocation.getLongitude();
    }else
    {
        Toast.makeText(getApplicationContext(), "Cannot get lat and lon", Toast.LENGTH_SHORT).show();
    }
}

then after that i do want to put marker on current location, my problem is mLastlocation still null
@Override
public void onMapReady(GoogleMap googleMap) {
    dGoogleMap = googleMap;

    if(mLastLocation != null)
    {
        MarkerOptions marker = new MarkerOptions()
                .position(new LatLng(currentLat, currentLon))
                .title("My Current Location");

        dGoogleMap.addMarker(marker);
        dGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(currentLat, currentLon), 16));
    }
}

Or this is my fault missunderstand the flow of async, or just my poor logic needs to be improved.

A: Put below line in your onMapReady method
dGoogleMap.setMyLocationEnabled(true);


text:
Q: TortoiseSVN: got warning message when update file I have used TortoiseSVN  to check out the source code from the server, Today I changed  one file: theme.css on my local computer, instead click commit, I clicked update, afterwards, I got a warning message, then exclamatory mark added on my file: theme.css, and got three more files: theme.css.mine, theme.css.r3588, theme.css.r3656 and in theme.css, I saw at the beginning there is <<<<<<< .mine, and at the end there is >>>>>>> .r3656, so what happened here? and what should I do now?

A: This is standard conflict handling for SVN, It means the file you tried to update has changes on it that conflicted with the version currently on the server.  It adds the <<<<< and >>>>> carots around the areas that are in conflict.  You need to use a conflict merge tool (TortoiseSVN comes with one but you can download and use others if you like).  Right click your conflicted file and choose the option to edit conflicts, then make edits to resolve the conflicts and save a new final file that doesn't contain all the conflict symbols.


text:
Q: Is this hard drive still usable? I wanted to check the health of an older hard drive after it fell from a small height (~20 cm). smartctl -l selftest logged the following self tests:
=== START OF READ SMART DATA SECTION ===
SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
\# 1  Short offline       Completed: read failure       90%     10728         225080

However smartctl -A gave following output:
=== START OF READ SMART DATA SECTION ===
SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   100   100   051    Pre-fail  Always       -       1063
  2 Throughput_Performance  0x0026   252   252   000    Old_age   Always       -       0
  3 Spin_Up_Time            0x0023   061   044   025    Pre-fail  Always       -       12000
  4 Start_Stop_Count        0x0032   097   097   000    Old_age   Always       -       3935
  5 Reallocated_Sector_Ct   0x0033   252   252   010    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x002e   252   252   051    Old_age   Always       -       0
  8 Seek_Time_Performance   0x0024   252   252   015    Old_age   Offline      -       0
  9 Power_On_Hours          0x0032   100   100   000    Old_age   Always       -       10728
 10 Spin_Retry_Count        0x0032   252   252   051    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   252   252   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   097   097   000    Old_age   Always       -       3918
181 Program_Fail_Cnt_Total  0x0022   099   099   000    Old_age   Always       -       30835999
191 G-Sense_Error_Rate      0x0022   100   100   000    Old_age   Always       -       161
192 Power-Off_Retract_Count 0x0022   252   252   000    Old_age   Always       -       0
194 Temperature_Celsius     0x0002   059   044   000    Old_age   Always       -       41 (Min/Max 11/58)
195 Hardware_ECC_Recovered  0x003a   100   100   000    Old_age   Always       -       0
196 Reallocated_Event_Count 0x0032   252   252   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   100   100   000    Old_age   Always       -       6
198 Offline_Uncorrectable   0x0030   252   252   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0036   100   100   000    Old_age   Always       -       14
200 Multi_Zone_Error_Rate   0x002a   100   100   000    Old_age   Always       -       37
223 Load_Retry_Count        0x0032   252   252   000    Old_age   Always       -       0
225 Load_Cycle_Count        0x0032   090   090   000    Old_age   Always       -       111034

In particular these results:
5 Reallocated_Sector_Ct   0x0033   252   252   010    Pre-fail  Always       -       0
196 Reallocated_Event_Count 0x0032   252   252   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   100   100   000    Old_age   Always       -       6

Doesn't this mean while there are 6 bad sectors waiting to replaced, no other sectors have ever been replaced? Isn't there a way to tell the HDD to replace the bad sectors? Can I define 'unused sectors', so the HDD can use them to replace the bad sectors? Or shouldn't I bother to get more life out of this HDD?
I've done the recommended steps described by @heynnema and this are the results:
sudo e2fsck -fccky /dev/sdb1
e2fsck 1.42.13 (17-May-2015)
Checking for bad blocks (non-destructive read-write test)
Testing with random pattern: done
test: Updating bad block inode.
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information

test: ***** FILE SYSTEM WAS MODIFIED *****
test: 11/122101760 files (0.0% non-contiguous), 7713426/488378390 blocks

A: To test your disk for bad blocks, and to map out any bad blocks found...
Note: do NOT abort a bad block scan!

Note: do NOT bad block a SSD

Note: backup your important files FIRST!

sudo e2fsck -fcky /dev/sdXX # read-only test
or
sudo e2fsck -fccky /dev/sdXX # non-destructive read/write test (recommended)
The -k is important, because it saves the previous bad block table, and adds any new bad blocks to that table. Without -k, you loose all of the prior bad block information.
The -fccky parameter...
   -f     Force checking even if the file system seems clean.

   -c     This option causes e2fsck to use badblocks(8) program  to  do  a
          read-only  scan  of  the device in order to find any bad blocks.
          If any bad blocks are found, they are added  to  the  bad  block
          inode  to  prevent them from being allocated to a file or direc‐
          tory.  If this option is specified twice,  then  the  bad  block
          scan will be done using a non-destructive read-write test.

   -k     When combined with the -c option, any existing bad blocks in the
          bad blocks list are preserved, and any new bad blocks  found  by
          running  badblocks(8)  will  be added to the existing bad blocks
          list.

   -y     Assume  an answer of `yes' to all questions; allows e2fsck to be
          used non-interactively.  This option may not be specified at the
          same time as the -n or -p options.


text:
Q: Append "view-source:" to button click url output I'm trying to get the rendered html of a webpage. The ctrl+u equivalent (in firefox or chrome).
Currently I must .click() load the page, get the url and then load it again adding view-source: to the url
search = browser.find_elements_by_xpath('//*[@id="edit-keys"]')
button = browser.find_elements_by_xpath('//*[@id="edit-submit"]')
browser.execute_script("arguments[0].value = 'bla';", search[0])
browser.execute_script('arguments[0].target="_blank";', button[0].find_element_by_xpath('./ancestor::form'))
browser.execute_script('arguments[0].click();', button[0])
url = browser.current_url
browser.get("view-source:" + url)

Is it possible to do this without loading the url twice?
browser.execute_script('return document.documentElement.outerHTML') does not offer the view-source: equivalent
driver.page_source also does not match view-source:
maybe there is a way to add view-source: to browser.execute_script('arguments[0].click();', button[0])?

A: to get the rendered HTML with dynamic JS loaded elements and all you will need to get it with JS with a simple one-liner:
rendered_source = driver.execute_script('return document.documentElement.outerHTML;')


text:
Q: Fix background image in gap - skrollr I'm creating a parallax similar to this example:
http://prinzhorn.github.io/skrollr/examples/classic.html
I would like the third image that appears on scroll to be a fixed background image and not move at all, like on this page with the girl with the sunglasses about halfway down:
http://pollenlondon.com/prism/
I tried removing the transform styles and adding background-attachment:fixed but doesn't work. Any ideas?
Thanks!

A: Simply referencing the exact code shown in the classic example html page, there are several values you need to change as reflected below:
<div
    class="parallax-image-wrapper parallax-image-wrapper-100"
    data-anchor-target="#kittens + .gap"
    data-bottom-top="transform:translate3d(0px, 200%, 0px)"
    data-top-bottom="transform:translate3d(0px, 0%, 0px)">

    <div
        class="parallax-image parallax-image-100"
        style="background-image:url(images/kitteh3.jpg)"
        data-anchor-target="#kittens + .gap"
        data-bottom-top="transform: translate3d(0px, -100%, 0px);"
        data-top-bottom="transform: translate3d(0px, 100%, 0px);"
    ></div>
</div>

You'll be changing both the parallax-image-wrapper and parallax-image height values to 100 instead of 50. Honestly, I don't see any benefit to having a 50% height for the wrapper or bg image itself. Maybe there's a reason I'm missing, but I would expect anyone to want the bg image to span the entire height of the viewport as the exposed gap moves over it.
Because of this, I just set these two classes as having height:100% in my styles, and then drop the extra height classes applied in the html code for each image group above & outside the #skrollr-body. Not critical to do this, but it'll clean up your code a bit.
Then, change the data-bottom-top attribute for the parallax-image-wrapper to 200% y-axis value for translate3d to mirror what you see in the first two image groups.
Lastly, change the y-axis transform3d values for parallax-image from -60%/60% to -100%/100%. This will cause the bg image to remain static as the exposed gap scrolls over top of it and will make it appear to be fixed.


text:
Q: Improved Perlin Noise module for Lua I need Improved Perlin Noise in my Lua code.
Are there any decent open-source Lua C modules available?
Or is there any nice C library that I can write a wrapper for (perhaps with other noise functions)?
I know that it is not hard to write one myself (reference code in Java is trivial to port), but I do not want to reinvent the wheel here.

A: Ah, well, I'll have to roll my own then: http://github.com/agladysh/lua-noise/


text:
Q: Gradle FatJar task creating multiple MANIFEST.MF files When I run this FatJar/UberJar task, I end up with a .jar file whose META-INF\ folder contains two MANIFEST.MF files. One is the correct one with the attributes I inserted into the task definition, and the other simply contains "Manifest-Version: 1.0". This causes a "Could not find or load main class" error when attempting to run the application (I assume it is solely reading the first one and can't identify a main-class)
task fatJar(type: Jar) {
baseName = project.name

manifest {
    attributes 'Implementation-Title': 'Synchronizer',
               'Main-Class': 'net.xxx.yyy.Main'
}
     from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
     with jar
}

MANIFEST.MF #1
Manifest-Version: 1.0
MANIFEST.MF #2:
Manifest-Version: 1.0
Implementation-Title: Synchronizer
Main-Class: net.xxx.yyy.Main
Whats the reason for the duplicate Manifest?
I've tried excluding the MANIFEST.MF using
it.isDirectory() ? it : zipTree(it).matching{exclude{it.path.contains == 'META-INF'}}
it.isDirectory() ? it : zipTree(it).matching{exclude{it.name.contains == 'MANIFEST'}}

*** These do exclude the child JAR META-INF folders and Manifest files, so I'm not sure where MANIFEST.MF #1 is coming from. It appears to be a default?

A: On my version of gradle, I'm not getting 2 manifests with your code - I only end up with a single manifest containing Manifest-Version: 1.0 as you described.
The problem appears to be that your manifest closure isn't actually associated with the jar closure. The Jar task type assignement and "with jar" keyword don't do this for you. Therefore, it isn't recognized as the manifest file for the jar task. You should be able to fix this through one of these options:
task fatJar(type: Jar) {
    baseName = project.name

    jar.manifest {
        attributes 'Implementation-Title': 'Synchronizer',
               'Main-Class': 'net.xxx.yyy.Main'
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } with jar
}

Or, a cleaner way to write the same this would be to include the manifest and from closures in a jar closure:
task fatJar(type: Jar) {
    baseName = project.name

    jar{
        manifest {
            attributes 'Implementation-Title': 'Synchronizer',
                   'Main-Class': 'net.xxx.yyy.Main'
        }
        from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}


text:
Q: SQLAlchemy session.execute() return value CursorResult , return row as dict I am currently using sqlalchemy 1.4.2
I am using session.execute(statement) to fetch rows from my Db table. This is the code I have used below:
    query = f"SELECT * FROM mytable WHERE entity_guid IN {entity_guids}"
    results = session.execute(query)
    for result in results:
        print(results)
        final.append({**result})
    return final

The above code throws me the error:
*TypeError: tuple indices must be integers or slices, not str*
File "/opt/python/lib/python3.8/site-packages/layers/core/read_simple_entities/read_simple_entities.py", line 15, in read_entities
    final.append({**result})
  File "/opt/python/lib/python3.8/site-packages/sqlalchemy/engine/row.py", line 104, in __getitem__
    return self._data[key]

So I updated my code to use _asdict() method:
    results = session.execute(query)
    for row in results:
        final.append(row._asdict())
    return final

But I want to know the reason its passing for some devs with the first block of code where we just unpack result dict even though i use same version of 1.4.2

A: This is a bug in 1.4.2 version of SQLAlchemy and was fixed in later versions. To answer my question the error happens when we use dict(row) to return CursorResult's row as a dictionary. This happens even when unpacking row to dictionary i.e; {**row}
Updating to newer versions of sqlalchemy should be able to fix it. But if you want to use 1.4 and do not want to upgrade the version, the simple workaround for this is to use _asdict() instead of dict(row) or {**row} if you face this error.
The error is also difficult to reproduce on different environments as it happens only on specific os/environments
It was fixed in this commit: https://github.com/sqlalchemy/sqlalchemy/commit/dca3a43de60b064d863abb9b86b1f629fbd4b14d#diff-b4f6b6f09daad6f7b357a69e2c2c5844941fb51167de1c32ec34e018412700fd
Here's the link to discussion on this issue on Github: https://github.com/sqlalchemy/sqlalchemy/issues/6218


text:
Q: How to optimize deleting rows from a large table which has referential integrity? If I have small table with an foreign key(FK) to a large table. When I delete elements from the large table, postgres spends a lot of time calling the trigger for the FK constraint.
Example:
DROP TABLE IF EXISTS large_table CASCADE;
DROP TABLE IF EXISTS small_table CASCADE;

CREATE TABLE large_table (
    id serial primary key,
    name text
);

CREATE TABLE small_table (
    id serial primary key,
    large_table_id serial REFERENCES large_table(id) ON DELETE CASCADE
);

INSERT INTO
    large_table (name)
SELECT
    md5(random() :: text)
FROM
    generate_series(1, 500000) s(i);

-- (in reality we'll be deleting a subset of rows)
EXPLAIN ANALYZE DELETE FROM "large_table";

Delete on large_table  (cost=0.00..9459.09 rows=529209 width=6) (actual time=516.400..516.400 rows=0 loops=1)
  ->  Seq Scan on large_table  (cost=0.00..9459.09 rows=529209 width=6) (actual time=0.013..57.192 rows=500000 loops=1)
Planning Time: 0.055 ms
Trigger for constraint small_table_large_table_id_fkey: time=2272.971 calls=500000
Execution Time: 2810.341 ms

Even though there is no data in in the small_table, postgres is spending ~2 seconds Trigger for constraint small_table_large_table_id_fkey. Is there a way to optimize this without disabling triggers all together on the table?
Postgresql 12.1

A: That is a time of 0.005 milliseconds per check, which is not so bad in my opinion.
You cannot skip the check if you want to maintain referential integrity.
As a superuser, you could do
BEGIN;
SET LOCAL session_replication_role = replica;
DELETE FROM large_table;
COMMIT;

That would disable all triggers including the ones that guarantee referential integrity, so you can potentially cause data corruption that way. You have been warned.


text:
Q: Write a column in a Excel file from 2 different csv files having another column as a key I have 2 csv files of the following format-
file_name2.xlsx-
col1   col2 .    col3
A .    DAVID .   Music
       GILMOUR
B .    John .    Legend
       LENNON
C .    Clapton . Guitar

With_Comments_two.xlsx
Col1 .  col2
A .     PinkFloyd
A .     Britisher
B .     Beatles
        Britisher
C .     Guitarist
        Britisher

I want to write col2 of second file in the first file in the below format-
col1   col2 .    col3 .  col4
A .    DAVID .   Music   PinkFloyd
       GILMOUR           Britisher
B .    John .    Legend .Beatles
       LENNON            Britisher
C .    Clapton . Guitar .Guitarist
                         Britisher

My approach-
I am reading from the 2 excel files into pandas dataframes and then trying to compare them and if common column element found then appending it to a list and then planning to write that list into first file but I don't know how to do it.
Following is my code-
file_name = "With_Comments_two.xlsx"
xl_file = pd.ExcelFile(file_name)
df=pd.read_excel(file_name,sheet_name="Sheet 1 - With_Comments")
file_name_two = "PythonExport.xlsx"
xl_file2 = pd.ExcelFile(file_name_two)
df2 = pd.read_excel(file_name_two,sheet_name="Sheet1")
col1 = list(df.iloc[:,[0]].itertuples())
col2 = list(df2.iloc[[0]].itertuples())
col3 = df2.iloc[: ,[1]]
temp=[]
for ii in col1.itertuples():
   for jj in col2.itertuples():
      if col1[ii]==col2[jj]
        temp.append(col1[ii])

I don't know how to write it in file1 .Also, I don't know my procedure is correct or not. How to do it?


text:
Q: How to validate collection in a spring webflow? I am using Spring WebFlow
I need to check if i have at least 15 collections of type Practices, if not I can't transite to the next flow.
my register-flow:
<view-state id="practices" view="RegisterPractices" model="labs">
        <transition on="add" to="createNewPractice"></transition>
        <transition on="next" to="items" validate="true"></transition>
        <transition on="back" validate="false" to="owners"></transition>
</view-state>
<subflow-state id="createNewPractice" subflow="addPractice">
        <output name="practica" />
        <transition on="practiceAdded" to="practices">
            <evaluate expression="labs.addPractice(currentEvent.attributes.practice)"></evaluate>
        </transition>
        <transition on="practiceCancel" to="practices"></transition>
</subflow-state>

The jsp practices:

Practices

                Practice
                Operation
                Action

            <c:forEach items="${ labs.practices }" var="practice">

                ${ practice.practice}
                <c:choose><c:when test="${ practice.realize == 1}">Realize</c:when><c:otherwise>Deriva</c:otherwise></c:choose>

            </c:forEach>

        Add a New Practice
            Back
        Next

the View-State practices is just a jsp with a list of practices Added.
I have tried with a customValidator but I cant handle the MessageBuilder.source() because I don't have any object in that view.
I have tried too with decision-state but with that I can't show a message like "You have to select at least 15 practices to continue"

A: so this custom validator won't work?
@Component
public class LabsValidator {

    public void validatePractices(final Labs labs,final ValidationContext context) {
        if(labs.getPractices().size() < 15) {
            context.getMessageContext().addMessage(new MessageBuilder().error().code("labs.practices.min15").build());
        }
    }

}


text:
Q: Prolog change order of facts produces different outcomes New to Prolog.  I have a tiny glitch that I cannot explain, but the program appears to work if I add other dictionary(X) facts.  This program takes a string list where the letters have been encoded and produces a decoded list.  Each letter represents a different letter in the list of words.  So go([abccd,edfgh,ade,ifb,kdl],X) returns X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU'].  The problem is if the dictionary('HOW') fact comes before the dictionary('YOU') fact, then the program returns X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'HOW'].  Here is the glitchy code:
/*word bank*/
dictionary('HELLO').
dictionary('WORLD').
dictionary('HOW').
dictionary('ARE').
dictionary('YOU').

/*This spits out a single list where
the lengths of words in the dictionary
are matched to each word in the encoded
message, so [abccd,edfgh,ade,ifb,kdl]
matches [HELLO,WORLD,HOW,ARE,HOW] or
any combination*/
sameLength([X|XTail],[Y|YTail]) :-
   dictionary(Y),
   name(X,L1),name(Y,L2),
   length(L1,Z),length(L2,Z),
   sameLength(XTail,YTail).
sameLength([],[]).

/*Turns a list of lists into
a single list*/
oneWord([X|XTail],Y) :-
   name(X,L),
   append(L,Z,Y),
   oneWord(XTail,Z).
oneWord([],[]).

/*This replaces the letters that are in
the dictionary, with the letters in the
message.  If at any point a letter has
been replaced because it is UPPERCASE,
and that letter is being replaced by
something else then fail, other wise,
the letter has to be lowercase*/
replaceLetters(List,[X|XTail],[Y|YTail],Result) :-
   (X<91,X=Y);(X>96),
   replaceP(X,Y,List,Result1),
   replaceLetters(Result1,XTail,YTail,Result).
replaceLetters(Result,[],[],Result).

/*the call to action*/
go(X,Y) :-
   sameLength(X,Y),
   oneWord(X,A),
   oneWord(Y,B),
   replaceLetters(A,A,B,C),
   B=C,
   !.

/*replace thanks to @repeat*/
replaceP(_, _, [], []).
replaceP(O, R, [O|T], [R|T2]) :- replaceP(O, R, T, T2).
replaceP(O, R, [H|T], [H|T2]) :- dif(H,O), replaceP(O, R, T, T2).

I would like to add that Prolog is cool.  Thanks for your help.

A: my solution allowed me to understand from were the problem come out
go(X,Y) :-
    go(X,Y,[]).

go([],[],_Dict).
go([W|Ws],[T|Ts],Dict) :-
    assoc_codes(W,T,Dict,DictUpd),
    go(Ws,Ts,DictUpd).

assoc_codes(W,T,Dict,DictUpd) :-
    atom_codes(W, Cs),
    dictionary(T),
    atom_codes(T, Tcs),
    upd_dict(Cs, Tcs, Dict, DictUpd).

upd_dict([], [], DictUpd, DictUpd). % done, all went well
upd_dict([C|Cs], [D|Ds], Dict, DictUpd) :-
        memberchk(C-T, Dict)    % if C already 'assigned', must match D
    ->  T = D,
        upd_dict(Cs, Ds, Dict, DictUpd)
    ;   \+ ( memberchk(X-D, Dict), X \= C ),
        upd_dict(Cs, Ds, [C-D|Dict], DictUpd).

note the else branch: when C has not still been assigned, the same must be true for D. If we comment it out (i.e.
...
;   % \+ ( memberchk(X-D, Dict), X \= C ),
...

) we have the problem you report
?- go([abccd,edfgh,ade,ifb,kdl],X).
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'HOW'] ;
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU'] ;
false.

It come out from the fact that 'L' must be assigned to both 'c' and 'g'.
After uncommenting the test, we have
?- go([abccd,edfgh,ade,ifb,kdl],X).
false.

?- go([abccd,edfch,ade,ifb,kdl],X).
X = ['HELLO', 'WORLD', 'HOW', 'ARE', 'YOU'] ;
false.

A: a couple of points:

*

*I think you have the ';' precedence wrong and need another set of brackets.

*The double HOW is actually a valid answer as you are not checking that e.g. both 'a' and 'k' map to H (by chance, the middle 'O' fits both 3-letter patterns).

*There is probably a more 'Prolog' way to solve your problem, by using the natural unification of vars, i.e.

Respresent [abccd,edfgh,ade,ifb,kdl] as a similar list of vars:
[[A,B,C,C,D],[E,D,F,G,H],[A,D,E],[I,F,B][K,D,L]]

and store your dictionary as letter lists
e.g.
dictionary(['H','E','L','L','O']).
dictionary('['W','O','R','L','D']).

Then just use Prolog backtracking to match all the words:
solve([],[]).
solve([Word|Ps],[Word|Words]) :- dictionary(Word), solve(Ps,Words).

and call with something like
:- solve([[A,B,C,C,D],[E,D,F,G,H],[A,D,E],[I,F,B],[K,D,L]], Answer).

Note that this still has the same 'bug' your code has - there is no check all the vars match different letters - you will have to code for that...


text:
Q: AWS - An error occurred (AccessDenied) when calling the GetObject operation: Access Denied I'm unable to read from S3 in my lambda. Public access to the bucket is blocked. Is there something in here that looks out of order?
Here's a snippet from the yml
provider:
  name: aws
  runtime: python3.8
  lambdaHashingVersion: 20201221
  iam:
    role:
      statements:
        - Effect: 'Allow'
          Action:
            - 's3:GetObject'
            - 's3:PutObject'
          Resource: "arn:aws:s3:::my_bucket"

Here's the code failing:
def check_s3(user):
    s3 = boto3.client('s3')
    obj = s3.get_object(Bucket="my_bucket", Key=user)
    data = json.loads(obj['Body'].read())
    return data

And here's the IAM role permissions
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::my_bucket/*",
                "arn:aws:s3:::my_bucket"
            ],
            "Effect": "Allow"
        }
    ]
}

After googling around for quite some time trying different things I feel like it looks as what everyone recommends when seeing this error. What am I doing wrong?


text:
Q: Issue with SUM with two LEFT JOINs In the query below I have trouble when I have two left joins. What happens is the sums are incorrect (elevated) with both left joins. When I remove the second left join, the query runs correctly. How can I run this query with the second left join?
SELECT o.IdNoLocation,
COUNT(DISTINCT o.EncodedId) AS "Frequency",
ISNULL(SUM(o.Subtotal), 0) AS "Spend",
ISNULL(SUM(os.Amount), 0) AS "Surcharges",
ISNULL(SUM(od.Amount), 0) AS "Discounts"
FROM ((tblOrder o
LEFT JOIN tblOrderSurcharge os ON o.OrderId=os.OrderId)
LEFT JOIN tblOrderDiscount od ON o.OrderId=od.OrderId)
WHERE
o.BusinessDate BETWEEN '2014-01-01' AND '2014-12-31'
AND o.IdNoLocation <> 'X'
GROUP BY o.IdNoLocation

A: This is the expected result when there is more than one related row in either tblOrderSurcharge or tblOrderDiscount... you've got an implicit semi-cross join between the rows from those two tables.
There's a couple of approaches to "fixing" this, if you need the totals returned in a single statement.
One option is to use inline views to perform the totals, and then combine the rows. Essentially, run separate queries to get the totals from each table, and then combine the results on a unique key. For example:
SELECT o.IdNoLocation
     , o.Frequency
     , ISNULL(o.Spend, 0)       AS Spend
     , ISNULL(s.Surcharges), 0) AS Surcharges
     , ISNULL(s.Discounts), 0)  AS Discounts
  FROM ( SELECT ooo.IdNoLocation
              , COUNT(DISTINCT ooo.EncodedId) AS Frequency
              , SUM(ooo.Subtotal) AS Spend
           FROM tblOrder ooo
          WHERE ooo.BusinessDate BETWEEN '2014-01-01' AND '2014-12-31'
            AND ooo.IdNoLocation <> 'X'
         GROUP BY ooo.IdNoLocation
       ) o
  LEFT
  JOIN ( SELECT oso.IdNoLocation
              , SUM(oss.Amount) AS Surcharges
           FROM tblOrderSurcharge oss
           JOIN tblOrder oso
             ON oso.OrderId = oss.OrderId
          WHERE oso.BusinessDate BETWEEN '2014-01-01' AND '2014-12-31'
            AND oso.IdNoLocation <> 'X'
          GROUP BY oso.IdNoLocation
       ) s
    ON s.IdNoLocation = o.IdNoLocation
  LEFT
  JOIN ( SELECT odo.IdNoLocation
              , SUM(odd.Amount) AS Discounts
           FROM tblOrderDiscount odd
           JOIN tblOrder odo
             ON odo.OrderId = odd.OrderId
          WHERE odo.BusinessDate BETWEEN '2014-01-01' AND '2014-12-31'
            AND odo.IdNoLocation <> 'X'
          GROUP BY odo.IdNoLocation
       ) d
    ON d.IdNoLocation = o.IdNoLocation

(This isn't tested, just desk checked. Run each of the inline view queries (o, s, d) and verify the results from each of those queries is as you expect. Then, run the entire query, to combine the rows... in the outer query, we'll do the "outer" joins and deal with the "missing" rows and replacing NULLs with zeros)
Another option is to use correlated subqueries in the SELECT list.

A: To see why this doesn't work, run this query:
SELECT o.IdNoLocation,
o.EncodedId AS "Frequency",
o.Subtotal AS "Spend",
os.Amount AS "Surcharges",
od.Amount AS "Discounts"
FROM ((tblOrder o
LEFT JOIN tblOrderSurcharge os ON o.OrderId=os.OrderId)
LEFT JOIN tblOrderDiscount od ON o.OrderId=od.OrderId)
WHERE
o.BusinessDate BETWEEN '2014-01-01' AND '2014-12-31'
AND o.IdNoLocation <> 'X'

The 'correct' answer is to use one table for both surcharges and discounts. I would assume that's no longer an option, but you can fake it with a view that performs a UNION ALL between the two tables.


text:
Q: Problem accessing params.id in the filter I need to create a filter that is triggered on any save/update action in order to record the history of whats being done. I am having a problem getting id of the object that is being manipulated.
My controllers simplified:
class FooController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def save = {

        def fooInstance = new Foo(params)

        if (fooInstance.save()) {
           // params.id = fooInstance.id
            return redirect(action: "show", id: fooInstance.id)
        } else {
            return render(view: "create", model: [fooInstance: fooInstance])
        }
    }
}

My filter needs to get the id of the object that I put in return redirect but unless I uncomment params.id = fooInstance.id above my filter gets null for params.id, I must be missing something dealing with scopes of the variable:
 def filters = {

        history(controller: '*', action: 'save|update|delete|restore') {

            after = {
                println params.id
            }
    }
}

I also tried passing model to after = expecting to get my fooInstance but I get null  as well. Any ideas on whats wrong? Thanks.

A: Look into this plugin http://grails.org/Hibernate+Events+Plugin or the grails audit log plugin. I think they will get you pretty far along.
It is a different approach then you mention in your question, but I think you might prefer it.


text:
Q: Android Studio Relative Layout does not fill the screen I think relative layout is a very powerful utility for designing a user interface because it can eliminate nested view groups and keep your layout hierarchy flat, which improves performance. However I used relative layout for my Android app recently. The problem is that it can't fill the screen. how can I solve the problem? Relative layout does not support weight or gravity? Do I need to using linear layout for that? Is there any solution for that? thank you for your kind answer.
            <?xml version="1.0" encoding="utf-8"?>
            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

            <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_margin="2dp"
            android:id="@+id/picturelayout">

            <ImageView
            android:id="@+id/logoID"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/binanceprofittrace" />

            </RelativeLayout>
            <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:background="@color/Teal"
            android:id="@+id/buyLayout"
            android:layout_margin="2dp"
            android:layout_below="@+id/picturelayout">
            <TextView
            android:id="@+id/buyPriceText"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:textColor="@color/White"
            android:layout_marginRight="10dp"
            android:text="Buy price" />

            <EditText
            android:id="@+id/buyPriceID"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/rounded_corner"
            android:hint="Enter your bid price"
            android:inputType="number|numberDecimal"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textSize="14sp" />
            <TextView
            android:id="@+id/quentityText"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_below="@+id/buyPriceText"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textColor="@color/White"
            android:text="Quentity" />

            <EditText
            android:id="@+id/quentityID"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/buyPriceID"
            android:background="@drawable/rounded_corner"
            android:hint="Enter your quentity"
            android:inputType="number|numberDecimal"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textSize="14sp" />
            <Button
            android:id="@+id/totalAmountButtonID"
            android:layout_width="152dp"
            android:layout_height="42dp"
            android:layout_alignParentBottom="true"
            android:layout_below="@+id/quentityText"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:text="caulculate TOTAL AMOUNT"
            android:textSize="9sp" />
            <TextView
            android:id="@+id/totalAmountResultD"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/quentityID"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textColor="@color/White"
            android:textSize="12sp" />

            </RelativeLayout>
            <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:background="@color/White"
            android:id="@+id/PrecentageLayout"
            android:layout_margin="2dp"
            android:layout_below="@id/buyLayout">
            <TextView
            android:id="@+id/profitRateText"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textColor="@color/Teal"
            android:text="Enter profit rate %" />
            <EditText
            android:id="@+id/profitRateID"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:background="@drawable/rounded_corner"
            android:hint="Enter profit percentage"
            android:inputType="number|numberDecimal"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentRight="true"
            android:textColor="@color/Teal"
            android:textSize="14sp" />
            <Button
            android:id="@+id/percentageBnbButtonID"
            android:layout_width="152dp"
            android:layout_height="42dp"
            android:text="trade with bnb"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/profitRateText"
            android:textColor="@color/Teal"
            android:textSize="12sp" />

            <Button
            android:id="@+id/percentageBtcButtonID"
            android:layout_width="152dp"
            android:layout_height="42dp"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_below="@+id/profitRateID"
            android:text="trade with btc/eth/usdt"
            android:textColor="@color/Teal"
            android:textSize="9sp" />
            <TextView
            android:id="@+id/percentageBnbResult"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/percentageBnbButtonID"
            android:textColor="@color/Teal"
            android:textSize="12sp" />

            <TextView
            android:id="@+id/percentageBtcResult"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/percentageBtcButtonID"
            android:textColor="@color/Teal"
            android:textSize="12sp" />

            </RelativeLayout>
            <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:background="@color/Teal"
            android:id="@+id/sellLayout"
            android:layout_margin="2dp"
            android:layout_below="@id/PrecentageLayout">
            <TextView
            android:id="@+id/selltRateText"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:textColor="@color/White"
            android:text="Enter sell price" />
            <EditText
            android:id="@+id/sellRateID"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:background="@drawable/rounded_corner"
            android:hint="Enter sell price"
            android:inputType="number|numberDecimal"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentRight="true"
            android:textSize="14sp" />
            <Button
            android:id="@+id/sellBnbButtonID"
            android:layout_width="152dp"
            android:layout_height="42dp"
            android:text="trade with bnb"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/selltRateText"
            android:textSize="12sp" />

            <Button
            android:id="@+id/sellBtcButtonID"
            android:layout_width="152dp"
            android:layout_height="42dp"
            android:layout_alignParentRight="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_below="@+id/sellRateID"
            android:text="trade with btc/eth/usdt"
            android:textSize="9sp" />
            <TextView
            android:id="@+id/sellBnbResult"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/sellBnbButtonID"
            android:textColor="@color/White"
            android:textSize="12sp" />

            <TextView
            android:id="@+id/sellBtcResult"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/sellBtcButtonID"
            android:textColor="@color/White"
            android:textSize="12sp" />
            <TextView
            android:id="@+id/sellBnbPercentage"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/sellBnbResult"
            android:textColor="@color/White"
            android:textSize="12sp" />

            <TextView
            android:id="@+id/sellBtcPercentage"
            android:layout_width="152dp"
            android:layout_height="32dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:layout_marginRight="10dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/sellBtcResult"
            android:textColor="@color/White"
            android:textSize="12sp" />

            </RelativeLayout>

            </RelativeLayout>

A: this worked for me as the second activity and played a video in full screen
added no title bar in manifests
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PlayVideo">

<VideoView
    android:id="@+id/videoview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    />

</RelativeLayout>


text:
Q: Kotlin and AOSP Development I am new to AOSP development and wanted to know the following:

*

*Can the Kotlin be used for AOSP development for Automotive Domain?

*If yes, are there any examples for the same?

*If No, reason why Kotlin cannot be used?

Thanks in advance :)

A: Hi it is possible to use Kotlin for your automotive android project.
in android studio when you choose android automotive from templates you can choose default language and Kotlin is one of options.


text:
Q: How to combine a comonad and a monad into a comonad? Assume I have

*

*a comonad D

*a monad T

*a distributive law l : D T -> T D of the comonad D over the monad T.

How can I define the comonad D T?

A: You can't. Suppose D is the identity comonad and T is Cont Void, i.e. the continuation monad at the empty type.
newtype D a = D {runD :: a}
newtype T a = T {runT :: (a -> Void) -> Void}

Then distributivity holds trivially. But extract :: D (T a) -> a is not definable as a total computable program. It would be double negation elimination forall a. ((a -> Void) -> Void) -> a, which is not definable in constructive languages.


text:
Q: Rails link_to for other user's account I have an app set up where a user can nominate a keyholder who will have read-only access to some of their account. The keyholder is just a user with a keyholder boolean field set to true. They also have an access_id equal to the user_id of the account they can access.
Now what I am trying to do is have a link that points to the folders of the user from the keyholder's account, but I'm stumped how to write the link.
E.g.
<%= link_to 'Folder', folder_path(current_user.folder) %>

would link to their own folder, but how do I do:
<%= link_to 'Other User's Folder', folder_path(user.id = access_id) %>

if you see what I mean? Thanks!

A: If I understand you correctly, it looks like you're looking for:
<%= link_to 'Others users folder', folder_path(User.find(current_user.access_id).folder) %>

Now there are better ways to do this. For example if you define the association between the two users in your User model:
belongs_to :access, :class_name => "User"

So now user.access points to the user that can the first one can access. Therefore you can do
<%= link_to 'Others users folder', folder_path(current_user.access.folder) %>


text:
Q: A counterexample of reducible Markov chains about Birkhoff's ergodic theorem In R.Durrett's boos Probability Theory and Examples(5th). There is an example 6.2.4(CH6.2 P301),

"Let $X_{n}$ be an $\textbf{irreducible}$ Markov chain on a countable state space that has a stationary distribution $\pi$..., and applying the ergodic theorem,
  $$ \frac{1}{n} \sum_{m=0}^{n-1} f(X_{m}) \longrightarrow \sum_{x}f(x)\pi(x)."$$

I want to know if there exists a counterexample removing the condition "irreducible", in other words, how about the reducible Markov chain? In this counterexample, the Birkhoff's ergodic theorem does not hold.

A: Take the example of a Markov chain with three states $0$, $1$ and $2$, with transition probabilities

This Markov chain has precisely two irreducible components corresponding to the two absorbing states $1$ and $2$.  Every distribution $\pi$ with $\pi(1)+\pi(2)=1$ is stationary.  But depending on the initial state, the Markov chain will eventually be absorbed to one of the two absorbing states.  Therefore, the ergodic averages $(1/n)\sum_{m=0}^{n-1}f(X_m)$ will converge almost surely to a random variable with two possible values $f(1)$ and $f(2)$, and in particular will not converge to a constant unless $f(1)=f(2)$.
In general, if a Markov chain is not irreducible, then it may have $0$, $1$ or more irreducible components, and each of these components may or may not support a stationary distribution.  The convergence of the ergodic averages will then depend on whether or not the chain ends up in an irreducible component and whether or not that irreducible component supports a stationary distribution ($\equiv$ is positively recurrent).  If $C_i$ is an irreducible component with stationary distribution $\pi_i$, then conditioned on the event that the Markov chain ends up in $C_i$, the ergodic averages will converge almost surely to the mean $\sum_x\pi_i(x)f(x)$.
Just a final remark that for the convergence of the ergodic averages, aperiodicity is irrelevant.


text:
Q: How to play drm contents in cobalt I am developing using cobalt master.
I want to play the drm contents using cobalt. but as far as i know, cobalt(open-source) is not integrated with widevine or playready due to license.
So I have to the widevine integrating.. But I don't know what to do..
Below is question lists. I'd really appreciate it if your guys could answer this.

*

*I found the sources about widevine in the cobalt source tree('cobalt/src/starboard/shared/widevine')
I think it is about widevine porting. then I just need to put in the widevine.so or the widevine source.
Is it right?

*I made a ce_cdm(it is widevine 3.5 source) derectory in 'cobalt/src/third_party' and then tried 'cobalt/build/gyp_cobalt -C debug linux-x64x11' but following message is printed the Terminal.

    $cobalt/build/gyp_cobalt -C debug linux-x64x11  gyp: Dependency '/home/amedia/cobalt4/cobalt/src/third_party/boringssl/boringssl.gyp:crypto#host' not found while trying to load target /home/amedia/cobalt4/cobalt/src/starboard/shared/widevine/widevine3.gyp:protoc#host

I have no idea what this means...

*Please let me know if your guys have a guide or a way to do this.

Thank you.

A: From the gyp errors it looks like the version of widevine you have depends on boringssl which is not currently supported by Cobalt 19. And you might have some trouble integrating boringssl because it is a fork of openssl which is used by multiple components in Cobalt 19.
It might not be too difficult to replace openssl with boringssl. And maybe you can find a version of widevine that's also compatible with openssl, though I'm not sure about the feasibility.
Please also stay tuned to Cobalt's release announcements. We regularly upgrade our third party libraries and you should find new Cobalt releases easier to integrate with additional libraries.


text:
Q: Why this piece of code prints `undefined` at the end? While I am running the following piece of code in Chrome's developer tools javascript console,
var solution = 1;
for(var i = 1; i <= 12; ++i)
    solution *= i;
console.log(solution.toString());

I get the following output:
479001600
undefined

When I remove the last line, that is console.log(solution.toString());, I get just 479001600. What happens?

A: The undefined is simply the console's way of telling you that the statement:
console.log(solution.toString());

doesn't, itself, return a value (it outputs a value, but doesn't return one). It's not something to worry about when your actual code executes because it's a specific behavior to the developer's console.
As another example, if you type: 5 + 6 into the console, it will report 11 on the next console line, because the console always wants to report any value returned from the statement it just executed.

A: The console in google chrome will always return the value of the last executed statement.
Since your last statement in the console was
console.log()

one which did not return any value it showed 'undefined';
Try
var a=[];a.push(5);

It will show 1 on the next line as the push method returns the length of the  newly formed array


text:
Q: How to remove the association after deleting a model object I have a simple has_many/belongs_to association between 2 of my models.
My problem is that when I delete an object that I no longer want (from the parent model), the foreign key within the child model's object remains. For example:
Forest
has_many :trees, :inverse_of => :forest
Tree
belongs_to :forest
When I delete a Forest object, all the associated Tree objects still contain a value for forest_id, which results in errors on the frontend. Is there some sort of hook like before_destroy that I can use? Though I'm thinking there's probably a very simple solution to this.
Thanks

A: I think that you want the :dependent option.
has_many :trees, :inverse_of => :forest, :dependent => :nullify

This will set the foreign keys to nil when the associated model is destroyed. You could also use :dependent => :destroy to destroy the model.
The documentation here might help.

A: You have add the :dependent option with the association like
has_many :trees, :dependent => :destroy
It will delete all trees of a particular Forest object.


text:
Q: Regex to match all types of percentage I have some % cases as the follow -
12.02
16.59
81.61%
45
24.812
51.35
19348952
88.22
0
000
021
.85%
100

I want to match all the percentages type except anything larger than 100.
Expected Output:
12.02
16.59
81.61
45
24.812
51.35

88.22
0
000
21
.85
100

I have tried (Regular Expression for Percentage of marks). But this one fails to get all the cases that I want. Also, I am replacing the non-match with empty string. So my code in python looks like like this -
pattern=r'(\b(?<!\.)(?!0+(?:\.0+)?%)(?:\d|[1-9]\d|100)(?:(?<!100)\.\d+)?$)'
df['Percent']=df['Percent'].astype(str).str.extract(pattern)[0]

Many thanks.
Edit: The solution (by @rv.kvetch) matches most of the edge cases except the 0 ones but I can work with that limitation. The original post had requirement of not matching 0 case or 0%.

A: If you want, you can do it without using regex.
nums = ['12.02'
'16.59',
'81.61%',
'45',
'24.812',
'51.35',
'19348952',
'88.22',
'0',
'000',
'021',
'.85%',
'100']

for n in nums:
  x = n.sptrip('%')
  x = int(x)
  if x <= 100:
    print(n)

A: I'm probably very close but looks like this is working for me so far:
^(?:0{0,})((?:[1-9]{1,2}|100)?(?:\.\d+)?)%?$
Regex demo

Description
First non-capturing group

*

*(?:0{0,}) - non-capturing group which matches a leading 0, that appears
zero or more times.

First capture group

*

*(?:[1-9]{1,2}|100)? - Optional, non-capturing group which matches the digits 1-9 one to two times, to essentially cover the range 1-99. Then an or condition so we also cover 100. This group is made optional by ? to cover cases like .24, which is still a valid percentage.

*(?:\.\d+)? - Optional, non-capturing group which matches the fractional part, e.g. .123. This is optional because numbers like 20 are valid percentage values by themselves.

Last non-capturing group

*

*%? - finally, here we match the optional trailing percent (%) symbol that can come at the end.

Update
Here is a non-regex approach that should be more efficient than a regex approach. This also covers edge cases like .0 that the regex currently hasn't been updated to handle:
string = """
12.02
16.59
81.61%
45
24.812
51.35
19348952
88.22
0
000
.0%
021
.85%
100
150
1.2.3
hello world
"""

for n in string.split('\n'):
    try:
        x = float(n.rstrip('%'))
    except ValueError: # invalid numeric value
        continue
    # Check if number is in the range 0..100 (non-inclusive of 0)
    if 0 < x <= 100:
        print(x)


text:
Q: Is the network card used when the WCF service and the app calling the service are both hosted on the same machine?
*

*If I host Web service and WCF service on the same machine. The web service consumes the WCF service. Will the communication go through only memory or also the physical network card.

*I can also put it this way. If I have two programs running on the same machine, and they use tcp sockets to communcates to each other, will the IP packet be delivered through the physical network card or it only go through memory. The difference is: if it go through the network card, it may be limited by the speed or cache of the card, right?

Thanks

A: The answer is.... kind of.  :) The services will communicate through a socket or port on the system.  They will reach out to the network device, which very high in the stack will identify that the services are on the same machine then the loopback device will redirect the communications back to the host computer before it ever actually goes out on the network.  So, is it all done in memory? No. But it also does not actually hit the network.


text:
Q: Hibernate LazyInitializationException if entity is fetched in JWTAuthorizationFilter I'm using Spring Rest. I have an Entity called Operator that goes like this:
@Entity
@Table(name = "operators")
public class Operator {

    //various properties

    private List<OperatorRole> operatorRoles;

    //various getters and setters

    @LazyCollection(LazyCollectionOption.TRUE)
    @OneToMany(mappedBy = "operator", cascade = CascadeType.ALL)
    public List<OperatorRole> getOperatorRoles() {
        return operatorRoles;
    }

    public void setOperatorRoles(List<OperatorRole> operatorRoles) {
        this.operatorRoles = operatorRoles;
    }
}

I also have the corresponding OperatorRepository extends JpaRepository
I defined a controller that exposes this API:
@RestController
@RequestMapping("/api/operators")
public class OperatorController{

    private final OperatorRepository operatorRepository;

    @Autowired
    public OperatorController(OperatorRepository operatorRepository) {
        this.operatorRepository = operatorRepository;
    }

    @GetMapping(value = "/myApi")
    @Transactional(readOnly = true)
    public MyResponseBody myApi(@ApiIgnore @AuthorizedConsumer Operator operator){

        if(operator.getOperatorRoles()!=null) {
            for (OperatorRole current : operator.getOperatorRoles()) {
                //do things
            }
        }

    }
}

This used to work before I made the OperatorRoles list lazy; now if I try to iterate through the list it throws LazyInitializationException.
The Operator parameter is fetched from the DB by a filter that extends Spring's BasicAuthenticationFilter, and is then somehow autowired into the API call.
I can get other, non-lazy initialized, properties without problem. If i do something like operator = operatorRepository.getOne(operator.getId());, everything works, but I would need to change this in too many points in the code.
From what I understand, the problem is that the session used to fetch the Operator in the BasicAuthenticationFilter is no longer open by the time i reach the actual API in OperatorController.
I managed to wrap everything in a OpenSessionInViewFilter, but it still doesn't work.
Anyone has any ideas?

A: I was having this very same problem for a long time and was using FetchType.EAGER but today something has clicked in my head ...
@Transactional didn't work so I thought "if declarative transactions don't work? Maybe programmatically do" And they do!
Based on Spring Programmatic Transactions docs:
public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    private final TransactionTemplate transactionTemplate;

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager,
                                  PlatformTransactionManager transactionManager) {
        super(authenticationManager);
        this.transactionTemplate = new TransactionTemplate(transactionManager);

        // Set your desired propagation behavior, isolation level, readOnly, etc.
        this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    }

    private void doSomething() {
        transactionTemplate.execute(transactionStatus -> {
            // execute your queries
        });
    }

}

It could be late for you, but I hope it helps others.


text:
Q: Retain only one copy of an activity on the stack when called from non-activity How can I make sure I only retain one copy of an activity on the stack when called from non-activity?
When called from an activity I can just add the FLAG_ACTIVITY_REORDER_TO_FRONT flag to the Intent, but how can I do this from e.g. a widget or a notification?


text:
Q: Remembering or Authenticating a Device with IdentityServer4 I am building a time clock application for work. My boss wants the app to run on company ipads. He does not want employees to be able to clock in on their own devices.
I have already setup Implicit Flow between IdentityServer4, an Asp.net Core API and an Angular app.
How can I use IS4 to authorize the device remember it or cookie it? The old app I am trying to replace required an admin to login and click a button which would create a cookie in the tablet's browser history with a month long expiration. Is there a way to duplicate this type of functionality but turn it over to IS4 and also hopefully make it a bit more secure?

A: Your "old approach" looks pretty match the authorization code flow with refresh token. Your admin logs in once, fetches an access+refresh token pair. After a short, the access token expires, and (one time) refresh is used to obtain a new pair, and so on. You may store the pair into the local storage, and later use a custom grant to authenticate an (ordinary) user and validate the device at the same time.


text:
Q: Stop submitting form multiple times by jquery on click event I am submitting a form using jquery submit() function but it's submitting multiple time. i used everything i know but not able to stop it.
Below is my function :
function submit(){
    $("#save").prop('disabled', true);
    $("#loader").modal('show');
    $("#save").off('click');
    if($("#name").val() == ''){
        alert("Please Enter Name!");
        $("#save").prop('disabled', false);
        $("#save").on('click', submit);
        $("#loader").modal('hide');
        return false;
    }
    // Other validations as well
    $("#form").submit();
}

$("#save").off('click').on('click', submit);

Below is my form:
<form action="abc.php" method="post" id="form">
    <input type="text" id="name" />
    <button type="button" id="save">save</button>
</form>

But sometime click working multiple time if user click button multiple time too fast. not every time. anyone have any idea?

A: One option that comes to mind, is to add a className to the "Save" button on click, and check for this className in your callback, if the class exists, return, else submit. Something like the following:
function submit(){
    const $saveBtn = $('#save');
    //if the button has been clicked already, return
    if($saveBtn.hasClass('clicked'){
        return;
    }else{ //add the class to prevent multiple submission
       $saveBtn.addClass('clicked');
    }
    $saveBtn.prop('disabled', true);
    .......
}

EDIT
Since you say the above solution of adding a className doesn't work, use a global boolean:
at the top of your script declare the boolean:
let submitted = false;

function submit(){
    //if the boolean is true, return
    if(submitted){
        return;
    }else{ //set to true
        submitted = true;
    }
    const $saveBtn = $('#save');
    $saveBtn.prop('disabled', true);
    .......
}


text:
Q: How to position a DIV in relation to another DIV I illustrated in HERE a situation with a simple layout. I would like that all the elements keep their position when another element is modified. For example, if I change the Title font to more or less, the button2, will move and I don't want that. So is there a way to keep their position fixed even when other elements are modified?

TITLE GOES HERE

Description goes here

BUTTON1

BUTTON2

#slides{
width:600px;
height:280px;
background:yellow;
}
p.title{
font-size:28px;
text-align:center;
position: relative;
top:40px;
}
p.description{
text-align: center;
position:relative;
top:20px;
}
#button1{
width:150px;
height:35px;
background:blue;
margin:0 auto;
line-height:35px;
text-align: center;
position:relative;
top:40px;
}
#button2{
width:85px;
height:25px;
background:red;
margin:0 auto;
line-height:25px;
text-align:center;
position:relative;
top:135px;
}

A: You're looking for elements relatively absolute positioned (or absolute relatively?).
You should set the parent #slides to position: relative and then the child elements should be position: absolute, with this you can set top, right, bottom or right properties in the children relatively to the #slide.
This way the children of #slides won't follow the flow when some other child changes.
http://codepen.io/anon/pen/yhFnb

A: Modify your css like this :
    #slides{
        width:600px;
        height:280px;
        background:yellow;
      position: relative;
    }

  #button2{
    width:85px;
    height:25px;
    background:red;
    line-height:25px;
    text-align:center;
    position:absolute;
    left: 50%;
    margin-left : -42px;
    bottom : -12px;
   }

Demo http://codepen.io/anon/pen/gAcka
Hope it help.


text:
Q: Video Ended When Injected into DOM I'm trying to use jQuery to detect when a video has stopped playing.
Previously, I've done this
$("video").bind("ended", function(){
     alert('Video Ended');
});

but because the video is being added to the DOM from an AJAC call, it doesn't seem to be working.
I've also tried this, but can't get it to work either.
$(document).on('ended', 'video', function(){
     alert('Video Ended');
});


text:
Q: Local intranet zone sites opening in IE instead of Edge In our enterprise Windows environment, we have started using Microsofts cloud offerings. One problem we have encountered is that login.microsoftonline.com always switches from Edge to IE during login.
EnterpriseMode is enabled in the environment, however, login.microsoftonline.com is not in the EnterpriseMode sites list. When sites are opened in EnterpriseMode we can see it in the tools menu of IE, but this is not the case with login.microsoftonline.com.
*.microsoftonline.com is, however, in the local intranet zone.
Is there a GPO that makes local intranet zone behave like EnterpriseMode?

A: Yes, there is a GPO settings called: "Send all intranet sites to Internet Explorer 11"
You can find this GPO Under Administrative Templates -> Windows Components -> Microsoft Edge.


text:
Q: make dictionary to objects of class in python i made the class for making dict keys to object accessor but this is not working in nested case
d= {'c': {'v': {'a'}}, 'e': 'x', 'r': 'e'}
class A:
     def __init__(self, dicti):
         self.__dict__.update(dicti)
o = A(d)
# i want something like o.c.v=a , o.e=x, o.r=e
# i'm unable to make nested dict object accessor

looking for help

A: You can use recursion to traverse the structure, creating a series of nested class A objects:
d= {'c': {'v': {'a'}}, 'e': 'x', 'r': 'e'}
class A:
  def __init__(self, dicti):
     self.__dict__ = {a:A(b) if isinstance(b, dict) else b for a, b in dicti.items()}

a = A(d)
print(a.c.v)
print(a.r)

Output:
{'a'}
'e'


text:
Q: Appending data while doing Exchange partition in Oracle I am trying to build Archival method for my database application. I have few reporting tables which are already partitioned. These reporting tables are huge and are partitioned on monthly basis. I am using Exchange partition method for faster performance. By default the archival job runs every 30 days.
Note: I have specific archival tables for each reporting table.
Problem statement: I need to store archive data for an year in the archival tables. Can I append the data in archival tables using Exchange partitioning method?


text:
Q: MapsForge 0.4.0: is it possible to implelment a Marker 's onTap event? i'm using MapsForge latest branch (master) and i'd like to implement a Marker's onTap event.
I think it was possible on 0.3.0, but i can't use 0.3.0 because i use a different Drawable for each Marker on the map.
ArrayList<Monument> monuments = getMonuments();

mListOverlay = new ListOverlay();
ArrayList<OverlayItem> markers = new ArrayList<OverlayItem>();

for(Monument m : monuments){
    GeoPoint gp = new GeoPoint(m.getLat(), m.getLon());
    Marker m = createCustomMarker(R.drawable.marker, gp, p.getNumber()));
    markers.add(m);
}

mListOverlay.getOverlayItems().addAll(markers);

mMapView.getOverlays().add(mListOverlay);

"createCustomMarker" returns a Marker that uses a Drawable with a number on top.
Anyone knows how i can override the behaviour of "m" when it is tapped?
Remember: branch master! not 0.3.0!!
Thanks

A: Create a class that inherits from Marker and overwrite onTab, the following way.
This solution checks if the tab was within the bounds of the Layer's bitmap (plus 10%).
If this is true the Runnable action will be called.
In Mapsforge each Marker is just a simple Layer which are stacked on top of the map. Each tab will call the topmost layer's ontab. If that returns false, the next topmost layer's ontab will be called, unless the function returned true or the last layer has been reached.
public class InfoMarker extends Marker {

    private Runnable action;

    public InfoMarker(LatLong latLong, org.mapsforge.core.graphics.Bitmap bitmap, int horizontalOffset, int verticalOffset) {
        super(latLong, bitmap, horizontalOffset, verticalOffset);
    }

    public void setOnTabAction(Runnable action){

        this.action = action;
    }

    @Override
    public boolean onTap(LatLong tapLatLong, Point layerXY, Point tapXY) {

        double centerX = layerXY.x + getHorizontalOffset();
        double centerY = layerXY.y + getVerticalOffset();

        double radiusX = (getBitmap().getWidth() / 2) *1.1;
        double radiusY = (getBitmap().getHeight() / 2) *1.1;

        double distX = Math.abs(centerX - tapXY.x);
        double distY = Math.abs(centerY - tapXY.y);

        if( distX < radiusX && distY < radiusY){

            if(action != null){
                action.run();
                return true;
            }
        }

        return false;
    }

}

A: To who it may concern, i've finally switched to OsmDroid, which can easily cover my needs.
For the onTap one, what i've done basically is:
http://mobiledevstories.wordpress.com/2014/03/01/osmdroid-bonus-pack-markers-with-clickable-infowindows/
Hope it saves time to someone!


text:
Q: Updated MikTeX, now "Sorry, but xelatex.exe did not succeed. The log file hopefully contains the information to get MiKTeX going again" I might have made a big mistake by updating MikTeX after I updated TeXstudio a few weeks before. Now when I try to Build my file, I get the error: "Sorry, but xelatex.exe did not succeed. The log file hopefully contains the information to get MiKTeX going again:"
The indicated log file says this (several times):

2022-04-14 19:02:31,434-0700 FATAL xelatex.core - The memory dump file
could not be found.
2022-04-14 19:02:31,434-0700 FATAL xelatex.core - Data:
fileName="xelatex.fmt"
2022-04-14 19:02:31,434-0700 FATAL xelatex.core - Source:
Libraries\MiKTeX\TeXAndFriends\texmfapp.cpp:717
2022-04-14 19:02:31,434-0700 FATAL xelatex - The memory dump file
could not be found.
2022-04-14 19:02:31,434-0700 FATAL xelatex - Info:
fileName="xelatex.fmt"
2022-04-14 19:02:31,434-0700 FATAL xelatex - Source:
Libraries\MiKTeX\TeXAndFriends\texmfapp.cpp
2022-04-14 19:02:31,434-0700 FATAL xelatex - Line: 717
2022-04-14 19:02:31,450-0700 INFO  xelatex - this process (19068)
finishes with exit code 1
2022-04-14 19:02:31,450-0700 ERROR xelatex - minor issue: It has been
a long time since you have checked for MiKTeX updates.
2022-04-14 19:02:56,274-0700 INFO  xelatex - this process (1452)
started by 'texstudio' with command line: xelatex.exe -synctex=1
-interaction=nonstopmode ErrorAndUPBmaybeNotLOCC.tex
2022-04-14 19:02:56,305-0700 INFO  xelatex - allowing known shell
commands
2022-04-14 19:02:56,414-0700 INFO  xelatex - going to create file:
xelatex.fmt
2022-04-14 19:02:56,507-0700 INFO  xelatex.core - start process:
initexmf --enable-installer --dump-by-name=xelatex --engine=xetex
2022-04-14 19:03:08,322-0700 ERROR xelatex - C:\Program
Files\MiKTeX\miktex\bin\x64\initexmf.exe did not succeed; exitCode: 1
2022-04-14 19:03:08,322-0700 ERROR xelatex - output:
2022-04-14 19:03:08,322-0700 ERROR xelatex -  Sorry, but "MiKTeX
Configuration Utility" did not succeed.
The log file hopefully contains the information to get MiKTeX going
again:
C:\Users\cohen5\AppData\Local\MiKTeX\miktex\log\initexmf.log

I truly hope that I don't have to uninstall and reinstall Texstudio, because I fear it will be a nightmare trying to get everything set back up again the way I have it now.
Thanks in advance for your assistance!

A: It seems I hadn't actually updated MikTeX, but rather, I had installed a newer version, MikTeX 21.3 to be precise. What I did to fix the issue is, I updated MikTeX through the MikTeX console. Then after reopening TeXStudio, everything seems to work fine, just like it did before installing the newer version of MikTeX.


text:
Q: jQuery text selection event I have the following event handling code:
$('#main').delegate('.slide', 'click', function () {
  slideshow.next();
});
$('#main').delegate('a', 'click', function (e) {
  e.stopPropagation();
});

.slide is a large div with content. slideshow.next() is called when .slide is clicked, except when a link is clicked, in which case stopPropagation(), and .slide never receives the click event.
I'd like to make it possible to select text on the slide. At the moment, if I click and drag, when I release the mouse the selection works but .slide registers the click and fires the slideshow.next() function. Is there an event I can intercept?
The page is available here.

Edit: Interestingly, if the selection spans more than one HTML element, click isn't fired, but it the selection is within an element, it is fired.

Edit2: Ok, here's my solution:
function setupHandlers() {
  var prevX = 0;
  var prevY = 0;

  $('#main').delegate('.slide', 'click', function (e) {
    var clickTolerance = 2;
    var dx = Math.abs(e.pageX - prevX);
    var dy = Math.abs(e.pageY - prevY);
    //if mouse has moved less than two pixels in any direction this is a click
    if (dx < clickTolerance && dy < clickTolerance) {
      slideshow.next();
    }
  });
  $('#main').delegate('.slide', 'mousedown', function (e) {
    prevX = e.pageX;
    prevY = e.pageY;
  });
  $('#main').delegate('a', 'click', function (e) {
    //Clicks on links shouldn't fire '.slide'.click() above
    e.stopPropagation();
  });
}

A: What is the difference between a single click and a click that selects text ?
I would say it could either relate to the time passed between the down click and the upclick of the mouse.  Alternatively and perhaps more importantly it could be diagnosed by difference in the screen position of the mouse at the time of the down click and at the time of the mouse up event.
When the mouseDown event is fired record the event.pageX and event.pageY values.
When the mouseUp event is fired compare the stored x,y coords with the current. If they are different it was a text select... do nothing. If they are the same, swap your page.
Not sure how to implement this in JScript unfortunately ;)

A: use $('.slide').select to catch the selection event and stop propagation.


text:
Q: How to check if a std::function is set and valid? I have an std::function which is being set like below:
typedef std::function<void(bool some_state)> TheListener;
void ListenTo(TheListener the_listener) {
    m_the_listener = the_listener;
}

How do I check if the std::function is set?
private:
    void SomePrivateMethod() {
        // How do I check here that m_the_listener is set by calling ListenTo ?
        m_the_listener();
    }

Is it enough to check if (m_the_listener) before calling m_the_listener() ?

A: This does state that verifying the std::function instance in a condition should be sufficient to verify if it has a valid callable target. So yes, if (m_the_listener) should be enough.


text:
Q: Finding abelian groups Find all abelian groups of order $2^83^45^6$.

I can find the total number of abelian groups but there are too many. I find the number of abelian groups 22.5.11. I can't find all the groups, so is there a short way to show all of them?


text:
Q: Persist same dependency in different transactions issue I have a part of program where implemented synchronization in parallel way with another system. The each synchronization process opens new transaction. Synchronized objects going to map on some data and to persist.
The data on which objects are going to be mapped can be persisted before and can be persisted in synchronization time.
My persistent layer provides cascade operation, so I do not care to persist about all dependencies.
Issue
In mapped object was not persisted before and in synchronization time it is going to be save in different threads at same time appears hibernate exception:
org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [my.project.entity.CrmCaseLink#27];
nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [my.project.entity.CrmCaseLink#27]

My tries to solve issue did not help
1.
I tried to use cache where from I can get same CrmCaseLink for different threads but it does not solved my issue.
2.
Another time I tried
@CacheConfig(cacheNames = Constants.CRM_CASE_LINK_CACHE, cacheManager = Constants.GUAVA_CACHE_MANAGER)
@Service
public class CrmCaseLinkService {

    private static final Logger LOGGER = LogManager.getLogger(CrmCaseLinkService.class);
    @Autowired
    private CrmCaseLinkRepository crmCaseLinkRepository;

    @Cacheable(key = "#id")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public synchronized CrmCaseLink findOne(Long id) {
        LOGGER.debug("trace loading crm case link by specified id: {}", id);
        return Optional.ofNullable(crmCaseLinkRepository.findOne(id))
                .orElseGet(() -> crmCaseLinkRepository.save(new CrmCaseLink(id)));
    }
}

Question
Why cache is mistake here? I expected hiberate able to manage same non persisted entity in different transactions. I was sure that cache solution with new transaction in separate spring bean is indisputable solution, but it also doesn't help me.
Additional details
java8, spring, spring data jpa, postgres, hibernate5, jetty container

A: The issues reason explanation
I think the issue appears because of in provided solution detached entity objects are used. As you see I create new transaction for synchronized singleton method
@Transactional(propagation = Propagation.REQUIRES_NEW)
public synchronized CrmCaseLink findOne(Long id) {
    LOGGER.debug("trace loading crm case link by specified id: {}", id);
    return Optional.ofNullable(crmCaseLinkRepository.findOne(id))
            .orElseGet(() -> crmCaseLinkRepository.save(new CrmCaseLink(id)));
}

to persist new object if one is absent in DB storage. But public synchronized CrmCaseLink findOne is used from another transaction to get the CrmCaseLink and to map it on other object. To map and persist other entity successfully I have to use attached CrmCaseLink.
Solution code example
I've changed code in next way:

*

*DB lookup and persist are different methods

*Persist method must be synchronized and processed in new tranzaction

*Remove caching because mapping needs attached entities, and different transactions use this service to load CrmCaseLink.

Code example:
@Service
public class CrmCaseLinkManager implements CrmLinkManager {
    @Autowired
    private CrmCaseLinkRepository crmCaseLinkRepository;

    @Override
    public CrmCaseLink findOne(Long id) {
        return crmCaseLinkRepository.findOne(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public synchronized void save(Long id) {
        if (crmCaseLinkRepository.exists(id)) {
            return;
        }
        crmCaseLinkRepository.save(new CrmCaseLink(id));
    }
}

code part where from it is used demonstrates how to get necessary attached entity from implemented service:
T getOrCreateCrmLink(Long id, CrmLinkManager<T> crmLinkManager) {
    T crmLink = crmLinkManager.findOne(id);
    if (crmLink == null) {
        crmLinkManager.save(id);
        crmLink = crmLinkManager.findOne(id);
    }
    return crmLink;
}


text:
Q: How to read datas from several files with python I am new to python and this may be a foolish question but it troubles me for several days.
I have about 30 log files, and each of them contains strings and data. They are almost the same except the difference of several data, and their names are arranged regularly, like 'log10.lammps', 'log20.lammps', etc.(The '10''20'represent the temperature of the simulation). I want to write a python script, which loops all these files and read their data in a specific line, (say line3900). Then I want to write these data to another data file, which is arranged like these:
10 XXX
20 XXX
30 XXX
.
.
.
I can read and write from a single file, but I cannot achieve the loop. Could anyone please tell me how to to that. Thanks a lot!
PS. Still another difficulty is that the data in line 3900 is presented like this: "The C11 is 180.1265465616", the one I want to extract is 180.1265465616. How can I extract the number without the strings?

A: #assuming files is a list of filenames
for filename in files:
    with open(filename) as f:
        <do stuff with file f>

ps. float(line.split(' ')[-1])

A: This answer covers how to get all the files in a folder in Python. To summarize the top answer, to get all the files in a single folder, you would do this:
import os
import os.path

def get_files(folder_path):
    return [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

The next step would be to extract the number from the line The C11 is 180.1265465616.
I'm assuming that you have a function called get_line that given a filename, will return that exact line.
You can do one of three things. If the length of the number at the end is constant, then you can just grab the last n characters in the string and convert it to a number. Alternatively, you could split the string by the spaces and grab the last item -- the number. Finally, you could use Regex.
I'm just going to go with the second option since it looks the most straightforward for now.
def get_numbers():
    numbers = []
    for file in get_files('folder'):
        line = get_line(file)
        components = line.split(' ')
        number = float(components[-1])
        numbers.append(number)
    return numbers

I wasn't sure how you wanted to write the numbers to the file, but hopefully these should help you get started.

A: Well, I can give you a hint which path I would have taken (but there might be a better one):

*

*Get all files in a directory to a list with os.listdir

*Loop over every one and perform the following:

*

*Use the re module to extract the temperature from the filename (if not match pattern break) else add it to a list (to_write_out)

*Read the right line with linecache

*Get the value (line.split()[-1])

*Append the value to the list to_write_out.

*Join the list to_write_out to a string with join

*Write the string to a file.

Help with the regex
The regular expressions can be a bit tricky if you haven't used them before. To extract the temperature from your filenames (first bullet beneath point number 2) you would use something like:
for fname in filenames:
    pattern = 'log(\d+)\.lammps'
    match = re.search(pattern, fname)
    if match:
        temp = match.group(1)

        # Append the temperature to the list.

    else:
        break

    # Continue reading the right line etc.


text:
Q: What is the best way to store HTML elements with BeautifulSoup for later use? My aim is to use BeautifulSoup, extract certain HTML elements (in this case those containing alphabets), store them and later identify them on the original website with javascript (for eg. with document.getElementsbyClassName...)
I am extracting HTML elements with the following Python code:
from bs4 import BeautifulSoup
import re

def parse_html(html):
    soup = BeautifulSoup(r.text, 'html.parser')

    text_only = []

    for elem in soup(text= re.compile('[A-Za-z]+')) :
            text_only.append(elem)

    return text_only

I then store this in a DB. My use case is that I would want to later use these to identify that particular element on the original website. But I am not sure how do I do this? I used this code to generate the Xpath, store and then use it on the original website with this JS code:
let parse = document.evaluate("/html/body/div[1]/div[2]/div[4]/ul/li[3]/a", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

However, this returns undefined. How do I solve this?

A: You can save the HTML content in json or txt provided the HTML content should be string. I have saved in txt format. Try this out and see if you are meeting your expectation or not.
URL = 'some_url'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')

#open and write the file (html should be stored in string format)
file_open = open("html_file.txt", "w")
file_open.write(str(soup))
file_open.close()

#open and read file
file_open = open("html_file.txt", "r")
file_read = file_open.read()
file_open.close()

#reuse saved HTML code
reuse_html = BeautifulSoup(file_read, 'html.parser')
print(reuse_html)