text:
Q: LinkedList in Assembly x86 Irvine The following is a linked list Assembly program found in Kip Irvine's Assembly Language x86 book. In main, a loop traverses the list and displays all the node values. Rather than using a fixed counter for the loop, the program checks for the null pointer in the tail node and stops looping when it is found. My question is the following:
(a) Can someone explain < Counter, ($ + Counter * SIZEOF ListNode) >? How does it work and what does it mean?
(b) Can someone explain (ListNode PTR [esi]).NextPtr? What does that mean?
INCLUDE Irvine32.inc

    ListNode STRUCT
    NodeData DWORD ?
    NextPtr DWORD ?
    ListNode ENDS
    TotalNodeCount = 15
    NULL = 0
    Counter = 0

.data

    putc     macro   ptr

     push    eax

     mov     al, ptr
     call    writechar

     pop     eax
     endm

     ;to use:
     ;putc        'a'

    LinkedList LABEL PTR ListNode

REPEAT TotalNodeCount
    Counter = Counter + 1
    ListNode <Counter, ($ + Counter * SIZEOF ListNode)>
    ;struct variables Counter, and ($+Counter*SIZEOF ListNode) being declared
    ;
    ENDM

    ListNode <0,0> ; tail node

.code

main PROC
    mov esi,OFFSET LinkedList
    ; Display the integers in the NodeData fields.
    NextNode:
    ; Check for the tail node.

    putc    'a'; ->first node, then third node

    mov eax,(ListNode PTR [esi]).NextPtr
    cmp eax,NULL
    je quit
    ; Display the node data.

    putc   'b' ;->fourth node

    mov eax,(ListNode PTR [esi]).NodeData
    call WriteDec
    call Crlf
    ; Get pointer to next node.

    putc   'c' ;->first node
    putc   'd' ;->second node
    mov esi,(ListNode PTR [esi]).NextPtr
    ;references a struct using [esi]
    jmp NextNode
    quit:

    exit
main ENDP
END main

A:
Can someone explain (ListNode PTR [esi]).NextPtr? What does that mean?

It means that there is a pointer to the beginning of a ListNode structure in the ESI register. It dereferences that pointer, and evaluates to the NextPtr field.
It is basically like if you had the following in C:
ListNode* esi;
...
return esi->NextPtr;

Can someone explain < Counter, ($ + Counter * SIZEOF ListNode) >? How does it work and what does it mean?

No, honestly I cannot. Well, sorry, this turned out to be a pretty crappy answer. :-)
I can tell you how I would figure it out, though. First I'd go to the documentation for MASM and see if I could spot anything that looked relevant. I would find (or, actually, I already know) that $ means the current value of the location counter, and that SIZEOF is an operator that returns the number of bytes in the specified type.
So this gobbledygook looks like it multiplies the value of Counter by the size of the ListNode structure, and then adds the current value of the location counter.
But I still have no idea what the angle brackets mean. So I'd try a Google search, something like "angle brackets MASM". I get this question, which isn't very useful, since it doesn't have an answer. In the MASM32 help file, I see:

Treats as a single literal string. Angle brackets are often used in macro calls and with the FOR directive to ensure that values in a parameter list are treated as a single parameter . . . The assembler removes one set of angle brackets each time it inserts an argument into a macro expansion.

but that doesn't really help me too much, either.
Where to go from here? Well, assuming that the code works, I'd assemble it and ask MASM to produce a listing file (/Fl). I would then inspect this listing file to see what effect this actually had on the generated code.
Update: My dedication paid off, and I came across an old manual for MASM 6.1 online. I wasn't able to find this in Microsoft's online documentation, but in this manual, it clearly says on pg. 98:

Defining Structure and Union Variables
Once you have declared a structure or union type, you can define variables of that type. For each variable defined, memory is allocated in the current segment in the format declared by the type. The syntax for defining a structure or union variable is:
[[name]] typename < [[initializer [[,initializer]]...]] >
[[name]] typename { [[initializer [[,initializer]]...]] }
[[name]] typename constant DUP ({ [[initializer [[,initializer]]...]] })

The name is the label assigned to the variable. If you do not provide a name, the assembler allocates space for the variable but does not give it a symbolic name. The typename is the name of a previously declared structure or union type.
You can give an initializer for each field. Each initializer must correspond in type with the field defined in the type declaration. For unions, the type of the initializer must be the same as the type for the first field. An initialization list can also use the DUP operator.

So it looks like this declares an unnamed variable of type ListNode, and the stuff in brackets is the initializer for the ListNode struct, sort of like the C code:
struct ListNode { ... } = { Counter, ($ + Counter * sizeof(ListNode)) };

That fits with the feeble attempt at an explanatory comment:

; struct variables Counter, and ($+Counter*SIZEOF ListNode) being declared

since it's initializing the first two fields of the ListNode struct, NodeData and NextPtr, with those values.


text:
Q: Using isotope, why doesn't my grid update? This is my first time ever using isotope. So, I create the isotope instance inside of my document.ready function like so:
                        var grid = $('.headshots-list');

                    grid.isotope({
                        // options
                        itemSelector: '.headshots-list-item-alt',
                        layoutMode: 'fitRows',
                        sortBy: '[data-number]'
                    });

Then I set the values of each element in my grid layout including setting the data-number attribute.
 $("#headshot_" + $(this).val()).attr('data-number', 2); // Users who are not chairpersons

 $("#headshot_" + $(this).val()).attr('data-number', 1); // Users who are chairpersons

Then I try to sort the grid. Currently, I am using the setTimeout only because I was testing to see if maybe I had a race condition but it made no difference. The grid does not order itself in the way that I am expecting so that the user with data-number 1 will show before all other users. These attributes are being set. I have viewed the elements in dev tools to be sure.
As I mentioned earlier, this is the first time I have ever used isotope so not sure what I am doing wrong. Any pointers in the right direction will be greatly appreciated.
As requested below, this is the HTML where I build out the li that goes with this.
    <li id="headshot_<?php echo $user->ID; ?>"
                            data-number = "1" class="headshots-list-item-alt js-headshot <?php echo $user_terms_classes . ' ' . $board_status . ' ' . $number; ?>"
                            data-toggle="modal"
                            data-target="#memberInfo_<?php echo $member_id; ?>">

                                    <?php //suppress photo until they come in
                                    ?>
                                    <?php if ($photo_id): ?>
                                        <?php // echo wp_get_attachment_image( $photo_id, 'Avatar' ); ?>
                                    <?php else: ?>
                                        <?php // echo ''; ?>
                                    <?php endif; ?>

                                    <?php echo $name; ?>
                                    <input type="hidden" class="user_id" value="<?php echo $user->ID; ?>">
                                    <span style="font-size:14px; display: block; position: relative; width: 100%;"
                                          class="chair_designation" id="chair_designation_<?php echo $user->ID ?>">

<?php echo $title; ?>

                                View Bio

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accept changes in model with admin in ASP.Net MVC 5 I have 3 different types of users in my ASP.Net MVC website: admin, user, company. I want to let the companies change their info but the changes won't be applied until the admin accepts those changes. I was wondering what's the recommended method to achieve such functionality. I was thinking maybe I should  create 2 models for each type (for instance Company and Company_temp with identical fields and add the info to the temp table whenever the company submits changes. Then read them in the admin account and then apply them back to the real table. Would that be acceptable?

A: Sounds perfectly reasonable to me.  The only thing I would possibly change would be to call the second type CompanyUnapproved, or CompanyAwaitingApproval, something along those lines.  It makes your code more readable and your intentions clearer.


text:
Q: Remove multi-line C style /* comments */ using Perl regex How do I remove multi-line C style comments like:
/* comments
   comments
   comments
   comments */

I am able to remove comments in one line like /* comments */ by using several codes provided in other questions.
s#/\*[\s\S]*?\*/##sg;
s#/\*(.*?)\*/##sg;
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse

All three regexes above do not work with multi-line comments. How can they be handled?

A: I would do like,
perl -0777pe 's/\/\*(?:(?!\*\/).)*\*\/\n?//sg' file

Example:
$ cat fi
/* comments
   comments
   comments
   comments */
bar
$ perl -0777pe 's/\/\*(?:(?!\*\/).)*\*\/\n?//sg' fi
bar


text:
Q: UI on different resolutions devices for BB10 I have developed a static library for BB10 that provides a UI for capturing user credentials and then authenticate those credentials.
I have used this library in one of my app.
Problem I am facing is, whenever I run that app in BB Q10 device( Resolutions 720*720 ) the logo I am providing at the top of UI is not completely visible. but it works fine when i run the app in Z10( 768 x 1280 ).
Can anyone suggest what should I do such that this doesn't happens.

A: You need to provide a 720x720 specific asset: logo or layout. Basicaly, in your assets folder, make a 720x720 folder. If you put some content (with same name as your assets root folder content) inside of it, the Q10 will load the one in the 720x720 folder instead of the default one. It will change nothing on the Z10. See here for a complete explanation: http://developer.blackberry.com/cascades/documentation/ui/resolution/using_static_asset.html


text:
Q: keeps filling up memory with cached I tried to clear cache but it keeps filling up the memory. I also decreased swappiness but no luck.
[root@ip-10-0-0-140 src]# free -m
             total       used       free     shared    buffers     cached
Mem:         34240      34080        159          0         12      32644
-/+ buffers/cache:       1423      32816
Swap:         2047          0       2047

836.0 KiB + 555.0 KiB =   1.4 MiB       bash (2)
  2.3 MiB + 325.5 KiB =   2.7 MiB       udevd (3)
  1.7 MiB +   1.9 MiB =   3.5 MiB       sshd (3)
  9.5 MiB +   3.3 MiB =  12.8 MiB       nginx (5)
 23.8 MiB + 700.0 KiB =  24.5 MiB       php
180.1 MiB + 356.5 KiB = 180.5 MiB       mysqld
760.9 MiB +   9.7 MiB = 770.6 MiB       php-fpm (14)
---------------------------------
                          1.0 GiB

I am using aws ami. How can i find the bottleneck of such writing on disk. i found that the disk is busy.


text:
Q: Which is a more efficient approach to decoding escape sequences in text? I'm working on parsers that not only process delimited content, but also escape sequences within certain portions of that content. I'm contemplating the efficiency of several approaches to tokenization and would appreciate thoughts on the following.
To use JSON as but one example, there's a few ways to process the following:
["Foo\n"]

Consider that the input stream might be multi-megabyte with lots of varied escaped/un-escaped sequences
Approaches:
By Character
The first option is simply to tokenize by character:
[array string #"F" #"o" #"o" #"^/" /string /array]

Pro: uniform, quick to implement, works well with streamed content
Con: not at all efficient as you are invoking the token handler for near as many tokens as there are characters in the input stream.
By Escaped/Un-Escaped Tokens
A somewhat more efficient tokenizer might result in:
[array string "Foo" "^/" /string /array]

Pro: Somewhat more efficient, quick to implement
Con: There's still a lot of tokens for heavily escaped content, can't imply that two tokens represent one or two items
By Whole Tokens
A minimal tokenizer might produce the following:
[array "Foo^/" /array]

Pro: Far fewer tokens to handle
Con: This raises many questions, chief amongst them—how is the string "Foo^/" created? To break this down, will consider two sub-approaches:
Match the sequence, then resolve escapes:
This might be handled thus:
[
      "[" (emit 'array)
    | "]" (emit /array)
    | {"} copy value string-sequence {"} (emit de-escape value)
]

Pros: Quickly identify matches, use and modify a single string
Cons: This is effectively a two-pass process—there may be two separate rules to match escape sequences: one in string-sequence and one in de-escape—there's the extra effort in ensuring they are consistent
Match portions of the string and append to a buffer:
This might look like:
[
      "[" (emit 'array)
    | "]" (emit /array)
    | {"} (buffer: make string! "") some [
          copy part unescaped-sequence (append buffer part)
        | "\n" (append buffer "^/")
    ] {"} (emit buffer)
]

Pros: One pass
Cons: Now we're back to handling chunks similar to the 'Handling escaped/un-escaped sequence' method and managing an additional value buffer.

A: Most parsers decode string escapes during tokenization. Note that the tokenizer needs to be aware of escapes anyway to determine the end of a string, since the string delimiter " itself may be escaped. That means it is not fundamentally more complicated to also decode it in one pass.
It is not worse to first recognize the string literal and then process escapes. In low-level languages (like C) a two-phase approach would allow you to know the exact size of the decode string before you process escapes. This is not a good argument in your case. It may still be a good idea if this approach is simpler, but your de-escape function will amount to something like the single-pass tokenizer anyway.
A tokenizer should produce one token per literal because that makes it much easier to handle for consumers of the token stream. In particular, a string literal split into multiple tokens would be concatenated into a single string anyway at some point, so we ought to do that right away.
A notable scenario where that is not the case is in complicated languages with string "literals" that allow interpolation – tokenizing those elegantly is challenging, and would likely lead to something like your "tokenize by escaped/unescaped tokens" suggestion. As another example, the XML document model may contain multiple consecutive text nodes. XML entities are tricky because a tokenizer will have to parse the DTD before entities can be expanded, and because eagerly expanding entities opens the program to a denial-of-service attack.
TL;DR: Prefer your By Whole Tokens approach, ideally implemented via your  Match portions of the string and append to a buffer idea.


text:
Q: Replace strings via regexp by groups in Javascript I would like to replace many terms using regexp with a single call, is it possible? In the example below I want to replace all spaces and ö chars to _ and - respectively.

Pattern: ( +)|(ö+)
Source string: Abc dfö/ab.ai dois ö
Replace pattern: $1_$2-
Current result: Abc _-df_ö-/ab.ai _-dois _-_ö-
Expected result: Abc_df-/ab.ai_dois_-

Thanks.

A: Use a callback function to check which group "worked" and replace accordingly:

var re = /( +)|(ö+)/g;
var str = 'Abc dfö/ab.ai dois ö';
var result = str.replace(re, function (m, g1, g2) {
    return g1 ? "_" : "-";
});
document.getElementById("r").innerHTML = result;
<div id="r"/>

The second argument in .replace() accepts a function.

A function to be invoked to create the new substring (to put in place of the substring received from parameter #1).

See more details on the callback  function parameters in the Specifying a function as a parameter section.
UPDATE
You may map the symbols (since you are searching for single symbols) to the replacement symbols, and specify them all in 1 regex. Then, in the callback function, you can get the necessary value using the first character from the matched text.

var rx = / +|ö+|ë+|ü+/g;
str = "Abc dfö/ab.ai dois ööö üüü";
console.log(str);
map = {
    " ": "_",
    "ö": "-",
    "ü": "+",
    "ë": "^"
};
result = str.replace(rx, function (match) {
    return map[match[0]]; }
);
console.log(result);
// Abc dfö/ab.ai dois ööö üüü => Abc_df-/ab.ai_dois_-_+


text:
Q: Could the allocation unit size on my backup drive cause it to run of space when used to backup my main drive? I'm using two hard drives for conducting monthly backup for certain data in my PC.
However, I found out the folder the backup data inside my second hard drive has larger size on disk compare to the data in my first hard drive. This causes my second hard drive rapidly running out of space.
I did some research, and it could be the different file system in both of the hard drives might be causing this?
Can anyone verify if I change the second hard drive's file system and allocation unit to match my first hard drive will it resolve the high size on disk issue?
First HDD

*

*File System: NFTS

*Allocation Unit: 4096 B

Second HDD

*

*File System: ExFAT

*Allocation Unit: 128 KB

Example of size on disk gap

A: Unless it's a pretty large volume and you're running into limitations with exFAT there shouldn't really be any reason to go for 128 kB allocation units.
With your current setup 1 kB file on your primary system is going to take about 4 kB at a minimum and on you backup disk 128 kB. If you do deal with a lot of smaller files this would explain the significant overhead.
Bringing them inline should reduce the on disk usage. In addition you might want to think about your chosen filesystem. Unless you have a particular need for it there shouldn't be a reason to use exFAT on your backup disk. Even most modern Linux distributions can at least read NTFS.
By design exFAT is more vulnerable to corruption than NTFS or other filesystems that offer journaling and e.g. redundancy of especially important information that's needed to use the system. As such using exFAT for your backup drive might not be the best idea.

A: Just look at the image you provided.
On the right it says 41.9gb of space and right below that it says 41.9gb of files is using 65.2gb of hard drive.
The drive on the left is only using 42.4gb for the same files.
Therefore you are wasting 22.8gb of hard drive.
While an extra 22gb is a moderate amount even if you have a 128gb hard drive you should still have a lot of space.
So unless your using a 64gb hard drive or smaller I would not classify 22gb as "filling up your hard drive"
In short, by changing to a 4kb allocation unit you will get 22gb back.  So if your expecting to gain 100gb in free space your out of luck, but if your expect 22gb back then your correct.


text:
Q: How can I programmatically render fullscreen openGL at a specific resolution? I am working on a OSX/Cocoa graphics application which (for performance reasons) I would like to render at 640x480 when the user selects "full screen" mode. For what it's worth, the content is a custom NSView which draws using openGL.
I understand that rather than actually change the user's resolution, it's preferable to change the backbuffer (as explained on another SO question here: Programmatically change resolution OS X).
Following that advice, I end up with the following two methods (see below) to toggle between fullscreen and windowed. The trouble is that when I go fullscreen, the content does indeed render at 640x480 but is not scaled (IE it appears as if we stayed at the window's resolution and "zoomed" into a 640x480 corner of the render).
I'm probably missing something obvious here - I suppose I could translate the render according to the actual screen resolution to "center" it, but that seems overcomplicated?
- (void)goFullscreen{

  // Bounce if we're already fullscreen
  if(_isFullscreen){return;}

  // Save original size and position
  NSRect frame = [self.window.contentView frame];
  original_size = frame.size;
  original_position = frame.origin;

  NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:NO],NSFullScreenModeAllScreens,
                         nil];

  // In lieu of changing resolution, we set the backbuffer to 640x480
  GLint dim[2] = {640, 480};
  CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSurfaceBackingSize, dim);
  CGLEnable ([[self openGLContext] CGLContextObj], kCGLCESurfaceBackingSize);

  // Go fullscreen!
  [self enterFullScreenMode:[NSScreen mainScreen] withOptions:options];
  _isFullscreen=true;

}

- (void)goWindowed{

  // Bounce if we're already windowed
  if(!_isFullscreen){return;}

  // Reset backbuffer
  GLint dim[2] = {original_size.width, original_size.height};
  CGLSetParameter([[self openGLContext] CGLContextObj], kCGLCPSurfaceBackingSize, dim);
  CGLEnable ([[self openGLContext] CGLContextObj], kCGLCESurfaceBackingSize);

  // Go windowed!
  [self exitFullScreenModeWithOptions:nil];
  [self.window makeFirstResponder:self];
  _isFullscreen=false;

}

Update
Here's now to do something similar to datenwolf's suggestion below, but not using openGL (useful for non-gl content).
// Render into a specific size
renderDimensions = NSMakeSize(640, 480);
NSImage *drawIntoImage = [[NSImage alloc] initWithSize:renderDimensions];
[drawIntoImage lockFocus];
[self drawViewOfSize:renderDimensions];
[drawIntoImage unlockFocus];
[self syphonSendImage:drawIntoImage];

// Resize to fit preview area and draw
NSSize newSize = NSMakeSize(self.frame.size.width, self.frame.size.height);
[drawIntoImage setSize: newSize];
[[NSColor blackColor] set];

[self lockFocus];
[NSBezierPath fillRect:self.frame];
[drawIntoImage drawAtPoint:NSZeroPoint fromRect:self.frame operation:NSCompositeCopy fraction:1];
[self unlockFocus];

A: Use a FBO with a texture of the desired target resolution attached and render to that FBO/texture in said resolution. Then switch to the main framebuffer and draw a full screen quad using the texture rendered to just before. Use whatever magnification filter you like best. If you want to bring out the big guns you could implement a Lancosz / sinc interpolator in the fragment shader to upscaling the intermediary texture.


text:
Q: Custom UITableCell has nil outlets I have a Table view that I need to use a custom cell with a label and text field. I've designed the cell in the storyboard. I've set the custom cell's class to ItemRowCell and I've given it a reuse identifier of itemRowCell. I've connected the label and text field to the appropriate outlets in ItemRowCell.
This is the code for my ItemRowCell class
class ItemRowCell: UITableViewCell {
@IBOutlet weak var itemDescription: UILabel!
@IBOutlet weak var quantity: UITextField!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

In my data source I have this code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "itemRowCell", for: indexPath) as! ItemRowCell
    let (description, quantity) = self.currentItems[indexPath.row]

    cell.itemDescription.text = description
    cell.quantity.text = String(quantity)

    return cell
}

Unfortunately, both outlets in the cell are nil.

A: Disconnecting and reconnecting the outlets fixed the issue.


text:
Q: how to combine scen2d and OrthogonalTiledMapRenderer using libgdx What i'am doing is showing a tiledmap on the full screen , and it works fine.
The character moves perfectly and the camera too.
What i want is :
Showing some text or imageButton over the map  like a menu button on the left of the screen.
I tried to use a stage from scene2d library and i was able to draw what i want over the screen , the problem is that my player Sprite is hideen.
My code look as follows:
public class MapScreen implements Screen {

    private TiledMap initialMap;
    private static OrthogonalTiledMapRenderer orthogonalTiledMapRenderer;
    private OrthographicCamera camera;
    //player with x and y coordinates
    private Player player;

        public MapScreen() {
        //my player
        player = new player();
        //the map
        initialMap = getinitialMap();
        //i ask the orthogonalTiledMapRenderer to render my map
        orthogonalTiledMapRenderer = new OrthogonalTiledMapRenderer(currentmap);
        //I create the camera and i make the player in the middle of the screen
        camera = new OrthographicCamera();
        camera.position.set(w / 2, h / 2, 0);
        camera.translate(player.getPosition().x * 32, player.getPosition().y * 32);
        camera.translate(-16 * 32, -8 * 32);
        camera.update();
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        orthogonalTiledMapRenderer.getSpriteBatch().begin();
        orthogonalTiledMapRenderer.setView(camera);
        MapLayers mapLayers = initialMap.getLayers();
        //I render all the layer with the orthogonalTiledMapRenderer
        for (int i = 0; i < mapLayers.getCount(); i++) {
            orthogonalTiledMapRenderer
                    .renderTileLayer((TiledMapTileLayer) mapLayers.get(i));
        }
        //handling event
        handleEvent();
        //i update the player position
        player.move();
        //renderig the player sprite
        player.render(orthogonalTiledMapRenderer.getSpriteBatch());
       orthogonalTiledMapRenderer.getSpriteBatch().end();

    }

}

**my player Sprite becomes invisible **

A: Try to move

stage.draw();

before you begin sprite batch.
Or maybe after, but then your player will have less z-index then stage elements.


text:
Q: "label" for process to be able to kill it by "label" I need to run more player programs at once (in linux), but I want to kill it by subprocess separately. So I am thinking about something like adding "label" for each player process when I start it, e.g. player "1", player "2", player "3", player "3", player "3" and then I would like to call subprocess to kill all instances of player "3".
How to do this?

A: If all your labels are unique you can simply save the popen instances in a dictionary with the label as the key.
import subprocess
process_dict = {}

def startNewProcess(command, label):
    p = subprocess.Popen(command, shell=True)
    process_dict[label] = p

def killProcess(label):
    if label in m_process_dict:
        p = process_dict.pop(label)
        p.terminate()

If the process labels will not be unique, or if you want to have multiple labels per process, it may be better to use a list and save both the process and your labels.
import subprocess
process_list = {}

def startNewProcess(command, labels):
    p = subprocess.Popen(command, shell=True)
    process_list.append({'process':p, 'labels':labels})

def killProcess(label):
    for ii, entry in enumerate(process_list):
        if label in entry['labels']:
             entry['process'].terminate()
             process_list.remove(ii)


text:
Q: How to detect collision with more than 2 objects in Swift/SpriteKit So I am creating an air hockey game and there are 5 major SKSpriteNodes. I need to detect collision between the puck and goal1 and goal2. When it does detect collision it needs to add 1 to the scoreLeft or scoreRight which are SKLabelNode's. I have used the Gamescene.sks file to make the visual representation. I commented the didBeginContact because thats where it doesn't work. Thank You in advance.
class GameScene: SKScene, SKPhysicsContactDelegate {

let paddle1CategoryName = "paddle1"
let paddle2CategoryName = "paddle2"
let puckCategoryName = "puck"
let goal1CategoryName = "goal1"
let goal2CategoryName = "goal2"
let scoreLeftCategoryName = "scoreLeft"
let scoreRightCategoryName = "scoreRight"
var isFingerOnPaddle1 = false
var isFingerOnPaddle2 = false

var paddle1Category: UInt32 = 0x1 << 0
var paddle2Category: UInt32 = 0x1 << 1
var puckCategory: UInt32 = 0x1 << 2
var goal1Category: UInt32 = 0x1 << 3
var goal2Category: UInt32 = 0x1 << 4

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    let paddle1 = childNodeWithName(paddle1CategoryName) as! SKSpriteNode
    let paddle2 = childNodeWithName(paddle2CategoryName) as! SKSpriteNode
    let puck = childNodeWithName(puckCategoryName) as! SKSpriteNode
    let goal1 = childNodeWithName(goal1CategoryName) as! SKSpriteNode
    let goal2 = childNodeWithName(goal2CategoryName) as! SKSpriteNode
    let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
    let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
   /* Called when a touch begins */
    var touch = touches.first! as UITouch
    var location = touch.locationInNode(self)
    if let body = physicsWorld.bodyAtPoint(location){
        if body.node!.name == paddle1CategoryName {
            print("The game has begun.")
            isFingerOnPaddle1 = true
        } else if body.node!.name == paddle2CategoryName{
            print("The game has begun.")
            isFingerOnPaddle2 = true
        }
    }
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    let paddle1 = childNodeWithName(paddle1CategoryName) as! SKSpriteNode
    let paddle2 = childNodeWithName(paddle2CategoryName) as! SKSpriteNode
    let puck = childNodeWithName(puckCategoryName) as! SKSpriteNode
    let goal1 = childNodeWithName(goal1CategoryName) as! SKSpriteNode
    let goal2 = childNodeWithName(goal2CategoryName) as! SKSpriteNode
    var touch = touches.first! as UITouch
    var touchLocation = touch.locationInNode(self)
    var previousLocation = touch.previousLocationInNode(self)

    if isFingerOnPaddle1{

    let paddle1X = paddle1.position.x + (touchLocation.x - previousLocation.x)
    let paddle1Y = paddle1.position.y + (touchLocation.y - previousLocation.y)
    if (touchLocation.x <= paddle1.position.x && (touchLocation.y <= paddle1.position.y || touchLocation.y >= paddle1.position.y)){
    paddle1.position = CGPoint(x: paddle1X, y: paddle1Y)
    }
    }
    if isFingerOnPaddle2{
    let paddle2X = paddle2.position.x + (touchLocation.x - previousLocation.x)
    let paddle2Y = paddle2.position.y + (touchLocation.y - previousLocation.y)

    if (touchLocation.x >= paddle2X && (touchLocation.y >= paddle2Y || touchLocation.y < paddle2.position.y)){
        paddle2.position = CGPoint(x: paddle2X, y: paddle2Y)
    }
    }

}
/*
func didBeginContact(contact: SKPhysicsContact) {
    let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
    let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode
    var score = 0
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask{
    case puckCategory | goal1Category:
        if contact.bodyA.categoryBitMask == puckCategory{
            puckCategory = contact.bodyA.categoryBitMask
            goal1Category = contact.bodyB.categoryBitMask
            score++
            scoreRight.text = "\(score)"
        }else{
            puckCategory = contact.bodyB.categoryBitMask
            goal1Category = contact.bodyA.categoryBitMask
            score++
            scoreRight.text = "\(score)"
        }
    case puckCategory | goal2Category:
        if contact.bodyA.categoryBitMask == puckCategory{
            puckCategory = contact.bodyA.categoryBitMask
            goal2Category = contact.bodyB.categoryBitMask
            score++
            scoreLeft.text = "\(score)"
        }else{
            puckCategory = contact.bodyB.categoryBitMask
            goal2Category = contact.bodyA.categoryBitMask
            score++
            scoreLeft.text = "\(score)"
        }
    default:

        // Nobody expects this, so satisfy the compiler and catch
        // ourselves if we do something we didn't plan to
        fatalError("other collision: \(contactMask)")

    }
}*/
override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
}

}

A: One issue is using a local var score = 0 at the beginning of your function. Remove it. The score should be stored in the game's model so that logic about winning can be applied but matching your code, at least do this.
if let score = Int(scoreLeft.text) {
  scoreLeft.text = "\(score + 1)"
}

Additionally there is a problem with
  case puckCategory | goal1Category:
        if contact.bodyA.categoryBitMask == puckCategory{
            puckCategory = contact.bodyA.categoryBitMask

What you are saying is if contact.bodyA.categoryBitMask is equal to puckCategory, then set puckCategory to contact.bodyA.categoryBitMask. That is a no-op, nothing changes AND more importantly you don't want to change the bit masks that your child nodes are compared against.  Make puckCategory, goal1Categoy, and goal2Category constants. Good luck.
Follow Up To OP Comment:
So, throw away the code in didBeginContact that set the category mask variables for two reasons. 1) Setting variables like puckCatergory to their same value is wasteful and confusing. 2) Since variables like puckCategory are compared to child node bit masks, it would be disasterous if they ever did change.  That function should look like this.  Also be sure and add handlers for the other types of contacts before you get too far.
func didBeginContact(contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch contactMask {
    case puckCategory | goal1Category:
       let scoreRight = childNodeWithName(scoreRightCategoryName) as! SKLabelNode
       if let score = Int(scoreRight.text) {
          scoreRight.text = "\(score + 1)"
       }
    case puckCategory | goal2Category:
       let scoreLeft = childNodeWithName(scoreLeftCategoryName) as! SKLabelNode
       if let score = Int(scoreLeft.text) {
          scoreLeft.text = "\(score + 1)"
       }
    default:
        // There are other contacts that need to be handled; paddle+puck,puck+wall, etc
        fatalError("other collision: \(contactMask)")
    }
}


text:
Q: ColorBox - auto pop-up (how to?) Is there anyway to make ColorBox (jquery popup script) actually 'pop-up' automatically, and if so, what part do i edit for that?
I need it popped up after about 3 seconds on home page.
thanks!

A: Set the open parameter to true. (It defaults to false); if want a delay you'll have write a bit of javascript with an interval.

A: You can set open property to true.
<script type="text/javascript">
    $(document).ready(function() {
        //For url
        $.fn.colorbox({href:"example.html", open:true});

        //For link
        $("a.example").colorbox({open:true});

        //For delay
        setTimeout("$.fn.colorbox({href:'example.html', width:500, height: 300,
        open:true});", 3000);

        //For inline
        $.fn.colorbox({inline:true, width: 660, height: 405, href:"#example"});
});
</script>

Here is the documentation: jacklmoore.com/colorbox


text:
Q: Android get background color of parent view if no background color set I have a a TextView for which I have not set a background color yet. I would like go the background color, but when I do ((ColorDrawable) mTextView.getBackground()).getColor() I obviously get a null pointer exception.
How would I traverse the view hierarchy of the TextView to find the most recent background color in the hierarchy that the TextView uses as background as a result.
And how would I determine the background color if no background color has been set in the hierarchy? And how would I determine that situation? How can I tell that no background has been set?
I basically have difficulty to determine the background color of a view when it has not been set explicitly.

A: I don't know how generally applicable this is but it does the trick for me:
int getBackgroundColor(View view, int fallbackColor) {
    if (view.getBackground() instanceof ColorDrawable) {
        return ((ColorDrawable) view.getBackground()).getColor();
    } else {
        if (view.getParent() instanceof View)
            return getBackgroundColor((View) view.getParent(), fallbackColor);
        else
            return fallbackColor;
    }
}

It tries to cast the background as ColorDrawable and if that fails it tries again on its parent, recursively. If the parent is not a View, the specified fallback color is returned.
Now for some Kotlin poetry:
tailrec fun View.getBackgroundColor(): Int? =
    (background as? ColorDrawable)?.color
        ?: (parent as? View)?.getBackgroundColor()

A: Traverse in hierarchy depends upon what controls you have used.
now, to get color of layout, this can only be accomplished in API 11+ if your background is a solid color.
            int color = Color.TRANSPARENT;
            Drawable background = view.getBackground();
            if (background instanceof ColorDrawable)
            color = ((ColorDrawable) background).getColor();

once you get colorcode you can do operations based on that.


text:
Q: A basic question on conditional expectation and variance How calculate variance of $X$ from the following statements :
$$ E[X\mid Y=1] = 2 + E[X]$$
$$ E[X\mid Y=2] = 3 + E[X]$$
$$ E[X\mid Y=3] =0$$
$$ P(Y=1)=0.5, P(Y=2)=0.3 ~~\text{and}~~ P(Y=3) =0.2 $$

A: I think you need to give more information. You can easily find
$$
  \mathbb{E}[X]
= \mathbb{E}[\mathbb{E}[X\mid Y]]
= 0.5(2 + \mathbb{E}[X]) + 0.3(3 + \mathbb{E}[X])
= \frac{19}{10} + \frac{4}{5}\mathbb{E}[X]
$$
so that $\mathbb{E}[X] = \frac{19}{2}$, but to find the variance you will need to know
$\mathbb{E}[X^2]$ or at least $\mathbb{E}[X^2\mid Y]$. Otherwise, there may be two different random variables with the properties you list yet having different variances. For example, the condition you gave is the same as
$$
  \mathbb{E}[X \mid Y ]
= -2Y^2 + 7Y - 3 + \frac{19}{2} \chi\{ Y \neq 3 \},
$$
so let
$$
  X_1
= -2Y^2 + 7Y - 3 + \frac{19}{2} \chi\{ Y \neq 3\}
$$
and let
$$
  X_2
= -2 N(Y^2,10) + 7U(0,2Y) - 3 + \frac{19}{2}\chi\{ Y \neq 3\},
$$
where $N(Y^2,10)$ is a normal random variable with mean $Y^2$ and variance $10$, and $U(0,2Y)$ is a uniform random variable on the interval $(0,2Y)$.
Both satisfy the given conditions, yet obviously have different variances.


text:
Q: PostGIS: Merge Multipolygons and keeping boundaries We are trying to merge two Multipolygons which are stored in our PostGIS 2.1 database without losing the boundaries that are contained in each Multipolygon.
Our spatial data matches the following criteria.
-- Check whether the polygons share points (boundaries?)
-- ST_Intersects:
-- Returns TRUE if the Geometries/Geography "spatially intersect in 2D" - (share any portion of space)
-- and FALSE if they don't (they are Disjoint).
ST_Intersects(higher_geom,lower_geom) = TRUE

-- ST_Crosses:
-- Returns TRUE if the supplied geometries have some, but not all, interior points in common.
ST_Crosses(higher_geom,lower_geom) = FALSE

-- Since ST_Crosses would return FALSE if the polygons have all interior points in common
-- we have to ensure this is not the case
ST_Within(higher_geom,lower_geom) = FALSE

If we then try to aggregate the columns lower_geom and higher_geom (both of type MultiPolygon) with the following query, the result of ST_Union is lacking the borders of the original polygons.
SELECT
    ST_Union(lower_geom, higher_geom)
FROM
    myTable

To make it more clear, we have added a screenshot. In our desired result, both, the green and the red multipolygons should be contained in ONE new multipolygons still containing ALL boundaries.

Does anyone have an idea!?
Thanks in advance,
Cord & Martin

A: This works for me for a few test polygons I threw together. It uses an ST_Dump trick to unmerge the geometry collection that otherwise results from the inner query, aliased as table c, and then recollects the geometries using ST_Multi(ST_Collect(geom...). The inner query combines the intersection of the two sets of geometries with the difference of the intersection and the union.
select ST_multi(ST_Collect(d.geom))
  from (select (ST_Dump(c.geom)).geom
    from (select ST_Collect(ST_Intersection(a.geom, b.geom),
            ST_SymDifference(ST_Intersection(a.geom, b.geom),
            ST_Union(a.geom, b.geom))) as geom
        from lower_geom a, higher_geom b)
   as c)
 as d;

There will be a more elegant and efficient way to write this, but I would like to know if this works with your data, before trying.


text:
Q: make it easier to call often used terminal commands I have a java tool that I use quite often from the command line but to use it I have to type java -jar dsim.jar. I want to make it so that I can call it just by typing dsim regardless of what directory I am in, but I can't quite work out how to accomplish this.
I have created a file at ~/.bash_profile and put into it:
alias dsim='java -jar dsim.jar'

And I have placed the dsim.jar file into /usr/local/bin as I read this is where user created command line tools should be kept. This location is in my $PATH.
I think the alias works well but location of the file doesn't seem to be accessible from anywhere. If I call dsim from within /usr/local/bin it works fine but if I am in any other directory I get:
Error: Unable to access jar file dsim.jar

How can I get this to work from any directory?

A: Use absolute paths for the jar file:
alias dsim='java -jar /path/to/dsim.jar'

A: This is not a direct answer, but you can consider the following solution as an useful one for often repeated commands:

Create ~/.inputrc and fill it with this:
"\e[A": history-search-backward
"\e[B": history-search-forward
set show-all-if-ambiguous on
set completion-ignore-case on

This allows you to search through your history using the up and down arrows … i.e. type "cd /" and press the up arrow and you'll search through everything in your history that starts with "cd /".

(via https://coderwall.com/p/oqtj8w)


text:
Q: Where did this switchmap's argument come from? I'm currently following Jogesh Muppala's Angular course on Coursera, and the issue is with the following line of code.
   this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id'])))

The rest of the code is below. My understanding so far is that this.route.params is an Observable, and that this.dishService.getDish(+params[id]) will also return an Observable. My issue is understanding how the (params: Params) got there. It's used as the parameters in the arrow function, and that gets used by the getDish function near the end of the statement. However,  at the start of the line we could only access params via this.route.params. Is it a different params? The type declaration params: Params makes it look like it's a completely new instance of a Params type. But if so, how could it be used by getDish?
import { Component, OnInit} from '@angular/core';
import {Params, ActivatedRoute} from '@angular/router';
import {Location} from '@angular/common';
import{ Dish} from '../shared/dish';
import { DishService} from '../services/dish.service';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-dishdetail',
  templateUrl: './dishdetail.component.html',
  styleUrls: ['./dishdetail.component.scss']
})
export class DishdetailComponent implements OnInit {

  dish: Dish;
  dishIds: number[];
  prev: number;
  next: number;

  constructor(private dishService: DishService, private route: ActivatedRoute,
    private location: Location) {

  }

  ngOnInit() {
    this.dishService.getDishIds().subscribe(dishIds => this.dishIds = dishIds);
    this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id'])))
    .subscribe(dish => { this.dish = dish; this.setPrevNext(dish.id); });
  }

  setPrevNext(dishId: number) {
    const index = this.dishIds.indexOf(dishId);
    this.prev = this.dishIds[(this.dishIds.length + index - 1) % this.dishIds.length];
    this.next = this.dishIds[(this.dishIds.length + index + 1) % this.dishIds.length];
  }

  goBack(): void{
      this.location.back();
  }

}

Thank you for reading.

A: The (params: Params) is from the router.params and it's the rxjs 6 way of doing observable operator chaining.
In essence what is really going on is .pipe takes a list of functions and each function through the list gets the value of the previous one except if it's preceded by a tap or filter etc...
So
this.route.params.pipe(switchMap((params: Params) => this.dishService.getDish(+params['id'])))

Before was written like
this.route.params.switchMap((params: Params) => this.dishService.getDish(+params['id']))

So it would get the value from route.params pass it into the switchMap operator which would return a new Observable of the the result from the function which you passed into it.

A: It is a bit like this:
const bmw = {
  type: car,
  attributes: {
    color: 'red',
    year: 2000
  }
}

const attributes = bmw.attributes;

We happen to name two different things with the same name attributes: one is a variable and the other is a property in an object. They are not related except by the unfortunate coincidence of sharing the same name.
In your case, in this.route.params, params is a property in this.route which returns an Observable.
(params: Params) => this.dishService... is an anonymous function which would be the same as writing (function anon(params: Params) { this.dishService... }).bind(this). Here, params is name given to the argument that the function receives.
The above function executes when a new value is emitted on the Observable from this.routes.params. The value that is emitted here is passed into the anonymous function as its argument, which happens to be called params. So it doesn't need a dot notation because it is not referring to the same thing: it's referring to the value that comes out of the Observable.
At the root of this though the anonymous function (the arrow function) is a function that is passed switchMap and this gets executed once for every value that is put on the source Observable (this.route.params). Each time it executes, switchMap passes in the current value in the Observable as that first argument params. SwitchMap expects this function to return to it a new Observable, which is what is returned by this.dishService.getDish.
HTH


text:
Q: Fade in and out bug with jQuery On my page, when the user gets to say 1000 pixels scrolled down the page, my navigation fades out, when i scroll back up the navigation fades in. Im using the following which works perfectly...
// Fade Navigation

if(!$('nav ul').is(':visible')) {
    $('nav ul').stop().fadeIn(500);
} else {
    $('nav ul').stop().fadeOut(500);
}

My only problem is that if you scroll really quickly, the animation doesnt know if its visible or not, is there a way to stop this?

A: If you pass in true as a second parameter to .stop(), it'll stop the animation and jump the element to the state it should be in if the animation actually finished.
i.e. if you call $('nav ul').stop(true, true).fadeIn(500) while an element is fading out, it will stop the fade out, and make it jump to it's logical end (which is completely faded out) before starting the .fadeIn() animation.
Using that, you should be able to get away with the following instead of your code block above:
$('nav ul').stop(true, true).fadeToggle(500);

It'll look a little jerky though, but you can work around it with a bit more complicated logic.

A: I've been playing around with this.  See comments in code.

One

Two


text: Q: What is the use of the "domain" field in verifiable presentations? In the wc3 spec for verifiable presentation, it says that the "domain" and "challenge" fields are used to prevent replay attacks, you can read it as a comment in the second example here. But why do we need two fields to protect us against replay attacks? Isn't one enough? Do the values of those fields have any specific format or are they completely random?


text:
Q: Desktop doesn't start after upgrade to Ubuntu 20 I've a dual boot ( windows + ubuntu ) with grub2.
I had Ubuntu 16 and I upgraded it via UI ( I was informed about some crashes about packages it couldn't get, but the process continued until the very end ).
After this, windows works normally but Desktop doesn't start showing the following message:
ln: /tmp/mountroot-fail-hooks.d//scripts/init-premount/lvm2: No such file or directory
I guess that's all information I have.
Thanks in advance.
Update:
I have all terminals working ( ctrl+alt+f2-7 ), desktop does not start and I just got the line I mentioned above ( log referring to lvm2 ) and the blinking caret. If I switch between tty's like a crazy man, sometimes, when I go to the desktop one, desktop appears for a fraction of a second. My GPU is XFX RX 5500 XT Thicc II Pro.
I wanted to go from 16 to 18, and then 18 to 20, obviusly, but Ubuntu's upgrade system didn't show any option about OS version target and went straight to 20, so I guessed it would manage to get it done right.
Update 2:

I tried to unplug monitors from GPU, plug it directly to motherboard's gpu & restart pc, but doesn't work this way neither.
Grub screen use to be purple, now it's black.


text:
Q: how can sort alphabetically a text file? I'm trying to sort a text file
with text like that
word1,word2,word3
word1,word2,word3
word1,word2,word3
.
.
.
word5,word6,word3
I need to sort but this code is not working
using System;
using System.IO;

class myclass
{
    static void Main()
    {
        string infile =  File.ReadAllText(@"C:\Users\diego\Desktop\finalregex.txt");
        string outfile = File.ReadAllText(@"C:\Users\diego\Desktop\finalregex.txt");
        var contents = File.ReadAllLines(infile);
        Array.Sort(contents);
        File.WriteAllLines(outfile, contents);
    }
}

please help me

A: Assuming the format in your example, this should suffice:
// File paths.
const string inFile = "in.txt";
const string outFile = "out.txt";

// Read file.
var inContents = File.ReadAllText(inFile);

// Organize contents.
var contentsArray = inContents.Replace(Environment.NewLine, ",")
    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

// Sort contents.
var sortedContents = contentsArray.OrderBy(c => c);

// Write file.
File.WriteAllText(outFile, string.Join(",", sortedContents));


text:
Q: Derivatives of dot product Let $ A\in M_{n}$. Define $f: \mathbb{R}^{n} \rightarrow \mathbb{R}$ by $f(x) = \langle Ax,x\rangle$. Find $f'$ and $f''$.
It seems that I need to define $g(x)=Ax$, so $g'(x)=A$
$$f(x+h)-f(x)=\langle A(x+h),x+h\rangle-\langle Ax,x\rangle\\
\langle Ax,h\rangle+\langle Ah,x\rangle+\langle Ah,h\rangle.$$
The first two added up seems like $f'$.
But I still have problem to get $f''$. Why define $g$? How to get $f',f''$?

A: $$\frac{\mbox{d}}{\mbox{d}x}\langle a(x),b(x)\rangle=\langle \frac{\mbox{d}a}{\mbox{d}x},b(x)\rangle+\langle a(x),\frac{\mbox{d}b}{\mbox{d}x}\rangle$$Therefore,
$$\frac{\mbox{d}^2}{\mbox{d}x^2}\langle a(x),b(x)\rangle=\frac{\mbox{d}}{\mbox{d}x}\left(\langle \frac{\mbox{d}a}{\mbox{d}x},b(x)\rangle+\langle a(x),\frac{\mbox{d}b}{\mbox{d}x}\rangle\right)=\frac{\mbox{d}}{\mbox{d}x}\langle \frac{\mbox{d}a}{\mbox{d}x},b(x)\rangle
+\frac{\mbox{d}}{\mbox{d}x}\langle a(x),\frac{\mbox{d}b}{\mbox{d}x}\rangle\\
=\langle \frac{\mbox{d}^2}{\mbox{d}x^2}a,b(x)\rangle+\langle a,\frac{\mbox{d}^2b}{\mbox{d}x^2}\rangle+2\langle\frac{\mbox{d}a}{\mbox{d}x},\frac{\mbox{d}b}{\mbox{d}x}\rangle$$


text:
Q: React native switch between screens based on login token I am building a react native app and I am new to it. I have 3 files currently -
1) App.js
2) Login.js
3) FlightList.js
When I have not logged in, I need to show login screen. When I log in, I need to store the token and display Flights list screen.
This is my code -
App.js
import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Login from './Login';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        //Check if token is there and if there show flight list screen else login screen
      </View>
    );
  }
}

Login.js
'use strict';
import React, { Component } from 'react';
import {
  StyleSheet,
  TextInput,
  TouchableHighlight,
  AsyncStorage,
  Text,
  View
} from 'react-native';
import {
    StackNavigator,
  } from 'react-navigation';
  import FlightList from './FlightList';

  const FlightListScreen = StackNavigator({
    FlightList: { screen: FlightList }
  });

const ACCESS_TOKEN = 'access_token';

export default class Login extends Component {
  constructor(props){
    super(props);

    this.state = {
      email: "",
      password: "",
      error: ""
    }
  }

async storeToken(accessToken){
      try {
          await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
      } catch (error) {
          console.log("something went wrong");
      }
    }

  async onLoginPressed() {
    try {
      const reqOptions = {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({

            email: this.state.email,
            password: this.state.password,

        })
      };

      console.log("error of json is " + JSON.stringify(reqOptions))
      let response = await fetch('https://...login', reqOptions);

      if (response.status >= 200 && response.status < 300) {
        const body = await response.json();
          this.storeToken(body.token);
          this.props.navigation.navigate('FlightListScreen');
      } else {
          //Handle error
          let error = res;
          throw error;
      }
    } catch(error) {
        this.setState({error: error});
        console.log("error " + error);
    }
  }
  render() {

    return (
      <View style={styles.container}>
      //view here
      </View>
    );
  }
}

FlightList.js
'use strict';
import React, { Component } from 'react';
import {
  StyleSheet,
  TextInput,
  TouchableHighlight,
  AsyncStorage,
  Text,
  View
} from 'react-native';
import {
    StackNavigator,
  } from 'react-navigation';

const ACCESS_TOKEN = 'access_token';

export default class FlightList extends Component {
  constructor(props){
    super(props);
  }

async getToken() {
    try {
        let token = await AsyncStorage.getItem(ACCESS_TOKEN);
        console.log("token is" + token);
    } catch (error) {
        console.log("error while getting token");
    }
 }

 async getFlights() {
    try {
        const reqOptions = {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${getToken()}`
          },
          body: JSON.stringify({
            // no body since it is GET call

          })
        };

        let response = await fetch('https://.../flights', reqOptions);

        if (response.status >= 200 && response.status < 300) {
          const body = await response.json();
          //update the view
        } else {
            //Handle error
            let error = res;
            throw error;
        }
      } catch(error) {
          this.setState({error: error});
          console.log("error " + error);
      }
 }

 componentDidMount(){
    getFlights();
  }
}

My questions is-
1) In App.js how can  I check if token is there and if there show flight list screen else login screen
2) Also the getToken() method how can I use it globally since I need it as header for all the API calls

A: You can create two other files, the first one is a utility file contains all your necessary functions you need to define global. For example your getToken will be like this:
export default class Utility {

    static async getToken() {
        try {
            let token = await AsyncStorage.getItem(ACCESS_TOKEN);
            return token
        } catch (error) {
            console.log("error while getting token");
            return 'error
        }
    }
}

If you use static before your function, you can use that function every where you import Utility file.
and for your first question... you can make an splash screen and check the token and decide to navigate to which page. I advise you to create a file for your api requests and another file for router. you can define all routing definition in router.js and start app with it:
import React, { Component } from 'react';
import { View } from 'react-native';
import { StackNavigator, TabRouter, DrawerNavigator } from 'react-navigation';
import Splash from './../views/SplashScreen'
import Login from './../views/Login'
import Verification from './../views/Verification'
import Home from './../views/Home'
import Contents from './../views/Contents'
import ContentList from './../views/ContentList'
import MessageInbox from './../views/MessageInbox'

export default class AppRouter extends Component {

    public static Routes = StackNavigator({
    SplashScreen: { screen: Splash },
    Login: { screen: Login },
    Verification: { screen: Verification },
    Private: {
        screen: DrawerNavigator({
            Main: {
                screen: StackNavigator({
                    Home: { screen: Home },
                    Contents: { screen: Contents },
                    ContentList: { screen: ContentList },
                }, { initialRouteName: 'Home' })
            },
            MessageInbox: { screen: MessageInbox },
        }, { initialRouteName: 'Main' })
    }
}, { initialRouteName: 'SplashScreen' })

render() {
    return (
        <View></View>
    )
}

}

and index.js will be:
import React, { Component } from 'react';
import AppRouter from './../router/routes';
export default class App extends Component {
    render() {
        return (
            <AppRouter.Routes />
        )
    }
}

I hope i can help you
EDIT:
If you use AppRouter, it will be the starter of your app and the first page called by it so it has a navigation prop. If you want to navigate to each page, you can just use this.props.navigation.navigate('FlightList') . remember that if you are using a component in a page and you want to navigate from this component, you need to pass this.props.navigation as a prop to that component and then, it can change the stack navigation.
in your case, your pages will be something like this...:
Router.js
export default class AppRouter extends Component {

public static Routes = StackNavigator({
    SplashScreen: { screen: Splash },
    Login: { screen: Login },
    FlightList: { screen: FlightList},
}, { initialRouteName: 'SplashScreen' })

render() {
    return (
        <View></View>
    )
}
}

SplashScreen.js:
export default class SplashScreen extends Component {
constructor(props) {
    super(props);
    let token = Check token...
    if (token) {
        this.props.navigation.navigate('FlightList')
    } else {
        this.props.navigation.navigate('Login')
    }
}
render() {
    return (
        <View style={{ flex: 1 }}>
            <Text>Loading...</Text>
        </View>
    )
}
}

A: So I have a very similar problem. I solved it by creating a loading screen and on componentDidMount I called a function that like your getToken request fetches the token it also makes a decision once I have a value back from storage to go to the login page or my other page based on if I get a value back or not.


text:
Q: Update filtered objects in array I have an array of objects. I want to filter them and then do something to the filtered objects. This is my attempt so far.
Positions Object
    function Position (title, type, purchasable){
    this.title = title;
    this.type = type;
    this.purchasable = purchasable || false;
}
function Purchasable (prices){
    this.owner = "unowned";
    this.rating = 0;
    this.prices = prices;
    this.price = this.prices[this.rating];
}
function City (title,set,prices){
    Position.call(this, title, "city", true);
    Purchasable.call(this, prices);
    this.set = set;
}
positions = [
    new City("Cairo", "brown", [60,2,10,30,90,160,250]),
    new City("Vienna", "brown", [60,4,20,60,180,320,450]),
    new City("Vienna", "blue", [60,4,20,60,180,320,450])
    ];
});

Function
function test() {
    var set = "brown";
    positions.filter(function(obj){
        obj.set === "brown"; //do something to every brown set, eg owner = me
    });
    //I want to change the values of the objs in positions array

}

A: var set = "brown"
var filtered = positions
  .filter(function (obj)
  {
    return obj.set === "brown"
  })
  .map(function (obj)
  {
    obj.owner = me
    return obj
  })
;
console.log(filtered);

A: You need your filter callback to return true/false.  You want to return true when the current item should be included in the resulting array and false if it should be excluded.  So if you want to filter where obj.set === "brown", do:
var filtered = positions.filter(function(obj){
    if (obj.set === "brown") {
        obj.owner = "me";  // your additional action to perform
        return true;
    }
    return false;
});

As 'just somebody' notes in the comments, It is generally bad practice to make filter do anything other than the filtering part.  But this above example shows you how to do this inside of the filter per your original question.

A: What about the jQuery .each() function ?
https://api.jquery.com/each/
function test() {
    var set = "brown";
    var filtered = positions.filter(function(obj){
        obj.set === "brown"; //do something to every brown set, eg owner = me
    }).each(function(index, item){
         //do something with the object here; your objects are the item parameter

         obj.owner = "me";
    });

}


text:
Q: Invalid format for geopy distance I start in python and I see that my cities with the coordinates are not used, which makes me a format error, because it does not print the coordinates of the city.
from geopy.distance import geodesic

ville1 = input("Entrez la ville de départ : ")
ville2 = input("Entrez la ville d'arrivée : ")

Paris = (48.864716, 2.349014)
Bordeaux = (44.835241, -0.573289)
Marseille = (43.301631, 5.373301)
Lyon = (45.760346, 4.837617)
Toulouse = (43.606225, 1.459017)
Nice = (43.714026, 7.259467)
Nantes = (47.226733, -1.560644)
Montpellier = (43.606620, 3.869740)
Strasbourg = (48.561351, 7.753844)
Rennes = (48.105276, -1.688280)

print(ville1)
print(ville2)
print(geodesic(ville1, ville2).kilometers)

On console
Entrez la ville de départ : Bordeaux
Entrez la ville d'arrivée : Paris
Bordeaux
Traceback (most recent call last):
Paris
  File "D:/Documents/Ynov/Projet_Camion/calcul.py", line 11, in <module>
    print(geodesic(ville1, ville2).kilometers)
  File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\geopy\distance.py", line 389, in __init__
    super(geodesic, self).__init__(*args, **kwargs)
  File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\geopy\distance.py", line 164, in __init__
    kilometers += self.measure(a, b)
  File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\geopy\distance.py", line 410, in measure
    a, b = Point(a), Point(b)
  File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\geopy\point.py", line 156, in __new__
    return cls.from_string(arg)
  File "C:\Users\me\AppData\Roaming\Python\Python37\site-packages\geopy\point.py", line 391, in from_string
    "Failed to create Point instance from string: unknown format."
ValueError: Failed to create Point instance from string: unknown format.

A: Your inputs that define ville1 and ville2 are read as strings. Python doesn't know you want these strings to refer to the variables you've defined.
A better way is to put the locations in a dict and access them like so:
from geopy.distance import geodesic

ville1 = input("Entrez la ville de départ : ")
ville2 = input("Entrez la ville d'arrivée : ")

locations = {
    'Paris': (48.864716, 2.349014),
    'Bordeaux': (44.835241, -0.573289),
    'Marseille': (43.301631, 5.373301),
    'Lyon': (45.760346, 4.837617),
    'Toulouse': (43.606225, 1.459017),
    'Nice': (43.714026, 7.259467),
    'Nantes': (47.226733, -1.560644),
    'Montpellier': (43.606620, 3.869740),
    'Strasbourg': (48.561351, 7.753844),
    'Rennes': (48.105276, -1.688280),
}

print(ville1)
print(ville2)
print(geodesic(locations[ville1], locations[ville2]).kilometers)

An example of the above:
Entrez la ville de départ : Paris
Entrez la ville d'arrivée : Nice
Paris
Nice
685.9425720999892


text:
Q: HAProxy crashes on all requests in 1.5-dev12 I'm having an issue where HAProxy is crashing with no explanation when I switch from 1.4.12 to 1.5-dev12. The reason I'm switching is for the SSL offloading.
My config file doesn't have any errors, it's quite simple and it works well with 1.4 - but for some reason when I run it with 1.5-dev12 I see the logs noting that the two backends I have have been set up, and then when I hit one of the frontends, I get an HTTP 400 in the browser and suddenly HAProxy isn't running anymore when I check.
I understand that a common workaround to the lack of SSL support for HAProxy is to use Stud, and I may go with that since I am in need of an SSL solution for my service, but before I dele into that world I thought I might see if anybody has experienced the same problems and might know how to fix it.
The server is Ubuntu 10.04 and I followed the make instructions on the Exceliance blog here.
EDIT: On the advice of Kyle Brandt, I did a bit more investigation. I attached gdb to the haproxy process and when the crash occurred this is what I got:
Program received signal SIGSEGV, Segmentation fault.
0x0804e5c2 in dequeue_all_listeners (list=0x9e1a418) at src/protocols.c:184
184     list_for_each_entry_safe(listener, l_back, list, wait_queue) {

P.S. HAProxy is awesome, so thank you Exceliance for providing us with something so useful :)

A: sorry I did not see your post.
We fixed a segfault this week related to the change in connection management. However it
was not as easy to get as yours and given your gdb output I'm not sure it's the same one.
Could you please try with the latest snapshot from this night and see if you can reproduce
it ? If so I'm interested in getting the core and the config file off-list.
Thanks to you and Kyle for his endless help on the subject :-)


text:
Q: Drag and drop within PyQt5 TreeView? I'm trying to implement a file directory using PyQt5. I'd like to incorporate drag and drop functionality within this tree to support both internal and external files (i.e. if I had some files on my desktop I'd like to be able to drop them into a folder in my PyQt view). This is what I have currently:
from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication,
QMenu, QAbstractItemView
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from src import config

class Tree(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)
        cfg = config.get()

        model = QFileSystemModel()
        model.setRootPath("/Users/")

        self.setModel(model)
        self.setRootIndex(model.index("/Users/"))
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.open_menu)

        self.setSelectionMode(self.SingleSelection)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)

    def open_menu(self):
        menu = QMenu()
        menu.addAction("Create new folder")
        menu.exec_(QCursor.pos())
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    w = Main()
    w.show()
    sys.exit(app.exec_())

With the above code I can show a directory and its contents. I can drag an item but dropping it does nothing and no drop indication is seen. It's unclear how to
a. get drag and drop working within the view and
b. get it working with items outside of that context (like from the desktop for example).

A: According to the docs:

readOnly : bool
This property holds whether the directory model allows writing to the file system
If this property is set to false, the directory model will allow
renaming, copying and deleting of files and directories.
This property is true by default

so if you want to be able to move files you must set it to False:
model.setReadOnly(False)

You must overwrite the dragEnterEvent method and if there is a QUrl relative to a local resource you must accept it.
Then you have to overwrite the dropEvent method and if the event does not have source then it implies that it comes from an external source as a local file, then a logic is implemented to move files or directories checking if the file or directory exists or not creating the new one path.
class Tree(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)
        model = QFileSystemModel()
        model.setRootPath(QDir.currentPath())

        self.setModel(model)
        self.setRootIndex(model.index(QDir.currentPath()))
        model.setReadOnly(False)

        self.setSelectionMode(self.SingleSelection)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)

    def dragEnterEvent(self, event):
        m = event.mimeData()
        if m.hasUrls():
            for url in m.urls():
                if url.isLocalFile():
                    event.accept()
                    return
        event.ignore()

    def dropEvent(self, event):
        if event.source():
            QTreeView.dropEvent(self, event)
        else:
            ix = self.indexAt(event.pos())
            if not self.model().isDir(ix):
                ix = ix.parent()
            pathDir = self.model().filePath(ix)
            m = event.mimeData()
            if m.hasUrls():
                urlLocals = [url for url in m.urls() if url.isLocalFile()]
                accepted = False
                for urlLocal in urlLocals:
                    path = urlLocal.toLocalFile()
                    info = QFileInfo(path)
                    n_path = QDir(pathDir).filePath(info.fileName())
                    o_path = info.absoluteFilePath()
                    if n_path == o_path:
                        continue
                    if info.isDir():
                        QDir().rename(o_path, n_path)
                    else:
                        qfile = QFile(o_path)
                        if QFile(n_path).exists():
                            n_path += "(copy)"
                        qfile.rename(n_path)
                    accepted = True
                if accepted:
                    event.acceptProposedAction()

A: In your tree view subclass you must implement dragEnterEvent dragMoveEvent and dropEvent.
class Tree(QTreeView):
    def __init__(self):
        QTreeView.__init__(self)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            # to get a list of files:
            drop_list = []
            for url in event.mimeData().urls():
                drop_list.append(str(url.toLocalFile()))
            # handle the list here
        else:
            event.ignore()


text:
Q: Symfony3 - MISD Phone Number Bundle format Is it possible to set the format returned by the entity containing a phone number property when using MISD Phone-Number-Bundle? For example I have a property $phoneNumber
When I call $this->getPhoneNumber() it returns the string formatted:
Country Code: 1 National Number: ########## Country Code Source:
but I want it in the format (or similar):
1 (###) ###-####
The reason I want to change this is because in that entity I am implementing the __toString() method and want the string returned to be a combination of 2 properties one being the "nickName" and other being the phone number in this type of format or similar NickName - 1 (###) ###-#### The purpose of this is to display them in a drop down form element setup in a form type I created.

A: Phone number is instance of libphonenumber\PhoneNumber. This class has __toString method, which returns not formated debug information about object's properties

*

*https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumber.php
I have formated phone number with temlate option with SonataAdminBundle:
$listMapper
    ->add('phoneNumber', PhoneNumberType::class, [
        'template' => ':CRUD:phoneNumber_list_field.html.twig'
    ]);

Template :CRUD:phoneNumber_list_field.html.twig contents:
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}

{% block field %}
    {% if object.phoneNumber is null %}
        -
    {% else %}
        {{ object.phoneNumber|phone_number_format(2) }}
    {% endif %}
{% endblock %}

Here argument 2 for twig filter is \libphonenumber\PhoneNumberFormat::NATIONAL

*

*https://github.com/giggsey/libphonenumber-for-php/blob/master/src/PhoneNumberFormat.php

A: I think I solved my own problem... My __toString() method looks like this and seems to do what I want.
use libphonenumber\PhoneNumberUtil;
//...
public function __toString()
{
    $phoneNumberUtil = PhoneNumberUtil::getInstance();
    $number = $phoneNumberUtil->format($this->phoneNumber, \libphonenumber\PhoneNumberFormat::NATIONAL);

    return $this->nickName . " - " . $number;
}

Anyone see any issues or better ways to do this?


text:
Q: Id handling / inserting in multiple tables. (basic forum) So I started to write a forum, because I want to learn a little SQL (MySQL).
So firstly, I have a posts table, and there are a post_id and topic_id columns.
But, on the other side I have a topics table.
In the topics table I also have a last_post_id and topic_id, too !
So they are referencing to each other.
So the question is: When a user creates a topic (and the same time writes the first post), how to INSERT these id's effectively??
Because now I have to do the following steps:

*

*Insert topic related data (topic title..etc, insert last_post_id =0 cause I dont know this value here), then retrieve topic_id

*Insert post data (text, username.., topic_id), and retieve this particular post_id

*Update topics table, with the retrieved post_id (set last_post_id).

Isn't it too long, tedious, uneffective..?
Thanks for your time. My english is not the best.. sry.

A: You could do it using a single transaction, but the basic idea is the same. You need to insert the new topic before having topic_id, and you need to insert the new post before having last_post_id. With your current tables, there's no way around that.
You could also use a TRIGGER that automatically updates the last_post_id field when a new record is added to posts. That doesn't change the number of queries executed, but it would be handled transparently by MySQL itself.
Also, the point raised by mu is too short in his answer about setting last_post_id to NULL is a good idea.

A: last_post_id is meaningless, and just extra work. Instead you should grab the last post for a specific topic dynamically, whenever you need it. There's no reason to store it in the database.
About the topic / post, the normal procedure is to create the topic if it doesn't exist, grab the created id, and insert a new post with that topic Id, just like you said.


text:
Q: Spring Custom Properties File Under Subfolder Read in The Application Start Hi I have a custom properties file.And I have a aspect and it has condition.If my.properties under resource directly PropertySourcesPropertyResolver read myproperties and find it in applicationstart process.How can I force my properties file under subfolder read by propertysourcespropertyresolver
 [restartedMain] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Found key 'myenable' in PropertySource 'configurationProperties' with value of type String

But When I add subfolder in resource like Resource/myfolder/my.properties that time PropertySourcesPropertyResolver cannot resolve it at the beginning
@Configuration
    @PropertySource("classpath:/myfolder/my.properties")
    public class MyConfigProperties

 private String myenable;

....

@Service
@ConditionalOnExpression("'${myenable}'=='true'")
public class MyAspect

A: @PropertySource will work only if you put this annotation on a configuration class(annotated with @Configuration or any other annotation extending @Configuration like @SpringBootApplication, @SpringBootConfiguration etc.).
In your case annotate your class MyConfigPropertie with @Configuration along with @PropertySource
@PropertySource("classpath:/myfolder/my.properties")
@Configuration
public class MyConfigPropertie {

}

OR
put this @PropertySource("classpath:/myfolder/my.properties") on spring main class annotated with  @SpringBootApplication


text:
Q: Improve performance in converting large execl file to list of objects I know this question have been asked multiple times . But I could not find much help from anyone of those.
I don't want to convert the excel into data table but I want it to be converted to a list of objects and sent to server side for processing.
If it has more than 2K rows it should throw an error. Currently what I am doing is something like :
   using (var excel = new ExcelPackage(hpf.InputStream))
    {
        var ws = excel.Workbook.Worksheets["Sheet1"];

        for (int rw = 4; rw <= ws.Dimension.End.Row; rw++)
        {
            if (ws.Cells[rw, 1].Value != null)
            {
                int headerRow = 2;

                GroupMembershipUploadInput gm = new GroupMembershipUploadInput();

                for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++)
                {
                    var s = ws.Cells[rw, col].Value;

                    if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id"))
                    {
                        gm.cnst_mstr_id = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
                    }
                    else if (ws.Cells[headerRow, col].Value.ToString().Equals("Prefix of the constituent(Mr, Mrs etc)"))
                    {
                        gm.cnst_prefix_nm = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
                    }
                    else if (ws.Cells[headerRow, col].Value.ToString().Equals("First Name of the constituent(Mike)"))
                    {
                        gm.cnst_first_nm = (ws.Cells[rw, col].Value ?? (Object)"").ToString();
                    }
                    .....................
                    .....................

                    }
            }

                    iUploadedCnt = iUploadedCnt + 1; //Increase the count by 1
                }

                if (lgl.GroupMembershipUploadInputList.Count < 2003) //Check for the uploaded list count
                {

                       //throw the error

                 }

But this approach seems slow.
Conversion of the excel to list seems slow to me. For example ,  when I upload more than 2k records , the list gets converted first to list and then the count is checked if more than 2003 . This process is definitely slower.
How can it be achieved in a faster /better way ?

A: You do a lot of repeated string processing which is unnecessary. For each row you check the column headers again if they fit some predefined value. (for instance if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id")).
You could do this once before you start parsing all rows and create for instance a Dictionary<int, SomeEnum> which maps the column number to a specific enum value. When parsing the rows you then can make a quick lookup in the dictionary, which column maps to which property.
Furthermore, you define a var s = ws.Cells[rw, col].Value; but never use it. Instead, you read this cell value again, when you assign it to a property of your object. You could just make the necessary conversions and checks here, and then use only s;
// define this enum somewhere
enum ColumPropEnum {
   cnst_mstr_id,  cnst_prefix_nm, ...
}

//define this prop somewhere
Dictionary<int, ColumnPropEnum> colprops = new Dictionary<int, ColumnPropEnum>();

//do this once before processing all rows
for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++) {
    if (ws.Cells[headerRow, col].Value.ToString().Equals("Existing Constituent Master Id"))
        colprops.Add(col, ColumnPropEnum.cnst_mstr_id);
    else if (ws.Cells[headerRow, col].Value.ToString().Equals(" ..."))
        colprops.Add(col, ColumnPropEnum.cnst_prefix_nm);
    ...
}

//now use this dictionary in each row
for (int rw = 4; rw <= ws.Dimension.End.Row; rw++)
{
....
    for (int col = ws.Dimension.Start.Column; col <= ws.Dimension.End.Column; col++) {

        //the single ? checks, whether the Value is null, if yes it returns null, otherwise it returns ToString(). Then the double ?? checks whether the result if the operation is null, if yes, it assigns "" to s, otherwise the result of ToString();
        var s = ws.Cells[rw, col].Value?.ToString() ?? "";
        ColumnPropEnum cp;
        if (colpros.TryGetValue(col, out cp)) {
            switch (cp) {
                case cnst_mstr_id: gm.cnst_mstr_id = s; break;
                case cnst_prefix_nm: gm.cnst_prefix_nm = s; break;
                ...
            }
        }
    }

}
I'm not sure at which position you add this object to a list or upload it to the server, as this is not part of the code. But it could be faster, to first check only the first column of each row if you have the necessary count of non-null values and throw an error if not and do all the other processing only if you didn't throw the error.
int rowcount = 0;
//If you need at minimum 2000 rows, you can stop after you count 2000 valid rows
for (int rw = 4; rw <= ws.Dimension.End.Row && rowcount < 2000; rw++)
{
    if (ws.Cells[rw, 1].Value != null) rowcount++
}

if (rowcount < 2000) {
    //throw error and return
}

//else do the list building and uploading


text:
Q: if imagesNamesList==["None" for x in range(len(listOfImages)]: I am getting a syntax error at the line
if imagesNamesList==["None" for x in range(len(listOfImages)]:
I am not sure what I have done wrong...can someone point it out please?

A: You are missing a closing parenthesis:
if imagesNamesList==["None" for x in range(len(listOfImages))]:
#                                                     here--^

However, you could write this code better (cleaner and more efficiently) like so:
if imagesNamesList == ["None"]*len(listOfImages):

Or, if your lists are huge, you can do as @mgilson noted:
if all(x == "None" for x in imagesNamesList) and len(imagesNamesList) == len(listOfImages):

Though this method requires more syntax, it is actually more efficient because of the short-circuiting property of all (it will stop evaluating at the first x == "None" that comes back False, if any).


text:
Q: Bootsrap fixed navbar doesnt have margin bottom I creatad a simple theme with bootstrap 4. The navbar has a fixed-top class. Under the nav, i have this div, that has the page title as content.

<?php get_site_cim($siteID); ?>

My problem is, that this div "goes up" to the navbar. I give it some margin-top, but its not okay, i think because the fixed navbar.

Can someone help me fix this? You can see my site on this link.
Thank you.

A: give margin-top for .aloldal_text_div your header height
.aloldal_text_div{
   width: 100%;
   padding: 20px 0;
   background:#d3bf84;
   color:#fff;
   margin: 67px 0 0; /*edit here*/
}


text:
Q: Approach to sample 'C' challenge I was recently asked a theoretical C question and I was wondering what the best way to approach it would be:
If I had a document with 10 words on it what would be the best way to determine if there were duplicate words and if there were duplicates how would I keep track of how many there were?
Any insight on how you would approach this would be great.

A: The keyword is "ten": this means that the simplest approach with two nested loops checking each word against each other in front of it will do just fine. If the number was, say, 10000000, an approach with hash tables, heaps, or sorted arrays would be warranted. With only ten words, however, you do not need to build anything complex - just the basic C string read/compare knowledge would be required.

A: Theoretical interview questions like this always deal in small numbers (like 10 words). However, the number means nothing; it's there to separate out those candidates who really can think around the problem in the general form from those who simply regurgitate fixed answers to fixed interview questions they find on the internet.
The best software houses will only favour solutions that are scalable. Therefore, you will gain top marks in an interview if your answer is simple, but also scalable to any size of problem (or, in this case, document). Therefore, sorting, loops inside loops, O(n^2) complexity, forget them all. If you presented any solutions like these to a leading-edge software company at interview you would fail.
Your particular question is checking to see if you know about Hash Tables. The most efficient solution to this problem can be written in pseudo-code as follows:

1. Initialise a new hash table.
   For each word in the document...
2.     Generate a hash key for the word.
3.     Lookup the word in the hash table using the key. If it is found,
4.         Increment the count for the word.
       Otherwise,
5.         Store the new word in table and set its count to one.

The most important benefit of the above solution is that only a single scan of the document is required. No reading words into memory and then processing (two scans), no loops in loops (many scans), no sorting (even more passes). After exactly one pass of the document, if you read out the keys in the hash table, the count of each word tells you exactly how many times each word appeared in the document. Any word with a count greater than one is a duplicate.
The secret to this solution is its use of hash tables. Generation of the hash key (step 2), key lookup (step 3), and key storage (step 5) can be implemented as near constant-time operations. This means the time these steps take hardly changes as the size of the input set (i.e. number of words) grows. It means that whether it's the 10th word in a document, or the 10 millionth word, inserting that word into the hash table (or looking it up) will take roughly the same very small amount of time. In this case, we additionally keep a count of each word's frequency in step 5. Incrementing a value is known to be a very efficient fixed-time operation.
Any solution to this problem must scan all words in the document at least once. As our solution processes each word exactly once, with all words taking approximately the same very small constant time to process, we say our solution performs optimally and scales linearly, yielding O(n) performance (put simply, processing 1,000,000 words will take around 1000 times longer than processing 1000 words). In all, a scalable and efficient solution to the problem

A: *

*read the words into array of strings, using scanf

*for each word, compare to others later in the list, using strncmp

There are speed and space optimizations, but I (usually) optimize for simplicity.

A: For a larger implementation you can use a hash table and check collisions
For a small n (ex. n = 10), we can go through the elements and add them to an array. For each element check the array to see if it is a duplicate.
Checking the array is in O(n) and going through each of the 10 elements is in O(n). Since we can implement this simply with a nested loop, we can perform this in O(n^2) time complexity. This is sufficient because with such a small n value, performance impacts would be negligible.

A: Since the length of the individual words is likely "small", I would begin with a radix sort http://en.wikipedia.org/wiki/Radix_sort which takes O(nk) time, where k is the maximum word length. In this case you would definitely want to first sort the words into separate lists according to length (up to n of them).
Because you're interested only in duplicates you can throw out any list (in this step or any subsequent step) of length 1.
For each list, compare the last character of each list member, creating a new list of words for each distinct character seen (up to 26 of them, assuming the words are all ASCII characters), truncating the last character. Again, throw out lists of length 1 and recursively sort the new list(s).
In the worst case (all words are the same length and differ only in the first character, assuming LSD radix sort) you'll get O(nk) time. In the best case (all words have different length) you'll get O(n) time. In real-world cases you'll probably get significantly better than O(nk) time so the solution should scale up well to longer word lists.


text:
Q: Finding the summation of $c_i$ for $c_i=\begin{cases}i &\quad\text{if $i-1$ is exact power of $2$ }\\1&\quad\text{otherwise.}\\ \end{cases}$ While reading the text Introduction to Algorithms by Cormen et. al. I came across a few mathematical step which I felt like proving in a more detailed manner, as I could not get steps of the mathematics which they did in short.
Below is the excerpt from the text.

$$c_i = \begin{cases}
        i &\quad\text{if $i-1$ is an exact power of $2$ }\\
       1&\quad\text{otherwise.}\\
\end{cases}$$
So,
$$\sum_{i=1}^{n}c_i\leq n+\sum_{j=0}^{\lfloor lg(n) \rfloor}2^j\tag 1$$
$$<n+2n=3n$$

The following is my attempt to understand the step $(1)$
$$\sum_{i=1}^{n}c_i=\sum_{\text{$i-1$ is a power of 2}}c_i +\sum_{\text{$i-1$ is not a power of 2}}c_i $$
$$=\sum_{\text{$j$ is a power of 2}}(j+1) +\sum_{\text{$j$ is not a power of 2}}(1) ,\quad\quad\text{where $j=i-1$}$$
$$=\sum_{\text{$j$ is a power of 2}}(j) +\sum_{\forall j}(1) = \left (\sum_{\text{$j$ is a power of 2}}j\right )+n \tag 2$$
$$\text{where $0\leq j \leq n-1$}$$
for the situation in which $j$ is power of $2$ let $2^k$ be the maximum possible value of $j$. So,
$$2^k=n-1 \implies k=\lfloor \log_2(n-1) \rfloor$$
Now we know,
$$n-1<n \implies \log_2(n-1)<\log_2(n) \implies \lfloor\log_2(n-1)\rfloor\leq\lfloor\log_2(n)\rfloor \tag3$$
Let $j=2^t$ , $t=0$ to $k$
So from $(2)$ and $(3)$ we have,
$$\sum_{i=1}^{n}c_i\leq n+\sum_{t=0}^{\lfloor lg(n) \rfloor}2^t \tag 4$$
The step which the authors achieved directly in $(1)$ took me so many steps to understand or derive in $(4)$. Is there a shorter method available or some intuition which the authors used to achieve the result directly?

A: If $i-1=2^j$, where $i\le n$ then $j=\lg(i-1)<\lg n$. Moreover, $j$ is an integer, so $j\le\lfloor\lg n\rfloor$. Thus, each term of $\sum_{i=1}^nc_i$ is either $1$ or $2^j+1$ for some $j$ such that $0\le j\le\lfloor\lg n\rfloor$. Thus, we automatically get a contribution of $1$ from each of the $n$ terms, for a total of $n$. We get another $2^j$ for the terms with $0\le j\le\lfloor\lg n\rfloor$, which contribute
$$\sum_{j=0}^{\lfloor\lg n\rfloor}2^j=2^{\lfloor\lg n\rfloor+1}-1<2\cdot2^{\lg n}=2n\;.$$
Thus,
$$\sum_{i=1}^nc_i\le n+\sum_{j=0}^{\lfloor\lg n\rfloor}2^j<n+2n=3n\;.$$


text:
Q: "Qt: Untested Windows 10.0 version detected!" when using python-vlc I'm setting up a program to play youtube links in vlc, and I get this error. I don't have Qt installed, and to be honest I'm not even fully sure what it is or what it has to do with anything.
I've tried to ignore the error using try but this didn't work
import pafy
import vlc

url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
video = pafy.new(url)
best = video.getbest()
playurl = best.url
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()

A: Fixed it! My actual VLC install was out of date. Reinstalled that (twice, had to make sure both python and VLC were 32 bit) and everything worked!


text:
Q: sed program, what does it do?  "sed \'s/\t/ /g\' "

Thank you! It is part of code like this
string cmd = "sed \'s/\t/ /g\' " + string(filename) + " > sample.clean";
            system(cmd.c_str());
            ifstream infile("sample.clean");
            if (!infile){
                cerr << "error loading file after clean-up!\n";
                return 0;
            }

A: It replaces tabs with spaces, but it does so poorly.  Within sed itself, 'y/\t/ /' is better, but sed is the wrong tool and it is even better written tr '\t' ' '

A: It replaces tab characters \t with spaces.

A: it seems like it replaces tabulations (\t) by spaces. The g means that the replacement should not stop at the first match on a line.


text:
Q: Custom tick size on axis (d3js) I am creating a svg x-y-chart in d3.js. Is it possible to create ticks of different lengths depending on tickValue?
I have made my own tickFormat function myTickFormat and use that in .tickFormat([format]) and that works fine because [format] is expected to be a function. But it is not possible to do the same with .innerTickSize([size]), which expects a number.
E.g. if I want the tick at value 70 to be longer I want to do something like this:
var myTickSize = function(d) {
    if (d === 70) { return 20;}
    return 6;
};

But when I use myTickSize as argument to .innerTickSize():
var yScale = d3.scale.linear();
var yAxis = d3.svg.axis()
               .scale(yScale).orient("left")
               .innerTickSize(myTickSize);

I get an Error: Invalid value for  attribute x2="NaN" error for each tick.

A: The tickSize function can only accept a number as argument, not a function, but there are other solutions.
The easiest approach? After the axis is drawn, select all the tick lines and resize them according to their data value. Just remember that you'll have to do this after every axis redraw, as well.
Example:
https://jsfiddle.net/zUj3E/1/
Key code:
d3.selectAll("g.y.axis g.tick line")
    .attr("x2", function(d){
    //d for the tick line is the value
    //of that tick
    //(a number between 0 and 1, in this case)
       if ( (10*d)%2 ) //if it's an even multiple of 10%
           return 10;
       else
           return 4;
    });

Note that the tick marks at the max and min values are also drawn as part of the same <path> as the axis line, so shortening them doesn't have much effect.  If you don't like that lack of control, declare the "outer" ticks to have zero length when you set up the axis.  That turns off the corners of the path, but the outer ticks will still have lines that you can control the same as the other tick lines:
var axis = d3.svg.axis()
    .tickSize(10,0)

Example: https://jsfiddle.net/zUj3E/2/
If that doesn't work, google for examples of major/minor tick patterns.  Just make sure the example you're looking at uses d3 version 3: there were a few extra tick-related methods added in version 2 that are no longer supported.  See this SO Q&A.

A: Variant on the answer that suits my requirements. Picked the values I just wanted tick marks for instead of ticks and value, added the "hide" class. But this can be used for any variation on the theme.
            var gy = humiditySVG.append( "g" )
                .attr( "class", "y axis" )
                .attr( "transform", "translate(" + 154 + "," + 0 + ")" )
                .call( yAxis );

            humiditySVG.selectAll( "text" )
                .attr( "class", function ( d ) {
                                           if ( $.inArray(d, [0,50,100])==-1  ) {
                               return "hide";
                           }
                           return;
                       } );
            humiditySVG.selectAll( "line" )
                .attr( "x2", function ( d ) {
                           if ( $.inArray(d, [0,50,100])==-1  ) {
                               return 1;
                           } else {
                               return 3;
                           }
                           return;
                       } );