text:
Q: How to create a custom video: Uncaught TypeError: Cannot read properties of null (reading 'querySelector') I watching a video on how to create a custom video player in Atom. I have got to step to creating the different const but getting a error message take saying that line 2 of const video = player.querySelector('.player-video');
Uncaught TypeError: Cannot read properties of null (reading 'querySelector')
When the user clicks on the play video button, I want the user to watch the video:
I have my class name with: <video controls class="player-video" height="369px" width="610px" class="video" id="video" preload="metadata" poster="assets/img/photo.jpg">

const player = document.querySelector('.player');
const video = player.querySelector('.player-video');
const progress = player.querySelector('.progress');
const progressFilled = player.querySelector('.filled-progress');
const toggle = player.querySelector('.toggle-play');
const skippers = player.querySelectorAll('[data-skip]');
const ranges = player.querySelectorAll('.player-slider');

function togglePlay() {
  const playState = video.paused ? 'play' : 'paused';
 }

function updateButton() {
  const togglePlayBtn = document.querySelector('.toggle-play');

  if(this.pause) {
    togglePlayBtn.innerHTML + `<svg class="" width="16" height="16" viewBox="0 0 16 16"><title>play</title><path d="M3 2l10 6-10 6z"></path></svg>`;
  } else {
    togglePauseBtn.innerHTML + `<svg class="" width="16" height="16" viewBox="0 0 16 16"><title>pause</title><path d="M3 2l10 6-10 6z"></path></svg>`
  }
}

video.addEventListener('click', togglePlay);
video.addEventListener('play', updateButton);
video.addEventListener('pause', updateButton);
video.addEventListener('timeupdated', progressUpdate);

toggle.addEventListener('click', togglePlay);
skippers.forEach(button => button.addEventListener('click', skip));
ranges.forEach(range => range.addEventListener('change', rangeUpdate));
range.forEach(range => range.addEventListener('mousemove', rangeUpdate));

let mousemove = false;

progress.addEventListener('click', scrub);
progress.addEventListener('mousemove', (e) => mousedown && scrub(e));
progress.addEventListener('mousedown', () => mousedown = true);
progress.addEventListener('mouseup', () => mousedown = false);

            <video controls class="player-video" height="369px" width="610px" class="video" id="video" preload="metadata" poster="assets/img/photo.jpg">
                <source src="/assets/video/bjp__video.mp4" type="video/mp4">
                <source src="/assets/video/bjp__video.webm" type="video/webm">
            </video>

I help  people with disabilities and entrepreneurs  to find there hide abilities and resources for there businesses.

     <button class="player-btn toggle-play" title="Toggle Play" id="play">
          <svg class="" width="16" height="16" viewBox="0 0 16 16"><title>play</title><path d="M3 2l10 6-10 6z"></path></svg>
     </button>

A: The error tells you .querySelector cannot be called on the object player, because player is null and not an object. This means the node you tried to store a reference to in the player variable was not found in your document at the time. Are you sure that the element is present at the time of storing the reference, or is it perhaps rendered asynchronously by any chance?
/e: Referring to your comments above: the value printed to console.log is evaluated later on (Chrome used to display hints for that because it is somewhat misleading). You can try to console.log any attribute or other form of your variable. For objects you could JSON.stringify(), for nodes that could be .innerHTML of the parent container for example.


text:
Q: Line drawing in python using inputs I need your help!
I'm making a maze game that, in the long run, will use microphone inputs to control a player or a line of paint in a maze. I'm not sure how to do this however do know that i will need to use pyaudio and speech_recognition. This is the code so far which creates the maze but I'm not sure how to add the player input  where they can try and solve it. Thankyou in advance :)
import pygame, random, sys

class Node:

    def __init__(self, row, col, size):
        self.m_row = row
        self.m_col = col
        self.m_walls = {}  #walls are inner walls
        self.m_size = size
        self.x = self.m_size*self.m_col + self.m_size  # x, y is topleft corner of node
        self.y = self.m_size*self.m_row + self.m_size

    def disconnect(self, node, flag=True):  #disconnect means break wall
        #self.m_walls.pop(which_one)
        for key,value in self.m_walls.items():
            if  value != None and value.m_row== node.m_row and value.m_col== node.m_col:
                self.m_walls[key] = None
            else:
                #print("node to disconnect not found")
                pass
        if flag:
            node.disconnect(self, False)

    def connections(self):
        m_list = []
        for key,value in self.m_walls.items():
            if value != None:
                m_list.append(key)
        return m_list

    def draw(self, screen, y_offset):
        if self.m_walls["north"] != None:
            start_pos = (self.x, self.y + y_offset)
            end_pos =   (self.x + self.m_size, self.y +y_offset)
            pygame.draw.line(screen, (0,0,0), start_pos, end_pos, 1)

        if self.m_walls["south"] != None:
            start_pos = (self.x, self.y + self.m_size + y_offset)
            end_pos =   (self.x + self.m_size, self.y + self.m_size + y_offset)
            pygame.draw.line(screen, (0,0,0), start_pos, end_pos, 1)

        if self.m_walls["west"] != None:
            start_pos = (self.x, self.y + y_offset)
            end_pos = (self.x, self.y + self.m_size + y_offset)
            pygame.draw.line(screen, (0,0,0), start_pos, end_pos, 1)

        if self.m_walls["east"] != None:
            start_pos = (self.x + self.m_size, self.y + y_offset)
            end_pos = (self.x + self.m_size, self.y + self.m_size + y_offset)
            pygame.draw.line(screen, (0,0,0), start_pos, end_pos, 1)

class Maze:

    def __init__(self, num_rows, num_cols, node_size):
        self.m_num_rows = num_rows
        self.m_num_cols = num_cols
        self.m_node_size = node_size
        self.m_nodes = [ [Node(i, j, self.m_node_size) for j in range(self.m_num_cols)] for i in range(self.m_num_rows) ]

    def connect_nodes_default(self):
        for node in self.iter_node():
            node.m_walls["north"]= self.get_node(node.m_row-1, node.m_col)
            node.m_walls["south"]= self.get_node(node.m_row+1, node.m_col)
            node.m_walls["west"]= self.get_node(node.m_row, node.m_col-1)
            node.m_walls["east"]= self.get_node(node.m_row, node.m_col+1)

    def iter_node(self):
        for i in range(self.m_num_rows):
            for j in range(self.m_num_cols):
                yield self.m_nodes[i][j]

    def get_node(self, row, col):
        if row >= 0 and row < self.m_num_rows \
                and col >= 0 and col < self.m_num_cols:
            return self.m_nodes[row][col]
        else:
            return None

    def printme(self):
        for node in self.iter_node():
            print(node.m_row, node.m_col, node.connections())

    def draw(self, screen, y_offset = 0):
        self.draw_outer_boundary(screen, y_offset)
        for node in self.iter_node():
            node.draw(screen, y_offset)

    def draw_outer_boundary(self, screen, y_offset):
        topleft = (self.m_node_size,self.m_node_size+y_offset)
        topright = (self.m_node_size+self.m_node_size*self.m_num_cols, self.m_node_size+y_offset)
        bottomleft = (self.m_node_size, self.m_node_size+self.m_node_size*self.m_num_rows + y_offset)
        bottomright=(self.m_node_size+self.m_node_size*self.m_num_cols,self.m_node_size+self.m_node_size*self.m_num_rows + y_offset)

        pygame.draw.line(screen, (0,0,0), topleft, topright, 5)
        pygame.draw.line(screen, (0,0,0), topleft, bottomleft, 5)
        pygame.draw.line(screen, (0,0,0), topright, bottomright, 5)
        pygame.draw.line(screen, (0,0,0), bottomleft, bottomright, 5)

    def make_maze(self):
        for node in self.iter_node():
            node_to_disconnect_north= self.get_node(node.m_row-1, node.m_col) #north
            node_to_disconnect_east= self.get_node(node.m_row, node.m_col+1) #east

            if node_to_disconnect_north== None and node_to_disconnect_east==None:
                node_to_disconnect = None
            elif node_to_disconnect_north != None and node_to_disconnect_east==None:
                node_to_disconnect= node_to_disconnect_north
            elif node_to_disconnect_north == None and node_to_disconnect_east!=None:
                node_to_disconnect= node_to_disconnect_east
            else:
                rand_num = random.randint(0,1)
                if rand_num:
                    node_to_disconnect = node_to_disconnect_north
                else:
                    node_to_disconnect = node_to_disconnect_east
            if node_to_disconnect != None:
                #print('curr node:', node.m_row, node.m_col)
                #print('disconnecting:', node_to_disconnect.m_row, node_to_disconnect.m_col)
                node.disconnect(node_to_disconnect)

def main():
    pygame.init()
    screen = pygame.display.set_mode((900,900), 0, 32)
    screen.fill((255,255,255))

    num_rows = 30
    num_cols = 30
    node_size = 26
    maze = Maze(num_rows, num_cols, node_size)
    maze.connect_nodes_default()
    #maze.printme()
    #maze.draw(screen)

    maze.make_maze()
    #maze.printme()
    #maze.draw(screen, num_rows*node_size +100)
    maze.draw(screen, node_size)

    running = True
    held_down = False
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                held_down = True
            elif event.type == pygame.MOUSEBUTTONUP:
                held_down = False
            elif event.type == pygame.MOUSEMOTION:
                if held_down:
                    pygame.draw.circle(screen, (250,20,50), event.pos, 5, 0)
        pygame.display.update()

    pygame.quit()
    sys.exit()

#client code
main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Condition number of a rectangular matrix From what I understand, the condition number of a rectangular matrix $A$ is its largest singular value divided by its smallest nonzero singular value
$$\kappa(A) := \frac{\sigma_1 (A)}{\sigma_n (A)}$$
Where $\sigma_1 (A)$ is the operator norm of $A$ and $\sigma_n (A)$ is the operator norm of $A^\dagger$, the pseudoinverse of A. Is this correct and is it generally accepted?
I have not been able to find much on the subject online. Is this used in any notable applications?

A: Condition number of square nonsingular matrix $A$ is defined by
Definition $1$: $cond(A) = \|A\| \|A^{-1}\|$, where the norm $\|.\|$ above could be any of the norms defined for matrices. If we use the usual Euclidean norm on vectors and the associated matrix norm, then the condition number is the ratio of the largest singular value of matrix A to the smallest.
Definition $2$: Condition number for any matrix is defined as:
$cond(A) = \|A\| \|A^+\|$, where $A^+$ is the pseudo inverse of the matrix $A$. Note that for a square non singular matrix $A^+ = A^{-1}$ which implies that Definition $2$ is the generalization of Definition $1$ to find out condition number of any matrix .


text:
Q: Nginx not started, homebrew says it is brew services says nginx is started..
MacBook-Pro-van-Youri:Homebrew youri$ brew services start nginx
Service `nginx` already started, use `brew services restart nginx` to restart.

Same for launchctl
MacBook-Pro-van-Youri:Homebrew youri$ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
/Users/youri/Library/LaunchAgents/homebrew.mxcl.nginx.plist: service already loaded

My homebrew.mxcl.nginx.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>homebrew.mxcl.nginx</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <false/>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/opt/nginx/bin/nginx</string>
        <string>-g</string>
        <string>daemon off;</string>
    </array>
    <key>WorkingDirectory</key>
    <string>/usr/local</string>
  </dict>
</plist>

brew services list says the following:
MacBook-Pro-van-Youri:LaunchAgents youri$ brew services list
Name    Status  User  Plist
mariadb started youri /Users/youri/Library/LaunchAgents/homebrew.mxcl.mariadb.plist
nginx   error   youri /Users/youri/Library/LaunchAgents/homebrew.mxcl.nginx.plist
php71   started youri /Users/youri/Library/LaunchAgents/homebrew.mxcl.php71.plist

The syntax is oke:
MacBook-Pro-van-Youri:LaunchAgents youri$ plutil -lint homebrew.mxcl.nginx.plist
homebrew.mxcl.nginx.plist: OK

When i run sudo nginx i can access my website

A: Because nginx is going to start at port 80, it needs to be root. LaunchAgents are run as non-root user when that user logs in. LaunchDaemons are loaded at boot as root user.
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist

Move the homebrew.mxcl.nginx.plist
sudo mv ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist /Library/LaunchDaemons/

Load the plist from the LaunchDaemons folder
sudo launchctl load -w /Library/LaunchDaemons/homebrew.mxcl.nginx.plist

Now, sudo brew services list shows a running nginx process
Name    Status  User  Plist
nginx   started root  /Library/LaunchDaemons/homebrew.mxcl.nginx.plist

Running brew services list without root will result in an error status, because you need to be root to read the status.

A: As said, this happens because port 80 is reserved, it needs to be root.
An easier way is run brew services with sudo
sudo brew services start nginx


text:
Q: Use VS Code for Cross-Platform Scalable C++ Project This tutorial provided by the VS Code team explains how to setup C++ in VS Code with MinGW (https://code.visualstudio.com/docs/cpp/config-mingw), however it seems to only target small-scale projects as it is configured to rebuilds all files each time, and isn't setup to allow for easy configuration of a project (global defines, adding link libraries etc.) (or am I missing something?).
I am looking into using CMake as my build tool inside VS Code, however am really turned off by the idea of having to update the CMakeLists.txt file to change my project's configurations, e.g. every time I add files to my project or link a new library, as I have grown up using IDEs who do this process for me, which I find magnitudes easier as it allows me to purely to focus on writing code.
My question is, is there a known method to setup VS Code that will allow me to use a tool such as CMake without having to tinker with it too often?
This tutorial seems like a good starting point to setup CMake, but its method requires CMake knowledge https://pspdfkit.com/blog/2019/visual-studio-code-for-cpp/
I ideally would like the setup to cater for both small-scale and large-scale projects, both of which should allow for cross-platform building.
Thanks

A: As Visual Studio Code is not a heavy weight IDE, you will need to put some effort to get it run the way you want it to have, either:
Write a CMake InputFile generator, e.g. :
list(APPEND EXECUTABLE_LIST executable_1 executable_2)
list(APPEND LIBRARY_LIST library_2 library_2 library_3)

foreach(lib IN LISTS LIBRARY_LIST)
     add_library(${lib} STATIC ${lib}.cpp)
endforeach()

foreach(exe IN LISTS EXECUTABLE_LIST)
    add_executable(${exe} ${exe}.cpp)
    target_include_directories(${exe} PUBLIC ${CMAKE_CURRENT_LIST_DIR})
    target_link_libraries(${exe} ${LIBRARY_LIST})
endforeach()

or you could also use Visual Studio Code CMake Tool extention
For sure, you couldn't expect the highly functionality like Visual Studio in VS Code  as they serve different purpose (highly specialised, deep system couple but slow and big vs small, fast, highly configurable).


text:
Q: Swagger UI - How to protect swagger UI access with Auth I have integrated swagger bundle for my dropwizard(v2) app. Now I want to protect my app with the Auth means before accessing the swagger UI username and password show be mandatory. I tried a lot but did not get any success so please can anyone help me on this.

A: firstly you can add springdoc-openapi-ui dependency after you should create configuration class for swagger ui. I added example codes below.
@Bean
public OpenAPI customOpenAPI(@Value("${application-description}") String description,
                             @Value("${application-version}") String version) {
    final String securitySchemeName = "bearerAuth";
    return new OpenAPI()
            .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
            .components(
                    new Components()
                            .addSecuritySchemes(securitySchemeName,
                                    new SecurityScheme()
                                            .name(securitySchemeName)
                                            .type(SecurityScheme.Type.HTTP)
                                            .scheme("bearer")
                                            .bearerFormat("JWT")
                            )
            )
            .info(new Info().title("API")
                    .version(version)
                    .description(description)
                    .license(new License().name("API")));
}


text:
Q: Add as Playlist - error looping through tracks I'm trying to loop through a album which have x tracks, then add them to the playlist.
But I'm getting the follow error message in the console:
Uncaught Error: link not allowed
Code:
var album = models.Album.fromURI(uri);

$('.add-playlist').live('click', function() {
    var newPlaylist = new models.Playlist('Awesome album ' + album.name);
    $.each(album.data.tracks, function(i, track) {
        console.log(i + ' ::: ' + track.name);
        newPlaylist.add(track);
    });
});

It works if I add a single track to the playlist when I'm pressing the .add-playlist button but not when looping through the album.data.tracksarray.
Probably something little I've missed. ;)
Update:
I got it working by removing the .data. from album.data.tracks so it says only album.tracks.


text:
Q: Fade in after every line Instead of individually doing a javascript for each line (separately creating a div that functions on a timer), I was wondering if it would be possible to fade in each line in the html that splits the line by "BR" by creating a universal javascript function.

*

*Accepts a string, a div, and a speed as an argument.

*Splits the line by "br>" and separated it into an array.

*Fades in every line in the array in syncronization with the last line that previously faded in.

A: Just read the comments in the code and let me know if something not clear..
Tested on Chrome

function action(delay, str) {
  // split the string into array
  var lines = str.split('
');

  $.each(lines, function(index, h) {
    // create a div to each line
    var div = $('
').html(h);
    // hide it, append it into the body
    div.hide().appendTo(document.body).delay(index * delay);
    // wait by the div index and the delay
    setTimeout(function() {
      // do the fadeIn
      div.fadeIn();
    }, index * delay);
  });
}

action(300, 'Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum
 Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum
 Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum
 Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum');

  Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum

  Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum

  Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum

  Lorem Ispum Lorem Ispum Lorem Ispum Lorem Ispum


text:
Q: Insert/transform to 0 or 1 based on presence of text I'd like to insert to a table's bit column either 0 or 1, 0 where there is no text, 1 where there is. I am pulling data through an excel source in SSIS. In the example below, it should go:
Client 1: 1    1    1
Client 2: 1    0    1

How it looks in excel:
Products:   Ball    Bicycle     Bat

Client 1:   Ball    Bicycle     Bat

Client 2:   Ball                Bat

Client 3:   Ball

Client 4:           Bicycle     Bat

Any way to achieve this in SSIS?

A: You'll need to use a few items to accomplish this.
How do I add new columns to a data flow task?
A Derived Column will allow you to create these new boolean columns. A derived column uses an Expression to compute a value. You'll need to specify the column name when you create a new one. You'll also want to ensure the data types are as expected.
What's my expression?
The first is whether the no text comes in as NULL, an empty string or a padded string. Knowing whether the current row satisfies one of those conditions will tell us whether we need to make our new column 1 or 0.
A value is either NULL or NOT NULL. If it's not null, then we need to worry about whether it's empty/padded. We test for NULL via the ISNULL expression.
A boolean OR is expressed as ||
An equality test is done via ==
We check for an empty string using the LEN expression.
We need to remove all the trailing spaces from our column to see if it reduces down to an empty string. We'll use RTRIM to accomplish this.
An Expression must evaluate to something, but we have conditional (if) logic. The way we work around that is the ternary operator (boolean test) ? (true expr) : (false expr)
The SSIS system data type for boolean is DT_BOOL
A cast is performed by (DT_TYPE) VALUE
Putting it all together
Add a derived column component to your data flow. Make the column name Col1HasText
Line breaks added for readability
(isnull([Col1]) || LEN(RTRIM([Col1])) == 0) ?
((DT_BOOL) 0) :
((DT_BOOL) 1)

English version: If Col1 is null or if the length of the right-trimmed version of Col1 is zero, then we want to cast one to a data type of DT_BOOL (boolean). Otherwise, cast zero to a data type of DT_BOOL


text:
Q: launch a PyQT window from a main PyQt window, and get the user input? I have a main PyQt window, from which I need to get a string of User Input when they hit a certain button.
Here is my code for the User Input window:
 class InputDialog(QtGui.QDialog):
   '''
   this is for when you need to get some user input text
   '''
   def __init__(self, parent=None, title='user input', label='comment', text=''):

       QtGui.QWidget.__init__(self, parent)

       #--Layout Stuff---------------------------#
       mainLayout = QtGui.QVBoxLayout()

       layout = QtGui.QHBoxLayout()
       self.label = QtGui.QLabel()
       self.label.setText(label)
       layout.addWidget(self.label)

       self.text = QtGui.QLineEdit(text)
       layout.addWidget(self.text)

       mainLayout.addLayout(layout)

       #--The Button------------------------------#
       layout = QtGui.QHBoxLayout()
       button = QtGui.QPushButton("okay") #string or icon
       self.connect(button, QtCore.SIGNAL("clicked()"), self.close)
       layout.addWidget(button)

       mainLayout.addLayout(layout)
       self.setLayout(mainLayout)

       self.resize(400, 60)
       self.setWindowTitle(title)

From the main window, I am saying:
inputter = InputDialog(mainWindowUI, title="comments", label="comments", text="")
inputter.show()
comment = inputter.text.text()
print comment

This prints an empty string, even if the user types a comment and hits "OK". Obviously because the main window script does not wait on the InputDialog to close. So, how do I get it to wait, so that I may retrieve the user input?

A: Use
inputter.exec_()

instead of
inputter.show()

From: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdialog.html#exec

This method is also a Qt slot with the C++ signature int exec().
Shows the dialog as a modal dialog, blocking until the user closes it.
  The function returns a DialogCode result.
If the dialog is application modal, users cannot interact with any
  other window in the same application until they close the dialog. If
  the dialog is window modal, only interaction with the parent window is
  blocked while the dialog is open. By default, the dialog is
  application modal.
See also open(), show(), result(), and setWindowModality().

A: I know that utdemir's response solved your problem but I just wanted to say that Qt comes with several convenience input dialogs included. Have a look at QInputDialog.getText for instance.


text:
Q: Backoffice java client framework - load on deman We are building our new Next generation server for a medium sized back office application.
We already decided we would like to use a java framework for the client side (gwt \ vaadin \ zkoss)
What we would like now is to create a Proof Of Concept example of each technology.
our back office ui is pretty standard, we have tables \ grids with filters that should show entries straight from the DB.
Problem is we got huge amount of rows in each table (1M minimum)
which mean that we must use a load on demand tables for them.
My questions is: how do i implement a load on demand table for my big tables? I looked around and saw the following concept again and again:
you create a container, you populate it with data, the data is being displayed on the client side.
problem is i tried this naive way to populate the containers with 1M entries and it was awful. are there any built in on demand containers?>
any code examples \ references will be a huge help!

A: You would want to use GWT Cell Table, which has the AsyncDataProvider, that lets you handle the user's paging and sorting events by grabbing data from your server.
It also provides an alternative ListDataProvider, which lets you grab your data as a list of objects, then set that data to your table. If you use ListDataProvider, you have to define how to sort your objects with Comparators, and table will handle sorting and paging against that list.
Google "gwt celltable asyncdataprovider example" for more examples and tutorials.

A: Vaadin has a nice concept of lazy loading data in most of the components.
For example the table, list, dropdown's etc. have that concept.
The only thing you realy need to know at start, is the number of total rows.
Everything else can then be handled "ondemand".
For example the Table component initially only loads about 30 rows (can be customized)
and then fetches rows as needed. (Or better they are usually fetched just before the user scrols to the next rows)
A example is this demo
http://demo.vaadin.com/dashboard/#!/transactions
How you retrieve the data from your backend depends on the technology used.
But vaadin has working concepts where you don't need to load all 1mio. rows into memory,
it will handle the "fetch on demand" as the rows need to be displayed.


text:
Q: Postgres Index not working. Always executing Sequential Scan I have created index as below:
CREATE INDEX CONCURRENTLY IF NOT EXISTS employee_emp_id_index ON employee ((lower(emp_id))); --'emp_id' is of type : VARCHAR2

EXPLAIN ANALYZE SELECT * FROM employee where lower(emp_id) = 'abc12345';

Execution plan:
Seq Scan on employee  (cost=0.00..2765.53 rows=16323 width=11) (actual time=0.071..13.247 rows=16340 loops=1)
Filter: (lower((emp_id)::text) = 'abc12345'::text)
Rows Removed by Filter: 11967
Buffers: shared hit=2341
Planning Time: 0.336 ms
Execution Time: 14.000 ms

Always executing sequential scan. Even if I turn off sequential scan, it is invoking Bitmap Heap Scan but not index scan.
Please suggest what I am missing here.


text:
Q: Does intel core i5 belong to the family i686 or x86_64 To which family does intel core i5 processors belong to? x86_64 or i686.
I was installing MinGW. I know it auto selects i686. But i686's are all 32 bit right? and intel i5 is actually a 64bit processor. This sprung up the doubt as to which family does it belong to?
THanks

A: Both. When running in 64-bit mode, it is x86_64. In 32-bit mode, it is i686.

A: As 64-bit processors, Core i3, i5 and i7 are all part of the x86_64 family.


text:
Q: How to save entries sorted by entrytype in JabRef? With JabRef it is possible to specify the sort order used when saving and exporting a bib file. When exporting the bib file, you can specify to use the current sorting of the entries shown in the GUI. When setting the library properties, there is no corresponding option in the save sort order section. I want to sort the bib file so that entries are grouped with a primary sort criterion of entrytype, but this is not in the drop down list. Is it possible to save a bib file sorted based on entrytype directly from JabRef?

A: Why bother about? Like in any database, when each entry have enough information, the order in which each entry is stored is completely irrelevant. However, if you insist, for example, to order by the keys in inverse order:
File
   Library Properties
      Save sort order
           🔘 Save entries ordered as specified
               Primary sort criterion bibtextekey▼ ☑    Descending
      OK
Ctrl+S


text:
Q: Rotation of sprite, libgdx android I want my sprite which is a basketball to rotate. How can i make my sprite to rotate counter-clockwise based on delta time? Do you have a calculation for it?

A: call rotateSprite() method whenever you want to rotate your ball.
Take a look of my Test code.
public class TestGame extends Game {

    SpriteBatch spriteBatch;
    Sprite ball;
    Texture ballTex;
    private int spriteRotationSpeed=1;

    @Override
    public void create() {

        spriteBatch=new SpriteBatch();
        ballTex=new Texture("image/bone.png");
        ball=new Sprite(ballTex);
        ball.setSize(50,50);
        ball.setOrigin(25,25);
        ball.setPosition(0,0);

    }

    @Override
    public void render() {
        super.render();

        Gdx.gl.glClearColor(1,1,1,1);
        gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        spriteBatch.begin();
        ball.draw(spriteBatch);
        spriteBatch.end();
        rotateSprite();
    }

    private void rotateSprite(){

        float rotation=ball.getRotation();
        rotation+=spriteRotationSpeed;
        if(rotation>360)
            rotation-=360;
        ball.setRotation(rotation);
    }

    @Override
    public void resize(int width, int height) {
        super.resize(width, height);
    }

    @Override
    public void dispose() {
        super.dispose();
        ballTex.dispose();
        spriteBatch.dispose();
    }
}


text:
Q: Regex question - need to make sure I'm getting the right thing I need to parse a couple of name value pairs from line in a log file.
One  of the names is 'ruser=data' and another is 'user=data'.
Both will be on the same line.
How can I make sure that when I match 'user' I'm not getting the data for ruser?
Many thanks
Joe
Edit:
I'm using javascript, and I've tried:
var u = line.match(/user=\w+/);
var user = u[0].replace(/(^user=*)/, "");
var r = line.match(/ruser=\w+/);
var ruser = r[0].replace(/(^ruser=*)/, "");

Many thanks

A: /\buser=\w+/

and
/\bruser=\w+/

should work. \b is a word boundary anchor that only matches at the start/end of an alphanumeric "word".


text:
Q: Kernel Crash with following code to clear process cache in Linux kernel I am doing a Linux kernel module to cleanup a process cache.
Below is the code I am using to do that.

static void clear_process_cache(struct task_struct *p)
{
        struct mm_struct *mm;
        struct vm_area_struct *vma;
        struct page *page;
        char *my_page_address;
        unsigned long uaddr, paddr;
        long res;
        unsigned int level;
        pte_t *pte;

        mm = p->mm;
        for (vma = mm->mmap; vma; vma = vma->vm_next) {
                for(uaddr = vma->vm_start; uaddr < vma->vm_end; uaddr += PAGE_SIZE) {
                        down_read(&p->mm->mmap_sem);
                        res = get_user_pages(p, mm, uaddr, 1, 0, 1, &page, NULL);
                        if (res == 1) {
                               my_page_address = kmap(page);
                               paddr = (unsigned long)page_address(page);
                               pte = lookup_address(paddr, &level);
                               if (pte && (pte_val(*pte) &_PAGE_PRESENT)) {
                                       clflush_cache_range(my_page_address, PAGE_SIZE);
                               }
                               kunmap(page);
                               put_page(page);
                       }
                       up_read(&p->mm->mmap_sem);
                }
        }
}

When the code is called intensively, the Linux kernel crashed.
I checked my code, but could NOT find why it caused kernel crash.
Would you like to help on it, or is there any other high performance way to do that ??
Here is the crash dump.

[  391.693385] general protection fault: 0000 [#1] SMP
[  391.694435] Modules linked in: xt_CHECKSUM iptable_mangle ipt_MASQUERADE nf_nat_masquerade_ipv4 iptable_nat nf_nat_ipv4 nf_nat nf_conntrack_ipv4 nf_defrag_ipv4 xt_conntrack nf_conntrack ipt_REJECT nf_reject_ipv4 xt_tcpudp bridge stp llc ebtable_filter ebtables ip6table_filter ip6_tables iptable_filter ip_tables x_tables vmw_vsock_vmci_transport vsock kvm_intel kvm irqbypass vmw_balloon input_leds joydev serio_raw shpchp vmw_vmci i2c_piix4 mac_hid ib_iser rdma_cm iw_cm ib_cm ib_sa ib_mad ib_core ib_addr iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi autofs4 btrfs raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx xor raid6_pq libcrc32c raid1 raid0 multipath linear crct10dif_pclmul crc32_pclmul ghash_clmulni_intel aesni_intel aes_x86_64 lrw gf128mul glue_helper vmwgfx ablk_helper
[  391.702930]  cryptd ttm drm_kms_helper syscopyarea psmouse sysfillrect pata_acpi sysimgblt mptspi fb_sys_fops mptscsih drm mptbase vmxnet3 scsi_transport_spi floppy fjes
[  391.705034] CPU: 3 PID: 1716 Comm: java Not tainted 4.4.131 #4
[  391.706080] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 07/28/2017
[  391.708180] task: ffff88042607c600 ti: ffff8804292b8000 task.ti: ffff8804292b8000
[  391.709244] RIP: 0010:[<ffffffff811a34dc>]  [<ffffffff811a34dc>] put_compound_page+0x5c/0x1b0
[  391.710358] RSP: 0000:ffff8804292bbcc8  EFLAGS: 00210202
[  391.711439] RAX: 00d0a78b4c535441 RBX: ffffffff810dc4f9 RCX: 000507e043713000
[  391.712523] RDX: ffff8804292bbd44 RSI: 000507e043713000 RDI: ffffffff810dc4f9
[  391.713586] RBP: ffff8804292bbcd8 R08: ffff880002213cf0 R09: 00003ffffffff000
[  391.714653] R10: 0000000000000080 R11: 0000000000000000 R12: 00d0a78b4c535440
[  391.715712] R13: 0000160000000000 R14: ffff8804292bbd88 R15: ffffffff810dc4f9
[  391.716764] FS:  00007fb138d5b700(0000) GS:ffff88042d6c0000(0000) knlGS:0000000000000000
[  391.717829] CS:  0010 DS: 0000 ES: 0000 CR0: 000000008005003b
[  391.718877] CR2: 0000000000000000 CR3: 00000000351d1000 CR4: 00000000001606f0
[  391.719972] Stack:
[  391.720993]  ffffffff810dc4f9 ffff880000000000 ffff8804292bbcf0 ffffffff811a364d
[  391.722055]  ffff8804292bbdc8 ffff8804292bbdf8 ffffffff8102e21e ffff8804292bbd48
[  391.723122]  0000000000000000 ffff88042607c600 ffff880429e6ac00 ffff880425e9f388
[  391.724165] Call Trace:
[  391.725190]  [<ffffffff810dc4f9>] ? vprintk_default+0x29/0x40
[  391.726222]  [<ffffffff811a364d>] put_page+0x1d/0x50
[  391.727259]  [<ffffffff8102e21e>] clear_process_cache+0x11e/0x1f0
[  391.728298]  [<ffffffff810dc4f9>] ? vprintk_default+0x29/0x40
[  391.729318]  [<ffffffff811918d0>] ? printk+0x5a/0x76
[  391.730328]  [<ffffffff8102e93d>] do_signal+0x20d/0x770
[  391.731310]  [<ffffffff81193459>] ? unlock_page+0x69/0x70
[  391.732297]  [<ffffffff811972c0>] ? __probe_kernel_read+0x40/0x90
[  391.733271]  [<ffffffff8106d3c3>] ? bad_area+0x43/0x50
[  391.734220]  [<ffffffff810034fc>] exit_to_usermode_loop+0x8c/0xd0
[  391.735143]  [<ffffffff81003c26>] prepare_exit_to_usermode+0x26/0x30
[  391.736062]  [<ffffffff8185184e>] retint_user+0x8/0x34
[  391.736941] Code: ff 5b 41 5c 5d c3 48 89 df e8 01 f6 ff ff 48 89 df 31 f6 e8 17 76 ff ff 5b 41 5c 5d c3 48 8b 47 20 4c 8d 60 ff a8 01 4c 0f 44 e7 <41> f6 44 24 08 01 74 08 49 8b 04 24 a8 80 74 1a 48 8b 43 20 a8
[  391.739698] RIP  [<ffffffff811a34dc>] put_compound_page+0x5c/0x1b0
[  391.740571]  RSP <ffff8804292bbcc8>


text:
Q: why does the Epoch reset when training SGDClassifier? My understanding of an Epoch is that it's the number of times we have gone through the entire training set during training. But when I train SGDClassifier with verbose=true, I see the below. It just resets after 5 Epochs and begins counting at 1 again. Why would it do that?
Here is how I am instantiating the model:
clf = linear_model.SGDClassifier(loss='log', verbose=True)
clf.fit(X_train, y_train)

And here is the output:
-- Epoch 1
Norm: 5.26, NNZs: 448659, Bias: -5.164052, T: 1912007, Avg. loss: 0.005248
Total training time: 0.91 seconds.
-- Epoch 2
Norm: 5.13, NNZs: 448659, Bias: -5.286860, T: 3824014, Avg. loss: 0.004764
Total training time: 1.72 seconds.
-- Epoch 3
Norm: 5.07, NNZs: 448659, Bias: -5.353568, T: 5736021, Avg. loss: 0.004655
Total training time: 2.57 seconds.
-- Epoch 4
Norm: 5.03, NNZs: 448659, Bias: -5.398900, T: 7648028, Avg. loss: 0.004587
Total training time: 3.41 seconds.
-- Epoch 5
Norm: 5.00, NNZs: 448659, Bias: -5.432728, T: 9560035, Avg. loss: 0.004547
Total training time: 4.28 seconds.
-- Epoch 1
Norm: 5.33, NNZs: 448659, Bias: -5.161117, T: 1912007, Avg. loss: 0.009731
Total training time: 0.98 seconds.
-- Epoch 2
Norm: 5.23, NNZs: 448659, Bias: -5.276683, T: 3824014, Avg. loss: 0.009210
Total training time: 1.84 seconds.

A: Thats because of implementing a One-vs-Rest Strategy in multi-class problems.
From the documentation:

SGDClassifier supports multi-class classification by combining
  multiple binary classifiers in a "one versus all" (OVA) scheme. For
  each of the K classes, a binary classifier is learned that
  discriminates between that and all other K-1 classes.

So that means if your data has 4 different classes, then 4 different instances of the model will be trained and so each model will print its number of epochs.
The default number of epochs (max_iter param) is 5. So each instance will print upto these many epochs.
In a simple binary classification task, only a single model is trained and hence the verbose output will contain single mentions of epochs only.
Hope you understand that now.


text:
Q: Special case in singly connected graph I'm trying to write an algorithm to determine whether a giving graph is singly connected. The homework definition says that a singly connected graph means between two nodes, there is at most one simple path.
I see lots of answer here says that using DFS-visit for each node, and if there's a black node been visited, it means there are two simple paths. As a result, the given graph is not simply connected.
I rewrite DFS algorithm to achieve that, but the problem is it can solve all the given graph except one special case. I already consider the situation which there are multiple edges between two nodes, but it does not work.
So my question is that is there any special case which can not be solved by using DFS-visit for each node?
def dsf(self, source):
    source.color = 'g'
    for node in source.next:
        if node.color == 'w':
            if not self.dsf(node):
                return False
        elif node.color == 'b':
            return False
    source.color = 'b'
    return True

if dsf encounter black node, it will return False and terminate the function.
def singly(self):
    for node in self.nodes:
        if not self.dsf(node):
            return False
        self.__clear()
    return True

And then using this function to check each node in the graph. Self.__clear can reset all the node's color back to white.
The algorithms work for all the case except for one special case.

A: Is there any special case which can not be solved by using DFS-visit for each node?
No, dfs must perfectly solve your problem.
Keep trying to find a bug. This code might help you. It computes all connected components in undirected graph.


text: Q: PCM to AAC conversion take too much time in devices I need to convert a linear PCM recorded audio file to AAC format and its working fine too. But in simulator it takes less than 2 Sec but in iPhone4 it is 33Sec and in iPhone 4S it is 51 sec. Its a 6 min audio file. What to do for reducing convertion time in device?? Please help..


text:
Q: How to umount a USB drive? I want to know how to umount my USB drive via command line. I am using Ubuntu 12.04 LTS 32-bit.

A: Suppose your usb drive is mounted to /media/usb then it would be sufficient to do
sudo umount /media/usb

Suppose the your usb is /dev/sdb1 then you could also do
sudo umount /dev/sdb1

You may also have a look at the anwers of one of my questions, how to umount all attached usb devices with a single command: Umount all attached usb disks with a single command

A: You can also use
udisks --unmount /dev/sdb1

which does not require root.

For macOS:
diskutil umount /dev/sdb1

A: Better than using sudo to unmount as root, just install the pmount package and do:
pumount /media/usb

As man pumount says:
NAME
       pumount - umount arbitrary hotpluggable devices as normal user

SYNOPSIS
       pumount [ options ] device

DESCRIPTION
       pumount  is  a wrapper around the standard umount program which permits
       normal users to umount removable devices without a matching  /etc/fstab
       entry.


text:
Q: How to use CarrierWaveDirect with embedded Mongo documents and legacy Carrierwave files I'm looking for the best ways to upload a file in a Rails app on Heroku.
Setup: Rails 3, Carrierwave, Heroku, Mongoid
Problem: Sporadically, when a user uploads a file of varying sizes, the image is saved to the database, but not available in any form on Amazon S3. This results in the image displaying as a missing image placeholder on the front end.
Probable Cause:
Image is uploaded but processing is too time consuming and the request times out due to Heroku's hard 30 second request time limit, or image size is too large and in attempting to upload, the request times out with H12 error.
Solution: Implement carrierwave-direct and move processing to background
Blocker:
CarrierWaveDirect is not a drop in replacement for CarrierWave. In fact, it introduces some major changes in the process of uploading an image, notably the image is not uploaded at the same time of db record persistence. Also, it does not work with my existing directory structure, so moving my existing files to a new structure seems overly arduous. CarrierWaveBackgrounder does not play nice with embedded documents.
Question: How do I do this? Example code if needed, but trying to think through this moreso than just coding it.

A: If you need to handle single files, check out this Railscast which covers CarrierWaveDirect and uploading to S3 in depth. Combined with the carrierwave-mongoid gem, you should be able to get single file uploads running if you want to go that route.
Honestly though, I'd just go for multiple file upload and be done with it. In the second part he shows off a multi-file upload setup using standard Carrierwave and jQuery File Upload instead of CarrierWaveDirect. I tend to agree with that decision. I just couldn't get it working right, most likely because of all the black magic required to POST directly to S3.
Ryan's setup looks intimidating at first, but it's pretty simple, and in the source code for the episode he includes a helper class that takes care of all that form data funny business S3 requires.
The basic workflow is something like:
1) File gets uploaded directly from browser to temporary bucket or folder on S3 through jQuery plugin.
2) AJAX POST request with the temp upload URL goes to app telling it to persist in the database and start a worker process.
3) Worker process downloads temporary file, runs it through your CarrierWave setup and stores the finished versions in the right place.
I think he uses sidekiq for the background jobs, but I have something similar set up with IronWorker and it works beautifully. Once you have the jQuery stuff and CarrierWave set up, you can use whatever you want for the jobs really.
Also, in the comments there I explained how I take care of deleting the raw upload files from the temp bucket as part of the job to keep things tidy. And for all the dirty details on how POSTing straight to S3 works see here. Still a good idea to understand that even if you have the helper class.


text:
Q: StartSSL just for encrypted data transfer I am developing browser extension, that sends some data from currently browsed page to my backend server. User is aware of it, it is intended.
I don't want to cause any user-data exposure, when the user is e.g. on unsecured wifi. So I just want to ensure, the data and the url goes over the net encrypted and only my backend will see them.
Do I understand correctly, that any SSL certificate, even free one from StartSSL will do the trick?
What other side effects with free SSL certificate should I consider?
- will the user's http-client trust such a certificate?
Thanks.

A: The SSL certificate will do the trick as long as it can be validated. That means that the root certificate of the certificate chain needs to be within the trusted certificate store of the browser.
Furthermore, the certificate will have to be for the right address (URL), must not be revoked, CRL's and OCSP must be configured correctly etc. etc. In other words, the usual steps required to have your web-service certificate validated must be met.


text:
Q: How do I adjust or suppress interletter spaces in math mode In other words, how do achieve the effect of wrapping an entire equation in \mathit, except without italicizing numbers?
More generally, how do I change the amount of whitespace that's added between consecutive letters in math mode?
I found many questions on the site about removing spacing around operators, but none about inter-letter spacing. Here's what I want:

A: Not sure how rich your TeX code is, anyway hope the following specimen code will help:
\documentclass{article}

\usepackage{amssymb}
\usepackage{txfonts}

\DeclareSymbolFont{mymathvariables}{OT1}{txr}{m}{it}

\DeclareMathSymbol{a}{\mathalpha}{mymathvariables}{`a}
\DeclareMathSymbol{b}{\mathalpha}{mymathvariables}{`b}
\DeclareMathSymbol{c}{\mathalpha}{mymathvariables}{`c}
\DeclareMathSymbol{d}{\mathalpha}{mymathvariables}{`d}
\DeclareMathSymbol{e}{\mathalpha}{mymathvariables}{`e}
\DeclareMathSymbol{f}{\mathalpha}{mymathvariables}{`f}
\DeclareMathSymbol{g}{\mathalpha}{mymathvariables}{`g}
\DeclareMathSymbol{h}{\mathalpha}{mymathvariables}{`h}
\DeclareMathSymbol{i}{\mathalpha}{mymathvariables}{`i}
\DeclareMathSymbol{j}{\mathalpha}{mymathvariables}{`j}
\DeclareMathSymbol{k}{\mathalpha}{mymathvariables}{`k}
\DeclareMathSymbol{l}{\mathalpha}{mymathvariables}{`l}
\DeclareMathSymbol{m}{\mathalpha}{mymathvariables}{`m}
\DeclareMathSymbol{n}{\mathalpha}{mymathvariables}{`n}
\DeclareMathSymbol{o}{\mathalpha}{mymathvariables}{`o}
\DeclareMathSymbol{p}{\mathalpha}{mymathvariables}{`p}
\DeclareMathSymbol{q}{\mathalpha}{mymathvariables}{`q}
\DeclareMathSymbol{r}{\mathalpha}{mymathvariables}{`r}
\DeclareMathSymbol{s}{\mathalpha}{mymathvariables}{`s}
\DeclareMathSymbol{t}{\mathalpha}{mymathvariables}{`t}
\DeclareMathSymbol{u}{\mathalpha}{mymathvariables}{`u}
\DeclareMathSymbol{v}{\mathalpha}{mymathvariables}{`v}
\DeclareMathSymbol{w}{\mathalpha}{mymathvariables}{`w}
\DeclareMathSymbol{x}{\mathalpha}{mymathvariables}{`x}
\DeclareMathSymbol{y}{\mathalpha}{mymathvariables}{`y}
\DeclareMathSymbol{z}{\mathalpha}{mymathvariables}{`z}

\DeclareMathSymbol{A}{\mathalpha}{mymathvariables}{`A}
\DeclareMathSymbol{B}{\mathalpha}{mymathvariables}{`B}
\DeclareMathSymbol{C}{\mathalpha}{mymathvariables}{`C}
\DeclareMathSymbol{D}{\mathalpha}{mymathvariables}{`D}
\DeclareMathSymbol{E}{\mathalpha}{mymathvariables}{`E}
\DeclareMathSymbol{F}{\mathalpha}{mymathvariables}{`F}
\DeclareMathSymbol{G}{\mathalpha}{mymathvariables}{`G}
\DeclareMathSymbol{H}{\mathalpha}{mymathvariables}{`H}
\DeclareMathSymbol{I}{\mathalpha}{mymathvariables}{`I}
\DeclareMathSymbol{J}{\mathalpha}{mymathvariables}{`J}
\DeclareMathSymbol{K}{\mathalpha}{mymathvariables}{`K}
\DeclareMathSymbol{L}{\mathalpha}{mymathvariables}{`L}
\DeclareMathSymbol{M}{\mathalpha}{mymathvariables}{`M}
\DeclareMathSymbol{N}{\mathalpha}{mymathvariables}{`N}
\DeclareMathSymbol{O}{\mathalpha}{mymathvariables}{`O}
\DeclareMathSymbol{P}{\mathalpha}{mymathvariables}{`P}
\DeclareMathSymbol{Q}{\mathalpha}{mymathvariables}{`Q}
\DeclareMathSymbol{R}{\mathalpha}{mymathvariables}{`R}
\DeclareMathSymbol{S}{\mathalpha}{mymathvariables}{`S}
\DeclareMathSymbol{T}{\mathalpha}{mymathvariables}{`T}
\DeclareMathSymbol{U}{\mathalpha}{mymathvariables}{`U}
\DeclareMathSymbol{V}{\mathalpha}{mymathvariables}{`V}
\DeclareMathSymbol{W}{\mathalpha}{mymathvariables}{`W}
\DeclareMathSymbol{X}{\mathalpha}{mymathvariables}{`X}
\DeclareMathSymbol{Y}{\mathalpha}{mymathvariables}{`Y}
\DeclareMathSymbol{Z}{\mathalpha}{mymathvariables}{`Z}

%\DeclareSymbolFont{mymathnumerals}{T1}{ybv}{m}{n}
%\SetSymbolFont{mymathnumerals}{normal}{T1}{ybv}{m}{n}
%\DeclareSymbolFontAlphabet{\mathnormal}{mymathnumerals}

\begin{document}

$qpdb_0+1$

$\mathit{qpdb_0+1} \lambda$

\end{document}

Note: Here I used txfont to show the change, you may replace the {<encoding>} and {<family>} in \DeclareSymbolFont accordingly in your code.
Useful links:

*

*https://www.slac.stanford.edu/comp/unix/package/tex/latex/fntguide/node17.html

*http://latex-community.org/forum/viewtopic.php?f=48&t=9537

A: Since you seem to be using some Times-like font, here's an example:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{newtxtext,newtxmath}
\usepackage{microtype}

\begin{document}

$math$ $is$ $difficult$ $qpdb_0+1$

{\boldmath$math$ $is$ $difficult$}

\end{document}

This outputs

Now transform this into
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{newtxtext,newtxmath}
\usepackage{microtype}

\DisableLigatures{encoding=OT1,family=ntxtlf}

\DeclareSymbolFont{unspacedletters}{OT1}{ntxtlf}{m}{it}
\SetSymbolFont{unspacedletters}{bold}{OT1}{ntxtlf}{b}{it}
\DeclareMathSymbol{A}{\mathalpha}{unspacedletters}{`A}
\DeclareMathSymbol{B}{\mathalpha}{unspacedletters}{`B}
\DeclareMathSymbol{C}{\mathalpha}{unspacedletters}{`C}
\DeclareMathSymbol{D}{\mathalpha}{unspacedletters}{`D}
\DeclareMathSymbol{E}{\mathalpha}{unspacedletters}{`E}
\DeclareMathSymbol{F}{\mathalpha}{unspacedletters}{`F}
\DeclareMathSymbol{G}{\mathalpha}{unspacedletters}{`G}
\DeclareMathSymbol{H}{\mathalpha}{unspacedletters}{`H}
\DeclareMathSymbol{I}{\mathalpha}{unspacedletters}{`I}
\DeclareMathSymbol{J}{\mathalpha}{unspacedletters}{`J}
\DeclareMathSymbol{K}{\mathalpha}{unspacedletters}{`K}
\DeclareMathSymbol{L}{\mathalpha}{unspacedletters}{`L}
\DeclareMathSymbol{M}{\mathalpha}{unspacedletters}{`M}
\DeclareMathSymbol{N}{\mathalpha}{unspacedletters}{`N}
\DeclareMathSymbol{O}{\mathalpha}{unspacedletters}{`O}
\DeclareMathSymbol{P}{\mathalpha}{unspacedletters}{`P}
\DeclareMathSymbol{Q}{\mathalpha}{unspacedletters}{`Q}
\DeclareMathSymbol{R}{\mathalpha}{unspacedletters}{`R}
\DeclareMathSymbol{S}{\mathalpha}{unspacedletters}{`S}
\DeclareMathSymbol{T}{\mathalpha}{unspacedletters}{`T}
\DeclareMathSymbol{U}{\mathalpha}{unspacedletters}{`U}
\DeclareMathSymbol{V}{\mathalpha}{unspacedletters}{`V}
\DeclareMathSymbol{W}{\mathalpha}{unspacedletters}{`W}
\DeclareMathSymbol{X}{\mathalpha}{unspacedletters}{`X}
\DeclareMathSymbol{Y}{\mathalpha}{unspacedletters}{`Y}
\DeclareMathSymbol{Z}{\mathalpha}{unspacedletters}{`Z}
\DeclareMathSymbol{a}{\mathalpha}{unspacedletters}{`a}
\DeclareMathSymbol{b}{\mathalpha}{unspacedletters}{`b}
\DeclareMathSymbol{c}{\mathalpha}{unspacedletters}{`c}
\DeclareMathSymbol{d}{\mathalpha}{unspacedletters}{`d}
\DeclareMathSymbol{e}{\mathalpha}{unspacedletters}{`e}
\DeclareMathSymbol{f}{\mathalpha}{unspacedletters}{`f}
\DeclareMathSymbol{g}{\mathalpha}{unspacedletters}{`g}
\DeclareMathSymbol{h}{\mathalpha}{unspacedletters}{`h}
\DeclareMathSymbol{i}{\mathalpha}{unspacedletters}{`i}
\DeclareMathSymbol{j}{\mathalpha}{unspacedletters}{`j}
\DeclareMathSymbol{k}{\mathalpha}{unspacedletters}{`k}
\DeclareMathSymbol{l}{\mathalpha}{unspacedletters}{`l}
\DeclareMathSymbol{m}{\mathalpha}{unspacedletters}{`m}
\DeclareMathSymbol{n}{\mathalpha}{unspacedletters}{`n}
\DeclareMathSymbol{o}{\mathalpha}{unspacedletters}{`o}
\DeclareMathSymbol{p}{\mathalpha}{unspacedletters}{`p}
\DeclareMathSymbol{q}{\mathalpha}{unspacedletters}{`q}
\DeclareMathSymbol{r}{\mathalpha}{unspacedletters}{`r}
\DeclareMathSymbol{s}{\mathalpha}{unspacedletters}{`s}
\DeclareMathSymbol{t}{\mathalpha}{unspacedletters}{`t}
\DeclareMathSymbol{u}{\mathalpha}{unspacedletters}{`u}
\DeclareMathSymbol{v}{\mathalpha}{unspacedletters}{`v}
\DeclareMathSymbol{w}{\mathalpha}{unspacedletters}{`w}
\DeclareMathSymbol{x}{\mathalpha}{unspacedletters}{`x}
\DeclareMathSymbol{y}{\mathalpha}{unspacedletters}{`y}
\DeclareMathSymbol{z}{\mathalpha}{unspacedletters}{`z}

\begin{document}

$math$ $is$ $difficult$ $qpdb_0+1$

{\boldmath$math$ $is$ $difficult$}

\end{document}

and you get

Ligatures must be disabled; it's easier having T1 as normal font encoding and using OT1 for the math letters.
The two f's just seem to form a ligature.


text:
Q: Is it a good idea to use a common viewModel for my Administration screens? I have MVC administration screens that I use to create/delete/edit and list data. Right now I have many viewModels (edit/delete etc) for each class of model. For example:
public class cityViewModel () {
   public City City { get; set; }
}
public class buildingViewModel () {
   public Building Building { get; set; }
}

What I would like to know is would it be better for me to combine these viewModels into one and use this common model. Something like:
public class adminViewModel () {
   public City City { get; set; }
   public Building Building { get; set; }
}

A: There are no official guidelines from creators of asp.net-mvc about when and how to use ViewModels. But from practical experience, single view model should be created for single view, 1:1. At the beginning, it may seem simpler to use single view model for everything, but as more data and fields appear on view model, you may find yourself explicitely excluding attributes while model-binding, complicated ifs when rendering views, etc. So include in view models only fields needed for its view.
Also, check out How we do MVC – View models by Jimmy Bogard

A: That should be fine. Its quiet common for people to create View pages, by combining multiple partial view pages. And each partial view page is responsible for displaying a particular Model object. In this scenario, like you have done, people break down their model objects into separate small model entities and create a consolidated model object by combining these small entities. Back in view, they will associate each of these small model entities along with ther corresponding partial views. For e.g.
public class cityViewModel () {
   public City City { get; set; }
}
public class buildingViewModel () {
   public Building Building { get; set; }
}

public class adminViewModel () {
   public City City { get; set; }
   public Building Building { get; set; }
}

And then in main view page :
<% Html.RenderPartial(<View Name>,Model.City) %>


text:
Q: Saving single field to two (or multiple) tables - Rails 4 I have three models - Books, Authors and BookAuthors. Books and Authors are in many-to-many
relationship, through BookAuthors.
I want to create a form for entering books into database, but there lies my problem. I'd like for the Author field there to do two things:

*

*If there is no author with entered name in Authors table, save it there.

*Regardless of what happens in 1), it should create an entry in BookAuthors, with book_id, author_id (wether it's freshly created, or
  found an existing one in Authors table), and author_type_id.

I don't know how to make one field refer to multiple tables.

A: I would do this:
#app/controllers/books_controller.rb
def new
    @book = Book.new
    @authors = Author.all
end

def create
    @book = Book.new(book_params)
    @book.save
end

private

def book_params
    require(:book).permit(:name, author_id: [], authors_attributes: [:name])
end

#app/views/books/new.html.erb
<%= form_for @book do |f| %>
    <%= f.text_field :name, placeholder: "Name" %>
    <%= f.collection_select :author_id, Author.all, :id, :name, prompt: "Pick an Author"> %>
    <%= f.fields_for :authors do |author| %>
        <%= author.text_field :name, placeholder: "New Author Name" %>
    <% end %>
<% end %>

Process
This basically gives you a way to select a pre-defined author OR create a new one
If a new one is created, the system will save & reference the new author, whilst an existing author will just show the id of the existing author


text:
Q: Counting longest occurrence of repeated sequence in Python What's the easiest way to count the longest consecutive repeat of a certain character in a string?  For example, the longest consecutive repeat of "b" in the following string:
my_str = "abcdefgfaabbbffbbbbbbfgbb"

would be 6, since other consecutive repeats are shorter (3 and 2, respectively.) How can I do this in Python?

A: Here's my really boring, inefficient, straightforward counting method (interjay's is much better). Note, I wrote this in this little text field, which doesn't have an interpreter, so I haven't tested it, and I may have made a really dumb mistake that a proof-read didn't catch.
my_str = "abcdefgfaabbbffbbbbbbfgbb"
last_char = ""
current_seq_len = 0
max_seq_len = 0

for c in mystr:
    if c == last_char:
        current_seq_len += 1
        if current_seq_len > max_seq_len:
            max_seq_len = current_seq_len
    else:
        current_seq_len = 1
        last_char = c

print(max_seq_len)

A: Using run-length encoding:
import numpy as NP

signal = NP.array([4,5,6,7,3,4,3,5,5,5,5,3,4,2,8,9,0,1,2,8,8,8,0,9,1,3])

px, = NP.where(NP.ediff1d(signal) != 0)
px = NP.r_[(0, px+1, [len(signal)])]
# collect the run-lengths for each unique item in the signal
rx = [ (m, n, signal[m]) for (m, n) in zip(px[:-1], px[1:]) if (n - m) > 1 ]

# get longest:
rx2 = [ (b-a, c) for (a, b, c) in rx ]
rx2.sort(reverse=True)

# returns: [(4, 5), (3, 8)], ie, '5' occurs 4 times consecutively, '8' occurs 3 times consecutively

A: How about a regex example:
import re
my_str = "abcdefgfaabbbffbbbbbbfgbb"
len(max(re.compile("(b+b)*").findall(my_str))) #changed the regex from (b+b) to (b+b)*
# max([len(i) for i in re.compile("(b+b)").findall(my_str)]) also works

Edit, Mine vs. interjays
x=timeit.Timer(stmt='import itertools;my_str = "abcdefgfaabbbffbbbbbbfgbb";max(len(list(y)) for (c,y) in itertools.groupby(my_str) if c=="b")')
x.timeit()
22.759046077728271

x=timeit.Timer(stmt='import re;my_str = "abcdefgfaabbbffbbbbbbfgbb";len(max(re.compile("(b+b)").findall(my_str)))')
x.timeit()
8.4770550727844238

A: Here is a one-liner:
max(len(list(y)) for (c,y) in itertools.groupby(my_str) if c=='b')

Explanation:
itertools.groupby will return groups of consecutive identical characters, along with an iterator for all items in that group. For each such iterator, len(list(y)) will give the number of items in the group. Taking the maximum of that (for the given character) will give the required result.

A: Here is my code, Not that efficient but seems to work:
def LongCons(mystring):
    dictionary = {}
    CurrentCount = 0
    latestchar = ''

    for i in mystring:
        if i == latestchar:
            CurrentCount += 1
            if dictionary.has_key(i):
                if CurrentCount > dictionary[i]:
                    dictionary[i]=CurrentCount
        else:
            CurrentCount = 1
            dictionary.update({i: CurrentCount})
            latestchar = i
    k = max(dictionary, key=dictionary.get)
    print(k, dictionary[k])
    return


text:
Q: TextReader class line count Hello. Recently, I learned about the class TextReader and about how to read a text file.
However, there are some things I don't really understand.
Assuming this is a new object:
TextReader TR = new StreamReader(@"C:\Users\Administrator\Desktop\Text1.txt");

So I want to know how many letters are in there so I'm typing this, right?
Console.WriteLine(TR.ReadToEnd().Length);

However, it returns a number for the first line, it's current, but when I'm adding new lines.
The length increases with or without anything typed.
Assuming it's the \n code which is a new line [maybe I'm wrong but it's making sense]
So i need to decrease the length like that:
current length - line count*2

So I get the right amount of letters in my text file.
The problem is: how do I get the number of lines?
Is there another way to check for the letter's count? If there is, how? Anyway, how do I get the number of Lines in the text file??
Thanks. =)

A: Since .NET framework 2.0 there is a shortcut method ReadAllLines:
var lines = System.IO.File.ReadAllLines("file.txt");
var count = lines.Length;


text:
Q: Merge three different dataframes in Python I want to merge three data frames in Python, the code I have now provide me with some wrong outputs.
This is the first data frame
 df_1
   Year    Month        X_1    Y_1
 0  2021    January     $90     $100
 1  2021    February    NaN     $120
 2  2021    March       $100    $130
 3  2021    April       $110    $140
 4  2021    May         Nan     $150
 5  2019    June        $120    $160

This is the second data frame
  df_2
    Year    Month       X_2     Y_2
  0 2021    January     Nan     $120
  1 2021    February    NaN     $130
  2 2021    March       $80     $140
  3 2021    April       $90     $150
  4 2021    May         Nan     $150
  5 2021    June        $120    $170

This is the third  data frame
   df_3
     Year    Month      X_3     Y_3
  0 2021    January     $110    $150
  1 2021    February    $140    $160
  2 2021    March       $97     $170
  3 2021    April       $90     $180
  4 2021    May         Nan     $190
  5 2021    June        $120    $200

The idea is to combine them into one data frame like this:
 df_combined
    Year    Month       X_1    Y_1    X_2    Y_2    X_3    Y_3
0   2019    January     $90     $100  NaN    $120   $110    $150
1   2019    February    NaN     $120  NaN    $130   $140    $160
2   2019    March       $100    $130  $80    $140   $97     $170
3   2019    April       $110    $140  $90    $150   $90     $180
4   2019    May         Nan     $150  Nan    $150   Nan     $190
5   2019    June        $120    $160  $120   $170   $120    $200

The code I have for now does not give me the correct outcome, only df_3 has to the correct numbers.
 # compile the list of data frames you want to merge
 import functools as ft
 from functools import reduce

 data_frames = [df_1, df_2, df_3]
 df_merged = reduce(lambda  cross, right: pd.merge(cross,right,on=['Year'],
                                                           how='outer'),data_frames)
  #remove superfluous columns
  df_merged.drop(['Month_x', 'Month_y'], axis=1, inplace=True)

A: You can try with
df_1.merge(df_2, how='left', on=['Year', 'Month']).merge(df_3, how='left', on=['Year', 'Month'])

A: One option of probably many is to do
from functools import reduce
import pandas as pd

idx = ["Year", "Month"]
new_df = reduce(pd.DataFrame.join, (i.set_index(idx) for i in dataframes)).reset_index()

or
reduce(lambda x, y: pd.merge(x, y, how="outer", on=["Year", "Month"]), dataframes)


text:
Q: Problema com switch dentro do laço While Gostaria de uma ajuda para solucionar o problema que estou tendo com o switch dentro do laço, ele não finalza nunca, fica num loop eterno. O que devo fazer para solucionar ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
char nome[50], passatempo2, passatempo4, musica2, musica4, filme2, filme4, vicio2, vicio4;
int op, sexo, idade, idade2, idade3, idade4, passatempo, passatempo3, musica, musica3, filme, filme3, auto_declara, auto_declara2, vicio, vicio3;
int ab, valor_aluguel, quartos, banheiros, proximidade, adicional, ba, valor_aluguel2, quartos2, banheiros2, proximidade2, adicional2, profissao, profissao2;

printf("Ola, seja bem-vindo ao Colega de Quarto, como voce se chama ? ");
fflush(stdin);
scanf("%[^\n]s", &nome);
printf("\n");
printf("O que voce deseja, %s ?\n\n", nome);
printf("1 - Anunciar\n\n");
printf("2 - Procurar\n\n");
scanf("%d", &op);

while(op==1)
{
    printf("\n");

    printf("O que voce vai preencher primeiro %s ?\n\n", nome);
    printf("1 - Perfil\n\n");
    printf("2 - Caracteristicas da residencia\n\n");
    scanf("%d", &ba);
    switch(ba)
    {
    case 1:
        printf("\nFormule seu perfil de acordo com as opcoes abaixo: \n");

        printf("\n");

        printf("---Sexo---\n");
        printf("1 - Masculino\n");
        printf("2 - Feminino\n");
        scanf("%d", &sexo);

        printf("\n");

        printf("---Idade---\n");
        printf("1 - 16 a 19 anos\n");
        printf("2 - 20 a 21 anos\n");
        printf("3 - outro\n");
        scanf("%d", &idade3);
        if (idade3 == 3)
        {
            printf("Quantos anos voce tem ?\n");
            scanf("%d", &idade4);
        }

        printf("\n");

        printf("---Profissao---\n");
        printf("1 - Estudante\n");
        printf("2 - Profissional\n");
        printf("3 - Aposentado\n");
        scanf("%d", &profissao);

        printf("\n");

        printf("---Hobby---\n");
        printf("1 - Ler\n");
        printf("2 - Praticar esportes\n");
        printf("3 - Festar\n");
        printf("4 - Outro\n");
        scanf("%d", &passatempo3);
        if (passatempo3 == 4)
        {
            printf("Qual ?\n");
            scanf("%s", &passatempo3);
        }

        printf("\n");

        printf("---Gosto Musical---\n");
        printf("1 - Rock\n");
        printf("2 - Funk\n");
        printf("3 - Sertanejo\n");
        printf("4 - Outro\n");
        scanf("%d", &musica3);
        if (musica3 == 4)
        {
            printf("Qual ?\n");
            scanf("%s", &musica4);
        }

        printf("\n");

        printf("---Tipo de Filme---\n");
        printf("1 - Acao\n");
        printf("2 - Suspense\n");
        printf("3 - Terror\n");;
        printf("4 - Comedia\n");
        printf("5 - Outro\n");
        scanf("%d", &filme3);
        if (filme3 == 5)
        {
            printf("Qual ?\n");
            scanf("%s", &filme4);
        }

        printf("\n");

        printf("---Voce e---\n");
        printf("1 - Caseira(o)\n");
        printf("2 - Festeira(o)\n");
        printf("3 - Um pouco dos dois\n");
        scanf("%d", &auto_declara2);

        printf("\n");

        printf("---Voce faz uso de---\n");
        printf("1 - Alcool\n");
        printf("2 - Cigarro\n");
        printf("3 - Entorpecentes\n");
        printf("4 - Nenhum\n");
        printf("5 - Outro\n");
        scanf("%d", &vicio3);
        if (vicio3 == 5)
        {
            printf("Qual \n");
            scanf("%s", &vicio4);
        }

        break;
        system("cls");

    case 2:
        printf("\n");

        printf("---Valor do aluguel---\n");
        printf("1 - R$ 250 - R$ 300\n");
        printf("2 - R$ 300 - R$ 350\n");
        printf("3 - R$ 350 - R$ 400\n");
        scanf("%d", &valor_aluguel2);

        printf("\n");

        printf("---Quantidade de quartos na casa---\n");
        printf("1 - 1 Quarto\n");
        printf("2 - 2 Quartos\n");
        printf("3 - 3 Quartos\n");
        scanf("%d", &quartos2);

        printf("\n");

        printf("---Quantidade de banheiros na casa---\n");
        printf("1 - 1 Banheiro\n");
        printf("2 - 2 Banheiros\n");
        printf("3 - 3 Banheiros\n");
        scanf("%d", &banheiros2);

        printf("\n");

        printf("---Proximo de----\n");
        printf("1 - Banco, farmacia, ponto de onibus, supermecado\n");
        printf("2 - Banco, ponto de onibus, supermecado\n");
        printf("3 - Farmacia, ponto de onibus, supermecado\n");
        scanf("%d", &proximidade2);

        printf("\n");

        printf("---Adicional---\n");
        printf("1 - Garagem\n");
        printf("2 - Quintal\n");
        printf("3 - Piscina\n");
        printf("4 - Nenhum\n");
        scanf("%d", &adicional2);

        break;
        system("cls");
    }
}

while(op==2)
{
    printf("\n");

    printf("O que voce vai preencher primeiro %s ?\n\n", nome);
    printf("1 - Perfil\n\n");
    printf("2 - Caracteristicas da residencia\n\n");
    scanf("%d", &ab);
    switch(ab)
    {
    case 1:
        printf("\nFormule seu perfil de acordo com as opcoes abaixo: \n");

        printf("\n");

        printf("---Sexo---\n");
        printf("1 - Masculino\n");
        printf("2 - Feminino\n");
        scanf("%d", &sexo);

        printf("\n");

        printf("---Idade---\n");
        printf("1 - 16 a 19 anos\n");
        printf("2 - 20 a 21 anos\n");
        printf("3 - outro\n");
        scanf("%d", &idade);
        if (idade == 3)
        {
            printf("Quantos anos voce tem ?\n");
            scanf("%d", &idade2);
        }

        printf("\n");

        printf("---Profissao---\n");
        printf("1 - Estudante\n");
        printf("2 - Profissional\n");
        printf("3 - Aposentado\n");
        scanf("%d", &profissao2);

        printf("\n");

        printf("---Hobby---\n");
        printf("1 - Ler\n");
        printf("2 - Praticar esportes\n");
        printf("3 - Festar\n");
        printf("4 - Outro\n");
        scanf("%d", &passatempo);
        if (passatempo == 4)
        {
            printf("Qual ?\n");
            scanf("%s", &passatempo2);
        }

        printf("\n");

        printf("---Gosto Musical---\n");
        printf("1 - Rock\n");
        printf("2 - Funk\n");
        printf("3 - Sertanejo\n");
        printf("4 - Outro\n");
        scanf("%d", &musica);
        if (musica == 4)
        {
            printf("Qual ?\n");
            scanf("%s", &musica2);
        }

        printf("\n");

        printf("---Tipo de Filme---\n");
        printf("1 - Acao\n");
        printf("2 - Suspense\n");
        printf("3 - Terror\n");;
        printf("4 - Comedia\n");
        printf("5 - Outro\n");
        scanf("%d", &filme);
        if (filme == 5)
        {
            printf("Qual ?\n");
            scanf("%s", &filme2);
        }

        printf("\n");

        printf("---Voce e---\n");
        printf("1 - Caseira(o)\n");
        printf("2 - Festeira(o)\n");
        printf("3 - Um pouco dos dois\n");
        scanf("%d", &auto_declara);

        printf("\n");

        printf("---Voce faz uso de---\n");
        printf("1 - Alcool\n");
        printf("2 - Cigarro\n");
        printf("3 - Entorpecentes\n");
        printf("4 - Nenhum\n");
        printf("5 - Outro\n");
        scanf("%d", &vicio);
        if (vicio == 5)
        {
            printf("Qual \n");
            scanf("%s", &vicio2);
        }

        break;
        system("cls");

    case 2:
        printf("\n");

        printf("---Valor do aluguel---\n");
        printf("1 - R$ 250 - R$ 300\n");
        printf("2 - R$ 300 - R$ 350\n");
        printf("3 - R$ 350 - R$ 400\n");
        scanf("%d", &valor_aluguel);

        printf("\n");

        printf("---Quantidade de quartos na casa---\n");
        printf("1 - 1 Quarto\n");
        printf("2 - 2 Quartos\n");
        printf("3 - 3 Quartos\n");
        scanf("%d", &quartos);

        printf("\n");

        printf("---Quantidade de banheiros na casa---\n");
        printf("1 - 1 Banheiro\n");
        printf("2 - 2 Banheiros\n");
        printf("3 - 3 Banheiros\n");
        scanf("%d", &banheiros);

        printf("\n");

        printf("---Proximo de----\n");
        printf("1 - Banco, farmacia, ponto de onibus, supermecado\n");
        printf("2 - Banco, ponto de onibus, supermecado\n");
        printf("3 - Farmacia, ponto de onibus, supermecado\n");
        scanf("%d", &proximidade);

        printf("\n");

        printf("---Adicional---\n");
        printf("1 - Garagem\n");
        printf("2 - Quintal\n");
        printf("3 - Piscina\n");
        printf("4 - Nenhum\n");
        scanf("%d", &adicional);

        break;
        system("cls");

    }
}

return 0;
}

A: while(op==1), essa condição aqui vai ser verdadeira sempre e ocasionar o loop infinito se voce digitar 1 para o valor de op e não alterar ele depois ou dar um break para sair do laço.


text:
Q: How to get output from subprocess.Popen(). proc.stdout.readline() blocks, no data prints out I want output from execute Test_Pipe.py, I tried following code on Linux but it did not work.
Test_Pipe.py
import time
while True :
    print "Someting ..."
    time.sleep(.1)

Caller.py
import subprocess as subp
import time

proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin=subp.PIPE)

while True :
    data = proc.stdout.readline() #block / wait
    print data
    time.sleep(.1)

The line proc.stdout.readline() was blocked, so no data prints out.

A: You obviously can use subprocess.communicate but I think you are looking for real time input and output.
readline was blocked because the process is probably waiting on your input. You can read character by character to overcome this like the following:
import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

A: Nadia's snippet does work but calling read with a 1 byte buffer is highly unrecommended. The better way to do this would be to set the stdout file descriptor to nonblocking using fcntl
fcntl.fcntl(
    proc.stdout.fileno(),
    fcntl.F_SETFL,
    fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
)

and then using select to test if the data is ready
while proc.poll() == None:
    readx = select.select([proc.stdout.fileno()], [], [])[0]
    if readx:
        chunk = proc.stdout.read()
        print chunk

She was correct in that your problem must be different from what you posted as Caller.py and Test_Pipe.py do work as provided.

*

*https://derrickpetzold.com/p/capturing-output-from-ffmpeg-python/

A: Test_Pipe.py buffers its stdout by default so proc in Caller.py doesn't see any output until the child's buffer is full (if the buffer size is 8KB then it takes around a minute to fill Test_Pipe.py's stdout buffer).
To make the output unbuffered (line-buffered for text streams) you could pass -u flag to the child Python script. It allows to read subprocess' output line by line in "real-time":
import sys
from subprocess import Popen, PIPE

proc = Popen([sys.executable, "-u", "Test_Pipe.py"], stdout=PIPE, bufsize=1)
for line in iter(proc.stdout.readline, b''):
    print line,
proc.communicate()

See links in Python: read streaming input from subprocess.communicate() on how to solve the block-buffering issue for non-Python child processes.

A: To avoid the many problems that can always arise with buffering for tasks such as "getting the subprocess's output to the main process in real time", I always recommend using pexpect for all non-Windows platform, wexpect on Windows, instead of subprocess, when such tasks are desired.


text:
Q: Loop to include different folders and patterns I have this code very inefficient and would like to make it better.
Each df is a list of files that match a certain pattern as described by term6.
Can someone show me the best method to make this is into efficient and easily understandable code? Would a loop be best?
term6 <- c("Casos de Malaria|MALARIA8|Casos según Entidades")
term7 <- c("Casos según Entidades|MALARIA8")
term8 <- c("Distrito Capital10|hasta")
term9 <- c("NA12")
term10 <- c("hasta la semana|NA12|NA16|Entidades Federales16")
term11 <- c("NA19|Cuadro|Malaria16")

df6 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2006", pattern = term6, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
df7 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2007", pattern = term7, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
df8 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2008", pattern = term8, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
df9 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2009", pattern = term9, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
df10 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2010", pattern = term10, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
df11 <- list.files(path = "J:\\GBD2017\\Venezuela\\xlsx\\2011", pattern = term11, recursive = FALSE, full.names = FALSE, ignore.case = TRUE)

A: c(
  "Casos de Malaria|MALARIA8|Casos según Entidades",
  "Casos según Entidades|MALARIA8",
  "Distrito Capital10|hasta",
  "NA12",
  "hasta la semana|NA12|NA16|Entidades Federales16",
  "NA19|Cuadro|Malaria16"
) -> terms

c(
  "J:\\GBD2017\\Venezuela\\xlsx\\2006",
  "J:\\GBD2017\\Venezuela\\xlsx\\2007",
  "J:\\GBD2017\\Venezuela\\xlsx\\2008",
  "J:\\GBD2017\\Venezuela\\xlsx\\2009",
  "J:\\GBD2017\\Venezuela\\xlsx\\2010",
  "J:\\GBD2017\\Venezuela\\xlsx\\2011"
) -> paths

unlist(lapply(seq_along(paths), function(.i) {
  list.files(
    path = paths[.i],
    pattern = terms[.i],
    recursive = FALSE,
    full.names = FALSE, # generally not a good idea; I always set this to TRUE
    ignore.case = TRUE
  )
}), use.names = FALSE)

However, I'd recommend keeping the terms and paths together. That way you can have a TSV (tab-separated file vs comma) file  with the path search metadata in it and also ensure the length equality constraint for each vector.
Its just as easy to use:
data.frame(
  term = c(
    "Casos de Malaria|MALARIA8|Casos según Entidades",
    "Casos según Entidades|MALARIA8",
    "Distrito Capital10|hasta",
    "NA12",
    "hasta la semana|NA12|NA16|Entidades Federales16",
    "NA19|Cuadro|Malaria16"
  ),
  path = c(
    "J:\\GBD2017\\Venezuela\\xlsx\\2006",
    "J:\\GBD2017\\Venezuela\\xlsx\\2007",
    "J:\\GBD2017\\Venezuela\\xlsx\\2008",
    "J:\\GBD2017\\Venezuela\\xlsx\\2009",
    "J:\\GBD2017\\Venezuela\\xlsx\\2010",
    "J:\\GBD2017\\Venezuela\\xlsx\\2011"
  ),
  stringsAsFactors = FALSE
)-> file_search_df

unlist(lapply(1:nrow(file_search_df), function(.i) {
  list.files(
    path = file_search_df$path[.i],
    pattern = file_search_df$term[.i],
    recursive = FALSE,
    full.names = FALSE, # generally not a good idea; I always set this to TRUE
    ignore.case = TRUE
  )
}), use.names = FALSE)

And, if you use the TSV approach, even more compact:
file_search_df <- read.csv("path-to-metadata-file.tsv", sep = "\t", stringsAsFactors=FALSE)

unlist(lapply(1:nrow(file_search_df), function(.i) {
  list.files(
    path = file_search_df$path[.i],
    pattern = file_search_df$term[.i],
    recursive = FALSE,
    full.names = FALSE, # generally not a good idea; I always set this to TRUE
    ignore.case = TRUE
  )
}), use.names = FALSE)

A: The following should tidy up your code quite a bit:
#myfilepaths <- paste0(rep(getwd(),6))
myfilepaths <-  c(paste0('J:\\GBD2017\\Venezuela\\xlsx\\',2006:2011))
allterms <- c("test","Casos según Entidades|MALARIA8","Distrito Capital10|hasta", "NA12", "hasta la semana|NA12|NA16|Entidades Federales16", "NA19|Cuadro|Malaria16")
length(myfilepaths)==length(allterms)
searchtree <- data.frame(myfilepaths, allterms, stringsAsFactors = F)
result <- apply(searchtree, 1, function(x) list.files(x["myfilepaths"], pattern=x["allterms"], recursive = FALSE, full.names = FALSE, ignore.case = TRUE))

The idea is to 1) generate your folder list by pasting the year range to the root, then to put all combinations of paths and patterns to search into a neat dataframe, and 2) to apply the list.files function to this df. This gives you a list of 6 elements.
> result
[[1]]
[1] "ctest.R"       "ExcelTest.csv" "test.csv"      "test.xls"

[[2]]
character(0)

[[3]]
character(0)

[[4]]
character(0)

[[5]]
character(0)

[[6]]
character(0)

Or you could also use a loop like so, yielding exactly the same:
result <- list()
for(i in 1:length(allterms)) {
  result[[i]] <- list.files(searchtree[i,"myfilepaths"], pattern=searchtree[i,"allterms"], recursive = FALSE, full.names = FALSE, ignore.case = TRUE)
}
result

edit: if you have more than one pattern per folder, for example if you want to search the 2006 folder for both "test" and "Casos según Entidades|MALARIA8", you should create the searchtree data.frame like so:
searchtree <- data.frame(myfilepaths[c(1,1:6)], allterms[c(1:2,2:6)], stringsAsFactors = F)
colnames(searchtree) <- c("myfilepaths", "allterms")

The function will search any pattern that is on the same row as any folder.
searchtree
                     myfilepaths                                        allterms
1 J:\\GBD2017\\Venezuela\\xlsx\\2006                                            test
2 J:\\GBD2017\\Venezuela\\xlsx\\2006                  Casos según Entidades|MALARIA8
3 J:\\GBD2017\\Venezuela\\xlsx\\2007                  Casos según Entidades|MALARIA8
4 J:\\GBD2017\\Venezuela\\xlsx\\2008                        Distrito Capital10|hasta
5 J:\\GBD2017\\Venezuela\\xlsx\\2009                                            NA12
6 J:\\GBD2017\\Venezuela\\xlsx\\2010 hasta la semana|NA12|NA16|Entidades Federales16
7 J:\\GBD2017\\Venezuela\\xlsx\\2011                           NA19|Cuadro|Malaria16

Or you could manage it manually:
allfolders <- c("folder1","folder1", "folder2")
allpatterns <- c("pattern1", "pattern2", "pattern2")
searchtree <- data.frame(myfilepaths, allterms, stringsAsFactors = F)
searchtree

  myfilepaths allterms
1     folder1 pattern1
2     folder1 pattern2
3     folder2 pattern2


text:
Q: using alter to add column with specific definition how do i add a column to an existing table with a given definition. For example i have a table called employee with column called hire_date. Now using alter and only alter, i want to add a column called tenure which contains the difference between (hire_date and 14-JULY-2012). this is what ive tried
alter table employee add(tenure numeric(10) where tenure=(select to_date(
'14-JULY-2012')-HIRE_DATE from employee));

A: Starting from 11g, this should work:
ALTER TABLE employee
 ADD tenure GENERATED ALWAYS
   AS (TO_DATE('20120714','YYYYMMDD') - hire_date) VIRTUAL

A: Since the new column can be derived from an existing column, I would not add it to the table.  It's hard work to keep a derived column consistent, and there are better alternatives.
Instead, you could create a view that adds the column:
create view ViewName as
select  hire_date
,       hire_date - TO_DATE('20120714','YYYYMMDD') as DaysSinceJuly14th
,       ... other columns ...
from    employees

Or you could do the calculation on the fly in any select statement:
select  hire_date - TO_DATE('20120714','YYYYMMDD') as DaysSinceJuly14th
from    employees
where   name = 'Jones'


text:
Q: Searching string while looping through $_SESSION variables Is there a better way to search through $_SESSION variables (or any array) for a particular string than:
foreach($_SESSION as $k => $v){
    if(strstr($k, 'p_')){

Thanks.
edit: My keys will look similar to:
p_123
p_456
i_123
...

A: If your $_SESSION structure must stay "as is", IMO it is Ok.
However if all 'p_' elements could go under an array index like $_SESSION['p'] = array('key1' => 'val1', ...), you could retrieve all 'p' elements at once.
BTW this is only micro optimization, go with the structure you're fine with.
EDIT: Just be careful with strstr(): if one day you must store keys like i_123_p_456 into your $_SESSION array, you should switch to if (strpos($k, 'p_') === 0).

A: I'm adding another answer as I'm taking a completely different approach.
If you're going to do this a lot, you could consider using filters.
function pprefix($var) {
  return(strstr($var, 'p_'));
}

$filtered = array_filter(array_keys($_SESSION), "pprefix");

foreach($fildered as $k) {
  echo("$k => " . $_SESSION[$k]);
}

A: try this:
if (array_key_exists('p_', $_SESSION)) {
  echo($_SESSION['p_']);
}

Or, if you only knows part of the name of the key (like the beggining), I'd use the array_keys() instead $k => $v, like so:
foreach(array_keys($_SESSION) as $k) {
  if(strstr($k, 'p_')){
    // do something.
  }
}


text:
Q: Save large text file without using too much memory I have a model that creates a KML file. I treat that KML as a string and then forward that to mailer which then delivers it:
def write_kml(coords3d, time)
  kml = String.new
    kml << header
    coords3d.each do |coords|
      coordinates = String.new
      coords.each do |coord|
        lat = coord[0].to_f
        lng = coord[1].to_f
        coordinates << "#{lng}" + "," "#{lat}" + ",0 "
        kml <<  polygon(coordinates)
      end
      end

    kml <<  footer
  kml

end

This gets used here:
  CsvMailer.kml_send(kml,time, mode, email).deliver

Mailer:
  def kml_send(kml, time, mode, email)
    @time = (time / 60).to_i
    @mode = mode
    gen_time = Time.now
    file_name = gen_time.strftime('%Y-%m-%d %H:%M:%S') + " #{@mode.to_s}" + " #{@time.to_s}(mins)"
    attachments[file_name + '(KML).kml'] = { mime_type: 'text/kml', content: kml}
    mail to: email, subject: ' KML Filem'
  end

It takes up a huge amount of memory. Some of these files are quite large (200MB), so on Heroku for example, they take up too much space.
I had some ideas using S3, but I would need to create this file to begin with, so it would still use the memory. Can I write straight to S3 without using memory?

A: You can do this with s3 multipart uploads, since they don't require you to know the file size upfront.
Parts have to be at least 5MB in size, so the easiest way to use this is to write your data to an in memory buffer and upload the part to s3 every time you get past 5MB. There's a limit of 10000 parts for an upload, so if your file size is going to be > 50GB then you'd need to know that ahead of time so that you can make the parts bigger.
Using the fog library, that would look a little like
def upload_chunk connection, upload_id, chunk, index
    md5 = Base64.encode64(Digest::MD5.digest(chunk)).strip
    connection.upload_part('bucket', 'a_key', upload_id, chunk_index, chunk, 'Content-MD5' => md5 )
end

connection = Fog::Storage::AWS.new(:aws_access_key_id => '...', :region => '...', :aws_secret_access_key => '...'
upload_id = connection.initiate_multipart_upload('bucket', 'a_key').body['UploadId']
chunk_index = 1

kml = String.new
kml << header
coords3d.each do |coords|
  #append to kml
  if kml.bytesize > 5 * 1024 * 1024
    upload_chunk connection, upload_id, kml, chunk_index
    chunk_index += 1
    kml = ''
  end
end
upload_chunk connection, upload_id, kml, chunk_index
#when you've uploaded all the chunks
connection.complete_multipart_upload('bucket', 'a_key', upload_id)

You could probably come up with something neater if you created an uploader class to wrap the buffer and stuck all the s3 logic in there. Then your kml code doesn't have to know whether it has an actual string or a string that flushes to s3 periodically


text:
Q: Efficient nested regular expressions Is there an efficient and general way to match regular expressions as well as compositions based on them ?
For instance, if I want matches for each of those 3 strings: "I like", "cats", and "I like .* cats", I can obviously make 3 separate queries.
Is there a more efficient way to do this (preferably in python) ?

A: patterns = ["I like", "cats", "I like .* cats"]

for stuff in patterns:
    re.search(r'%s' % stuff, string_to_search, flags)

More efficient, stops at the first match ordering patterns by lenght:
for stuff in sorted(patterns,key = len):
    if re.search(r'%s' % stuff, string_to_search):
        break


text:
Q: Material UI how to justify content inside FormControlLabel I'm trying to align the label and the radio button inside a FormControlLabel component so that the label consumes the same width regardless of the text inside of it. Here's what it currently looks like:

Here's the code I have:
<RadioGroup row>

    <FormControl>
      <FormControlLabel
        value={first_column_day}
        control={
          <Radio
            value={first_column_day}
          />
        }
        label={<Typography variant={"subtitle2"}>{first_column_day}</Typography>}
        labelPlacement="start"
      />
    </FormControl>

    <FormControl>
      <FormControlLabel
        value={second_column_day}
        control={
          <Radio
            value={second_column_day}
          />
        }
        label={<Typography variant={"subtitle2"}>{second_column_day}</Typography>}
        labelPlacement="start"
      />
    </FormControl>

</RadioGroup>

I tried adding justifyContent for FormControl:
<FormControl style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>

I also tried wrapping Typography in a div:

<Typography variant={"subtitle2"}>{first_column_day}</Typography>

But those didn't work. So far the only thing that worked is adding a fixed width to the Typography like so:
<Typography style={{ width: 75 }} variant={"subtitle2"}>{first_column_day}</Typography>

But I don't really like doing that because it's not responsive. Setting the width to 100% doesn't work either.

A: You can add min-width to FormControlLabel component if you need alignment like below without losing responsiveness  -

Working Sandbox here - https://codesandbox.io/s/material-demo-3u8i2?file=/demo.js