text:
Q: Problem with python packages and tests I have a directory struture like that:
project
|  __init__.py
| project.py
| src/
    | __init__.py
    | class_one.py
    | class_two.py
| test/
    | __init__.py
    | test_class_one.py

Which project.py just instantiate ClassOne and run it.
My problem is in the tests, I don't know how to import src classes. I've tried importing these ways and I got nothing:
from project.src.class_one import ClassOne

and
from ..src.class_one import ClassOne

What am I doing wrong? Is there a better directory structure?
----- EDIT -----
I changed my dir structure, it's like this now:
Project/
|   project.py
|   project/
    |   __init__.py
    |   class_one.py
    |   class_two.py
    |   test/
        |   __init__.py
        |   test_class_one.py

And in the test_class_one.py file I'm trying to import this way:
from project.class_one import ClassOne

And it still doesn't work. I'm not using the executable project.py inside a bin dir exactly because I can't import a package from a higher level dir. :(
Thanks. =D

A: It all depends on your python path.  The easiest way to achieve what you're wanting to do here is to set the PYTHONPATH environment variable to where the "project" directory resides.  For example, if your source is living in:
/Users/crocidb/src/project/

I would:
export PYTHONPATH=/Users/crocidb/src

and then in the test_one.py I could:
import project.src.class_one

Actually I would probably do it this way:
export PYTHONPATH=/Users/crocidb/src/project

and then this in test_one.py:
import src.class_one

but that's just my preference and really depends on what the rest of your hierarchy is.  Also note that if you already have something in PYTHONPATH you'll want to add to it:
export PYTHONPATH=/Users/crocidb/src/project:$PYTHONPATH

or in the other order if you want your project path to be searched last.
This all applies to windows, too, except you would need to use windows' syntax to set the environment variables.

A: From Jp Calderone's excellent blog post:

Do:

*

*name the directory something related to your project. For example, if your
  project is named "Twisted", name the
  top-level directory for its source
  files Twisted. When you do releases,
  you should include a version number
  suffix: Twisted-2.5.

*create a directory Twisted/bin and put your executables there, if you
  have any. Don't give them a .py
  extension, even if they are Python
  source files. Don't put any code in
  them except an import of and call to a
  main function defined somewhere else
  in your projects. (Slight wrinkle:
  since on Windows, the interpreter is
  selected by the file extension, your
  Windows users actually do want the .py
  extension. So, when you package for
  Windows, you may want to add it.
  Unfortunately there's no easy
  distutils trick that I know of to
  automate this process. Considering
  that on POSIX the .py extension is a
  only a wart, whereas on Windows the
  lack is an actual bug, if your
  userbase includes Windows users, you
  may want to opt to just have the .py
  extension everywhere.)

*If your project is expressable as a single Python source file, then put it
  into the directory and name it
  something related to your project. For
  example, Twisted/twisted.py. If you
  need multiple source files, create a
  package instead (Twisted/twisted/,
  with an empty
  Twisted/twisted/__init__.py) and place
  your source files in it. For example,
  Twisted/twisted/internet.py.

*put your unit tests in a sub-package of your package (note - this means
  that the single Python source file
  option above was a trick - you always
  need at least one other file for your
  unit tests). For example,
  Twisted/twisted/test/. Of course, make
  it a package with
  Twisted/twisted/test/__init__.py.
  Place tests in files like
  Twisted/twisted/test/test_internet.py.

*add Twisted/README and Twisted/setup.py to explain and
  install your software, respectively,
  if you're feeling nice.

  Don't:

*

*put your source in a directory called src or lib. This makes it hard
  to run without installing.

*put your tests outside of your Python package. This makes it hard to
  run the tests against an installed
  version.

*create a package that only has a __init__.py and then put all your code into __init__.py. Just make a module
  instead of a package, it's simpler.

*try to come up with magical hacks to make Python able to import your module
  or package without having the user add
  the directory containing it to their
  import path (either via PYTHONPATH or
  some other mechanism). You will not
  correctly handle all cases and users
  will get angry at you when your
  software doesn't work in their
  environment.


text:
Q: Add a column to spark dataframe whose value is hashMod of the existing dataframe row I want to add a column to spark dataframe whose value is hashMod of the existing dataframe row. In the below example,I  could achieve the same for hash of 1 specific column "data", how do I achieve the same for whole dataframe row (allcolumns)?
object Container {
  case class intContainer(data: Int)
}

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
val getBucket = udf((data: Object) => data.hashCode() %10 )
val schema = StructType(List(StructField("age", IntegerType)))

val userList = List(( 23),( 24), (25), (57) )
val df1:RDD[Container.intContainer] = sc.parallelize(userList).map(x=> Container.intContainer(x))
val df = df1.toDF()
df.registerTempTable("dfcount")
val countdf = sqlContext.sql("select data,data+1 as count, current_timestamp() as time  from dfcount")
val xx = countdf.withColumn("bucket_id", getBucket( col("data")))

A: The below snippets employs an udf that takes an array of columns whose hashcode is summed to get the bucket value. This function works for any arbitary number of columns and for any schema.
import sqlContext.implicits._
import org.apache.spark.sql.functions.udf
def hasher(data: AnyRef *) = (data.map(_.hashCode).sum % 10)
val getBucket = udf(hasher _)
val df = sc.parallelize(('a' to 'z').map(_.toString) zip (1 to 30)).toDF("c1","c2")
df.withColumn("bucket", getBucket(array(df.columns.map(df.apply): _*))).show()
+---+---+------+
| c1| c2|bucket|
+---+---+------+
|  a|  1|     6|
|  b|  2|     8|
|  c|  3|     0|
|  d|  4|     2|
|  e|  5|     4|
|  f|  6|     6|
|  g|  7|     8|
|  h|  8|     0|
|  i|  9|     2|
|  j| 10|     3|
|  k| 11|     5|
|  l| 12|     7|
|  m| 13|     9|
|  n| 14|     1|
|  o| 15|     3|
|  p| 16|     5|
|  q| 17|     7|
|  r| 18|     9|
|  s| 19|     1|
|  t| 20|     4|
+---+---+------+

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sheaves on Contractible Analytic Spaces Let $(X,\mathcal{O}_X)$ be a contractible complex analytic space. Suppose that $\mathcal{F}$ is a coherent sheaf of $\mathcal{O}_X$-modules. Can we invoke the fact that $X$ is contractible to conclude, in some cases, that $\mathcal{F}$ is isomorphic to $\mathcal{O}_X^{\oplus n}$ for some $n$? If you like, you may take $X$ to be the analytic space associated to a complex affine variety.
I ask because contractibility is often a useful condition when attempting to prove a fibre bundle is trivial.

A: The so-called Oka-Grauert principle states that for any Stein space $X$ the holomorphic and the topological classification of complex vector bundles on $X$ coincide.
The original reference is
Hans Grauert, Analytische Faserungen über holomorph-vollständigen Räumen, Math. Ann. 135 (1958), 263-273.
As a consequence, every locally free, coherent sheaf $\mathscr{F}$ defined on a contractible subvariety $X$ of $\mathbb{C}^n$ is free.
Of course, if $\mathscr{F}$ is not locally free this is no longer true. For instance, take a closed analytic subvariety $Z \subset X$; then the ideal sheaf $\mathscr{I}_Z \subset \mathscr{O}_X$ is coherent but not free.


text:
Q: Custom views are not showing up properly I am trying to show 3 custom views in an iOS screen but only one of them is showing up. 2nd one started showing up a bit in improper way after putting alot of constraints and third one is completely not showing up.For test I am calling the same view three times. See the code. I have just started doing iOs so just forgive me if I am making any blunder or obvious mistake.
I have tried to put constraints accordingly, put a scrollview behind but none of this seems to be working

I have remover container3 from storyboard because when I add it, the container2 doesn't show-up even slightly. Please help me with this layout problem.
class TestCustomViewController: UIViewController {

@IBOutlet weak var container : UIView?

@IBOutlet weak var container2 : UIView?

@IBOutlet weak var container3 : UIView?

var testView: CustomView!
var testView2: CustomView!
var testView3: CustomView!
override func viewDidLoad() {
    super.viewDidLoad()
    ////////First View//////
   testView = createGearItemView()
    testView.frame = (container?.frame)!
    container?.addSubview(testView)
    /////////Second View//////
    testView2 = createGearItemView()
    testView2.frame = (container2?.frame)!
    container2?.addSubview(testView2)
    ////// THird View/////////
    testView3 = createGearItemView()
    testView3.frame = (container3?.frame)!
    container3?.addSubview(testView3)
}

func createGearItemView () -> CustomView {
    let view = (Bundle.main.loadNibNamed("CustomView", owner: nil, options: nil)?.first as? CustomView)!

    view.backgroundColor = UIColor.clear
    return view
}

}

A: Except of the fact that you should familiarize yourself with Auto Layout (see Understanding Auto Layout) you have to use the containers' bounds as frames for your subviews (although it might not be the correct ones yet in viewDidLoad):
testView.frame = (container?.bounds)!
...

An even better way is using Auto Layout for your subviews instead of setting the frames directly:
testView = createGearItemView()
container?.addSubview(testView)
testView.translatesAutoresizingMaskIntoConstraints = false
testView.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true
testView.leadingAnchor.constraint(equalTo: container!.leadingAnchor).isActive = true
testView.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true
testView.trailingAnchor.constraint(equalTo: container!.trailingAnchor).isActive = true
testView2...


text: Q: chrome desktop PWA launch failed and closed The desktop PWA icon is installed successfully, but when I want to launch the app and click the icon, it flashed and closed. How to debug and what is the issue?


text:
Q: How to configure ExcelReaderFactory to solve problem of Encoding in c#? I use ExcelDataReader.DataSet nuggetPackage
var reader = ExcelReaderFactory.CreateReader(stream);
 var conf = new ExcelDataSetConfiguration
                {

                    UseColumnDataType = true,

                    FilterSheet = (tableReader, sheetIndex) => true,

                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        EmptyColumnNamePrefix = "Column",
                        UseHeaderRow = false,
                        }
                    }
                };
                var dataSet = reader.AsDataSet(conf);

I have the data in the dataset but some characters became ? (é => ?, ç => ?)
i try to use ExcelReaderConfiguration but i didn't find how to use dataset with this.
var readerConf = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration()
                {
                    FallbackEncoding = Encoding.GetEncoding(1252),
                    AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' },
                    LeaveOpen = false,
                    AnalyzeInitialCsvRows = 0,
                });


text:
Q: How to pass XML from Cakephp using helper to the iPhone app I'm stuck here...
Is there a way we can get results from MySQL database transform to XML with the option of sending as JSON to iPhone App using Cakephp XML helper?
If someone could kindly help me with some answer, that would be much appreciated!
Thank you.
Jae

A: What you are trying to do is expose the functionality of the server to other applications, in this case a mobile phone app. I would suggest that you do it using REST which is detailed here - Create a REST-style API with CakePHP and XML.
You can change it as need to return JSON as well.


text:
Q: Pygame check for collisions with the top most foreground rect I have 10 sprites which I objects of the main sprite I wrote with different images and starting positions etc. But they all behave the same way. They are sub sprites of the main sprite.
I want to be able to hold mouse click on one's rect and move it round the screen which works perfectly fine. But the problem is they all have the same controls click and drag to move them. So if I am clicking on one of the sprite rects and I drag it over another one it picks it up as well. And I don't want that to happen.
Is there a way to only check for collisions with the top most foreground rect or if someone could explain a way of doing this that would achieve similar results. I have had a look at the rect documentation but I can't find a solution.
def update(self,):
    self.move(self.rect)

def move(self,rect):

    if pygame.mouse.get_pressed() == (1, 0, 0) and the_rect.collidepoint(pygame.mouse.get_pos()):
        self.state = 1

    elif pygame.mouse.get_pressed() == (0, 0, 0) and the_rect.collidepoint(pygame.mouse.get_pos()):
        self.state = 0

    if self.state == 0:
        the_rect.centerx = the_rect.centerx
        the_rect.centery =  the_rect.centery
    elif self.state == 1:
        (the_rect.centerx, the_rect.centery) = pygame.mouse.get_pos()

A: Rather than using the pygame.mouse.get_pressed() function, use the event queue and check for a pygame.MOUSEBUTTONDOWN event. It will only get fired once when the button is first pressed.


text:
Q: Create buffer overflows in snow leopard As part of a course at university in computer security, I'm soon about to learn about buffer overflows and how to use them to as exploits. I'm trying to do some simple buffer overflow with the following code:
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char buffer_one[4], buffer_two[16];

    strcpy(buffer_one, "one");
    strcpy(buffer_two, "two");

    strcpy(buffer_one, argv[1]);

    printf("buffer_two is at %p and contains \'%s\'\n", buffer_two, buffer_two);
    printf("buffer_one is at %p and contains \'%s\'\n", buffer_one, buffer_one);
}

I'm able to overwrite the content of buffer_one with the null terminator if i run
$./overflow 1234567890123456
 buffer_two is at 0x7fff5fbff8d0 and contains '1234567890123456'
 buffer_one is at 0x7fff5fbff8e0 and contains ''

But if i send more than 16 characters as argument, the program sends Abort trap. I supposed this is some sort of buffer protection on Snow Leopard (ASLR maybe?). If if make the size of buffer_two < 16, the adresse is still 16 bits apart
I'm running gcc -o overflow overflow.c -fno-stack-protector to remove stack protection
Is there any solution to this problem, other than installing a VM running a linux dist.?

A: The key to why this is happening is the fact that buffer_one is located after buffer_two in memory. This means that when you overflow buffer_one, you are not overflowing into buffer_two. Instead you are overflowing into stack memory being used to hold other things, such as the saved ebp pointer and most importantly, the return address.
And this is exactly what you want to happen when attempting a buffer overflow exploit! When the program executes strcpy(buffer_one, argv[1]); the first four bytes from argv[1] go into the memory allocated for buffer_one. But then the next 12 start overflowing memory being used for other things, eventually overwriting the return address. Without seeing the machine code, I can't say for sure which bytes exactly are overflowing the return address. But I'm guessing the value of EIP at the time of the SIGABRT is 0x31323334 or something similar (hex representation of '1234'). The key is realizing that by being able to overwrite the return address, you control EIP. And when you control EIP,  you control the system. (somewhat overexaggerated, but in most cases not far off) When you control EIP, you control which instructions the processor will execute next (putting aside for the moment the fact that the OS/kernel actually stand in between).
Now if you find exactly which eight bytes overwrite the return address you can replace those bytes with the address of your buffer (0x00007fff5fbff8e0) and instead of returning to the original caller (libc in this case), the program will start executing the instructions  you provided (AKA the shellcode). Note that you will have to fill in the implied 0s in the most significant places and provide the address as the actual nonprintable ASCII characters (0x00 0x00 0x7f 0xff 0x5f and so on), not the actual digits/characters 7ff5 etc. If using an x86-64 architecture, you'll also have to take the little-endianness into account and supply it backwards -- 0xe0 0xf8 0xbf etc. Supplying these nonprintable characters is most easily accomplished using backticks and command substitution using a brief Python or Perl script:
./overflow `python -c 'print "AAAAAAAAAAAAAAAA\xe0\xf8\xbf\x5f\xff\x7f"'`

(The A's are padding to overflow the buffer.) Unfortunately, you won't be able to provide the 2 additional \x00 needed for the address. One of these NULLs will be placed there for you by strcpy, but you'll have to get lucky with the last NULL and hope the address you're overwriting already started with 0x00 (which is actually highly likely). Now when you execute this with the right number of A's, you'll probably still get a segmentation fault or even possibly illegal instruction, since you'll now jump to the capital A's and execute them as actual machine instructions (0x41 => inc ecx).
Then finally the last piece is putting in the actual shellcode. Given your limited buffer sizes, it will be very hard to provide anything useful in only 12 bytes or so. Since you are writing the code in this case, the easiest thing will probably be to make your buffer bigger. If this weren't an option, then you could either A) use buffer_two as well for 16 more bytes since it comes before buffer_one or B) provide the shellcode in an environment variable and jump to that instead.
If you wish to write the actual shellcode yourself, you'll have to know how to perform syscalls and what calling conventions are and how to use them, as well as how to avoid NULL bytes in the shellcode. The other alternative is to use a payload generator such as the one included with Metasploit which will make it a lot easier (although you won't learn nearly as much).
These are technically the only pieces you need, especially since you have a good idea of what the address will be. However, many times (especially when the shellcode address is not known) a so-called NOP sled will be placed in front of the shellcode so that you don't have to get the address exactly right. A NOP sled (short for No Operation) is simply hundreds to thousands of NOP instructions (0x90) that you can jump into the middle of and then have no effect until execution continues into the shellcode.
If you trace everything in GDB and execution jumps to the shellcode correctly but you still get access violations, it's likely because the NX bit is set on the stack page, meaning that the processor will refuse to execute data on from the stack as instructions. I'm not sure if execstack is included with OSX or not, but if so, you can use it for testing purposes to disable the NX bit (execstack -s overflow).
I apologize for the wall of text, but I wasn't sure how far you wanted to go studying buffer overflows. There's other guides you can check out as well, such as Aleph One's archetypal guide, "Smashing the Stack for Fun and Profit". The Shellcoder's Handbook is a good book to check out as well, and I'm sure others can add recommendations.
TL;DR: In short, you are overflowing your buffer and overwriting saved pointers and return addresses with garbage.

A: If you are learning about exploits then you'll need to really dig into details.
Go ahead, read the machine code! You might be able to find out how to slip the overflow past whatever check method Snow Leopard is using.
The problem may be simpler than that too. There's no rule that the compiler has to put buffer_one and buffer_two in any particular order on the stack or even put them on the stack at all. Notice that buffer_one would actually fit into a register.
That isn't the case here of course, but I see that buffer_two is placed before buffer_one. That means that writing an overflow into buffer_one will never write into buffer_two. I can't explain why it ends up containing '', but f8d0 is definitely before f8e0 in memory.

A: Data on the stack on x86 is 4-byte aligned. There is padding placed between buffer_two and buffer_one if buffer_two length is not a multiple of 4 bytes. change it to 12 or less and they should be 12 bytes apart, etc.
[Update] I overlooked the address size. You are on a 64-bit system, your stack is 8-byte aligned. The address differences won't change until your buffer size changes by at least 8 bytes.
Is this line correct:
strcpy(buffer_one, argv[1]);

The output looks like you are copying argv[1] into buffer_two.
Given that case, how much are you copying when it crashes? 17 bytes? 18? If it is more than 24 you will start clobbering the stack in ways which would lead to the abort.
Note that "1234567890123456" is actually copying 17 bytes which includes the null terminator truncating buffer_one.

A: Have you tried to disable FORTIFY_SOURCE when compiling?
-D_FORTIFY_SOURCE=0


text:
Q: Aborted (core dump) when outputting trie.dot I get this error when running my trie.o that is supposed to output a trie.dot file, so it only outputs one word instead of the whole dictionary. It gets the input from dictionary.txt. I cannot put my full code here as it`s a school assignment, that's why I tried to search where exactly the error occurs and I think it occcurs in this insert-function of my code.
In my search for the error I learned that this error usually has to do with the memory (especially malloc and free()) but I can't find the error in the code.
error
  *** Error in `./output.o': free(): invalid pointer: 0xb77b5470 ***
  ======= Backtrace: =========
 /lib/i386-linux-gnu/libc.so.6(+0x767e2)[0xb767c7e2]
 /lib/i386-linux-gnu/libc.so.6(+0x77530)[0xb767d530]
 ./output.o[0x80487fd]
 ./output.o[0x804876e]
  /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0xb761f935]
 ./output.o[0x8048641]
  ======= Memory map: ========
 08048000-0804a000 r-xp 00000000 08:01 922197     /home/jordy/Desktop/Practicum/output.o
 0804a000-0804b000 r--p 00001000 08:01 922197     /home/jordy/Desktop/Practicum/output.o
 0804b000-0804c000 rw-p 00002000 08:01 922197     /home/jordy/Desktop/Practicum/output.o
 09ee9000-09f0a000 rw-p 00000000 00:00 0          [heap]
 b75d6000-b75f1000 r-xp 00000000 08:01 394080     /lib/i386-linux-gnu/libgcc_s.so.1
 b75f1000-b75f2000 r--p 0001a000 08:01 394080     /lib/i386-linux-gnu/libgcc_s.so.1
 b75f2000-b75f3000 rw-p 0001b000 08:01 394080     /lib/i386-linux-gnu/libgcc_s.so.1
 b7605000-b7606000 rw-p 00000000 00:00 0
 b7606000-b77b3000 r-xp 00000000 08:01 394055     /lib/i386-linux-gnu/libc-2.17.so
 b77b3000-b77b5000 r--p 001ad000 08:01 394055     /lib/i386-linux-gnu/libc-2.17.so
 b77b5000-b77b6000 rw-p 001af000 08:01 394055     /lib/i386-linux-gnu/libc-2.17.so
 b77b6000-b77b9000 rw-p 00000000 00:00 0
 b77c9000-b77cd000 rw-p 00000000 00:00 0
 b77cd000-b77ce000 r-xp 00000000 00:00 0          [vdso]
 b77ce000-b77ee000 r-xp 00000000 08:01 394031     /lib/i386-linux-gnu/ld-2.17.so
 b77ee000-b77ef000 r--p 0001f000 08:01 394031     /lib/i386-linux-gnu/ld-2.17.so
 b77ef000-b77f0000 rw-p 00020000 08:01 394031     /lib/i386-linux-gnu/ld-2.17.so
 bfeb6000-bfed7000 rw-p 00000000 00:00 0          [stack]
 Aborted (core dumped)

A: As far as i can tell,
int trie_is_valid_key(const char* key)
{
    int i=0;
    while(i<=sizeof(key)){
        if('a'<= key[i] && key[i] <= 'z'){
            i++;
        }
        else return 0;
    }
    return 1;
}

will always return 0 because you're going to encounter a NUL byte at some point. You
probably want
   while (i<strlen(key))

Since trie_is_valid_key always returns 0, trie_insert is always going to execute
free(trie -> value);

which likely will try to free a NULL pointer, resulting in an error message from free.
You probably want
if(trie->value) {
    free(trie->value);
}

but I'm not sure you'd ever encounter anything but a NULL pointer there, so check your algorithm to be sure you really want to replace an existing value in that trie node.
Also, is TRIE_NB_CHILDREN at least 26? If not, the program may write outside the bounds of the trie->children array, trashing trie->value.


text:
Q: mysql how to best set up tables where relation is one to several I was trying a set up for my tables, which seemed simpler to me, but I am not managing to find the proper way.
This is to calculate after sales costs for vehicles where each vehicle will receive one of each of a sub-group of services from a price list to make up the total after sales cost.
Please see the scenario below:
Table AfterSalesPriceList would be like:
as_id   as_description      as_value

1       service kit1          1000
2       service kit2          1500
3       service kit3          2000
.......
10      repair kit1           5000
11      repair kit2           8000
12      repair kit3           9000
.....
21      pneu 1                1500
22      pneu 2                2500
23      pneu 3                4000
.....
31      battery 1              500
32      battery 2              800
33      battery 3              1000

Now, in another table? I would place which of these services each vehicle will receive.Each vehicle has to have one and ONLY 1 of each item from service, repair, pneu, battery,etc, like in a Table VehicleAS:
vehicle_id 1    service kit1, repair kit 2, pneu 3, battery 1
vehicle_id 2    service kit2, repair kit 2, pneu 1, battery 2
etc.....

Of course, this does not work in mysql, at least far as I know.
Is there a way to do this in mySql without the need to break apart Table After Sales in multiple tables, one for each subset (one for service, another for repair, another for battery, etc).
It will certainly work with exploding the AfterSalesPriceList Table, but I am trying to make it what seems to me more logical, ie, have all After Sales prices in a single table.
Thanks

A: It's a one to many relationship.  Both tables will have primary keys.  The child/many table will have a FOREIGN KEY column whose value will point back to the primary key in the parent/one table.
You'll find all the children that belong to the parent by doing a JOIN on parent primary key and child foreign key.

A: Table AfterSalesPriceList seems to be OK.
Your another Table VehicleAS however can have
vehicle_id, as_id FOREIGN KEY (as_id) REFERENCES AfterSalesPriceList(as_id)

it can have multiple rows for a vehicle_id for each service it has used.


text:
Q: Ready made Contours from SRTM data? I need to create a map with SRTM data but use contours instead of the grid data. I can use ESRI software to create contours but they aren't the nicest looking, mostly in flat areas. Does a good contour already exist for download somewhere? My Area of interest is North Vancouver, BC Canada and accross the border into the US (almost to Seattle).

A: If you're looking for a continuous DEM spanning Canada and the USA, you might want to check out the EarthEnv DEM90 data set. It's reprocessed product from SRTM and ASTER and gap filled so the accuracy is a bit better than using straight SRTM. You can download it by tile or by corner coordinates so that should help with data management.
The aesthetic problem is likely due to your choice of contour interval, the resolution of the data set that you're using, and the scale of your area of interest. If your study area is a couple square Km and you're using 90m resolution data, it's not going to be pretty (or accurate).


text:
Q: nginx infinite 302 Found redirect loop I am using nginx to map multiple domains to google app engine.
in this specific case i map multiple domains to the same tenant.
there is a configuration in my code that knows which domain is the main domain and when a request comes in i check if the host is the main domain and if it isn't i redirect to the main domain.
for example lets say www.aaa.com is the domain set as default
aaa.com     -> www.aaa.com
www.bbb.com -> www.aaa.com
ccc.com     -> www.aaa.com
...

what happens randomly from time to time is that a javascript url goes into a redirect loop on nginx.
note that the request never hits appengine. nginx is creating this 302 Found loop.
this happened 2 times in the past 2 weeks.
the request path looks like www.aaa.com/22/foobar.js where the first part of the path is the version number of the javascript file.
a css file with the same uri format www.aaa.com/22/foobar.css won't have this redirect loop.
if i deploy a new version the file will server correctly again. so deploying a version 23 and accessing www.aaa.com/23/foobar.js would work again.
also if i use a cachebuster on the request like www.aaa.com/22/foobar.js?345
restarting nginx or even restarting the machine where nginx is running does not help.
setting up a new machine with the same exact configuration serves the file with no problem.
so what could cause this redirect loop?
how could i get rid of it once it happens?
is there a cache on nginx (i know nginx is not caching by default) i dont know about?
does the machine maybe cache those redirects?
here my nginx.conf

user nginx;
worker_processes 2;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    server_names_hash_max_size 1024;
    server_names_hash_bucket_size 128;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    sendfile on;

    keepalive_timeout 65;
    # enable gzip compression
    gzip on;
    gzip_min_length 1100;
    gzip_buffers 4 32k;
    gzip_comp_level 5;
    gzip_types text/plain application/x-javascript text/xml text/css;
    gzip_vary on;

    server {
        server_name www.aaa.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name aaa.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name www.bbb.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name bbb.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name www.ccc.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name ccc.com;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://tenantname.myappid.appspot.com/$request_uri;
            proxy_set_header Host tenantname.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://tenantname.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        server_name ~^(?<sub>.+)\.maindomain\.com$;

        location / {
            resolver 8.8.8.8;
            proxy_pass http://$sub.myappid.appspot.com/$request_uri;
            proxy_set_header Host $sub.myappid.appspot.com;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header NexHost $scheme://$host;
            proxy_redirect http://$sub.myappid.appspot.com/ /;
            proxy_intercept_errors on;
        }
    }

    server {
        listen 80 default_server;
        server_name _;
        location / {
            root /etc/nginx/html;
        }
    }
}

A: so i solved this problem by redirecting from nginx rather than from the backend.
while the issue is solved by now i still didn't figure out why this redirect loop was happening in the first place.
every hint would be helpful.


text:
Q: JavaScript functions breaking with comma in string from PHP Step 1: On clicking a button, show a modal.
<button class="btn btn-sm fa fa-edit" onclick="updateJobModal('<?php echo $custContactName ?>','<?php echo $jobDesc ?>','<?php echo $detailedDesc ?>','<?php echo $poNumber ?>','<?php echo substr($dueDate, '0', '10') ?>','<?php echo $prevJobNumber ?>','<?php echo $totalSellPrice ?>','<?php echo $sellLevel ?>','<?php echo $brandType ?>','<?php echo $clientRef ?>')">  </button>

JavaScript:
const updateJobModal = (contact, jdesc, detailed, pono, duedate, prevjob, total, selllevel, brand, cliref) => {
  let recordInUse = <?php echo $recordInUse?>;

  if (recordInUse === 1) {
    swal('Error', 'Unable To Update! Job Is Currently Open In EPMS!!', 'warning');
  } else {
    console.log([contact, jdesc, detailed, pono, duedate, prevjob, total, selllevel, brand, cliref]);
    document.getElementById('jobdesc').value = jdesc;
    document.getElementById('contact').value = contact;
    document.getElementById('contact').innerText = contact;
    $('#ddesc').val(detailed);
    $('#ponumber').val(pono);
    $('#duedate').val(duedate);
    $('#prevno').val(prevjob);
    $('#totalprice').val(total);
    $('#selllevel').val(selllevel);
    $('#brand').val(brand);
    $('#clientref').val(cliref);
    $('#modal-form').modal('show');
  }
};

Now the problem is the field $detailedDesc has commas in it. Example:
Lot B--Box , Blank Tray , Top Insert, Mailing Label

It breaks the function and causes Uncaught SyntaxError: Invalid or unexpected token.
Function call causing the error:
updateJobModal('','Snack Pack Custom Box Mailing','Lot B--Box ,  Blank Tray ,  Top Insert,  Mailing Label
','Array','2018-07-31','','235315','20/30','Brand','Client Ref')

How do I get it to working correctly?


text:
Q: Is Superman vulnerable to magic? I remember reading or hearing somewhere that Superman's only weakness is Kyrptonite.... and Magic.
Is this an actual weakness for Superman? Or is he just susceptible to the effects of magic like most other people/beings?
Is there certain magic the Kryptonian is immune to?

A: In Kingdom Come when Wonder Woman and Superman are in space, Superman cuts himself on her sword. Wonder Woman warns him to be careful as he is weak to magic and the sword was forged by the gods.
Since KC Superman was identical to normal universe superman until the divergence point, then the answer is clearly yes.
This is further expanded on in World War 3 when Black Adam goes crazy, and Superman states he isn't a match for him.
Those are the most prominent examples that comes to mind.

A: In the series Smallville, Superman is weak to any form of magic, or at least doesn't have any kind of protection against it. Just as with anyone who is heavily protected, a chink in the armor can prove fatal.
There's an excelent article about this very topic as well on How Stuff Works.  Basically, it pits Superman vs Harry Potter and Gandalf, to which they suppose he would lose both battles.

A: In Superman/Shazam!: The Return of Black Adam, it is revealed that Superman is susceptible to Black Adam's magical powers.

 Outside, the battle rages on between Superman and Black Adam. Superman is barely able to hold his own against the magical based powers of his foe. Superman is again subdued by his adversary and is rendered unconscious.

A: No. Superman is no more vulnerable to magic than any other person in the DC Universe. But given his range of powers and normal ranges of invulnerability, this is counted as a great weakness relatively speaking. While magic-users do not abound in the DC Universe, there are a number of magical phenomenon which can make confrontations against those forces a surprise for the Man of Steel.
Superman is indeed vulnerable to only a tiny slice of phenomenon in the DC Universe, and each iteration was slightly different in their representation of those weaknesses. We will use the Golden Age Superman, Pre-Crisis Superman and Post Crisis Superman as the definitive canon models as reference. DCnU Superman's limits are still being defined, but it is likely they will not deviate too far from the norm.
All canon Supermen:

*

*Derived their powers from the yellow or higher energy wavelength stars. Orange or red stars do not completely trigger the genetic capabilities that give him his powers. Under orange stars, his powers are half of their strength and under red stars he has no access to his superhuman abilities.

*While this has never been effectively explained, Kryptonite appears to possess the ability to prevent him from accessing the solar energy somehow stored within his cells. In addition to denying him access to his solar powers, prolonged exposure is both dangerous and ultimately toxic to him. Upon the removal of Kryptonite, depending on the exposure, his access to his powers will return relatively shortly. Only a near-death encounter will leave him drained of power.

*possess a weakness to specific wavelengths of radiation. Advanced species who knew of Kryptonians (such as the denizens of the Fourth World, i.e. Darkseid, Highfather and other New Gods, as well as extraterrestrials, particularly during the period of Pre-Crisis Superman who spent a considerable amount of his time in space) used weapons capable of producing radion energy. Such weapons were rare but were capable of affecting Superman.

*Pre-Crisis Superman was also vulnerable to exotic radiations such as Q-radiation and weapons from advanced civilizations that either harnessed red sun wavelengths, or with sufficient energy could overcome his invulnerability making him vulnerable to their effects. Green Lanterns (and presumably the Guardians) can also use their rings to emulate the wavelengths of Kryptonite radiation.

*have less of a weakness and simply an inability to effectively counter magical energies. The true magic of the DCU has always been considered an effect of Chaos and derived from the Lords of Chaos. Such effects of Chaos render a being whose powers are derived from Order less than effective. Superman is not an agent of Order, only that his powers are created from a technological process that is Ordered.

*have a vulnerability to magic that is no greater than any ordinary human's and Superman has been able to fight magical foes, granted with more difficulty, but his overall effectiveness is on par with any of his other villains. One supposition used during the Byrne era's Superman was that magic bypasses his ability to defend against it due to his inability to understand it. Other suppositions assumed his alien heritage left him vulnerable but who can be sure? As usual, DC has never effectively explained why magic works against him when so many other things do not.

Inconsistent storytelling with poorly defined mechanics
Given that magic is not explained effectively, it can be inferred that metahumans such as Black Adam and Captain Marvel who derive their powers from a magical source are more effective against Superman and that would be a misnomer. The strength of Hercules used by Captain Marvel is super-strength on par with Superman's.
His ability to affect Superman is because his strength is as great as Kal-el's not because it is an active magical effect. Unless the Captain or Black Adam are using a directed energy attack such as the Summoning Lightning Discharge against Superman, or a directed magical energy attack, it is a struggle of physical equals. However, the summoning lightning is a powerful directed magical attack and has been used against Superman to stun and weaken him.
Magical objects, weapons and the like are able to affect him and bypass his natural defenses. Hence Wonder Woman's weapons, forged by powerful magical divine beings, are more than capable of harming Superman. He has also been scratched by werewolves and vampires whose magical nature is inherent and required for their very existence.
In most storylines, Superman has been considered to be equal to or slightly ahead of Captain Marvel in terms of raw power and durability. Superman has always been considered to be the DCU flagship hero on Earth in terms of physical superiority with Captain Marvel being considered second to him and titled "the World's Mightiest Mortal". Given that DC prefers to have the two characters locked in a perpetual dead heat because it promotes fanboy enthusiasm, it will likely never be revealed which of them is more powerful.
A note: All of the references used as examples in other answers are non-canon references, Superman/Shazam!: The Return of Black Adam, Smallville and Kingdom Come are all divergent timelines/continuities and do not reflect canon Superman. Nor should they be used as definitive references to the character.

A: Superman has indeed been shown to be vunerable to magic, at least in some universe versions For example, when he encountered Arathaza (New Earth, written/illustrated by John Byrne),

 he is essentially defeated, Arathaza draining all his life force and power from him. At the end of the battle he is an old white-haired and weak man. Eventually he is able to trick Arathaza, using only human powers and cunning to take away and destroy her magical staff, thus rendering her powerless. He then immediately regains his powers.

A: I think it's worth creating a sort of addendum for the all the answers here that it's not so much that Superman is weak against magic as it is that he is not specially strong against it. This is something other answers hinted at, but never outright stated.
I believe there is a subtle difference there, in that it does still allow Superman to do some things vs magic users and weapons that you or I would be unable to do. For example, a weapon that is magically enhanced to hit harder (say, 10x the force) will hit Superman harder. Superman is not immune to magic, and therefore Superman cannot negate the weapon's effect. He still has to deal with the 10x force blow. At the same time, the weapon does not get the ability to punch through Superman's defense and hurt him as if he were human. So it's not as if you or I took a punch with 10x the normal power. Because Superman still has his great durability, Superman may take the shot and keep fighting.

A: Old topic but yes, he is vulnerable to magic.
People say he is no more vulnerable than any other person in the DC universe.. but take that in context.
So Superman has the same defense vs it as a normal unpowered person. Magic is supposed to be a trump card Vs superman because getting a red sun or Kryptonite has not been an easy thing.
All superheroes have a weakness or they would be gods and even gods in Marvel and DC have weaknesses.
The only thing that can save Superman and lessen the impact is once he is aware of what he is facing he can use super speed to avoid most attacks or impacts.
Wonder Woman and the Lasso would own him. Dr Fate or Dr Strange (assuming a crossover) .. would own him. The issue is magic has to hit him so unless it's an area effect.. once known, his speed should compensate.
Superman also holds back and is arrogant. Again if this was not true.. almost nothing would be a fight for him.


text:
Q: how to write function for a specific document in firestore? below is the function, i have used from youtube .
     const functions = require("firebase-functions");
     const admin = require("firebase-admin");

     admin.initializeApp();

     exports.androidPushNotification =
     functions.firestore.document('MyMoneyNotifications/{MyPercentageMoney}').onCreate(

     (snapshot, context)=>
      {
         admin.messaging().sendToTopic(
      "new_user_forums",
   {
     notification:{
         title:snapshot.data().title,
         body: snapshot.data().body
                   }
            });});

it is working fine.
but i want to check for below structure.
        Notifications(collection)
              ->UserId(document)
                 ->MyNotification(collection)
                              ->notify1
                              ->notify2

now, i want to check for a specific user if he had any new notifications. how to check for the collection "MyNotification" in firebase functions

A: If you are trying to listen to sub-collections then you can set the path to:
exports.androidPushNotification =
     functions.firestore.document('Notifications/{userId}/MyNotification/{notificationId}')

You can read more about this in the documentation


text:
Q: How to automate webpage under a closed shadowDOM A part of the webpage is under closed shadow root mode. How do we automate it through selenium or javascript?
Edit:
we can see the DOM under the shadow in chrome://inspect/#apps. This seems to be the child DOM.
Is it possible to communicate between parent DOM and the above child DOM to perform actions on child DOM when our ShadowRoot DOM is hindering us to automate?

A: Simple answer: You can't.
More complex answer:
Override the Element.prototype.attachShadow function to override the closed setting and force it to be open.
Or rewrite your components to not use closed. This could be done with the components checking a query parameter and using closed most of the time and open when in testing mode.
UPDATE
A closed component is an attempt to allow the component creator some level of security that no one else can mess up their component. While the developer tools can still see inside, the outside code can't unless the component exposes the shadowRoot in some way.
What a closed component should do, instead of exposing their shadowRoot is to provide enough properties and functions to allow the user of the component to do everything they need.
Think of the <video> element. They have dozens of properties between it and its parent element HTMLMediaElement and dozens of functions and events. The component has everything needed for the users of <video> to be able to do almost anything.
If we write our component in this way then being close should not be an issue.
Sometimes people want to test every aspect of a Web Component, but they should really only focus on the public interface and not worry about the inner DOM.
How do you test an <input> element. Most of the time you set .value = "some value"; or add an event listener on change or input.
As long as your components properly expose everything needed to be able to test them then being close should no longer be an issue.


text:
Q: SSRS Using existing datasets to work out population and accountability I have 2 datasets within a report, 1 holds the total population and the 2nd holds reviews. What I need to do within a field is show the % done. e.g. dataset1.[Reviews] where Status =  "incomplete" and Status = "high risk" / dataset2.[Population] where type = "high risk"
Population Data example:

*

*NAME, RISK LEVEL

*Client123, HIGH RISK

*Client124, MEDIUM RISK

*Client125, HIGH RISK

*Client126, HIGH RISK

*Client127, HIGH RISK

*Client128, HIGH RISK

Review Data example

*

*CLIENT NAME, REVIEW STATUS

*Client123, INCOMPLETE

*Client124, COMPLETE

*Client125, COMPLETE

*Client126, INCOMPLETE

*Client127, INCOMPLETE

*Client128, INCOMPLETE

So 5 HIGH RISK Population, with 4 reviews incomplete = 80% delinquent
I need to try and do this in an expression and for the life of me I'm struggling! Maybe it's Friday brain!?
Any help appreciated.

A: Check below screenshots and steps to get desired output
Sample Output

Expression Details

Row Group Details - 1

Row Group Details - 2

DataSet1

select 'Client123' as [NAME],'HIGH RISK' as [RISK LEVEL]
union all
select 'Client124' as [NAME],'MEDIUM RISK' as [RISK LEVEL]
union all
select 'Client125' as [NAME],'HIGH RISK' as [RISK LEVEL]
union all
select 'Client126' as [NAME],'HIGH RISK' as [RISK LEVEL]
union all
select 'Client127' as [NAME],'HIGH RISK' as [RISK LEVEL]
union all
select 'Client128' as [NAME],'HIGH RISK' as [RISK LEVEL]

DataSet2

select 'Client123' as [CLIENT NAME] , 'INCOMPLETE' as [REVIEW STATUS]
union all
select 'Client124' as [CLIENT NAME] , 'COMPLETE' as [REVIEW STATUS]
union all
select 'Client125' as [CLIENT NAME] , 'COMPLETE' as [REVIEW STATUS]
union all
select 'Client126' as [CLIENT NAME] , 'INCOMPLETE' as [REVIEW STATUS]
union all
select 'Client127' as [CLIENT NAME] , 'INCOMPLETE' as [REVIEW STATUS]
union all
select 'Client128' as [CLIENT NAME] , 'INCOMPLETE' as [REVIEW STATUS]

Expression used in this report

1. Lookup(Fields!NAME.Value, Fields!CLIENT_NAME.Value, Fields!REVIEW_STATUS.Value, "DataSet2")
2. count(Lookup(Fields!NAME.Value, Fields!CLIENT_NAME.Value, Fields!REVIEW_STATUS.Value, "DataSet2"))
3. count(Lookup(Fields!NAME.Value, Fields!CLIENT_NAME.Value, Fields!REVIEW_STATUS.Value, "DataSet2"))/Count(Fields!NAME.Value,"RISK_LEVEL")
4. Count(Fields!NAME.Value, "RISK_LEVEL2")

I have created two sample report. I mentioned group properties of sample report1. For sample report2 the group property like as first one.


text:
Q: LRU Cache C++ implementation issue I was doing an exercise in an online judge:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
I basically use std::list and std::unordered_map and works good in small input case. But OJ give a Time Limit Exceeded on the input: cache size is 2048 and 20000+ get & set operations.
Time Limit Exceeded version:
class LRUCache {
public:
    LRUCache(int capacity):cacheSize(capacity) {

    }
    int get(int key) {
        auto it = mapping.find(key);
        if(it == mapping.end())
            return -1;
        itemList.splice(itemList.begin(),itemList,it->second);
        //mapping[key] == it->second still holds
        return it->second->second;
    }
    void set(int key, int value) {
        auto it = mapping.find(key);
        if(it != mapping.end()) {
            itemList.splice(itemList.begin(),itemList,it->second);
            it->second->second = value;
        } else {
            itemList.push_front(make_pair(key,value));
            mapping.insert(make_pair(key,itemList.begin()));
        }
        if(itemList.size() > cacheSize) {
            mapping.erase(itemList.back().first);
            itemList.pop_back();
        }
    }
private:
    int cacheSize;
    list<pair<int,int> > itemList;
    unordered_map<int,list<pair<int,int> >::iterator> mapping;
};

Then I thought why not erase element before insert one, so I modify set function and OJ accept!
Accept version:
    void set(int key, int value) {
        auto it = mapping.find(key);
        if(it != mapping.end()) {
            itemList.splice(itemList.begin(),itemList,it->second);
            it->second->second = value;
        } else {
            if(itemList.size() == cacheSize) {
                mapping.erase(itemList.back().first);
                itemList.pop_back();
            }
            itemList.push_front(make_pair(key,value));
            mapping.insert(make_pair(key,itemList.begin()));
        }
    }

I wonder what makes such a different?

A: The reason is that the OJ you use uses a C++ compiler which has std::list::size with linear complexity. In C++11 they require it to be constant, but in C++98 it could be up to linear, and many implementations actually have it linear.
See complexity here on the C++98 tab: http://www.cplusplus.com/reference/list/list/size/
I located the OJ that you were using, and managed to get TLE with your code, but managed to get it accepted with a small modification, which just tracks the size of the list instead of calling size()
class LRUCache {
public:
    LRUCache(int capacity):cacheSize(capacity) {
        listSize = 0;
    }
    int get(int key) {
        auto it = mapping.find(key);
        if(it == mapping.end())
            return -1;
        itemList.splice(itemList.begin(),itemList,it->second);
        //mapping[key] == it->second still holds
        return it->second->second;
    }
    void set(int key, int value) {
        auto it = mapping.find(key);
        if(it != mapping.end()) {
            itemList.splice(itemList.begin(),itemList,it->second);
            it->second->second = value;
        } else {
            itemList.push_front(make_pair(key,value));
            ++ listSize;
            mapping.insert(make_pair(key,itemList.begin()));
        }
        if(listSize > cacheSize) {
            mapping.erase(itemList.back().first);
            -- listSize;
            itemList.pop_back();
        }
    }
private:
    int cacheSize;
    int listSize;
    list<pair<int,int> > itemList;
    unordered_map<int,list<pair<int,int> >::iterator> mapping;
};


text:
Q: Awk double-slash record separator I am trying to separate RECORDS of a file based on the string, "//".
What I've tried is:
 awk -v RS="//" '{ print "******************************************\n\n"$0 }' myFile.gb

Where the "******" etc, is just a trace to show me that the record is split.
However, the file also contains / (by themselves) and my trace,  ****** is being printed there as well meaning that awk is interpreting those also as my record separator.
How can I get awk to only split records on // ????
UPDATE: I am running on Unix (the one that comes with OS X)
I found a temporary solution, being:
sed s/"\/\/"/"*"/g | awk -v RS="*" ...

But there must be a better way, especially with massive files that I am working with.

A: On a Mac, awk version 20070501 does not support  multi-character RS. Here's an illustration using such an awk, and a comparison (on the same machine) with gawk:
$ /usr/bin/awk --version
awk version 20070501

$ /usr/bin/awk -v RS="//" '{print NR ":" $0}' <<< x//y//z
1:x
2:
3:y
4:
5:z

$ gawk -v RS="//" '{print NR ":" $0}' <<< x//y//z
1:x
2:y
3:z

If you cannot find a suitable awk, then pick a better character than *. For example, if tabs are acceptable, and if your shell supports $'...', then you could use this incantation of sed:
sed $'s,//,\t,g'


text:
Q: java hibernate aggregation error qty|price
1 | 4
4 | 5
6 | 4
2 | 3
1 | 2

are entries on the database. i am trying to get the result: (group quantity by price)
qty|price
7 | 4
4 | 5
2 | 3
1 | 2

I am successful when i do this query using sqlwave to my local databse

SELECT price, sum(quantity) FROM table

but when I try this in java/hibernate.. and try to list, i don't get the results for sum() aggregation. i tried aggregation.. but it gives me the sum of all the quantities instead of by price. How do i restrict so I get the sum of the quantity for specific price??
Here's my method:
protected void listInventory(String productID)
{
Session session = sessionFactory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();

Query query = session.createQuery("SELECT price, sum(quantity) FROM table WHERE product_code=:productID GROUP BY price");

query.setParameter("product_code",productID);

List iv = query.list();
for(Iterator iterator = iv.iterator();iterator.hasNext();){
Products pb = (Products)iterator.next();
System.out.println("Price: "+pb.getPrice());
System.out.println("Quantity: " + pb.getQuantity());
}
tx.commit();
}catch (HibernateException e) {
       if (tx!=null) tx.rollback();
       e.printStackTrace();
    }finally {
           session.close();serverWriter.flush();
        }
}

A: If you want the sum of the quantity for a specific price, then you syntactically correct SQL.  Your expression:
SELECT price, sum(quantity) as quantity
FROM table;

Is not correct because there is no group by clause.  Try this:
SELECT price, sum(quantity) as quantity
FROM table
GROUP BY price;

If you only want the results for one price:
SELECT sum(quantity) as quantity
FROM table
WHERE price = xxx;


text:
Q: 404 Error when reload page in a Tomcat web application I've deployed a Java web application using spark-java and angularJS (ui-router) on a Tomcat9 web server. When I try to reload the page, tomcat will launch an HTTP Status 404. This happens with all the views except for the main route '/'.
Tomcat is mapped on port 80, started by root user, and the app has been deployed on webapps/ROOT folder. I don't really know what to do.
I also use html5mode in app.js:
app.config(["$locationProvider", function($locationProvider) {
     $locationProvider.html5Mode(true);
}]);

and added <base href="/"> in index.html <head>
UPDATE:
In my server.xml I added the following code:
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
    <Valve className="org.apache.catalina.valves.rewrite.RewriteValve"/>
</Host>

and in /conf/Catalina/localhost/rewrite.config:
RewriteRule ^/(.*) index.html [L]

And now i've this console error for all the imported scripts:
Uncaught SyntaxError: Unexpected token <

It looks like it replaces all the scripts with index.html text.

A: Have you properly included the filter in web.XML according to the 'Other Web server' section in spark java documentation. ?


text:
Q: Is it possible to start own kernel driver without Microsoft Sign and with TESTSIGNING OFF? Windows 10 x64 OS: Windows 10 x64
I've created my own kernel driver which works fine with TESTSIGNING ON
I've signed .cat file with self-signed cert, and added cert to Trusted Root Authorities.
Now, I'm switching to TESTSIGNING OFF
I'm ABLE to install driver (it trusts my sign).
Installation via .inf file is successfull.
But when I'm trying to "sc start mydriver", it shows
[SC] StartService: error: 577: Windows cannot verify the digital signature for this file. bla bla bla
Did I do something wrong? Or its impossible to use own drivers at windows 10x64 without MS sign, and with TESTSIGNING OFF?

A: You can not run kernel mode driver without MS signing. Windows 10 onward you will need Extended Validation Code Signing certificate (EV Certificate) for signing your driver. You can get more details from below link.
https://blogs.msdn.microsoft.com/windows_hardware_certification/2015/04/01/driver-signing-changes-in-windows-10/

A: If you're writing your own driver, you can temporary disable driver signature enforcement by restarting your PC and selecting Disable Driver Signature Enforcement.
Find below the steps.
Windows 8 and above

*

*Search and open Recovery in System settings.

*Select Advanced start-up and Restart now.

*During booting, in Advanced Boot Options, select Disable Driver Signature Enforcement.

Note: This setting will apply to a single user session.

Windows 7

*

*Restart PC.

*Keep pressing F8 till Advanced Boot Options menu is shown.

*Select Disable Driver Signature Enforcement.

Source: How to Fix "Windows cannot verify the digital signature (Code 52)" Driver Problem?


text:
Q: Printing full symbolic link information, starting from a root directory We are interested in printing all the symbolic link information, starting from a root directory.  We would like the information to be printed in the following format:
symbolic name -> actual name [Notice the same line]
We have tried the following and it gives us the symbolic name and actual name, but on different lines:
find . -type l -print -exec readlink -f {} \;

A: I don't think you were far off. Use -printf instead of -print (assuming your version of find has it) and you get this
find / -type l -printf "%p -> " -exec readlink -f {} \;

Example output
/bin/apropos -> /bin/whatis
/bin/awk -> /bin/gawk
/bin/bzcmp -> /bin/bzdiff

For reference,
ls -gl /bin/apropos
lrwxrwxrwx 1 roaima 10 Mar 28 20:15 /bin/apropos -> whatis

You will get overstruck lines for broken links (-printf without a newline)

A: With zsh:
for link (**/*(ND@^-@)) print -r -- "$link -> $link:P"

Where @^-@ restricts the glob expansion to non-broken symlink files (symlinks for which the target is accessible, a necessary condition for its canonical path to be determined, the equivalent of GNU find's -type l ! -xtype l). $link:P gives the realpath of the link (the canonical absolute path after symlinks resolution of all components similar to what the realpath() standard function does, or GNU readlink -f).


text:
Q: python (3.5) list comprehension vs foor loop over void funcs I wonder if when we have many void func that change values of some object inplace (in Python return None) like:
A = []

def foo():
    A.append(range(10))

Will there be any benefits of doing list comprehension with these funcs:
funcs = [ foo1, foo2, foo3, ..., foo10]

[
   func() for func in funcs
]

Is it similar to C++ brackets?
Or is it equivalent in performance to simple for loop:
for func in funcs:
    func()

Which one should I use and why? Mostly Im using Python 3.5 so Im asking about this version :P
EDIT_000:::
I wonder if when we have many func that change values of some object inplace and return some dummy boolean, like:
A = []
dummy = False #edit

def foo():
    A.append(range(10))
    return dummy             #edit, we return dummy not None now

Will there be any benefits of doing list comprehension with these funcs:
funcs = [ foo1, foo2, foo3, ..., foo10]

[
   func() for func in funcs
]

Is it equivalent in performance to simple for loop:
for func in funcs:
    dummy=func()

Or will there be some performance gain when we create list full of dummy (like we get more heat waste by pressing more gas in car so it will run faster)?


text:
Q: position absolute is not working for bootstrap dropdown I have a drop-down which is not working(onclick, dropdown menu isn't appearing) for position:absolute but it is working for position:relative. The problem with position relative is that the drop-down menu is not responsive as shown in the below image.the drop-down is changing its place based on the value of the drop-down.As you can see in the image the drop-down menu isnt visible completely. I want that drop-down menu to be in proper position either using position:absolute or position:relative. thanks in advance.

.dropdown-menu {
    position: relative;
    float: right;
    margin-top: 5vh;
    margin-right: -15vh;
    font-size: 1.5rem;
    font-weight: bold;
    color: #337ab7;
    }

    {{ editMode ? 'Edit' : 'Create'}} Test  - [in 3 STEPS]

{{selectedCourse}}

{{item.acr}}

  .
  .
  .
  .


text:
Q: Requested Facebook permissions not taking effect my app's extended permissions are not working, everytime I try to post to wall, I get this error (#200) The user hasn't authorized the application to perform this action, even though I have added in the right permissions, here is my code,
PHP:
$facebook = new Facebook(array(
  'appId'  => '1234456789',
  'secret' => 'secret'
));

$user = $facebook->getUser();

if ($user) {

    $logoutUrl = $facebook->getLogoutUrl(array(
        'next'=>'http://apps.facebook.com/my_app/'
    ));

} else {

$loginUrl = $facebook->getLoginUrl(array(
        'redirect_uri'=>'http://apps.facebook.com/my_app/',
        'req_perms'=>'email,user_birthday,status_update,publish_stream,user_photos,user_videos',
        'cancel_url' =>'http://apps.facebook.com/my_app/'
    ));

    echo "<script>top.window.location='".$loginUrl."';</script>";

}

any idea why the permissions are not being set? Or why this is happening?
Thanx in advance!

A: Without the specific code that fails it's hard to help you.  But... according to FB's privacy settings, a user can choose which details to make available to applications:
From facebook:
Choose Your Privacy Settings>Apps, Games and Websites>
"Control what information is available to apps and websites when your friends use them."
It's possible that some user's have denied specific permissions and that's why it's returning an error.  See http://developers.facebook.com/docs/reference/fql/permissions/ to check granted permissions by uid.
But do show us the code :)


text:
Q: how can I read a formatted graph data file Java I'm reading graph data for adj matrix, and it is formatted in this way:
0
   176     67
   665    185
  1129     26
  1414    114
  1748    205

1
   140    248
   591    175
  1920     68
  2229     31

2
   778    476
   825    447
   888    258
  1179   ....

Single number line is the starting vertex, followed by lines of ending vertices with edge length
0 - starting vertex
176 - end vertex
67 - edge length
665 - end vertex
185 - edge length
and so on
That's what I've tried:
public void ValueAssign()
         throws IOException {
         Scanner inFile = new Scanner(new File("list1.txt"));
         String s = inFile.nextLine();
         int NofV = Integer.parseInt(s); // number of vertices
         int NofE = Integer.parseInt(s); // number of edges
         int v1,v2, edge; // v1 - vertex 1, v2 - vertex 2
         while ((s = inFile.nextLine()) != null) {

             Scanner in = new Scanner(s);
             in.useDelimiter(" ");
             v2 = in.nextInt();
             edge = in.nextInt();
         }

    }

How can I read it?

A: Try this code
public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = new Scanner(new File("list1.txt"));
    int startingVertex, endingVertex, edgeLength;
    while (inFile.hasNextLine()) {
        String trimmedLine = inFile.nextLine().trim();

        //Skip empty lines
        if(trimmedLine.isEmpty()){
            continue;
        }

        String values[] = trimmedLine.split("\\s+");

        if(values.length > 1){
            endingVertex = Integer.parseInt(values[0]);
            edgeLength = Integer.parseInt(values[1]);

            //Do necessary operations

        }else if(values.length > 0){
            startingVertex = Integer.parseInt(values[0]);

            //Do necessary operations

        }
    }
}


text:
Q: How to set up a clipping rectangle or area How does one set up, modify, and clear a clipping rectangle inside a iOS drawRect for clipping generic CG drawing of lines, text, images, etc. to a small portion of a view?
Is it possible to use a more complex clipping region that is a composite of a bunch of rectangles and circles?

A: You can set a clipping area with arbitrary paths, not restricted to rectangles. The followings are some ways of doing it:

*

*You can draw an arbitrary path and set a clipping area with it. For example:
CGContextBeginPath(context);
//draw a path here
CGContextClosePath(context);
CGContextClip(context);
//following drawing on the context will be clipped

*If you want to use a mask image to set a clipping area, use CGContextClipToMask method.
See Apple's 'QuartzDemo' sample project for more usages.

A: If you just want to clip to a rect you can use:
CGContextClipToRect(context, clipRect);


text:
Q: A primitive to $\mathrm{Vol}(x)\pm \mathrm{Vol}(y)$ on $(\mathbb{S}^n \times \mathbb{S}^n)\backslash \Delta$ EDIT: I corrected some typos in my solution and wrote some details more precise (I was a bit sloppy first as I originally did not plan to discuss the full solution, but rather some ideas whether a solution can be constructed somewhat more naturally. E.g. using the Lie algebra and Lie group operations for $\mathbb{S}^3$.)
I am trying to solve the equation
$$ \mathrm{d}G(x,y) = \mathrm{Vol}(x)+(-1)^{n}\mathrm{Vol}(y):= H $$
for $G\in \Omega^{n-1}\bigl((\mathbb{S}^n\times \mathbb{S}^n)\backslash \Delta=:M\bigr)$. Here $\mathrm{Vol}$ is the standard volume form on $\mathbb{S}^n$ and $\Delta$ the diagonal. The solution for $n=1$ is
$$ G(x,y)= - \alpha(x,y)\quad \text{for all }x,y\in \mathbb{S}^1 $$
where $\alpha(x,y)$ is the counterclockwise angle from $x$ to $y$. I can find a solution for general $n\in \mathbb{N}$ as
$$ G = \int_{[0,1]} \psi^*H $$
for a contraction $\psi: [0,1]\times N \rightarrow N$ of an open thickening $N$ of $M$ onto the antidiagonal $\overline{\Delta}:=\{(x,-x)\}$ (on $\overline{\Delta}$ holds namely $H=0$). Here I use a closed extension of $\mathrm{Vol}$ to $\mathbb{R}^{n+1}_{\neq 0}$. However, the solutions I obtain (in coordinates $x^i$ on $\mathbb{R}^{n+1}$) look too complicated and it is computationally hard to work with it further.
Does anybody have any idea how to solve this equation "nicely" e.g. by some natural construction of $G(x,y)$ similar to the case $n=1$?
I am mainly interested in the case $n=3$. Can the Lie group structure be used to construct a solution?
Thanks for any ideas!
Big picture: $H$ is a smooth integral kernel of the orthogonal projection to harmonic forms and $G$ is a (singular) integral kernel of the Green operator (:=the inverse of $\mathrm{d}$)
UPDATE1: As Robert Bryant suggests, the sign is indeed $(-1)^n$.
UPDATE2: Reading the nice answer of Robert Bryant, I just typed my complicated solution for a comparison. Perhaps it is the same except Robert using a clever notation: For every $n$ a solution is
$$ G(x,y)=\sum_{k=0}^{n-1} g_k(x\cdot y) \omega_k(x,y) $$
where
$$ g_k(u) = \int_{0}^1 \frac{t^k(t-1)^{n-1-k}}{(2t(t-1)(1+u)+1)^{\frac{n+1}{2}}}\mathrm{dt} $$
can be solved inductively and
$$ \omega_k(x,y) = \frac{1}{k!(n-1-k)!} \sum_{\sigma\in \mathbb{S}_{n+1}} (-1)^\sigma x_{\sigma_1}y_{\sigma_2}\mathrm{d}x_{\sigma_3}\ldots\mathrm{d}x_{\sigma_{2+k}}\mathrm{d}y_{\sigma_{3+k}}\ldots\mathrm{d}y_{\sigma_{n+1}}$$
P.S. I am still tempted to say something like $G(x,y)((v_1,w_1),\ldots,(v_{n-1},w_{n-1}))$ is the angle between the hyperplane $\langle w_1,\ldots,w_{n-1}\rangle$ at $y$ and the parallel transport of the hyperplane $\langle v_1,\ldots,v_{n-1}\rangle$ from $x$ to $y$ along the shortest arc on the unique great circle through $x$ and $y$. This might be a complete nonsense as well... If my computations are correct then for $n=2$ holds
$$ G(e_1,\cos(\alpha)e_1 + \sin(\alpha)e_2) = \frac{\sin(\alpha)}{\cos(\alpha)-1}(\mathrm{d}y_3 - \mathrm{d} x_3 ). $$

A: NB: I have edited my answer to remove the comment at the beginning about correcting the original sign of the OP in the formula for $H$, since the OP has now corrected the erroneous sign in the question.  I have also added one remark at the end about the case when $n$ is even.
Now, one has
$$
H = x^*\Omega + (-1)^n\,y^*\Omega
\tag1
$$
where $x:\mathbb{S}^n\times \mathbb{S}^n \to \mathbb{S}^n\subset \mathbb{R}^{n+1}$ and $y:\mathbb{S}^n\times \mathbb{S}^n \to \mathbb{S}^n \subset \mathbb{R}^{n+1}$ are the projections on the first and second factors and $\Omega$ is the $\mathrm{SO}(n{+}1)$-invariant volume form on $\mathbb{S}^n$ corresponding to a fixed orientation and inner product on $\mathbb{R}^{n+1}$.
Thus, to remove any sign ambiguities, fix an orientation and inner product on $\mathbb{R}^{n+1}$, and let $(u_0,\ldots,u_n)$ be an oriented orthonormal basis of $\mathbb{R}^{n+1}$, so that $U = u_0\wedge\cdots\wedge u_n$ is a basis of $\Lambda^{n+1}(\mathbb{R}^{n+1})$.  Thus, for example, one has
$$
\tfrac1{n!}\,x\wedge (\mathrm{d}x)^n = x^*\Omega\,U
\quad\text{and}\quad \tfrac1{n!}\,y\wedge (\mathrm{d}y)^n = y^*\Omega\,U
\tag2
$$
To save writing, for a form $\phi$ with values in $\Lambda^{n+1}(\mathbb{R}^{n+1})$, I will henceforth write $[\phi]$ for the scalar-valued differential form such that $\phi = [\phi]\, U$. Thus, $x^*\Omega = [\tfrac1{n!}\,x\wedge (\mathrm{d}x)^n]$, etc.
Using this notation, for example, one has, when $n=1$, that $\mathrm{d}G = H$
where
$$
G = [\,f(x{\cdot}y)\,x\wedge y\,],\tag3
$$
where $f:[-1,1)\to\mathbb{R}$ is the (unique) smooth function that satisfies
$$
f(\cos t) = \frac{(\pi-t)}{\sin t}\quad\text{for}\quad 0<t<\pi,
$$
as one easily verifies by parametrizing as $x =(\cos\theta,\sin\theta)$ and $y=(\cos\phi,\sin\phi)$.  Note that, since $x{\cdot}y<1$ on $M$, $G$ is a smooth function on $M$ and that $G$ vanishes when pulled back to the anti-diagonal, where $x+y=0$.
When $n=2$, calculation yields that
$$
G = \frac{[x\wedge y\wedge \mathrm{d}(x{-}y)]}{1-x{\cdot}y}\tag4
$$
satisfies $\mathrm{d}G=H$, and, when $n=3$ (the case that the OP is particularly interested in), one finds that
$$
G = \left[\,x\wedge y \wedge \bigl(\,f(x{\cdot}y)\,(\mathrm{d}x)^2
-\left(\tfrac12 + (x{\cdot}y)\,f(x{\cdot}y)\right)\mathrm{d}x\wedge\mathrm{d}y
+f(x{\cdot}y)\,(\mathrm{d}y)^2\bigr)\,\right]\tag5
$$
satisfies $\mathrm{d}G = H$, where $f:[-1,1)\to\mathbb{R}$ is the (unique) smooth function that satisfies
$$
f(\cos t) = \frac{\pi-t+\sin t\cos t}{4\sin^3t} \quad\text{for}\quad 0<t<\pi.\tag6
$$
(It may not be apparent that $f$ is smooth at $-1$, but it is, once one sets $f(-1) = \tfrac16$.)
The general pattern is clear, i.e., that, for general $n$, there will be an expression for $G$ of the form
$$
G = \left[x\wedge y\wedge \left(\,f_0(x{\cdot}y)\,(\mathrm{d}x)^{n-1}
 + f_1(x{\cdot}y)\,(\mathrm{d}x)^{n-2}{\wedge}\mathrm{d}y + \cdots
 + f_{n-1}(x{\cdot}y)\,(\mathrm{d}y)^{n-1}\,\right)\right]\tag7
$$
where the $f_i$ are smooth functions on $[-1,1)$ that are determined by the condition that $\mathrm{d}G = H$.  These coefficients can be determined recursively, but the general answer does not seem to be particularly illuminating, so I won't include it here.
However, I will remark that when $n$ is even, the functions $f_i$ turn out to be rational functions of $x{\cdot}y$.  For example, when $n=4$, one finds
$$
G = \frac{\left[\,x\wedge y\wedge\bigl(\,(\mathrm{d}x-\mathrm{d}y)^3
+(1-x{\cdot}y)\,((\mathrm{d}x)^3-(\mathrm{d}y)^3)\bigr)\,\right]}
{18\,(1-x{\cdot}y)^2}
$$


text:
Q: getResourceAsStream() doesn't work on ubuntu, works on windows I have the following code snippet:
String name = "_a.properties"
InputStream in  = PropertyResolver.class.getClassLoader().getResourceAsStream(name);
String name2 = "folder/_b.properties"
InputStream in2  = PropertyResolver.class.getClassLoader().getResourceAsStream(name2);

This is a java/spring boot/maven project, directory structure is shown as follows:
/config
  _a.properties
  /folder
    _b.properties

On Windows 10 64bit (Java version 1.8.0_151) machine running java -jar (myfile) both of the inputstreams resolve successfully.
Running on Ubuntu 64bit (openjdk version 10.0.1) the second one resolves, while the first one is always null.
I have tried changing the values of name to "/_a.properties", and "./_a.properties" but nothing seems to work.
Any assistance appreciated.


text:
Q: Where does Android save the information of the permissions granted to all the applications Where does Android save the information of the permissions granted to all the applications?
i mean the permissions granted to applications during installation

A: After instalation, if you go to settings > aplications > click on application and you can see below what permissions are granted to it.
If you want to know a litle more about manage aplication permissions, you got a good article here

A: Android does not store it extra. Android installs your apk file. The permissions are in the apk file in the manifest part. No need to store them again. Well thats what i think.


text:
Q: Display p:dataTable Row Numbers In mkyong example, they show How To Display DataTable Row Numbers In JSF. They use javax.faces.model.DataModel to get row index without using backing bean value. How to achieve this by using primfaces p:dataTable. Thanks.

A: In primefaces p:datatable component, the component has rowIndexVar attribute, which is used to iterate to refer each row index. Thus, you can do like my example below
<p:dataTable
             var="cmr01Forms"
             value="#{cmr01Bean.cmr01Forms}"
             rowIndexVar="index">
    <p:column>
        <f:facet name="header">
            <h:outputText value="index" />
        </f:facet>
        <h:outputText
            value="#{index + 1}" />
    </p:column>
</p:dataTable>

A:  ***

*

*you can use rowindex. rowIndexVar="rowIndex". it starts with 0 so you
ve to plus 1 every row

<p:dataTable var="kat" value="#{kategoriBean.kategoriler}" rowIndexVar="rowIndex">
        <!--        <p:column headerText="Kategori Id"> -->
        <!--            <h:outputText value="#{kat.Id}" /> -->
        <!--        </p:column> -->
        <p:column headerText="NO">
            <h:outputText value="#{rowIndex+1}"></h:outputText>
        </p:column>
        <p:column headerText="Kategori Adı">
            <h:outputText value="#{kat.kategoriAdi}" />
        </p:column>
        <p:column>
            <h:outputText value="#{kat.kategoriKisaAciklama}"></h:outputText>
        </p:column>
    </p:dataTable>


text:
Q: touch and scroll a ListView inside a ScrollView cause the ScrollView not rendered anymore I have a ListView inside a ScrollView.
The listview can scroll vertically, and the scrollview can scroll horizontally.
The view hierarchy is like this: Top View --> ScrollView --> ListView.
When I touch and scroll the listview, the ScrollView's render function will not be called anymore. -The Top View's render function is called as expected, while it just don't update the ScrollView.
If I don't do the touch-and-scroll, then everything just goes fine.
And, after the touch-and-scroll, if I touch and scroll the ScrollView, then everything will go back well.
If feels like that the listview has got the focus after the touch-and-scroll, and things will not go well until it lose the focus.
Can you help? Thank you very much!

A: Found the root cause.
I'm setting a flag in onResponderGrant of the ScrollView, and clearing the flag in its onResponderRelease.
And in the ScrollView's shouldComponentUpdate, the flag is checked.
When I do the touch-and-scroll in the ListView, only onResponderGrant of the ScrollView is called and there's no call of its onResponderRelease, so the flag is not cleared.
Why the onResponderRelease is not called may be a bug of ReactNative.


text:
Q: How to strip single quote from a data attribute I need to strip a single quote from a  tag because it's conflicting with some javascript functionality on the page. What's the best method for me to do this?
Group A

A: This help you :

        Group A


text:
Q: Minifying a Flask application when templates have inline JS? The normal convention before deploying an application is to minify all assets (css, html, js). This usually assumes that all the assets are in an independent file (ie, all js code is in /js/mycode.js, which makes minifying the assets easier.
However, I have written a bunch of jinja2 templates that have

I am aware that I can stuff the js code into a file and then do {% include 'mycode.js' %}, but then I'd be importing ALL of my js code into the template. Some templates have inheritance, so then doing the include statement will cause the file to load the entire scripts multiple times into the page (not good). And I'm not sure how including scripts like this would work with minification.
Is there a good way to move all the inline JS code to an external file, without losing the benefits of jinja2's template variables, so that I can minify my javascript? Or rather, what's a good way to minify all my inline JS?

A: You can use jinja-assets-compressor for this.
https://github.com/jaysonsantos/jinja-assets-compressor
app.py
from jac.contrib.flask import JAC
from flask import Flask, render_template
import jinja2
from jac import CompressorExtension

app = Flask(__name__)
app.config['COMPRESSOR_DEBUG'] = app.config.get('DEBUG')
app.config['COMPRESSOR_OUTPUT_DIR'] = './static'
app.config['COMPRESSOR_STATIC_PREFIX'] = '/static'
jac = JAC(app)

env = jinja2.Environment(extensions=[CompressorExtension])
env.compressor_output_dir = './static'
env.compressor_static_prefix = '/static'
env.compressor_source_dirs = './static_files'

@app.route("/")
def hello():
    return render_template('index.html', name='rublex')

if __name__ == "__main__":
    app.run()

index.html
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Flask test</title>

Hello World

      <button onclick="sayHi()">Say Hi</button>

        {% compress 'js' %}

        {% endcompress %}

Outputs JS

function sayHi(){alert('rublex');}

A: If you just want simple inline js-minification, no output files... Here's what I did:
Took some time to get a simple custom jinja2 tag/node to work, but hopefully this helps anyone who might need something like this. This is likely not done the best way, but it works well enough. This runs the same "js-compressor" that jinja-assets-compressor does:

rjsmin  -  rJSmin is a javascript minifier written in python, based on the semantics of jsmin.c by Douglas Crockford.

Include this code snippet somewhere in you jinja2 code:
JSMinifyExtension
from jinja2 import nodes as j2_Nodes
from jinja2.ext import Extension as j2_Extension

import rjsmin  # https://pypi.org/project/rjsmin/

class JSMinifyExtension(j2_Extension):
    # simple js-minify for jinja2
    # by joedf (2021) - https://stackoverflow.com/a/66018269/883015

    # a set of names that trigger the extension.
    tags = {"jsminify"}

    def __init__(self, environment):
        super(JSMinifyExtension, self).__init__(environment)
        self._body_content = ""

    def parse(self, parser):
        tag = parser.stream.current.value
        lineno = next(parser.stream).lineno

        body = parser.parse_statements(['name:end{}'.format(tag)], drop_needle=True)
        self._body_content = body[0].nodes[0].data

        return j2_Nodes.CallBlock(self.call_method('_jsminify'), [], [], []).set_lineno(lineno)

    def _jsminify(self, caller):
        minified = rjsmin.jsmin(self._body_content, keep_bang_comments=False)
        return minified

And you can load in this extension into your jinja2 environment like so:
My_Example_Jinja_Env = Environment( extensions=['jinja2.ext.do', JSMinifyExtension] )

and use it your templates like so:
{% jsminify %}
function mySpecialFunction() {
    return 42;
}
{% endjsminify %}


text:
Q: Import Login and Password from Digest access authentication I would like to take from this text login and password but password probably is encrypted MD5?
This Text "String":

username="Domain\ik_r.test",realm="Digest",nonce="+Upgraded+v16223a53d44f99beb7dfaf10bf5738392669956ca1a21d101e949e262b02c7a7e268e9699b5824cd55c05d7bb900059b7b8985caa00174ace",uri="/Service1.svc",cnonce="+Upgraded+v1e077752581e4417aaefb76c90bca4fef0d9e033d4cb882c74cc04f2e95704b31",nc=00000001,algorithm=MD5-sess,response="6acc0f7e891fe4daa4174da35f098764",qop="auth",charset=utf-8,hashed-dirs="service-name,channel-binding",service-name="HTTP/test.eu",channel-binding="05439c3422ef9779e232067358231137"

Result:
string login = "Domain\\ik_r.test";
string password = ?;

Example:
https://en.wikipedia.org/wiki/Digest_access_authentication

A: As you linked in the question, that's HTTP digest authentication. The response value is constructed from an MD5 hash of MD5 hashes; in your case (MD5-sess, auth)

*

*a hash of "user:realm:password", then fed into a second hash with the two nonce strings in the request

*a hash constructed from the HTTP request line

*finally both of these hash outputs separated by one of the nonce strings is hashed again to construct the reponse.

The only way to recover the password from the response hash would be to repeat the process with every possible password until you find one that matches; since the request is constant that's three MD5 hashes per candidate password. This is likely too computationally expensive to actually do.
If you really need this password, and can't just change the password on the account or ask someone who knows, your best bet would be to try and recover it from the server: at worst, the server will need to have the very first hash of "user:realm:password" stored which would be only a single hash to brute-force to recover the password from. If you're lucky the server will have the password in plain text so that it can construct this hash for any arbitrary realm string.
Finally given your user has a 'domain' part this is probably a Windows account? There are tools out there which will help you recover or reset a Windows account password, although I don't know if they require domain admin access anyway, and can't recommend one.

A: You can't get the password from the data provided. You should find another way to authenticate


text:
Q: How to compare ordering of two groups with widely different scales I'm trying to compare if the order in col 1 is comparable to the order in col 2. The simplest thing I can do is just to compare both ranks using something like Friedman's test.
However, Col1 and Col2 is on a continuous basis. And for instance, the .94 and .93 in column 2 are closer together than 13.06 is to .94. Thus it's not quite ordinal data.
What would be a good way to compare the order but while taking into account the magnitude?
Thanks!
           Col1         Col2
7          1610635       1.61
8          3214571       2.04
9          2188633       1.30
4          1585069      13.06
5          2009116      14.74
1          2091101      12.50
2          2422071      14.64
3          1633422      13.05
10         3428149       0.93
11         2001198       1.20
12         2191020       0.94
13         2294395       8.83
14         2921134       9.18
15         2659132       6.60

*

*Background information:

As requested, here's the background. Column 1 represents the overall counts of a particular type of T-cell using one type of instrument which reads raw counts. Column 2 represents the number of t-cells found using a different type of instrument which provides things on a percentage basis.
We are looking to compare that the two instruments roughly act the same -- they should pick up roughly the same number (rather on a percentage or on a raw count).
I don't have any other data -- just these two columns.
Thanks!

A: I agree without more information it is difficult to assess what method might help you out. What is your reasoning for wanting to use Friedman's test?
What  you can try to do is center/normalize your data.
To center your data: Calculate the mean of each column, subtract the corresponding mean from each data point according to column.
To normalize: divide by the number of data points.
Then proceed to compare.
Again, without knowing what you are trying to achieve is difficult to provide an adequate answer.
Edit because of extra information:
You should either compare raw data to raw data or percentage to percentage. That is transform either one column either to raw or percentage. Then it will be easier to compare. Perhaps, you could do a difference test. For a graph just center and normalize the data.


text:
Q: How to detect blow in android device microphone How can I detect when the user blows into the device microphone? This would then be used to trigger some action by the app.

A: The job of detecting when a user blows into the microphone is separable into two parts: (1) taking input from the microphone and (2) listening for a blowing sound.
The noise/sound of someone blowing into the mic is made up of low-frequency sounds. We'll use a low pass filter to reduce the high frequency sounds coming in on the mic; when the level of the filtered signal spikes we'll know someone's blowing into the mic.
Source:
http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/
EDIT
And here is some small SoundMeter class for Android:
http://code.google.com/p/android-labs/source/browse/trunk/NoiseAlert/src/com/google/android/noisealert/SoundMeter.java?r=2

A: I would make and FFT and compare the spectrum with that of more sensible sounds. The blow will likely resemble white noise. Before seeing the spectrums of blow, speech and white noise, I have no idea how to tell one from another.


text:
Q: how to pass JSON data from login view to multiple view controller, is it possible or not? i am trying to pass JSON data in two different view controllers using perfrom segue and it is easy to pass data to single view controller or it is possible or not ?
func getlogin(){
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded"
        ]
        let parameters = [

            "UserName": username_textfield.text! as String,
            "Password": password_textfield.text! as String,
            "grant_type": "password",
            ]

        //        let url = NSURL(string: "http://192.168.100.5:84/Token")!
        Alamofire.request("http://192.168.100.5:84/Token", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case.success(let data):
                print("success",data)
                 let statusCode = (response.response?.statusCode)!

//                self.myResponse = JSON(data)
//                let login = Login(loginJson: self.myResponse)

                if statusCode == 200{
                    self.view.makeToast(message: "Welcome !!")

                    self.myResponse = JSON(data)
                    let login = Login(loginJson: self.myResponse)
                    DispatchQueue.main.async(execute: { () -> Void in
                        self.performSegue(withIdentifier: "dashboard", sender: login)
                        self.performSegue(withIdentifier: "rear_view", sender: login)

                    })

//
                }else{
                    self.view.makeToast(message: "Username or password invalid")
                }

            case.failure(let error):
                print("Not Success",error)
                self.view.makeToast(message: "Server Error!!")
            }

        }
    }

and my prepare segue from where i am trying to pass my JSON data ?
override  func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "dashboard" {
            let navController = segue.destination as! UINavigationController
            if let detailController = navController.topViewController as? ViewController,
                let loginData = sender as? Login {
                detailController.login_details = loginData
            }

 }
    if segue.identifier == "rear_view" {

        let navController = segue.destination as! UINavigationController
        if let dc = navController.topViewController as? MenuDrawerViewController,
                        let loginData = sender as? Login {
                        dc.login_details = loginData
                    }

    }
}

while user logs in JSON data is passed to viewController but not passing to MenuViewController , trying to pass data in both view controllers , how this issue can be solve ? or need some suggestions ?

A: Since you can only segue to a single controller, you cannot directly pass data to several ViewControllers in prepare(for segue).
However, you have several methods to pass data between several view controllers.

*

*Persist the data on disk, if it is not too complex and big, you can just store it in UserDefaults from your initial view controller and then access UserDefaults from your other two view controllers. If the data is more complex, you might have to use a database framework (Realm or CoreData for example).

*You can create static properties of your classes if you don't need to pass the data to a specific class instance, which you can access from all of your view controllers.

*Pass the data needed for both of your view controllers through the segue from your first view controller and then pass the data needed for your 3rd view controller when you segue from your 2nd one. However, this only works with a small number of view controllers and only if you can only segue to a view controller from the one to which you sent the data previously.

Edit: example on using static properties:
class FirstVC: UIViewController {  //this is your initial view controller
    ...
    let login = Login(loginJson: self.myResponse)
                ThirdVC.login = loginData
                DispatchQueue.main.async(execute: { () -> Void in
                    self.performSegue(withIdentifier: "dashboard", sender: login)
                })
    ...
}

class SecondVC: UIViewController {  // you segue here from FirstVC

}

class ThirdVC: UIViewController { //you segue here from SecondVC
    static var login: Login?
    override function viewDidLoad(){
       super.viewDidLoad()
       print(ThirdVC.login) // you can access the data sent from your FirstVC like this anywhere in ThirdVC.
    }
}


text:
Q: Creating a NSManagedObjectContext on a private/background queue: how to do? I am confused about how to create a MOC on other threads than the main thread.
On one hand, in the doc, one can read

A consequence of this is that a context assumes the default owner is
  the thread or queue that allocated it—this is determined by the thread
  that calls its init method. You should not, therefore, initialize a
  context on one thread then pass it to a different thread.

But on the other hand, I have seen code where an auxiliary MOC is created the following way, on the main thread:
    NSManagedObjectContext *parentContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

    [parentContext performBlockAndWait:^{
        [parentContext setUndoManager:nil]; // no point in it supporting undo
        [parentContext setPersistentStoreCoordinator:coordinator];
    }];

So, what is the good way to create an auxiliary MOC? Maybe I should precise that this auxiliary MOC is a @property of a central class of the project (AppDelegate for example).

A: The docs are ambiguous at best.
In my testing, you do not need to use a queue to attach the NSManagedObjectContext to its parent or the NSPersistentStoreCoordinator.
If you are doing a NSConfinmentConcurrencyType I set the parent or coordinator on the thread that created it (since that is the thread that can use it).
If you are doing a NSPrivateQueueConcurrencyType I set the parent or coordinator on the thread that created it as well.  It is the usage of the NSManagedObjectContext that is confined or restricted to the private queue.  I define the usage as executing a fetch, deleting an object, etc.  Configuring the NSManagedObjectContext is not restricted.
This of course is not in the documentation but the results were produced through testing back when accessing a NSManagedObjectContext incorrectly caused an exception.


text:
Q: Maximum number that can be formed from the given digits Given a Integer, find the maximum number that can be formed from the digits.
Input : 8754365
output : 8765543
I told solution in $O(n logn)$. He asked me optimize further.
We can use Hash Table to optimize further, $\rightarrow$ O(n)
Algorithm:
1. Take a hash table with size 10 (0 to 9).
2. Store the count of every digit from 0 to 9.
3. Print the index of the Hash table with respect to digit count in the reverse direction (from 9 to 0).
Example:
Hash table after digit count for 8754365 $\rightarrow$ (0 0 0 1 1 2 1 1 1 0)
Print the index of the hash table with respect to their count in reverse order $\rightarrow$ 8765543
Time Complexity : O(n)
Correct me if I am wrong.

A: The following greedy code does this in O(n) time. Where n is the number of digits in the number.
int num = 8756404;
int[] times = new int[10];
while(true){
    if(num==0){
        break;
    }
    int val = num%10;
    times[val]++;
    num /= 10;
}
for(int i=9; i>=0; i--){
    for(int j=0; j<times[i]; j++){
        System.out.print(i);
    }
}

It works by counting the number of occurences of each of the digits in the input number. Then printing each number the number of times it was in the input number in reverse order, ie. starting from 9 to 0.

A: RunTime: 00:00:00.01
public int Assignment(int number)
{
    // Consider that int.MaxValue equals to 2147483647
    var siblingString = String.Join("", number.ToString().ToCharArray().OrderByDescending(n => n));
    int sibling = -1;
    if (!int.TryParse(siblingString, out sibling) || sibling > 100000000)
    {
        return -1;
    }
    return sibling;
}

Performances tested with the following code:
static void Main()
{
    Stopwatch stopWatch = new Stopwatch();

    stopWatch.Start();
    var result = AssignmentOne(2147483646);
    stopWatch.Stop();

    TimeSpan ts = stopWatch.Elapsed;
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
}