text:
Q: SSL not fully trusted on ports 993 and 587 of our mail server by Zendesk We have our own mail server running using iRedMail on Apache.  It's been working for us for a number of years and there haven't been any issues with the SSL until now.  One of our clients is trying to connect their smtp credentials to their Zendesk account and Zendesk is rejecting the connection because it doesn't fully trust the SSL.  Zendesk support sent us to https://www.sslshopper.com/ssl-checker.html.  When we test the domain on there without any ports it gets a full pass.  If we put a ":587" or ":993" on the test we get the following error:

The certificate is not trusted in all web browsers. You may need to install an Intermediate/chain certificate to link it to a trusted root certificate. Learn more about this error. You can fix this by following Sectigo's Certificate Installation Instructions for your server platform (use these instructions for InstantSSL). Pay attention to the parts about Intermediate certificates.

We've ran tests on the ssl through ssllabs as well and both the imap. and smtp. addresses get A+ grades.  Does anybody have any ideas about how to get this to work?  Are there any port settings that we may not be thinking of?


text:
Q: Cut down on If statements VBA So right now I'm making an interactive graph in excel, where the user can select a variety of options via drop down menus. For example, if the user wants to change the color of one of the charts to red, they select the drop down menu for that chart, select red, and then the chart turns red. I've written macros to do this, but it composes of multiple if statements for each color. Is there a good way to cut down on all of these if statements? Current code works and is below. F16 is the where the drop down menu is in excel that indicates what color will change. also am using excel 2010
If Target = Range("F16") Then
    'Checks to see if the color is being changed for the Elevation Graph
    If Worksheets("Reference_Sheet").Range("H9").Value = "Black" Then
        Call Black_Line_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Tan" Then
        Call Tan_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Dark Blue" Then
        Call Dark_Blue_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Yellow" Then
        Call Yellow_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Olive Green" Then
        Call Olive_Green_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Green" Then
        Call Light_Green_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Green" Then
        Call Green_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Light Blue" Then
     Call Light_Blue_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Aqua" Then
        Call Aqua_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Orange" Then
        Call Theme_Orange_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Orange" Then
        Call Standard_Orange_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Purple" Then
        Call Standard_Purple_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Purple" Then
        Call Theme_Purple_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Blue" Then
        Call Theme_Blue_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Blue" Then
        Call Standard_Blue_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Standard Red" Then
        Call Standard_Red_ELE
    ElseIf Worksheets("Reference_Sheet").Range("H9").Value = "Theme Red" Then
        Call Theme_Red_ELE
        End if
End if

A: Time for some mapping! Reference the VBScript runtime and create a new Scripting.Dictionary object.
Dim colorActions As Dictionary
Set colorActions = New Dictionary

Or, don't reference the VBScript runtime and use late-binding to create the dictionary instead:
Dim colorActions As Object
Set colorActions = CreateObject("Scripting.Dictionary")

Next, map each value to a string representing the name of the procedure you want to run:
With colorActions
    .Add "Black", "Black_Line_ELE"
    .Add "Tan", "Tan_ELE"
    .Add "Dark Blue", "Dark_Blue_ELE"
    '...
    .Add "Theme Red", "Theme_Red_ELE"
End With

I would make the colorActions dictionary live at module-level, and then put the code to populate it at startup - doing that in the SheetChanged handler would be doing much more work than needed, for no reason: you don't need to recreate it everytime F16 changes!
Now assuming these methods are all public subs, you can use Application.Run to execute the named procedure mapped to the value of H9:
Dim key As String
key = Worksheets("Reference_Sheet").Range("H9").Value

If colorActions.Exists(key) Then
    Application.Run colorActions(key)
Else
    MsgBox "Not supported."
End If

This will scale much better than a Select Case block, and makes only 1 single place that actually executes something. And when you need to add a supported color/method, you just add a dictionary entry and you're done.
That said Call is useless clutter, you can safely omit it.

I also suspect that all these separate methods are really all doing the same thing and could all be removed and replaced with a single parameterized version - but there's no way of telling for sure without seeing your actual code... if you really want to clean up your code, bring it to Code Review and give as much context code as possible!

A: As @findwindow has stated in the comments, you may benefit from a Select statement. Consider the example below: -
If Target = Range("F16") Then
   'Checks to see if the color is being changed for the Elevation Graph
   Select Case Worksheets("Reference_Sheet").Range("H9").Value

       Case "Black"
           Call Black_Line_ELE

       Case "Tan"
            Call Tan_ELE

        '... [Your other options] ...

    End Select
End if

A: If Target = Range("F16") Then
    Select Case Worksheets("Reference_Sheet").Range("H9").Value
         Case "Black"
             Call Black_Line_ELE
         Case "Tan"
             Call Tan_ELE
         Case 'Do this for all cases
    End Select
End If

Look here for more details
Should make the structure of your code clearer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to Convert Functional Component to Class Component Typescript

I'm trying to convert FC to CC and face problem. How do I substitute useHistory? is withRouter a good option? If yes then should I import it from react-router, or react-router-dom.
What about dispatch and Redux in general? Spent a lot of time and could not find good example of Redux.
NOTE: I'm using Typescript, so all code should be written accord to its conventions.


text:
Q: Critical point and stability exercice We are given the system:
$$x' = -y ( y  ^{2} - x^{2})$$
$$y' = x ( y  ^{2} - x^{2})$$
How we can find the critical points of this problem?
Additionally, how we can study the stability of first and second bisector?

A: To find the critical points, you want to find the points where $x'$ and $y'$ are simultaneously equal to zero.
We are given:
$$f(x, y) = x' = -y ( y  ^{2} - x^{2})$$
$$g(x, y) = y' = x ( y  ^{2} - x^{2})$$
When we simultaneously set and solve $x' = 0$ and $y' = 0$, we get:
$$(x,y) = (0,0), x = y, x = -y$$
So, now we have a zero critical point, and a first and second bisector as you call them.
Next, we find the Jacobian matrix of the system as:
$$\displaystyle J = \begin{bmatrix} \frac{\partial f}{\partial x} & \frac{\partial f}{\partial y}\\\frac{\partial g}{\partial x} & \frac{\partial g}{\partial y}\end{bmatrix} = \begin{bmatrix}2xy & -3y^2+x^2\\y^2-3x^2 & 2xy\end{bmatrix}$$
Now, evaluate the eigenvalues of Jacobian matrix of those three critical point (point and two bisectors). What sort of solution do you get when you vary the values for those bisectors?
It looks menacing, but you will that for different $x = y, x = - y$, the Jacobian reveals a phase portrait that is split along those bisectors. For example:


text:
Q: iOS 7 dynamically change speech bubble color in messages Trying to figure out how to incorporate this effect into my app.
It is essentially the adjustment of the colors in the speech bubbles when the user scrolls, as seen in the messages app in iOS 7.
The bubbles close to the top of the screen are light blue, the bubbles towards the bottom are darker.

A: Create a gradient on your views. Set the start and end color's intensity according to the view's position in the scroll view's superview (using convertRect:toView:). As your scrollview scrolls, update the visible bubbles' background colors according to their current position. An optimization is to only update the views which are visible. Using a table or collection view can help you with that. It's a simple yet effective effect.


text:
Q: How to add multiple cmake target to android ndk project So I started an android ndk project, and added a new module another_lib in addition to the native-lib that comes with the new project, I have a cmakelists.txt file in as shown and the content is:
cmake_minimum_required(VERSION 3.4.1)
add_subdirectory(another_lib)
add_subdirectory(native_lib)

and for each subdirectory, i have defined a build target. then in my build.gradle i have
   externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
        }
    }

However, when I built the project, it only builts native_lib. Did i miss anything to add my own module to build?

A: It is the issue that android cannot create static lib unless it is added in the build.gradle file, for me I need to add line:
externalNativeBuild {
    cmake {
        ...
        targets "native-lib", "anotherlib"
    }
}

Refer to here for more details on why android studio cannot build static lib
How to create a static library (.a file) in Android Studio 3.2 with CMake


text:
Q: Incremental SQL dump of mysql I am using MySql as a development database as well as on the server where my website is hosted. Now everday I punch new data into the database and save it as SQL dump using SQLyog. But when it comes to updating the data for that day on the server Mysql database I have to truncate the tables and then insert the new data. Which leads  to following concerns :

*

*Data being 5000+ rows in each table the insert query fails to execute. So I have to insert data in batches of 2000 rows.

*For the time when I truncate a particular table and the new data is not yet inserted any request on the website will result in no data at all. Which is 5 to 7 minutes.

*Everyday only around 300 rows are added into each table but I have to insert the complete data for a table.
Please sugges how can I take incremental backup of my local MySql database so I can update the same on the server and not the complete data till that day.

A: If it's a simple development environment, I actually wouldn't recommend going the incremental dump route.  AFAIK, mysql doesn't provide a built in way to do this.  If you really want to do this,  you could use the binary log. Using the binary log to replay the statements from the following day. Internally, MySQL uses the binary log for replication.  (Disclaimer, I've never done this before, and I'm pretty sure you'll run into problems if you've inserted or deleted from your development copy.)
Alternatively, you could just create another database every, import the dump into that, and reconfigure your app to use the new db.  Once you've reconfigured, drop yesterday's DB, and you're good.  No downtime...

A: Why don't you just use command line dump and restore as follows -
To create dump -

mysql -u root -h localhost -p db_name > db_name_dump_version.sql

This will dump the DB to the file db_name_dump_version.sql
Then to restore from it -

mysql -u root -h localhost -p db_name < db_name_dump_version.sql

Command line mysql is blitzingly fast so you won't have to wait more than 10 seconds for even a million row DB.


text:
Q: Questions about Android function parameters and new Folder Path recognition As the title states.

*

*Q: What kind of function parametere should be passed for the R.id ?

For example:
public void setExample(parameter){
  Button br = (Button) findViewById(R.id.**parameter**)
}

*I wanted to put all the views in a certain folder, now for some reason:
setContentView(R.newFolder)
R. - doesn't recognize new Folder, in which way new Folder can be created so that the path is recognized by R ?


text:
Q: Erro de Exceção "' ', hexadecimal value 0x1F, is an invalid character. Line 1, position 1" Tenho um aplicativo feito em C# para mostrar o cardápio do restaurante universitário da minha universidade, o qual pega as informações por meio de um XML. O aplicativo permite a consulta individual de cada refeição (café da manhã, almoço e jantar). Ocorre que em momentos aleatórios do dia, quando alguma das consultas é solicitada, ocorre um erro e o aplicativo fecha bruscamente. Verificando com um debug, percebi que aparece a seguinte mensagem:
Erro

" ' ', hexadecimal value 0x1F, is an invalid character. Line 1,
  position 1".

Estou usando agora um bloco try/catch para ver se consigo evitar o fechamento brusco, mas não consegui ainda.

*

*Alguém poderia me ajudar a dar o devido tratamento a este erro?

*Como posso resolver esse problema, pelo menos para evitar o fechamento brusco da aplicação?
O meu bloco try/catch por enquanto fiz apenas isso, para tentar evitar que ele feche. O método LoadDataHoje() está como um loop, para que ele fique executando e tente conseguir acessar a informação.
catch (System.ArgumentException erro)
            {
                LoadDataHoje();
                contador++;
                if(contador == 5)
                {
                    throw new ArgumentException();
                    MessageBox.Show("O servidor está retornando um erro, tente novamente daqui a pouco :/","Erro no servidor", MessageBoxButton.OK);
                    this.NavigationService.Navigate(new Uri("/Src/Pages/MainPage.xaml", UriKind.Relative));
                }
            }

Verifiquei agora pelo debug que quando ele cai nessa exceção, ao final ele mostra outro erro, como na imagem abaixo.

Obrigado.

A: Para evitar o fechamento brusco altere o seu código assim:
try
{
     ...
}
catch (System.ArgumentException erro)
{
    LoadDataHoje();
    contador++;
    if (contador == 5)
    {
        // throw new ArgumentException(); Remova isso!!!-> Esse cara está fechando a aplicação.
        MessageBox.Show("O servidor está retornando um erro, tente novamente daqui a pouco :/", "Erro no servidor", MessageBoxButton.OK);
        this.NavigationService.Navigate(new Uri("/Src/Pages/MainPage.xaml", UriKind.Relative));
    }
}
catch(Exception ex)//Por precausão
{
     ...
}

Quanto a função XDocument.Parse(e.Result), o erro pode ser causado por causa da codificação do texto.


text:
Q: give runtime href of a link that doesn't set in source code How to give href of a link that set in runtime not in html source code:
there is a download link in a webpage:
...
but in runtime that link has a href:
...
I searched in html source and find that it use jquery aes to encrypt and set the link.
How can I access to runtime source code by PHP? file_get_contents() give me source html code not runtime code

A: with use of PHP
<a id="downloadLink" href="<?php echo $url?>" download>

with use of Jquery

I hope the above code helps

A: Simply do it like the code below. Initialize the variable ($url) to a url value, then use it to set href="" value.
<?php

$url =  "http://www.example.com/download/s/eyJjdCI6IkFpc003OERmME1uS3dhR1BQcXg1ckE9PSIsIml2IjoiNzg0OGI5NWRmMmRjZDg0ZjFlMjVjYTM3MjY1MjdjMTUiLCJzIjoiYjU1NTIyN2Q2MmJiODAyMSJ9.mp3";

?>

<a id="downloadLink" href="<?php echo $url; ?>">Text To Show


text:
Q: Changed files on github and now cant push So I have my git repository for a project I am working on.
I set up the settings.py file for the first commit like how I wanted it on the server and then I ran git update-index --assume-unchanged mysite/settings.py as I didnt want any changes to be pushed to the server, as the settings are different for production. Now, I wanted to add some new settings, so I added them in my browser, saved them, and git pulled them onto my server.
Now when I am trying to push new code from my laptop I get this error:
To https://github.com/badger1661/smart-survey.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/badger1661/smart-survey.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

How can I fix this. I want to keep the changes to the settings I made on github, but dont want them on my laptop.


text:
Q: Creating Assignment rules via APEX Code Is there any way possible that I can create a new assignment rule on lead via Apex code. If possible can someone help me with the code snippet for the same.
Also is it possible to transfer assigment rule via Unmanaged Package from one org to another?

A: @happy
I want to make below points:
1) Assignment rules are used to update ownerid field. We can always have this solution with clicks instead of code.
2) Now coming to your requirement we can easily create this in apex class, trigger.
Taking an example of case assignment below:
for (case c : []Select Id,origin from case]){
    if(c.origin==phone){
    c.ownerid='User id or Queue Id';
    }
    else if(c.origin==web){
    c.ownerid='User id or Queue Id';
    }
}

However, if you want to fire assignment rules from apex we have to use Dmloptions class and set assignment header.
    //Fetching the assignment rules on case
AssignmentRule AR = new AssignmentRule();
AR = [select id from AssignmentRule where SobjectType = 'Case' and Active = true limit 1];

//Creating the DMLOptions for "Assign using active assignment rules" checkbox
Database.DMLOptions dmlOpts = new Database.DMLOptions();
dmlOpts.assignmentRuleHeader.assignmentRuleId= AR.id;

Case newCase = new Case(Status = 'New') ;
//Setting the DMLOption on Case instance
newCase.setOptions(dmlOpts);
insert newCase ;

However, from your question it looks like you want to create metadata and save in salesforce. For this go through metadata api guide.
Now if you want to create a assignment rule via metadata api
please check the below link:
https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_assignmentrule.htm
Here you can find how to create metadata using apex:
http://andyinthecloud.com/2013/10/27/introduction-to-calling-the-metadata-api-from-apex/

A: This will help you all much more
http://developer.force.com/cookbook/recipe/running-case-assignment-rules-from-apex


text:
Q: Which bean can be termed highest in terms of performance? Stateful Session bean,MDB,CMP or BMP??
Though I am not sure how we can compare the performance against each other, I would like to know which is best in performance


text:
Q: Python - Find similar things in all dictionary values Suppose I have a dictionary:
mydict = {'first': ['cat', 'dog'], 'second': ['fish', 'cat']}

Is there something that will return 'cat'?
I'm using Python 2.7.

A: See the documentation for set.intersection(), it very useful for finding common elements in sequences, and you can use either the method or the syntax a & b where both a and b are sets.
Here is a concise way to do what you want:
>>> set.intersection(*map(set, mydict.values()))
set(['cat'])

Or a potentially more readable solution that uses reduce():
reduce(set.intersection, map(set, mydict.values()))

A: mydict = {'first': ['cat', 'dog'], 'second': ['fish', 'cat']}
def similar(x,y):return [c for c in set(x).intersection(set(y))]
reduce(similar, mydict.values())

A: >>> mydict = {'first': ['cat', 'dog'], 'second': ['fish', 'cat']}
>>> from collections import Counter
>>> c = Counter(i for v in mydict.values() for i in v)
>>> print [i for i in c if c[i]==len(mydict)]
['cat']

A: Just another way:
first = True
for x in mydict:
    if first:
        common = set(mydict[x])
        first = False
    else:
        common = common & set(mydict[x])
print common

A: l2=[x for x in mydict.values()]
dic = {}
for e in l2:
    for i in e:
        dic.setdefault(i,0)
        dic[i]+=1
for e in dic.items():
    if len(l2) == e[1]:
        print e[0] # cat


text:
Q: Page for all items with a catalog price rule active I have 5 catalog price rules that affects 3-4 categories each, they are applied one each day of the week (say: on monday we have cat 3 and 6 on sale, on tuesday it's cat 5, on wednesday it's 7, 10, 11...) on my catalog and I want to have a "SALE" page that will show all items with said discount. I've searched and found not many options for this.
I was thinking maybe I want to create a dynamic category using firegento (https://github.com/firegento/firegento-dynamiccategory/blob/develop/README.md) but I'm not sure what attribute/values should it look for that affect the price rules? I'd like to avoid having to create a template for this manually, hence why I'm looking into the category option, as it would maintain the look and feel of the website with it's layered navigation and all

A: Not 100% sure if this what you need, but I can recommend you this free extension: https://github.com/tzyganu/rule-products
This extension allows you to create separate product lists based on rules (with filters, sorting and everything a category has), kind of similar to the extension you mentioned, with the difference that you don't need to create categories.
But one additional thing it does, is to add a button on the catalog rule edit page that will allow you to clone the catalog rule to a list of products.

This way when you change something to a rule you don't need to replicate everything on a different screen to make your product list. You can click the button and it creates the list automatically.

A: Why not just filter by Product Category? Or better yet, add a new attribute to the relevant attribute set for something like "promo_day", with a value of M-F for example, and then in the Product Grid in the admin, bulk assign all of the products in the relevant category, save, and repeat until you've bulk assigned your products to a specific "promo_day" attribute.
Next, setup catalog price rules and/or shopping cart price rules based on that product attribute corresponding to a particular day of the week for each of your products. Here's a great extension to make that process a bit simpler: https://amasty.com/special-promotions-for-magento-2.html#screenshots
Tons of relevant features with Special Promotions for Magento 2 by Amasty that could solve help achieve your goal, possibly combined with a few other config options from additional modules.

Lastly for the "Sale" page, you can use Magento's Categories and Subcategories to depending on which theme you have configured currently. Happy to help more if it earns me the bounty here :)


text:
Q: Concurrent functions running in separate process using pygame and multiprocessing Suppose we want to drive an autonomous car by predicting image labels from a previous set of images and labels collected (A Machine Learning application). For this task, the car is connected via bluetooth serial (rfcomm) to the Host Computer (A PC with *NIX) and the images are streamed directly from an Android phone using IP Webcam, meanwhile, the PC is running a program that links this two functions, displaying the captured images in a drawing environment created by pygame, and sending the instructions back to the car using serial.
At the moment, I've tried to implement those processes using the multiprocessing module, the seemed to work, but when I execute the client, the drawing function (if __name__ == '__main__') works after the getKeyPress() function ends.
The question is: It is possible to parallelize or synchronize the drawing fuinction enclosed within the if __name__ == '__main__' with the process declared in getKyPress(), such that the program works in two independent processes?
Here's the implemented code so far:
import urllib
import time
import os
import sys
import serial
import signal
import multiprocessing
import numpy as np
import scipy
import scipy.io as sio
import matplotlib.image as mpimg
from pygame.locals import *

PORT = '/dev/rfcomm0'
SPEED = 115200

ser = serial.Serial(PORT)

status = False
move = None
targets = []
inputs = []
tic = False

def getKeyPress():
    import pygame
    pygame.init()
    global targets
    global status
    while not status:
          pygame.event.pump()
          keys = pygame.key.get_pressed()
          targets, status = processOutputs(targets, keys)
    targets = np.array(targets)
    targets = flattenMatrix(targets)
    sio.savemat('targets.mat', {'targets':targets})

def rgb2gray(rgb):
    r, g, b = np.rollaxis(rgb[...,:3], axis = -1)
    return 0.299 * r + 0.587 * g + 0.114 * b

def processImages(inputX, inputs):
    inputX = flattenMatrix(inputX)
    if len(inputs) == 0:
       inputs = inputX
    elif inputs.shape[1] >= 1:
       inputs = np.hstack((inputs, inputX))
    return inputs

def flattenMatrix(mat):
    mat = mat.flatten(1)
    mat = mat.reshape((len(mat), 1))
    return mat

def send_command(val):
    connection = serial.Serial( PORT,
                                SPEED,
                                timeout=0,
                                stopbits=serial.STOPBITS_TWO
                                )
    connection.write(val)
    connection.close()

def processOutputs(targets, keys):
    global move
    global status
    global tic
    status = False
    keypress = ['K_p', 'K_UP', 'K_LEFT', 'K_DOWN', 'K_RIGHT']
    labels = [1, 2, 3, 4, 5]
    commands = ['p', 'w', 'r', 'j', 's']
    text = ['S', 'Up', 'Left', 'Down', 'Right']
    if keys[K_q]:
       status = True
       return targets, status
    else:
       for i, j, k, g in zip(keypress, labels, commands, text):
           cmd = compile('cond = keys['+i+']', '<string>', 'exec')
           exec cmd
           if cond:
              move = g
              targets.append(j)
              send_command(k)
              break
    send_command('p')
    return targets, status

targetProcess = multiprocessing.Process(target=getKeyPress)
targetProcess.daemon = True
targetProcess.start()

if __name__ == '__main__':
   import pygame
   pygame.init()
   w = 288
   h = 352
   size=(w,h)
   screen = pygame.display.set_mode(size)
   c = pygame.time.Clock() # create a clock object for timing
   pygame.display.set_caption('Driver')
   ubuntu = pygame.font.match_font('Ubuntu')
   font = pygame.font.Font(ubuntu, 13)
   inputs = []
   try:
     while not status:
           urllib.urlretrieve("http://192.168.0.10:8080/shot.jpg", "input.jpg")
           try:
             inputX = mpimg.imread('input.jpg')
           except IOError:
             status = True
           inputX = rgb2gray(inputX)/255
           out = inputX.copy()
           out = scipy.misc.imresize(out, (352, 288), interp='bicubic', mode=None)
           scipy.misc.imsave('input.png', out)
           inputs = processImages(inputX, inputs)
           print inputs.shape[1]
           img=pygame.image.load('input.png')
           screen.blit(img,(0,0))
           pygame.display.flip()
           c.tick(1)
           if move != None:
              text = font.render(move, False, (255, 128, 255), (0, 0, 0))
              textRect = text.get_rect()
              textRect.centerx = 20 #screen.get_rect().centerx
              textRect.centery = 20 #screen.get_rect().centery
              screen.blit(text, textRect)
              pygame.display.update()
           if status:
              targetProcess.join()
              sio.savemat('inputs.mat', {'inputs':inputs})
   except KeyboardInterrupt:
     targetProcess.join()
     sio.savemat('inputs.mat', {'inputs':inputs})

   targetProcess.join()
   sio.savemat('inputs.mat', {'inputs':inputs})

Thanks in advance.

A: I would personally suggest writing this without using the multiprocessing module: it uses fork() which has unspecified effects with most complex libraries, like in this case pygame.
You should try to write this as two completely separate programs.  It forces you to think about what data needs to go from one to the other, which is both a bad and a good thing (as it may clarify things).  You can use some inter-process communication facility, like the stdin/stdout pipe; e.g. in one program (the "main" one) you start the other as a sub-process like this:
popen = subprocess.Popen([sys.executable, '-u', 'my_subproc.py'],
                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)

(The -u is for unbuffered.)
Then read/write the data to popen.stdin/popen.stdout in the parent process, and to sys.stdin/sys.stdout in the subprocess.  The simplest example would be if the two processes only need a synchronization signal, e.g. the parent process waits in a loop for the subprocess to say "next please".  To do this the subprocess does print 'next please', and the parent process does popen.stdin.readline().  (The print goes to sys.stdin in the subprocess.)
Unrelated small note:
keypress = ['K_p', ...]
...
cmd = compile('cond = keys['+i+']', '<string>', 'exec')
exec cmd
if cond:

This looks like very heavy code to just do:
keypress = [K_p, ...]     # not strings, directly the values
...
if keys[i]:

A: My suggestion is to use separate threads.
#At the beginning
import threading

#Instead of def getKeyPress()
class getKeyPress(threading.Thread):
    def run(self):
        import pygame
        pygame.init()
        global targets
        global status
        while not status:
               pygame.event.pump()
               keys = pygame.key.get_pressed()
               targets, status = processOutputs(targets, keys)
        targets = np.array(targets)
        targets = flattenMatrix(targets)
        sio.savemat('targets.mat', {'targets':targets})

#Instead of
#targetProcess = multiprocessing.Process(target=getKeyPress)
#targetProcess.daemon = True
#targetProcess.start()
gkp = getKeyPress()
gkp.start()

An alternative would be creating two different scripts and using sockets to handle the inter-process communication.


text:
Q: Elegantly hiding the navbar in a single page MEAN app. I have an app that has a navbar on everypage, so I factored it out into index.jade that inherits from my layout.jade file. This is fine for 99% of my app.
The only place it runs into issues is on the login screen as it just feels weird to have a navbar at the login screen, so I used angular to check a boolean against a $rootScope variable and hide the navbar if you are on the homepage.
This is okay but the navbar still loads for a split second, then it disappears. I know I could correct this by not factoring it out into a single file and just cramming it into every single jade file besides the login page, but this would be a maintenance nightmare.
Is there a way that I can keep my navbar factored out, hide it on the login screen using ng-hide, and not load at all until I login.
This is my code to give you an idea of what I did.
The controller that checks to see if you are at the root of the app ('/')
angular.module('app').controller('LoginCtrl', function($scope, $http, mvIdentity, mvNotifier, mvAuth, $location, $rootScope) {
  $rootScope.currentPath = $location.path();
 ....
 ....

The jade file that shows how this variable is being used to hide the navbar
block main-content
  section.content

  nav.navbar.navbar-default(ng-hide='currentPath=="/"', role='navigation')
....
....
....

Then upon successful login, the currentPath variable gets set to false to bring the navbar back.
$rootScope.currentPath = false;

I would like to keep this set up because that means any changes to the navbar can be made in a single file and would be inherited across the app, cutting maintenance down tremendously, but I would like for the navbar to wait to load until login. As opposed to flickering from shown, then to hidden, and then to shown again.

A: Yes, it's possible to do this.
The reason you're seeing things flash up is because the page loads before angular has bootstrapped and applied ng-hide.
There are two approaches to solve this.
1. Put your script files in the head of the page
This is my preferred approach. By putting the script files in the head element, the page won't render until the scripts have loaded. This means angular will bootstrap the page first, and when it does render, the ng-hide will be correctly applied.
Some people prefer the page to start loading first, so won't use this method, but I personally don't think it matters.
2. Use ngCloak on the elements you need to hide
Basically, by applying the ngCloak directive to elements, and embedding the style provided in the link, you can hide certain elements until after the page is loaded. Essentially all ngCloak does is applies display:none to elements and removes it when angular finishes loading.


text:
Q: CardView size issue on View Recycle I have created a recyclerview adapter class, with an item layout which contains a cardview inside which there are some textviews and imageviews. The problem I am facing is that when the views are recycled, my cardview size changes and it hides the content of another cardview.
I think the issue is because I have different card heights for each item. So when an item is recycled, it takes the height of another card which is different. How to fix this? Please help..
Video link of the problem: https://drive.google.com/file/d/1nlgq-eQ-rhRNadOyzg4FwjVzrIk88Ve8/view?usp=sharing
open_up_list_view.xml
 <?xml version="1.0" encoding="utf-8"?>
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="wrap_content">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    android:id="@+id/openUpCardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/nav_header_vertical_spacing"
    android:layout_marginEnd="@dimen/dimen_16x"
    android:layout_marginLeft="@dimen/activity_vertical_margin"
    android:layout_marginRight="@dimen/dimen_16x"
    android:layout_marginStart="@dimen/activity_vertical_margin"
    android:layout_marginTop="@dimen/dimen_4x"
    android:clickable="true"
    android:focusable="true"
    app:cardCornerRadius="@dimen/dimen_8x">

    <RelativeLayout
        android:id="@+id/openUpRelativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="@dimen/dimen_8x"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <ProgressBar
                        android:id="@+id/openUpAuthorImageProgress"
                        android:layout_width="wrap_content"
                        android:layout_height="match_parent" />

                    <de.hdodenhof.circleimageview.CircleImageView
                        android:id="@+id/openUpAuthorImage"
                        android:layout_width="@dimen/dimen_48x"
                        android:layout_height="@dimen/dimen_48x"
                        android:layout_marginBottom="@dimen/dimen_4x"
                        android:layout_marginLeft="@dimen/dimen_4x"
                        android:layout_marginRight="@dimen/dimen_4x"
                        android:layout_marginTop="@dimen/dimen_4x"

                        app:civ_border_color="#FF000000"
                        app:civ_border_width="2dp" />
                </RelativeLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/openUpAuthorName"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="@dimen/cardview_default_radius"
                        android:layout_marginLeft="@dimen/dimen_8x"
                        android:layout_marginRight="@dimen/dimen_8x"
                        android:layout_marginTop="@dimen/dimen_8x"
                        android:text="loading.."
                        android:textColor="@color/colorPrimaryDark"
                        android:textSize="@dimen/dimen_16x"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/openUpDate"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/openUpAuthorName"
                        android:layout_marginLeft="@dimen/dimen_8x"
                        android:textSize="@dimen/dimen_12x" />
                </RelativeLayout>

            </LinearLayout>

            <TextView
                android:id="@+id/openUpTextView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_gravity="left"
                android:autoLink="web"
                android:padding="@dimen/dimen_4x"
                android:textAlignment="textStart"
                android:textColor="@color/cardview_dark_background"
                android:textSize="@dimen/dimen_16x" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ProgressBar
                    android:id="@+id/openUpImageProgress"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                <com.github.chrisbanes.photoview.PhotoView
                    android:id="@+id/openUpImageView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/dimen_8x"
                    android:layout_marginLeft="@dimen/dimen_4x"
                    android:layout_marginRight="@dimen/dimen_4x"
                    android:layout_marginTop="@dimen/dimen_8x"
                    android:layout_weight="1"
                    app:srcCompat="@drawable/common_google_signin_btn_icon_dark" />

            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="0.5dp"
                android:background="@android:color/darker_gray"
                android:hapticFeedbackEnabled="false"></View>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <CheckBox
                    android:id="@+id/openUpLikeIcon"
                    android:layout_width="@dimen/dimen_32x"
                    android:layout_height="@dimen/dimen_24x"
                    android:layout_marginBottom="@dimen/dimen_4x"
                    android:layout_marginLeft="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="8dp"
                    android:background="@drawable/thumb_off"
                    android:button="@null"
                    android:checked="false"
                    android:clickable="true"
                    android:focusable="true"
                    android:stateListAnimator="@animator/scale"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/image" />

                <TextView
                    android:id="@+id/openUpLikeTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/nav_header_vertical_spacing"
                    android:layout_marginTop="@dimen/dimen_8x"

                    android:text="loading.."
                    android:textSize="@dimen/dimen_16x" />

                <ImageView
                    android:id="@+id/openUpCommentIcon"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="@dimen/fab_margin"
                    android:layout_marginTop="@dimen/dimen_8x"
                    app:srcCompat="@drawable/comment_icon" />

                <TextView
                    android:id="@+id/openUpCommentTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="@dimen/dimen_8x"

                    android:text="loading.."
                    android:textSize="@dimen/dimen_16x" />

                <TextView
                    android:id="@+id/openUpDeleteText"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dimen_4x"
                    android:layout_marginTop="@dimen/dimen_8x"
                    android:layout_weight="1"
                    android:gravity="center_horizontal"
                    android:text="Delete"
                    android:textSize="@dimen/dimen_16x" />

            </LinearLayout>

            <View
                android:id="@+id/commentSeparatorView"
                android:layout_width="match_parent"
                android:layout_height="1.5dp"

                android:layout_marginTop="@dimen/nav_header_vertical_spacing"
                android:background="@color/colorPrimaryDark"
                android:hapticFeedbackEnabled="false"></View>

            <TextView
                android:id="@+id/commentSeparatorText"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="@dimen/dimen_8x"
                android:gravity="center"
                android:text="Comments"
                android:textColor="@color/common_google_signin_btn_text_dark_focused" />

            <LinearLayout
                android:id="@+id/commentsLL"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="@dimen/dimen_4x"
                android:background="@null"
                android:orientation="vertical">

                <android.support.v7.widget.RecyclerView
                    android:id="@+id/commentsRecyclerView"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                </android.support.v7.widget.RecyclerView>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:hint="Add a comment..">

                        <android.support.design.widget.TextInputEditText
                            android:id="@+id/commentEditText"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" />
                    </android.support.design.widget.TextInputLayout>

                    <android.support.v7.widget.AppCompatButton
                        android:id="@+id/commentPostButton"
                        android:layout_width="80dp"
                        android:layout_height="wrap_content"
                        android:backgroundTint="@color/colorPrimaryDark"
                        android:text="POST"
                        android:textColor="@color/cardview_light_background" />

                </LinearLayout>

            </LinearLayout>
        </LinearLayout>

    </RelativeLayout>
</android.support.v7.widget.CardView>

</RelativeLayout>
</ScrollView>

EDIT: RecyclerView layout
fragment_open_up.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bittentech.localvariable.fragments.OpenUpFragment">

<!-- TODO: Update blank fragment layout -->

<TextView
    android:id="@+id/openUpEmptyView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical|center_horizontal"
    android:gravity="center_vertical|center_horizontal"
    android:text="All caught up!!" />
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/openUpSwipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/openUpRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="false"/>

</android.support.v4.widget.SwipeRefreshLayout>

</FrameLayout>


text:
Q: react-native link does not find project.pbxproj file I have a react-native project where I changed my project name in package.json due to eslint warnings. Now when I try to run react-native link to link any library, I'm getting the following error:

Scanning folders for symlinks in /Users/my-username/projects/myproject-folder/node_modules (20ms)
rnpm-install info Linking assets to ios project
rnpm-install ERR! Something went wrong while linking. Error: ENOENT: no such file or directory, open '/Users/my-user-name/projects/myproject-folder/ios/my-old-app-name.xcodeproj/project.pbxproj'

So it doesn't find the file project.pbxproj, as it is looking at it from the wrong folder.
What I have tried so far with failed outcomes:

*

*react-native upgrade

*react-native-rename

*Deleted node_modules and run npm install again

*Renamed app name to correct in index.ios.js for AppRegistry.registerComponent

Where does react-native link look for the file project.pbxproj? If I find that location, I could rewrite it to the new correct one. I have no xcode, and currently only android version. I (still) have the separate index files for both versions, even I heard that after some react-native upgrade they should have been merged...

A: Was able to solve this by deleting the other project folders in the ios -folder. Apparently react-native just loops through every project there it finds, and picks the first one.

A: I stumbled this problem just today. Here are the steps I made to make it work again

*

*Delete the ios folder

*react-native eject // this will re generate the ios folder

*react-native-link

I also did gradle clean before the earlier steps but I think its unnecessary.


text: Q: My configurable products need to have view details button instead of Addto Cart button How can I replace the add to cart button with a view details button for my configurable products? I searched everywhere but could only find solutions for Magento 1.9 not 2.1.8.


text:
Q: Why won't CloudSearch find substring matches in filename text field? I have a CloudSearch domain with a filename text field. My issue is that a text query won't match (some) documents with filenames I think it (logically) should. If I have documents with these filenames:

*

*'cars'

*'Cars Movie.jpg'

*'cars.pdf'

*'cars#.jpg'

and I perform a simple text query of 'cars', I get back files #1, #2, and #4 but not #3. If I search 'cars*' (or do a structured query using prefix) I can match #3. This doesn't make sense to me, especially that #4 matches but #3 does not.

A: TL;DR It's because of the way the tokenization algorithm handles periods.
When you perform a text search, you're performing a search against processed data, not the literal field. (Maybe that should've been obvious, but it wasn't how I was thinking about it before.)
The documentation gives an overview of how text is processed:

During indexing, Amazon CloudSearch processes text and text-array fields according to the analysis scheme configured for the field to determine what terms to add to the index. Before the analysis options are applied, the text is tokenized and normalized.

The part of the process that's ultimately causing this behavior is the tokenization:

During tokenization, the stream of text in a field is split into separate tokens on detectable boundaries using the word break rules defined in the Unicode Text Segmentation algorithm.
According to the word break rules, strings separated by whitespace such as spaces and tabs are treated as separate tokens. In many cases, punctuation is dropped and treated as whitespace. For example, strings are split at hyphens (-) and the at symbol (@). However, periods that are not followed by whitespace are considered part of the token.

The reason I was seeing the matches described in the question is because the file extensions are being included with whatever precedes them as a single token. If we look back at the example, and build an index according to these rules, it makes sense why a search of 'cars' returns documents #1, #2, and #4  but not #3.
#    Text                Index

1    'cars'              ['cars']
2    'Cars Movie.jpg'    ['cars', 'movie.jpg']
3    'cars.pdf'.         ['cars.pdf']
4    'cars#.jpg'         ['cars', '.jpg']

Possible Solutions
It might seem like setting a custom analysis scheme could fix this, but none of the options there (stopwords, stemming, synonyms) help you overcome the tokenization problem. I think the only possible solution, to get the desired behavior, is to tokenize the filename (using a custom algorithm) before upload, and then store the tokens in a text array field. Although devising a custom tokenization algorithm that supports multiple languages is a large problem.


text:
Q: Sharing contacts in android Im trying to share a contact using my android app, and Im stocked. Is there any way to share a contact directly using intents? Or do I have to send the contact information and re-build it in the other device? Also, is there any other way to do that without using intents?

A: You can use ContactsContract APIs to share a contact as a vcard file (e.g. to send via Whatsapp).
(I'm assuming you already have the contact's lookupKey, if you don't have it, let me know, and i'll add the code for getting it from contactId)
UPDATE added method to get LookupKey from ContactId
(make sure you import Contacts from ContactsContract.Contacts)
private String getLookupKey(long contactId) {
    String lookupKey = null;
    String[] projection = new String[]{Contacts.LOOKUP_KEY};
    String selection = Contacts._ID + "=" + contactId;
    Cursor c = getContentResolver().query(Contacts.CONTENT_URI, projection, selection, null, null);
    if (c != null) {
        if (c.moveToFirst()) {
            lookupKey = c.getString(0);
        }
        c.close();
    }
    return lookupKey;
}

String lookupKey = getLookupKey(long contactId);
if (TextUtils.isEmpty(lookupKey)) {
    Log.e(TAG, "couldn't get lookupKey");
    return;
}
Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(Contacts.CONTENT_VCARD_TYPE);
intent.putExtra(Intent.EXTRA_STREAM, shareUri);
intent.putExtra(Intent.EXTRA_SUBJECT, "Share a contact");
startActivity(intent);

A: The strategy I would use would be to fetch the desired contacts locally.  Then, parse these into JSON objects with the desired fields.  Either send the JSON to a server that the other user downloads from or send the JSON over bluetooth to other device.


text:
Q: sinch conference call hung up right after it starts I managed to start a conference call cut it closes right after I start it with HUNG_UP cause and I got this in my log:
11-03 17:28:08.940: E/sinch-android-rtc(19101): peermediaconnection: virtual void rebrtc::SetSDPObserver::OnFailure(const string&)Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
11-03 17:28:08.940: E/sinch-android-rtc(19101): mxp: Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.

can anybody help me solve this please?
Edit:
my scenario is when a user clicks the call button I ask him if he wants to start a new call or join an already created one.
I managed to make my code from this question (Sinch conference call error) work as my GroupService class had some bugs.
I start my call like this:
Intent intent1 = new Intent(CreateGroupCallActivity.this,SinchClientService.class);
            intent1.setAction(SinchClientService.ACTION_GROUP_CALL);
            String id = String.valueOf(uid) + "-" + call_id.getText().toString();
            intent1.putExtra(SinchClientService.INTENT_EXTRA_ID,id);
            startService(intent1);

and in my SinchClientService:
if(intent.getAction().equals(ACTION_GROUP_CALL))
            {
                String id = intent.getStringExtra(INTENT_EXTRA_ID);
                if(id != null)
                    groupCall(id);
            }

public void groupCall(String id) {
        if (mCallClient != null) {
            Call call = mCallClient.callConference(id);
            CurrentCall.currentCall = call;

            Log.d("call", "entered");

            Intent intent = new Intent(this, GroupCallService.class);
            startService(intent);
        }
    }

nd here is my GroupCallService
public class GroupCallScreenActivity extends AppCompatActivity implements ServiceConnection {

private SinchClientService.MessageServiceInterface mMessageService;
private GroupCallService.GroupCallServiceInterface mCallService;

private UpdateReceiver mUpdateReceiver;

private ImageButton mEndCallButton;

private TextView mCallDuration;

private TextView mCallState;

private TextView mCallerName;

//private TextView locationview;

private ImageView user_pic;

private long mCallStart;
private Timer mTimer;

private UpdateCallDurationTask mDurationTask;

ImageButton chat;
ImageButton speaker;
ImageButton mic;

boolean speaker_on = false;
boolean mic_on = true;

PowerManager mPowerManager;
WakeLock mProximityWakeLock;
final static int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;

com.galsa.example.main.ImageLoader mImageLoader;

/*String location;
String longitude;
String latitude;*/

private class UpdateCallDurationTask extends TimerTask {

    @Override
    public void run() {
        GroupCallScreenActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateCallDuration();
            }
        });
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    setContentView(R.layout.callscreen);

    doBind();

    mCallDuration = (TextView) findViewById(R.id.callDuration);
    mCallerName = (TextView) findViewById(R.id.remoteUser);
    mCallState = (TextView) findViewById(R.id.callState);
    //locationview = (TextView) findViewById(R.id.location);
    mEndCallButton = (ImageButton) findViewById(R.id.hangupButton);
    chat = (ImageButton) findViewById(R.id.chat);
    chat.setVisibility(View.GONE);
    speaker = (ImageButton) findViewById(R.id.speaker);
    mic = (ImageButton) findViewById(R.id.mic);
    user_pic = (ImageView) findViewById(R.id.user_pic);

    /*location = getIntent().getStringExtra("location");
    longitude = getIntent().getStringExtra("longitde");
    latitude = getIntent().getStringExtra("latitude");

    locationview.setText(location);*/

    mImageLoader = new com.galsa.example.main.ImageLoader(GroupCallScreenActivity.this, R.dimen.caller_image_height);

    //mCallerName.setText(mCall.getRemoteUserId());

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mProximityWakeLock = mPowerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, Utils.TAG);

    /*chat.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
        Intent intent = new Intent(GroupCallScreenActivity.this, MessagingActivity.class);
        intent.putExtra(SinchClientService.INTENT_EXTRA_ID, mCallService.getCallerId());
        intent.putExtra(SinchClientService.INTENT_EXTRA_NAME, mCallService.getCallerName());
        startActivity(intent);
        }
    });*/

    speaker.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if(speaker_on)
            {
                mMessageService.speakerOn(speaker_on);

                speaker_on = false;
                speaker.setImageResource(R.drawable.speaker_off);
            }
            else
            {
                mMessageService.speakerOn(speaker_on);

                speaker_on = true;
                speaker.setImageResource(R.drawable.speaker_on);
            }

        }
    });

    mic.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if(mic_on)
            {
                mMessageService.micOn(mic_on);

                mic_on = false;
                mic.setImageResource(R.drawable.mic_off);
            }
            else
            {
                mMessageService.micOn(mic_on);

                mic_on = true;
                mic.setImageResource(R.drawable.mic_on);
            }

        }
    });

    mEndCallButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallService.endCall();
        }
    });

    mCallStart = System.currentTimeMillis();
}

private void doBind() {

    Intent intent = new Intent(this, SinchClientService.class);
    bindService(intent, this, BIND_AUTO_CREATE);

    intent = new Intent(this, GroupCallService.class);
    bindService(intent, this, BIND_AUTO_CREATE);
}

private void doUnbind() {
    unbindService(this);
}

@Override
protected void onStart() {
    super.onStart();

    mUpdateReceiver = new UpdateReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(GroupCallService.ACTION_FINISH_CALL_ACTIVITY);
    filter.addAction(GroupCallService.ACTION_CHANGE_AUDIO_STREAM);
    filter.addAction(GroupCallService.ACTION_UPDATE_CALL_STATE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateReceiver, filter);
}

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

    if(mProximityWakeLock != null && !mProximityWakeLock.isHeld()){
        mProximityWakeLock.acquire();
    }

    mTimer = new Timer();
    mDurationTask = new UpdateCallDurationTask();
    mTimer.schedule(mDurationTask, 0, 500);
}

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

    if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
        mProximityWakeLock.release();
    }

    mDurationTask.cancel();
}

@Override
protected void onStop() {
    super.onStop();

    if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
        mProximityWakeLock.release();
    }

    if(mUpdateReceiver != null)
    {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
        mUpdateReceiver = null;
    }
}

@Override
public void onBackPressed() {
    // User should exit activity by ending call, not by going back.
}

private void updateCallDuration() {
    mCallDuration.setText(Utils.formatTimespan(System.currentTimeMillis() - mCallStart));
}

@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    if(iBinder instanceof GroupCallService.GroupCallServiceInterface)
    {
        mCallService = (GroupCallService.GroupCallServiceInterface) iBinder;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        ActionBar actionBar = getSupportActionBar();

        if(mCallService.getCallerName() != null)
            actionBar.setTitle(mCallService.getCallerName());
        else
            actionBar.setTitle("Group call");

        actionBar.setIcon(R.drawable.callscreen);

         if(mCallService.getCallerName() != null)
             mCallerName.setText(mCallService.getCallerName());
         else
             mCallerName.setText("Group call");

        mCallState.setText(mCallService.getCallState());

        String pic = ChatDatabaseHandler.getInstance(this).getFriendpic(mCallService.getCallerId());
        mImageLoader.displayImage(UserFunctions.hostImageDownloadURL + pic, user_pic);
    }
    else
        mMessageService = (SinchClientService.MessageServiceInterface) iBinder;

    mMessageService.enableMic();
    mMessageService.disableSpeaker();
}

@Override
public void onServiceDisconnected(ComponentName componentName) {
    mMessageService = null;
    mCallService = null;
}

@Override
public void onDestroy() {

    if(mUpdateReceiver != null)
    {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
        mUpdateReceiver = null;
    }

    doUnbind();

    super.onDestroy();
}

private class UpdateReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if(GroupCallService.ACTION_FINISH_CALL_ACTIVITY.equals(intent.getAction()))
        {
            finish();
        }
        else if(GroupCallService.ACTION_CHANGE_AUDIO_STREAM.equals(intent.getAction()))
        {
            setVolumeControlStream(intent.getIntExtra("STREAM_TYPE", AudioManager.USE_DEFAULT_STREAM_TYPE));
        }
        else if(GroupCallService.ACTION_UPDATE_CALL_STATE.equals(intent.getAction()))
        {
            mCallState.setText(intent.getStringExtra("STATE"));
        }
    }
}

}
I start the call with the same way whether the user will start a new call or join a created one.


text:
Q: Django Firebase I am trying to connect my Django website with Firebase. There is not enough material for that, luckily I got this https://github.com/thisbejim/Pyrebase but I am not able to understand where to write this code.
I have written this code in pyrebase.py file:
import pyrebase

config = {
    apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo",
    authDomain: "minor1-5e62c.firebaseapp.com",
    databaseURL: "https://minor1-5e62c.firebaseio.com",
    projectId: "minor1-5e62c",
    storageBucket: "minor1-5e62c.appspot.com",
    messagingSenderId: "69802125895"
  };
firebase=firebase.initializeApp(config);

and when I am running it on python terminal I am getting this error:

Traceback (most recent call last):   File
  "D:\Django2\mysite1\personal\dd.py", line 4, in
      apiKey: "AIzaSyD0kwTsifJAL3C7mTj6Hil6Lfutes0jdEo", NameError: name 'apiKey' is not defined

How can I fix this?

A: Python dicts use immutable values (like strings) as keys.
Try something like this instead:
import pyrebase

config = {
    'apiKey': '...',
    'authDomain': '...',
    'databaseURL': '...',
    'projectId': '...',
    'storageBucket': '...',
    'messagingSenderId': '...',
}

firebase = firebase.initializeApp(config)

Note also that semicolons usually aren't used with Python, though they are legal.


text:
Q: changing colors when link is clicked If I have a menu set up in the header which I use for most of my pages as "include/header.php" how do I setup so when I click on a link, it goes to that page, and that link changes colors (and shows as active)? Would jquery be good? or PHP?
Thanks!

A: You could use PHP to add a class to the current button by comparing it's URL, and the current page URL from $_GET. Without knowing what your URL structure is like, I can't say much more than that.
For example, using an array with button text and URLs:
$links = array('Home' => 'home', 'About' => 'about');

foreach($links as $text => $page)
{
    if($_GET['page'] == $page)
    {
        echo '' . $text . '';
    }
    else
    {
        echo '' . $text . '';
    }
}

This code will add a class of current to the button who's page matches the value in $_GET. This might not exactly fit your needs due to you probably having a different URL structure, among other things, but it gives a basic explanation and example of how to do this.

A: Use php, you could write a function before your include like so,
function activeLink ($page) {
    if ($page = 'home') echo ' class="active"';
    elseif ($page = 'about') echo ' class="active"';
    elseif ($page = 'posts') echo ' class="active"';
}

And in your header file,
echo 'Home
About
Posts';

And on your actual page;
$page = 'home';
include('header');

This will do the trick.


text:
Q: How do I install nodejs as an asset upload web service to work with my wordpress setup I have a Wordpress setup and my client needs users to upload large image and video files into the media library using a front-end form - NOT the wp backend.
I was thinking using something like express with a package like formidable
I want to know if it is possible to create an internal service on my vps server that wordpress could talk to.
Specifically, I want to know:

*

*How do I hit an external url like api.domain.com/uploads and send wordpress data through to that server

*How do I get the processed output back into wordpress and then save it

A: Here is an example on retrieving information from an external source through node.js & PHP
http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/
With that said, I would personally create a shortcode by plugin design or create a theme template for this particular Form setup and with a combination of PHP, JS, Jquery, and various functions
if(is_page("page_name")) {
    /*custom functions that will connect externally*/
    wp_insert_comment($array_of_values);  //pass values through standard PHP methods (global variables, etc)
}

Reference:
https://codex.wordpress.org/Writing_a_Plugin
http://codex.wordpress.org/Shortcode_API
http://codex.wordpress.org/Function_Reference/is_page
http://codex.wordpress.org/Function_Reference/wp_insert_comment
http://codex.wordpress.org/The_Loop#Nested_Loops


text:
Q: Redefine \footnote to change color of index in Latex For my work I shall make it possible to change the color of the footnote index optionally.
I found a way to change the color, but it is not flexible.
\RequirePackage{xcolor}
\definecolor{red}{RGB}{165,30,55}
\renewcommand{\thefootnote}{\textcolor{red}{\arabic{footnote}}}

\begin{document}
a footnote\footnote{lalala}
\end{document}

this works. But this does not:
\renewcommand{\thefootnote}[1]{\textcolor{#1}{\arabic{footnote}}}
\begin{document}
a footnote\footnote[red]{lalala}
\end{document}

I think it is because \footnote already has one optional parameter for the index number.
Is there a way to change it?

A: With a new command, one could do something like this:
\documentclass{article}

\RequirePackage{xcolor}

\newcommand{\cfootnote}[2][black]{%
    {\color{#1}\footnote{#2}}%
}

\begin{document}
a footnote\cfootnote{lalala}

a footnote\cfootnote[red]{lalala}
\end{document}

Another approach with redefining the footnote:
\documentclass{scrartcl}
\usepackage{scrletter}
\usepackage{xcolor}

\let\oldfootnote\footnote
\usepackage{xparse}
\usepackage{etoolbox}
\RenewDocumentCommand{\footnote}{ O{} m O{black}}{%
    \deffootnotemark{\color{#3}\textsuperscript{\thefootnotemark}}%
    \ifstrempty{#1}{%
        \oldfootnote{#2}%
    }{%
        \oldfootnote[#1]{#2}%
    }
}

\begin{document}

test\footnote{text}[red]

test\footnote{text}

test\footnote[42]{text}

test\footnote[42]{text}[blue]

\end{document}


text:
Q: unitialized local variable + using unitialized memory int main()
{

    int secretnum = 7;
    int Guess;

    while (secretnum != Guess) {
        cout << "Enter guess: ";
        cin >> Guess;
    }

    cout << "You win";

    return 0;
}

However, I get 1 warning and 1 error.
Warning: Using uninitialized memory "Guess"
Error: uninitialized local variable "Guess" used

A: The error says that you use the value of Guess (in the while statement) before you put any value into it.
As a rule of thumb, you should initialize your variables when defined, meaning:
int guess = 0;

Is better than:
int guess; // This memory is uninitialized!

Currently, the value in guess is whatever in that memory, and shouldn't be used!
In order to be as clear as possible - I agree that do...while is preferable over while in this context, I want to add that initializing is important nonetheless:
#include <iostream>
#include <limits>

int main()
{
    constexpr int secretnum = 7;
    int guess = (secretnum == std::numeric_limits<int>::max())
              ? secretnum + 1
              : secretnum - 1;

    do {
        std::cout << "Enter a guess: " << std::endl;
        std::cin >> guess;
    } while (secretnum != guess);

    std::cout << "You win" << std::endl;

    return 0;
}


text:
Q: Sticky table header with two header rows Considering the following table structure:

        Item No
        Store ABC
        Store DEF

        Baskets
        Customers
        Baskets
        Customers

I would like to make the table-header sticky so that when scrolling down the table, it remains visible.
Easy thing when there is only one header row. However, things get tricky when having two. I've come up with the following css:
thead th, thead td {
  position: sticky;
  top: 0;
  background: #eee;
}

It "almost" works, except when scrolling the table, the two header rows kind of "slip" to the same position, the second row coming on top of the first one.
How to make the two header rows sticky in a way that their appearance is not changed when scrolling down the table (i.e. the whole header remains a "block" and its two distinct rows stay in place)?
Mandatory jsFiddle: http://jsfiddle.net/juyvcLd6/3/
--- UPDATE
Identifying the two header rows with class="first" and class="second" respectively, plus adding the following css:
thead tr.first th, thead tr.first td {
  position: sticky;
  top: 0;
  background: #eee;
}

thead tr.second th, thead tr.second td {
  position: sticky;
  top: 17px;
  background: #eee;
}

has the effect of keeping the header rows together in place while scrolling the table. However, the top: 17px element is very much dependent on the actual rendered size of the row. If the user has its browser rendering text sizes differently, for instance, then everything will go off.
Plus, this method has the drawback of getting rid of header borders in quite a weird way.
How to make sure that, when scrolling the table:

*

*the top: xxx rule for the second row actually reflects the real height of the first row?

*the borders stay consistent with what they look like when the table is not scrolled?

See updated jsFiddle: http://jsfiddle.net/juyvcLd6/4/

A: You can remove the 'top' from  thead tr.second th, thead tr.second td
and add a jquery for getting and setting height of second header

    $(document).ready(function() {
        var firstheight = $('.first').height();
        $("thead tr.second th, thead tr.second td").css("top", firstheight)
    });
    table {
       height: 100%;
       border-collapse: collapse;
       width: 100%;
       margin: 10px;
       font-size: 0.8em;
   }

   thead tr.first th, thead tr.first td {
       position: sticky;
       position: -webkit-sticky; /* Safari */
       top: 0;
       background: #eee;
   }

   thead tr.second th, thead tr.second td {
       position: sticky;
       position: -webkit-sticky; /* Safari */
       background: #eee;
   }

        Item No
        Store ABC
        Store DEF

        Baskets
        Customers
        Baskets
        Customers

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

A: Since all your header rows are in thead, just apply the position: sticky; to thead instead of thead th, thead td. In this way you don't need to worry about the height of each header row or how many header row you have.
thead {
  position: sticky;
  top: 0;
  background: #eee;
}

I made the change to your first example and it works. https://jsfiddle.net/qcuxkng5/

table {
  height: 100%;
  border-collapse: collapse;
  width: 100%;
  margin: 10px;
  font-size: 0.8em;
}

thead {
  position: sticky;
  top: 0;
  background: #eee;
}

        Item No
        Store ABC
        Store DEF

        Baskets
        Customers
        Baskets
        Customers

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345

      123
      345
      345
      345
      345


text:
Q: Artisan returning localhost as url I'm using Laravel 5.2.43 to build an application. My config/app.php reads as follows:
'url' => env('APP_URL', 'http://domain.dev'),

and in the .env file
APP_URL=domain.dev

my schedule send an email with a link back to the website. But this url is returned as http://localhost instead of http://domain.dev. Can someone help?

A: It seems you need to had http:// to your APP_URL
so in your case the app URL in the config file should be http://domain.dev


text:
Q: How to share a file over "Windows Share" protocol from scientific linux? I have a file on my linux. I want to share it via "Windows Share" (IPMI can understand only one way of remote large files mounting). How to share my file over "Windows Share" from my scientific linux?

A: I don't know much about "Windows Share", do you mean the SMB protocol? I access files hosted on CentOS from Windows 7/8 machines with samba.  No client side installation needed.
https://www.samba.org/samba/docs/using_samba/ch03.html


text:
Q: Why the 'xargs' command do not work with figlet but works fine when i run it with 'ls' argument For example:

*

*find /usr/share/figlet/ -type f -name "*.flf" | xargs ls -l

-rwxr-xr-x 1 root root  3369 Mar 31 17:54 /usr/share/figlet/Tombstone.flf
-rwxr-xr-x 1 root root  7641 Mar 31 17:54 /usr/share/figlet/Train.flf
-rwxr-xr-x 1 root root  8336 Mar 31 17:54 /usr/share/figlet/Trek.flf
-rwxr-xr-x 1 root root  9363 Mar 31 17:54 /usr/share/figlet/Tubular.flf
-rwxr-xr-x 1 root root 15484 Mar 31 17:54 /usr/share/figlet/Univers.flf
-rwxr-xr-x 1 root root  6644 Mar 31 17:54 /usr/share/figlet/usaflag.flf

*find /usr/share/figlet/ -type f -name "*.flf" | xargs figlet -f

The first command generates an output but the second one does not. What is the reason behind this?

A: I'm going to attempt an answer:
find /usr/share/figlet/ -type f -name "*.flf" | xargs -n 1 figlet -f

This will run one figlet command with one file name, and another figlet command with another file name, and so on.
See for example the difference between
find /usr/share/figlet/ -type f -name "*.flf" | xargs -t ls -l

and
find /usr/share/figlet/ -type f -name "*.flf" | xargs -t -n 1 ls -l

(By the way, I always include '-r' on xargs, which will prevent xargs from running if there's no input. Otherwise you get a confusing empty line.)


text:
Q: Read list of different types from istream into vector I'm trying to read text of the following format from an istream (e.g. std::cin):
<type_code>
<n>
<elem_0> <elem_1> ... <elem_n-1>

where

*

*First line <type_code>: 0=int, 1=double, 2=char, 3=std::string;

*Second line <n> is the number of elements in the list;

*Third line contains the actual elements, separated by a space character.

For example, the following is a list of 5 std::strings:
3
5
apple banana orange kiwi tomato

Intuitive I did:
template<typename T>
void Work(std::vector<T> &A) {
    // do something ...
}

int main() {
    int type_code, len;
    std::cin >> type_code >> len;
    std::vector<int> ilist;
    std::vector<double> dlist;
    std::vector<char> clist;
    std::vector<std::string> slist;

    switch (type_code) {
        case 0:
            ilist.resize(len);
            for (int i = 0; i < len; ++i) {
                std::cin >> ilist[i];
            }
            Work(ilist);
            break;
        case 1:
            dlist.resize(len);
            for (int i = 0; i < len; ++i) {
                std::cin >> dlist[i];
            }
            Work(dlist);
            break;
        case 2:
            clist.resize(len);
            for (int i = 0; i < len; ++i) {
                std::cin >> clist[i];
            }
            Work(clist);
            break;
        case 3:
            slist.resize(len);
            for (int i = 0; i < len; ++i) {
                std::cin >> slist[i];
            }
            Work(slist);
            break;
        default:
            break;
    }
}

Due to the uncertainty of type until runtime, I have to instantiate 4 vector of different type. This produce duplicate code and more objects than I need (since eventually only 1 vector will be used).
What's the best way of handling here?

A: Since C++17 you can use std::any
std::vector<std::any> vectorName;

Another option can be std::variant, but here you have to specify the types the vector can hold as opposed to std::any.

A: std::variant should work nicely for this... (requires C++17)
#include <variant>
#include <vector>
#include <string>
#include <iostream>

template<typename T>
void Work(std::vector<T>& v) {
    // do more stuff
}

// this is a type that will hold either a vector<int>, vector<double>, etc, or nothing
using variantoftypes = std::variant<std::vector<int>,
                std::vector<double>,
                std::vector<char>,
                std::vector<std::string>>;

template<typename T>
void doStuff(std::istream& in, variantoftypes& v, int len) {

    //assign v to hold a vector<T>
    v = std::vector<T>();

    //get the vector it's holding out...
    std::vector<T> &v_alias = std::get<std::vector<T>>(v);

    // now v_alias will behave like you want it to
    v_alias.resize(len);
    for (int i = 0; i < len; ++i) {
        std::cin >> v_alias[i];
    }

    // work with the alias
    Work(v_alias);

}

int main() {
    variantoftypes v;

    int type_code, len;
    std::cin >> type_code >> len;

    switch (type_code) {
        case 0:
            doStuff<int>(std::cin, v, len);
            break;
        case 1:
            doStuff<double>(std::cin, v, len);
            break;
        case 2:
            doStuff<char>(std::cin, v, len);
            break;
        case 3:
            doStuff<std::string>(std::cin, v, len);
            break;
    }

}

A: (Note: Please also refer to answers by @Jake Schmidt and @anastaciu. They provide great examples of C++17 std::any and std::variant)

I figure out that putting everything in a template function fits my need just well.
C++ is statically typed (whatever that means) so you have to write that switch statement anyway and instantiate the template function 4 times with explicit type arguments (and call them). It's not like python where you can write type_arr=[int,float,str] and use type_code to index it.
btw. it's a demo for insertion sort.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>

template<typename T>
void print_vec(std::vector<T> vec) {
    for (auto &e : vec) std::cout << e << ' ';
    std::cout << std::endl;
}

template<typename T>
void Work(std::istream &in, int len) {
    std::vector<T> vec(len);
    for (int i = 0; i < len; ++i) in >> vec[i];
    for (int i = 1; i < len; ++i) {
        auto insert_it = std::upper_bound(vec.begin(), vec.begin() + i, vec[i]);
        std::rotate(vec.rend() - i - 1, vec.rend() - i, std::make_reverse_iterator(insert_it));
        print_vec(vec);
    }
}

void read(std::istream &in) {
    int type_code, len;
    in >> type_code >> len; // omitting garbage input check
    switch (type_code) {
        case 0:
            Work<int>(in, len);
            break;
        case 1:
            Work<double>(in, len);
            break;
        case 2:
            Work<char>(in, len);
            break;
        case 3:
            Work<std::string>(in, len);
            break;
        default:
            std::cout << "err" << std::endl;
            exit(EXIT_FAILURE);
    }
}

int main() {
//    std::istringstream iss{"0\n6\n21 25 49 25 16 8"};
//    read(iss);
    read(std::cin);
}


text:
Q: Could not load file or assembly 'Microsoft.CodeAnalysis.Workspaces, Version=2.3.0.0 in VSIX project Microsoft.CodeAnalysis Version Used: 2.3.2
Steps to Reproduce:
Create a VSIX (c#) project in Visual Studio 2015 Update 3 with .Net framework 4.6
Add latest Microsoft.CodeAnalysis library to VSIX project
Add menu command to the VSIX project
Add following code in menu command action
string projectFilePath = @"C:\ConsoleApp1\ConsoleApp1.csproj";
string outputFilePath = @"C:\ConsoleApp1\ConsoleApp1.dll";
Project project = null;

    using (var workspace = MSBuildWorkspace.Create())
    {
        project = workspace.OpenProjectAsync(projectFilePath).Result;
        var compilation = project.GetCompilationAsync().Result;
        var compilationStatus = compilation.Emit(outputFilePath);
        bool isSuccess = compilationStatus.Success;
    }

Expected Behavior:
Roslyn should be able to compile the project and emit output to target location.
Actual Behavior:
Following exception occurred when invoking the command.
Could not load file or assembly 'Microsoft.CodeAnalysis.Workspaces, Version=2.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Note:
Error doesn't occur and command executes successfully when version of the Microsoft.CodeAnalysis is downgraded to 1.3.2
Please let me know if any fix is available for this issue.

A: see What's the latest version of Roslyn my analyzer can target if I support VS2015?.  Roslyn 1.3.2 is the newest version that will work with Visual Studio 2015 Update 3


text:
Q: Visual Studio Line Highlight Colour Is there a way to highlight a given line with a background colour?
Example would be when you have a line of code your editing, you can see a differen't shade of colour in the background for that line.
How do I set that on any line that I want and have it remain there even when I'm not editing that line? Sort of the same as highlighting a sentence in a book. As I want to use it as a visual seperation/trigger for my code.
Perhaps someone can point me to an extension or something? I'm having trouble finding it myself.
Many thanks


text:
Q: How to target a class sevreal descendants down in jQuery? I have several parent divs, each with a bunch of children. All of the parents contain a child (several divs deep) called .nxt
I want to hide all of the .nxt divs in the parent1 div, but not the other two parents.
Shouldn't
$('#parent1 .nxt').hide();

do it?
or do I need to include all the elements that lead down to .nxt
Thanks for your help.

A: Never mind - it was working - I just had it BEFORE I'd actually added the parent1 div to the dom. Thanks guys.

A: Try:
$('div:first').find('.nxt').hide();

:first will select the first elements  into matched set.


text:
Q: Program, or workflow to update a single file and update all instances of it everywhere else Is there a program, or a workflow that is best for working with a single file, and when saving to update all instances of the file on the computer, whether it be in different projects folders?
Edit (Response to Comments):
Well, I have javascript and css files that are shared between multiple projects. When I update or amend a file, I find myself having to manually copy and paste to replace the same files in all the other projects that rely on the same file(s).

A: What you are describing might be accomplished with a hard link.
Hard links mean that one file on the drive is seen as a file in multiple folders.
So, if you had a file recipe.doc and stored in your ~/Documents folder, you could hard link it elsewhere - perhaps /Users/Shared and ~/Projects/Cooking/Pasta/recipe.doc
So, the link count would be 3 for that file and only one recipe would take space on the disk. If you deleted the file in /Users/Shared - rather than deleting the file, it just removes that one link and decrements the file counter to 2. When the last link goes away, you have a link count of 1 and the file remains, but no copies in other folders.
If you want to learn more, the link command is a terminal command written as ln.
Also, you could check that file into some sort of code control system like git and script the checkout in the folders of your liking. It really depends on how much time you'll save or if you just want to write a quick and dirty shell script to push the changed file elsewhere (or use rsync to copy just the changed bits and be über efficient).

A: Theoretically you could use Folder Actions to watch for changes on shared files and copy them over to all the other projects/folders. In practice this will not really work because Folder Actions tend to be not very reliable. I found that Hazel works quite well for this though, a lot of stuff can be automated that way.

Depending on your requirements you may also want to think about structuring your files differently because duplicating files will lead to problems especially if you use version control, work in larger setups or if several people are involved. So instead of having several projects in a structure like
+ project-1
  + common-file-1
  + common-file-2
  + specific-file-1.1
  + specific-file-1.2
+ project-2
  + common-file-1
  + common-file-2
  + specific-file-2.1
  + specific-file-2.2

and probably building/packaging them from there you could switch to something like
+ common
  + common-file-1
  + common-file-2
+ project-1
  + src
    + specific-file-1.1
    + specific-file-1.2
  + build

and then use a build script in project-1 to copy all the relevant files from common and project-1/src into project-1/build for further use. It may take some effort to change your current structure into something like that but it might bring benefits on the long run. If you want to dig depper into this, Pragmatic Project Automation is a good place to start with.


text:
Q: Feedback on answer I wrote out for a theoretical question regarding Linear Algebra I am new to linear algebra, and have no teacher at present. I have written out an answer to the following question, which I found very challenging, and would really appreciate any feedback. Many thanks in advance.
Let $V$ be a vector space over R. Let $v_1,v_2,v_3,u_1,u_2,u_3\in V$, so that $u_1,u_2,u_3 \in U = Sp\{v_1,v_2,v_3\}$, and so that the set $B = \{u_1-u_2,u_1+3u_3,4u_2+5u_3\}$  is linearly independent. Prove that $SpB \subseteq U$ and find the dimension of U.
My answer is the following:
It is easy to see that $B$ is a linear combination of $\{u_1,u_2,u_3\}$; in other words $B \subseteq Sp(u_1,u_2,u_3)$, and based on the information given $B \subseteq Sp(v_1,v_2,v_3)$.
$B$ is linearly independent, so $dimSpB = 3$.
Let α,β,γ be scalars in R.
We can write out B as:
$α(u_1-u_2)+β(u_1+3u_3)+γ(4u_2+5u_3)=0$
where α,β,γ are scalars in R.
Because $B$ is linearly independent, α=0,β=0 and γ=0.
We can rewrite this formula as:
$(α+β)u_1+(-α+4γ)u_2+(3β+5γ)u_3=0$
which shows that $u_1,u_2,u_3$ is also linearly independent. As such, $dimSp\{u_1,u_2,u_3\}=3$
So $dimSp\{u_1,u_2,u_3\}=dimSpB$.
We already saw that $SpB \subseteq Sp\{u_1,u_2,u_3\}$ and therefore $SpB = Sp\{u_1,u_2,u_3\}$
$u_1,u_2,u_3 \in U = Sp\{v_1,v_2,v_3\}$ and therefore includes its own linear combinations.
Therefore $SpB \subseteq U$

A: You've made a good start, but you've lost your way. Here's a line-by-line critique that I hope will help.

It is easy to see that $B$ is a linear combination of $\{u_1,u_2,u_3\}$; in other words $B \subseteq Sp(u_1,u_2,u_3)$, and based on the information given $B \subseteq Sp(v_1,v_2,v_3)$.

You have a type problem here: vectors are linear combinations of other vectors; sets of vectors are something different. What you probably meant was "It's easy to see that each element of $B$ is a linear combination of the elements of $U = \{ u_1, u_2, u_3 \}.$" But rather than asserting that it's easy to see, better would be to say "Each element of $B$ is expressed in the definition as a linear combination of the elements of $U$, hence all are in $\text{Span}(U)$.

$B$ is linearly independent, so $dimSpB = 3$.
  Let α,β,γ be scalars in R.

Both of these sentences are fine.

We can write out $B$ as:
  $α(u_1-u_2)+β(u_1+3u_3)+γ(4u_2+5u_3)=0$

This is wrong. $B$ is a set, while the left hand side of the equality above is a vector, so you're not writing out $B$.
What you can say is

"We can, by substituting the definition of each element of $B$, write out an arbitrary linear combination of elements of $B$ as
  $α(u_1-u_2)+β(u_1+3u_3)+γ(4u_2+5u_3)$, and we know that if this is zero,
  then $\alpha, \beta,$ and $\gamma$ must be zero.

That statement is at least true, although I'm not sure what you're going to do with it.

Because $B$ is linearly independent, α=0,β=0 and γ=0.

That sentence needs to be deleted.

We can rewrite this formula as:
  $(α+β)u_1+(-α+4γ)u_2+(3β+5γ)u_3=0$
  which shows that $u_1,u_2,u_3$ is also linearly independent.

What you can really say is that if $(α+β)u_1+(-α+4γ)u_2+(3β+5γ)u_3=0$, then $\alpha, \beta, \gamma$ must all be zero. To show that the elements of $U$ are independent, you need to show that if $au_1 + bu_2 + cu_3 = 0$, then $a, b, c$ are all zero. You haven't done that at all.

As such, $dimSp\{u_1,u_2,u_3\}=3$

If you had been able to conclude what you wrote in the previous sentence, this one would be OK.

So $dimSp\{u_1,u_2,u_3\}=dimSpB$.

Same for this one.

We already saw that $SpB \subseteq Sp\{u_1,u_2,u_3\}$ and therefore $SpB = Sp\{u_1,u_2,u_3\}$

And this.

$u_1,u_2,u_3 \in U = Sp\{v_1,v_2,v_3\}$ and therefore includes its own linear combinations.

I have no idea what that sentence means, because the "its" refers to something that I'd expect to be the subject of the sentence...but the subject is $u_1, u_2,_3$, which is plural.

Therefore $SpB \subseteq U$

Back when you said "We can wrote out $B$ as ...", you could have re=gathered terms to say that each element of $\text{span}(B)$ has the form $(\alpha + \beta) u_1 + (-\alpha + 4\gamma)u_2 + ...$, which is evidently a linear combination of elements of $U$, hence in $\text{Span}(U)$, and you'd have been done.


text:
Q: How to use/maintain my S4 class with same name as S4 class in another R package? How to use/maintain my S4 class with same name as S4 class in another R package?
I'm writing a large R package that includes an S4 class named 'FeatureSet'.  Unfortunately, this is also the name of a virtual S4 class in the widely used 'oligo' package.  When I load my package first, and then oligo, and call
new("FeatureSet")

I get the error
Error in new("FeatureSet") :
  trying to generate an object from a virtual class ("FeatureSet")

In the NAMESPACE file, I've tried including 'exportClasses' and 'exportClassPattern' to export this S4 definition, or all S4 definitions, from my package without luck.  I've also included
exportMethods(coerce, initialize, show)

as I've defined methods for these generics in my package.
Is there a best-practice way to write R code to recognize only a specific S4 definition when multiple definitions with the same name are attached?  I could, of course, give my class a different name, but there must be some way to make sure that my classes don't collide with those in some other package in the future.  I've spent quite a while looking through the usual forums and documentation and was surprised to see that this question was not answered anywhere.  Thanks in advance!

A: I think the best practice is to choose a different, more descriptive name. It is inherently confusing to have two objects of the same name but different structure.
You can construct an instance of 'your' class via
new(getClass("FeatureSet", where=getNamespace("YourPackage")))`

probably wrapped in a simple 'constructor' function.
While in principle the methods package 'knows' the difference between an instance of your class and a class of the same name from another package,  you are almost certainly going to run into implementation bugs that will frustrate you and your users.