text:
Q: deploying rails angularjs app with capistrano I have a rails app with angularjs front end. I am trying to deploy the app using capistrano. here are my steps (keep in mind I am a novice in both capistrano and angular)
1. instal nodejs and npm on server
2. run the following task in deploy namespace. (I have .bowerrc and bower.json in rails root directory)
namespace :deploy do
  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      task :bower_npm_install do
        on roles(:app), in: :sequence, wait: 5 do
          within release_path do
            execute :npm, "install"
            execute :bower, "install"
          end
        end
      end
    end
  end
end

The error I got is

Sprockets::FileNotFound: couldn't find file 'angular-cookie' with type
  'application/javascript'

Seems that the task :bower_npm_install is not running before angular-cookie is accessed. Here are my questions

*

*How can I run the task

*is it the correct approach to deploy app with angular?

*Are there any other steps I need to run?


text:
Q: Style in textfield strust2 Why does the textfield look like this?
[https://i.stack.imgur.com/TkQ0i.png]
I want to eliminate the background color
Specific code:
<s:form action ="Update_datos_XML">
        <s:hidden id="id" name="id_sesion" value="%{#session.Sesion_usuario.id_sesion}"/>

              <s:textfield name="nom_pre" id="nombre" key="Nombre" placeholder="<%= pre.getNom_pre()%>"/>

            <s:textfield label="Apellido paterno" name="app_pre" placeholder="<%= pre.getApp_pre()%>"/>
            <s:textfield label="Apellido materno" name="apm_pre" placeholder="<%= pre.getApm_pre()%>"/>

          <s:submit cssClass="btn btn-success" value="Actualizar Datos"/>
        </s:form>

I have tried many things but there is no result, it is still seeing the same, I do not know what to do.
Any suggestions?

A: All the Struts2 Form Tags can be styled with CSS classes and with CSS inline style using the attributes cssClass and cssStyle respectively.
Example:
<s:textfield name="nom_pre" cssClass="mytext" cssStyle="width:80%;margin-right:5px;"/>

From this point forward is a CSS issue.

A:

.enjoy-css {
  display: inline-block;
  -webkit-box-sizing: content-box;
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  padding: 6px 20px;
  border: none;
  -webkit-border-radius: 32px / 54px;
  border-radius: 32px / 54px;
  font: normal 18px/normal "Coda", Helvetica, sans-serif;
  color: rgba(0,142,198,1);
  -o-text-overflow: ellipsis;
  text-overflow: ellipsis;
  background: rgba(252,252,252,1);
  -webkit-box-shadow: 0 1px 2px 0 rgba(0,0,0,0.2) inset;
  box-shadow: 0 1px 2px 0 rgba(0,0,0,0.2) inset;
  text-shadow: 1px 1px 0 rgba(255,255,255,0.66) ;
  -webkit-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
  -moz-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
  -o-transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
  transition: all 200ms cubic-bezier(0.42, 0, 0.58, 1);
  background-color:pink;
}

.enjoy-css:hover {
  background: rgba(232,249,255,1);
  -webkit-box-shadow: 0 2px 2px 0 rgba(90,90,90,0.2) inset;
  box-shadow: 0 2px 2px 0 rgba(90,90,90,0.2) inset;
}

.enjoy-css:focus {
  background: rgba(255,253,232,1);
}
   <s:textfield name="nom_pre" cssClass="enjoy-css" id="nombre" key="Nombre" placeholder="<%= pre.getNom_pre()%>"/

css can be used to customize your text box and other elements.
http://enjoycss.com/start will helpful to generate above or better css
In struts2 if you dont want to use pre formatted tables generated for forms then use theme simple as below
<s:set name="theme" value="'simple'" scope="page" />
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>

              <title>Test page</title>

       <s:textfield name="name"  id="name"/>
       <s:textarea name="address" id="address"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fix JS object replacing/encoding of strings? I have an object with a value that has spaces in it, and it gets replaced with an encoded string, like:
alldata["test"] will return "Long+name"
or something like
alldata["test"] will return "%BLong+name%B"
when it's set by using
alldata["test"] = "Long name"  (or "[Long name]") via a series of code.
Am I missing something? I don't think using $.toEvalJSON is the right way to go because I haven't transformed the object into JSON. I'd rather not do a string.replace either because I'd have to capture every possible type of input that is encoded.
Thank you!

A: If your question is how to remove the encoding, you could always use
unescape(s)

See Escape and Unescape Functions

A: The issue is related to the fact that I failed to mention that the object was being assigned the string as a result of a .serialize() command. Hence a urldecode() will work perfectly.


text:
Q: Can I have several XML layout files and only one main class? I'm wondering if it is possible to have a few different XML layout files without a separate class file for each? If so, how would I go about changing the layout file that the class is using on the fly?

A: You can have different .xml files. To get them you need to call in the specific method setContentView(R.layout.yourlayout1); I recommend to take a look at the android developer documentation to get a basic knowhow of what is a layout used for. Themes could be interesting for you also.


text:
Q: CSS Line-Through not being removed I've got some code that puts a line-through on a TR for deleted rows, but this means that my "Actions" column (that only has) buttons suffers.  This is because there are individual spaces between the buttons, which wind up getting line-throughed as well.
After poking around on W3Schools, it boggles me why this example doesn't work:

        this needs to be line-throughed
        This shouldn't be line-throughed.

How am I supposed to clear the line-through on child elements?
EDIT
I've updated my example - the problem is that I do not want to take the style off the parent element, just a single child element.

A: You shouldn't have to use important or inline styles for this. Try
h2 {text-decoration:line-through;}
h2 span {text-decoration: none; border: 1px solid black;}

EDIT
In that case with tr since yeah you applied text-decoration to it, you have to take text-decoration off the same element tr not td. Otherwise do:
tr td { text-decoration: whatever }

and then when needed

A: There was a similar question a little while back and according to that answer you can't do what you're trying to accomplish.
EDIT: Given your example, why not just apply the line-through to TD elements individually

        this needs to be line-throughed
        This shouldn't be line-throughed.

A: The line-through is applied to the H2, so you have to take it off of the H2.

Line-through

This is heading 2, and shouldn't be line-throughed.

(Viewable here: http://jsbin.com/anopa/)
The child (span) cannot affect the style of the parent (h2), which is where the style is applied.  You have to alter where the style was originally applied.
Edit: updated example

A: One way to fix this would be to change
tr {text-decoration:line-through}

to
tr td {text-decoration:line-through}

As a result, the line-through is on the individual table cell and not the whole row. This allows you to specify a different style on a single cell.
BTW, the issue doesn't seem to exist with the example code you've given on IE5.5+. In FF3.5, however, the example behaves as you've explained. I'm not sure which is the actual correct behavior.

A: Try This

        this needs to be line-throughed
        This shouldn't be line-throughed.

Notice that the style is "tr td" for both.

A:

It works, unless what you're trying to uncross is a link to a URL.
Then this phrase also defeats the link.


text:
Q: How to calculate some conditional probabilities
A red die, a blue die, and a yellow die (all six sided) are rolled. Given that no two of the dice land on the same number, what is the conditional probability that blue is less than yellow which is less than red?

The Answer is a sixth. I have absolutely no idea how to do this though.

A: Imagine recording the outcomes as $(a,b,c)$, where $a$ is the number on the red, $b$ the number on the blue, and $c$ the number on the yellow.  Fix a particular set of distinct numbers, such as $\{1,4,5\}$. All ordered triples (permutations) of  these three numbers are equally likely. There are $3!$ such permutations. In exactly $1$ of these permutations, we have $\text{blue}\lt \text{yellow}\lt \text{red}$.  Thus the required probability is $\frac{1}{3!}$.

A: Since the three die rolls are unequal, every set of possible rolls $\{x,y,z\}$, with $x < y < z$, can be obtained in exactly six ways:
$$
\begin{array}{|c|c|c|}
\hline
 \text{blue} & \text{yellow} & \text{red} \\
\hline
x & y & z \\
y & z & x \\
z & x & y \\
x & z & y \\
y & x & z \\
z & y & x \\
\hline
\end{array}
$$
Note that out of these six equally likely possibilities, the only one where blue < yellow < red is $x, y, z$ (since we assumed $x < y < z$).


text: Q: Magento Paypal Express guest checkout on mobile browser I am using Paypal express checkout and enable guest checkout option. It's working fine on desktop but when try from mobile browser Paypal not give option to pay as guest checkout. Paypal force to create Paypal account. what should I change at Magento level in parameter of express checkout?


text:
Q: Getting Javascript to accept button clicks I am writing a program that is similar to an Etch-A-Sketch where moving the cursor over a block turns it from black to a random color. I want the user to be able to hold down the spacebar and the program will stop highlighting blocks, which will let the user move their cursor without messing up their drawing. I have tried line 10-25, but it does not do anything.
let flagVar = 0;
for(let i = 0; i < SQUARES; i++) {
  const square = document.createElement('div')
  square.classList.add('square')
  square.addEventListener('mouseover', () => setColor(square))
  square.addEventListener('button', () => removeColor(square))
  container.appendChild(square)
}

document.body.onkeydown = function(e){
  const square = document.createElement('div')
  if(e.keydown === 32){
    square.addEventListener('mouseout', () => removeColor(square))
    container.appendChild(square)
    flagVar++;
  }
}
document.body.onkeyup = function(e){
  const square = document.createElement('div')
  if(flagVar > 0 && e.keyup === 32){
    square.addEventListener('mouseover', () => setColor(square))
    container.appendChild(square)
    flagVar--;
  }
}

Edit: I have taken the code out of the for loop, and attempted to set a flag variable at the suggestion of IT goldman, but I am new to flag variables so I am unsure if I implemented this correctly. It still is not working

A: As It goldman pointed out, it's better to set a flag to see if the cursor should paint or not, and as Barman also stated, use a single event listener. You can separate the squares apart by setting an unique id on each of them.
See this below as pseudo code.
let shouldPaint = true;

for (let i = 0; i < SQUARES; i++) {
  const square = document.createElement('div')
  square.classList.add('square')
  square.setAttribute('id', 'square' + i);

  container.appendChild(square)
}

setShouldPaint = (_shouldPaint, keyCode) => {
   const SPACE = 32;

   if (keyCode == SPACE) {
     shouldPaint = _shouldPaint;
   }
}

square.addEventListener('onkeydown', (event) => setShouldPaint(false, event.keydown))
square.addEventListener('onkeyup',   (event) => setShouldPaint(true, event.keyup))
square.addEventListener('mouseover', (event) => setColor(event.target.id, shouldPaint))
square.addEventListener('click',     (event) => removeColor(event.target.id))


text:
Q: Recortar Imagen seleccionada de la Galería Lo que realizo en mi código es lo siguiente:
Selecciono una imagen de la galería, la redimensiono a 150x150, creo un .png en mi dispositivo y guardo la ruta en mi Sqlite, hasta ahí todo bien. Pero quiero cambiar algo, quiero poder recortar la imagen (desde la opción Recortar de la Galería) antes de crear el .png, me explico:
Seleccionar una imagen de la Galería > Poder recortar la imagen en 150x150 (pero desde la opción Recortar de la Galería, muestro abajo un ejemplo) > Guardar el .png en mi dispositivo > ... ya todo esto creo que no habría que modificarlo.
Quiero cambiar esto porque al redimensionar la imagen completa en 150x150 se ve deformada y si puedo recortar la imagen desde la Galería en esas medidas no habría problemas.
Ejemplo de lo que quiero:

Así es como selecciono la imagen de la Galería y guardo un .png en 150x150
clase:
// Metodo que abre la galeria
private void ventanaImagen() {
    try {
        final CharSequence[] items = { "Seleccionar de la galería" };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Seleccionar una foto");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        Intent intent = new Intent();
                        // Show only images, no videos or anything else
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        // Always show the chooser (if there are multiple options available)
                        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
                        break;
                }
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    } catch (Exception e) {
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri selectedImage = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
            //Define path donde sera guardada una nueva imagen con medidas 150x150px
            File dir = Environment.getExternalStoragePublicDirectory("Download");
            File file;
            if(ruta_imagen.isEmpty()) { //No contiene imagen
                Log.e(TAG, "NO contiene imagen, crea imagen.");
                file = new File(dir, "profile_" + System.currentTimeMillis() + ".png");
            }else{
                Log.e(TAG, "Contiene imagen, path " + ruta_imagen);
                file = new File(ruta_imagen);
            }
            if (!file.exists()) { //Si archivo no existe.
                try {
                    file.createNewFile(); //Procede a crearlo.
                } catch (IOException e) {
                    Log.e(TAG, "onActivityResult() " + e.getMessage());
                }
            }
            if (bitmap != null) {
                //Redimensiona imagen.
                Bitmap bitmapout = Bitmap.createScaledBitmap(bitmap, 150, 150, false);
                FileOutputStream fOut = null;
                try {
                    fOut = new FileOutputStream(file);
                    bitmapout.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage());
                }
                //Muestra imagen con nuevas medidas en ImageView.
                ImageView imageView = (ImageView) findViewById(R.id.imagenPersona);
                imageView.setImageBitmap(bitmapout);
                //Obtengo la ruta de la imagen creada en el dispositivo.
                Log.i(TAG, "Ruta imagen en archivo : " + file.getAbsolutePath());
                ruta_imagen = file.getAbsolutePath();
            } else {
                Toast.makeText(this, "Error obteniendo imagen", Toast.LENGTH_LONG).show();
            }

        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }
}

A: Una opción sin el uso de libraries, sería obtener la medida del bitmap y obtener una proporcional definiendo un porcentaje
private static int FACTOR = 5; //5%

de esta forma calcularía un tamaño proporcional al original:
                int bitmapWidth = bitmap.getWidth();
                int bitmapHeight = bitmap.getHeight();

                int bitmapWidthResized = (FACTOR * bitmapWidth)/100;
                int bitmapHeightResized = (FACTOR * bitmapHeight)/100;
                Log.i(TAG, "medidas originales, width : " + bitmapWidth + " ,height : " + bitmapHeight);
                Log.i(TAG, "nuevas medidas, width : " + bitmapWidthResized + " ,height : " + bitmapHeightResized);

A: He utilizado esta librería Android-Crop y realiza a la perfección lo que necesitaba. Solucionado!

A: Puedes usar una librería externa, como por ejemplo Android Image Cropper.


text:
Q: VS Remote Debugging I'm very unfamiliar with traditional debugging, but we are having an issue on a production server and it would come in very handy right now, but I can't even get VS to connect to the remote machine and show any processes.
I've installed the remote debugging tools from MS.  The remote computer is one that I have  VPN connection to (I can browse to \172.25.250.66\c$ from windows explorer -- I am not sure, but I thought this meant that I was on the same network as the remote machine, but maybe I'm wrong).
Debug -> Attach Process, even if I choose Remote (no authentication) I can't see any other computers besides my own.

A: Remote (no authentication) won't work for managed debugging.
You'll need to use Default transport. For that you will need the same users (and I believe also the same passwords) on both your computer where you are debugging and on the remote machine. On your computer, the Visual Studio process must run as that user, and of course on the remote machine the remote debugging process as well.


text:
Q: When does mod_php in apache seed the random number generator? I am using the php rand() function to generate coupon codes for my e commerce system.
It worked fine for a while but now I am getting a lot of errors that the code is already in the system.
This is the function I use:
function generateRandomString($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

And my codes are 32 characters long.
I did a sample of ~150 tries and noticed that more than 50% of the generated codes where laready in the system.
I have 4212 codes in the system. The odds of a 32 character random string with 36 different symbols producing a collision are basically zero, and I get 50% collisions.
When I re-seeded the random number generator in my function by calling srand(); I did not have any collisions any more.
But on the man page of php it cleary says:

Note: As of PHP 4.2.0, there is no need to seed the random number
  generator with srand() or mt_srand() as this is now done
  automatically.

I am running php version PHP 5.5.9
So my thoughts where something like that seeding is done, but only once per webserver worker, and then when the process is forked, it is not reseeded or something like that.
But that would be clearly a bug in apache...
I am running php as apache modul in apache version Apache/2.4.7 (Ubuntu) and the mpm_prefork_module module
So do I still need to call srand() at the top of every script dispite the manpages saying other wise, and why? Is it apaches fault or PHP's?
And yes, I am aware that I should not use this function for this purpose, and I will update it to use cryptographically secure numbers. But I think this should not happen anyway and I am still interested in what is going on!

A: If your codes are 32 characters long, then why don't you simply encrypt the current microtime with md5 ?
  $coupon = md5( microtime() );

One line simple.  And if you want a touch of randomness, just throw a
   $coupon = md5( microtime() . mt_rand( 0, 10000) );

On there like a salt.  That will almost guarantee you will never duplicate.  As for the why it is not as random.
PHP's random number generators are seeded only once per process.
See this posting ...
http://phpsecurity.readthedocs.org/en/latest/Insufficient-Entropy-For-Random-Values.html
by the way I don't think you need cryptographically secure hashes, only sufficiently random ones that cant be easily guessed.  Even with a cryptographic hash, users will enter said hash into the cart for the coupon, it's a simple matter to brute force even a cryptographically secure hash then, you'd do better to invest time in only allowing "n" attempts, or "n" attempts per second etc.  To reduce the rate a brute force attack can be done.
For example, I would just try all combinations of 32 character hashes. So it doesn't matter in the end, because you are not using plaintext entries like a password, and then hiding your salting and encryption method.  The number of coupons active would determine my success rate and the time it takes me in either case ... If you follow.
IMPLIED IN MY ANSWER IS THIS
PHP's random number generators are seeded only once per process.  Forking does not create a new process but copies the current processes state.
See
Calling rand/mt_rand on forked children yields identical results
and
http://wiki.openssl.org/index.php/Random_fork-safety
and
http://www.reddit.com/r/shittyprogramming/comments/2jvzgq/sometimes_it_takes_real_shitty_code_to_expose_an/
Additionally this is not an issue specific to php but more so to psudorandom number generation in general.

A: See this: https://github.com/php/php-src/blob/d0cb715373c3fbe9dc095378ec5ed8c71f799f67/ext/standard/rand.c#L66-L68
Apparently RNG is being reseeded on first call to rand() (or explicitly calling srand()).
Since fork copies parent's memory, child also gets parent's seed - never getting reseeded.

A: function generateRandomString($length) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return substr(time().$randomString,0,$length);
}


text:
Q: Efficient large file upload with Yesod I want to implement large file upload with my Yesod application. Right now I have:
module Handler.File where

import Import

import System.Random
import System.FilePath
import Control.Monad
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding

-- upload

uploadDirectory :: FilePath -- FIXME: make this configurable
uploadDirectory = "incoming"

randomFileName :: IO FilePath
randomFileName = do
  fname'base <- replicateM 20 (randomRIO ('a','z'))
  let fname = uploadDirectory </> fname'base <.> "bin"
  return fname

fileUploadForm :: Form (FileInfo, Textarea)
fileUploadForm = renderDivs $ (,)
    <$> fileAFormReq "Choose a file"
    <*> areq textareaField "What's on the file?" Nothing

getFileNewR :: Handler RepHtml
getFileNewR = do
  (formWidget, formEnctype) <- generateFormPost fileUploadForm
  defaultLayout $ do
       setTitle "Upload new file."
       $(widgetFile "file-new")

postFileNewR :: Handler RepHtml
postFileNewR = do
  user <- requireAuth
  ((result, formWidget), formEnctype) <- runFormPost fileUploadForm
  case result of
    FormSuccess (fi,info) -> do
                 fn <- liftIO randomFileName
                 liftIO (LBS.writeFile fn (fileContent fi))
                 let newFile = File (entityKey user) fn info (fileName fi) (fileContentType fi)
                 fid <- runDB $ insert newFile
                 redirect (FileViewR fid)
    _ -> return ()

  defaultLayout $ do
       setTitle "Upload new file."
       $(widgetFile "file-new")

It is mostly fine, except few issues:

*

*Maximum size of a file is around 2 megabytes. I have a fix, but is it right way to do this? My fix is overriding default implementation of maximumContentLength method in Yesod instance for my app, like this:
maximumContentLength _ (Just (FileNewR _)) = 2 * 1024 * 1024 * 1024 -- 2 gigabytes
maximumContentLength _ _ = 2 * 1024 * 1024 -- 2 megabytes

*The amount of memory used is equal to the size of a file. This is really suboptimal. I would like to use tempFileBackEnd from http://hackage.haskell.org/packages/archive/wai-extra/1.2.0.4/doc/html/Network-Wai-Parse.html but I have no idea how to actually wire that into my request and make it work with forms logic (hidden _token field etc.).

*The upload is 'single shot': any examples of how to make it work with Flash/Html5 based uploaders that show progress to user?

A: *

*Your solution is correct. The purpose of the maximumContentLength setting is to allow you to override this value for specific routes that need larger uploads.

*This is a shortcoming of the current setup of file handling in yesod-core. It's currently hard-coded to use in-memory file uploads. We've discussed on the mailing list in the past that this is suboptimal. I've just created a Github issue for this, and the fix will be included in Yesod 1.1 (no timetable on release though).

*I don't have an example of this, sorry.


text:
Q: lvalue error on the 10th line #include <stdio.h>
#include <conio.h>
void main ()
{
    clrscr ()   ;
    char a  [5];
    puts ("K?");
    gets (a);
    fflush (stdin);
    if (a = ("K"))
    {
        puts (a);
    }
    else
    {
        puts ("BAE");
    }
    getch ();
}

The 10th line shows an Lvalue error while compiling, please help. this is my first program ever and this is my first day ever on coding and I'm self teaching.

A: *

*fflush(stdin) is Undefined Behavior

*the comparison operator in C is a ==; = is the assignment operator. You can't assign anything to an array, so an error is thrown

*you can compare strings using strcmp() from <string.h>; == just compares their addresses

A: I think that instead of the assignment in the if statement
if (a = ("K"))

you mean a comparison.
Nevertheless arrays  do not have the comparison operator. You have to compare arrays element by element yourself. For character arrays there is function strcmp declared in header <string.h>.
Thus the valid code can look like
Also you should not use fflush function with standard input. Otherwise the program has undefined behaviour,
#include <string.h>

//...

if ( strcmp( a, "K" ) == 0 )
//...

A: There are two mistakes in this line
if (a = ("K"))

First, you are using = where you meant ==. But that is wrong anyway, you cannot test for string equality in C. It has to be something like this, which tests the first character of the string and its terminator
if (a[0] == 'K' && a[1] == '\0')

or, you can use a library function
#include <string.h>
...
if (strcmp(a, "K") == 0) {
    // are the same string.
}


text:
Q: how to identify a field separator from scanf? I need to read a text file which has names with numbers like below.
rENLAg:12182
TgAlKd:19773
SSqUpz:16466
QYStPh:4113
CodNhz:28920
SgoIGz:25343

I need to separate the letters from the numbers.fscanf only identifies spaces, but not other field separators. Therefore how do I do it?

A: One solution would be to use scan sets (see the entry for Conversion specifier [set] in the format specifiers table):
char buf[7];
int i;
/* Check result of fscanf(), which returns the number
   of assignments made, to ensure both 'buf' and 'i'
   were assigned values. */
if (fscanf(fp, " %6[^:]:%d", buf, &i) == 2)
{
}

where " %6[^:]" means skip any leading whitespace (new-line character from previous read for example) and read up to, but not including, the first : character but no more than 6 characters (to prevent buffer overrun).


text:
Q: Alt keyup lost when doing alt-tab I'm detecting alt with the following code. It works, but when I do alt-tab to switch to another program, I get a keydown of 18 (alt) and no keyup, and alt remains pressed. How can I solve this?
var altPressed = false;

$(document).keydown(function(evt) {
    console.log("keydown", evt.which);
    switch (evt.which) {
    case 18:
        altPressed = true;
    break;
    }
}).keyup(function(evt) {
    console.log("keyup", evt.which);
    switch (evt.which) {
    case 18:
        altPressed = false;
    break;
}

A: Alt + Tab removes the focus on your main window, thus the keyup event will not fire.
Here's a probable solution you could use. I'm not sure if escape is being registered from which though, might have to use keyCode instead.
Example:
var altPressed = false;

$(document).keydown(function(evt) {
    console.log("keydown", evt.which);
    switch (evt.which) {
    case 18:
        altPressed = true;
        break;
    case 9: //tab key
    case 27: //escape key
        if(altPressed) {
             altPressed = false;
        }
    break;
    }
}).keyup(function(evt) {
    console.log("keyup", evt.which);
    switch (evt.which) {
    case 18:
        altPressed = false;
    break;
});

A: As @Nathan points out correctly: Alt + Tab removes the focus on the main window, thus the keyup event will not fire.
Here is a solution that does not require jQuery and works for every focus loss:
Using the Blur event
Here is a VanillaJS example using your code, read more about the blur event in MDN docs
let altPressed = false;

function keyDownHandler(evt) {
  if(evt.key === "Alt")
    altPressed = true
}

function keyUpHandler(evt) {
  if(evt.key === "Alt")
    altPressed = false
}

document.addEventListener('keydown', keyDownHandler)
document.addEventListener('keyup', keyUpHandler)
window.addEventListener('blur', keyUpHandler)

Note: same as with @Nathans answer, this will not know whether the key is still down when moving back to the page (but with alt+tab it would not anyways).


text:
Q: How to put mat-sort-header in menu can anyone tell me how to extract the mat-sort-header functionality from the headers into a menu.
I want to open a menu when I click on one of the header. Within this menu I want to use the matSort functionality.
In fact, I want to trigger the matSortChange  event

A: You're asking about "contextual menu" and "mannage mat-sort". It's a broad question and really I don't know how answer, so a brief data
If you see the source of matSort. You can "override" the method sort.
You can use some like
@ViewChild(MatSort) sort: MatSort;

ngAfterViewInit(){
    this.sort.sort=(sortable: MatSortable)=>{
      //this only to update the variables active and direction

      if (this.sort.active != sortable.id) {
        this.sort.active = sortable.id;
        this.sort.direction = sortable.start ? sortable.start : this.sort.start;
      } else {
        this.sort.direction = this.sort.getNextSortDirection(sortable);
      }

      //this make the table sorted
      this.sort.sortChange.emit({active: this.sort.active, direction: this.sort.direction});
    }

    this.dataSource.sort = this.sort;
}

So you can choose "not emit the change" or emit in a contextual menu.
For contextual menu you can use cdk-overlay. It's not well documented, but if you want an example, sometime ago I wrote this SO.
Another option is that each td of your header was a mat-menu
NOTE: I don't know how many is your knowledge in Angular, so it's possible this answer don't help you so much. Give us more data
Update well, we has all necesary with this data, so go on!
First we "override" the sort function to do nothing and create a new function to make the sort
  ngOnInit()
  {
    this.sort.sort=(sortable: MatSortable)=>null
    this.dataSource.sort=this.sort
  }
  sortTable(active:string,direction:string)
  {
    this.sort.active=active
    this.sort.direction=direction as SortDirection
    this.sort.sortChange.emit({active: active, direction: direction as SortDirection});
  }

Then use mat-menu in the th. So our th will be like
  <ng-container matColumnDef="position">

      No.
      <mat-menu #position="matMenu">
        <button mat-menu-item (click)="sortTable('position','asc')">
          <mat-icon
            *ngIf="sort.active=='position' && sort.direction=='asc'"
            >checked</mat-icon
          >Ascend
        </button>
        <button mat-menu-item (click)="sortTable('position','desc')">
          <mat-icon
            *ngIf="sort.active=='position' && sort.direction=='desc'"
            >checked</mat-icon
          >Descend
        </button>
      </mat-menu>

    {{element.position}}
  </ng-container>

Finally we need some .css to "remove" the arrow that material add.
In styles.css
.custom-table .mat-sort-header-arrow
{
  visibility:collapse;
  min-width: 0;
}

And to beauty our menu in component.css
button.mat-menu-item
{

  height: 1.75rem!important;
  font-size:12px;
  text-overflow: unset;
  display:flex;
  align-items: center;
  justify-content: flex-start;
}

button.mat-menu-item >span
{
  padding-right: 24px;
  padding-left:24px;
}
button.mat-menu-item .mat-icon+span
{
  padding-left:0;
}

.mat-menu-item .mat-icon
{
  font-size:12px;
  height:1.75rem!important;
  margin-right: 0;
  margin-top:1rem;

}

the result in this stackblitz


text:
Q: ¿Como cambiar tamaño de la casilla de un checkbox? buen dia, quisiera saber ¿como se puede cambiar el tamaño de la casilla de un checkbox?
estoy programando en C# con WindowsForms

A: @Macx :
para qu puedas cambiar el tamaño en window form realiza este siguiente codigo.-
checkBox1.Appearance = Appearance.Button;
checkBox1.Font = new Font("Microsoft Sans Serif", 16);
checkBox1.AutoSize = false;
checkBox1.Size = new Size(100, 100);


text:
Q: How to get this type of font? I was not able to get the required font as shown below

Here is my MWE
 \documentclass[10.0pt,a4paper]{article}
 \usepackage[top=0.5cm,bottom=1.4cm,left=1.0cm,right=1cm]{geometry}
 \usepackage[table]{xcolor}
 \usepackage[all]{tcolorbox}
 \usepackage[portuges, brazil, english]{babel}
 \usepackage[utf8]{inputenc}

 \usepackage{multicol}
 \begin{document}

 \begin{tcolorbox}[colframe=green]

 \centering
 \fontsize{8}{22}\selectfont
 \Huge\textbf{Organic Field Effect Transistor}
 \end{tcolorbox}
 \end{document}

The output of my MWE is

A: Hope the below tag may help you:
\documentclass[10.0pt,a4paper]{article}
 \usepackage[top=0.5cm,bottom=1.4cm,left=1.0cm,right=1cm]{geometry}
 \usepackage[table]{xcolor}
 \usepackage[all]{tcolorbox}
 \usepackage[portuges, brazil, english]{babel}
 \usepackage[utf8]{inputenc}

 \usepackage{multicol}
\usepackage{times}
 \begin{document}

 \begin{tcolorbox}[colframe=green]

 \centering
 \fontsize{8}{22}\selectfont
 \Huge\textsf{\textbf{Organic Field Effect Transistor}}
 \end{tcolorbox}
 \end{document}

I've added the package "times" and the tag \textsf in your code.


text:
Q: Datamapper resource becomes collection in session value After running a function that (blah) returns a Datamapper object (LuckEvent), my code stores that in a Rack session. This is read in a HAML view, which consistently returns a DataMapper::Collection.
Code for getting the LuckEvent:
puts "|LX| Jumped, getting event"
session["lastLDEvent"] = ldg.get_event
puts "|LX| Jump event: #{session["lastLDEvent"].inspect}" #Consistently returns the right value.

Code for viewing it in HAML:
.w3-container.w3-pale-blue
  = session["lastLDEvent"].class if session["lastLDEvent"] #Consistently returns DataMapper::Collection.

Switching that to .inspect consistently returns [].

A: I would try casting the result of get_event to an Array. There might be an issue with storing DataMapper::Collection in the session.
session["lastLDEvent"] = ldg.get_event.to_a

If that doesn't work, you may need to store the IDs and then re-query the events.
session["lastLDEvent"] = ldg.get_event.map(&:id)


text:
Q: multisite not displaying thumbnail image after upload in nextgen gallery Namaste,
https://www.gitamritam.com/2017y/inaug/
In the above link, its a multisite in wordpress, where thumbnails and gallery images are not showing up. We have done it using nextgen plugin which is really awesome in wordpress. But here its showing broken images in gallery.
We checked the same thing in a free hosting server and it works fine. Not sure why its not showing up in this multisite.
This is current url of image in multisite:
https://www.gitamritam.com/2017y/images/sites/18/gallery/17y-inaug/17gita-inaug-16.jpg
The subsite name '2017y' is inserting in the image path, when we remove the multisite name from the image url its showing image.
https://www.gitamritam.com/images/sites/18/gallery/17y-inaug/17gita-inaug-16.jpg
Checked the same thing in another hosting server and it worked fine. Thumbnails are showing fine without removing subsite names, not broken.
Not sure why its not showing in gitamritam website.
Any help would be appreciable.
Thanks,
Editor – Gitamritam


text:
Q: Block Range of IPs I'm trying to block a range of IPs from visiting my website
Here is what I have in my .htaccess file
order allow,deny
Deny from 64.244.0.0/64.245.255.255
Deny from 64.244.0.0/15
allow from all

I'd like to know if anyone can tell (or estimate) me how many IPs have i blocked there?

A: I believe the first DENY FROM is just wrong.  I've always seen it this way
    64.244.0.0/15
Base Address^  ^Number of bits to use for subnet

This would mean that you have 2^15 addresses in the deny block.
Edit
Using the comments below, what you would want is
ORDER deny,allow
DENY from 64.244.0.0/15
ALLOW from all


text:
Q: Show/Hide thumbnail in loop In wordpress loop a wanna make thumbnail toggle on link click.
Part of loop:
<?php $i++; ?>
        <?php $aktualnosc_meta = get_post_meta($aktualnosc->ID); ?>

                    <a id="displayText-<?php echo $i; ?>" href="javascript:toggle();">show
                    <div id="toggleText-<?php echo $i; ?>" style="display: none">
                        <a href="<?php echo get_permalink($aktualnosc->ID) ?>">
                        <?= get_the_post_thumbnail($aktualnosc->ID, 'full', []) ?>

JS:

It dont work. I click on "show" link but nothing happens. Can you help me?

A: I don't know - whether you have one toggle function or bunch of toggle functions, both cases will not work. Try this:

        <a id="displayText-<?php echo $i; ?>" href="javascript:toggle(<?php echo $i; ?>);">show
            <div id="toggleText-<?php echo $i; ?>" style="display: none">
                <a href="<?php echo get_permalink($aktualnosc->ID) ?>">
                    <?= get_the_post_thumbnail($aktualnosc->ID, 'full', []) ?>

And toggle function should be one only:

A: By the time your event handlers run, the page is entirely in the browser and does not have access to PHP variables, functions, etc.
So, you need javascript references to toggleText and displayText for each clicked item.  Here's one way.
function toggle(text) {
    // text is the dom element that was clicked on
    var ele = text.parentNode.getElementsByTagName("div")[0];
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
}

Then you will need to change your onclick to:
href="javascript:toggle(this);"

To pass the "text" dom element to the handler function.
Note that all of your id attributes are unnecessary if you use this technique.


text:
Q: Splitting irregular columns in r I have a column in my data frame that I need to split into multiple columns using the delimiter "_".  However, I need to retain only the last two columns from the output (which will always contain the data that I need) in each row.  In many records, the number of delimiters is different, therefore resulting on a different number of columns when split.  How do I get only the last two columns of each observation. The following are examples of some of the records
unique(data$tagid.1)
[1] tag id                                    00000_0_0900_226000013189
[3] 00000_0_0986_114100005288                 00000_0_0900_226000132078
[5] 00000_0_09LA_00000_0_0900_226000          00000_0_0900_226000131998
[7] 0000_2004000000000847                     00000_0_0900_22600001\a\0048\022LI
[9] 00000_0_0900_226000013189I                00000_0_0986_114100006473

I'm trying to get an output something like:
tagid$C1         tagid$C2
0986             114100005288
0900             226000013189
0900             226000
etc....          etc....

My solution has some problems, i.e. it outputs two rows with 57k columns and its kind of slow, anyone have a better solution than:
 > data.tag <- as.data.frame(data$tagid.1)
>   tag1 <- cSplit(data.tag,"data$tagid.1",sep="_")
>
>   head(tag1)
   data$tagid.1_1 data$tagid.1_2 data$tagid.1_3 data$tagid.1_4 data$tagid.1_5          data$tagid.1_6 data$tagid.1_7
1:         tag id             NA             NA             NA             NA                 NA             NA
2:          00000              0           0900   226000013189             NA             NA             NA
3:          00000              0           0900   226000013189             NA             NA             NA
4:          00000              0           0900   226000013189             NA             NA             NA
5:          00000              0           0900   226000013189             NA             NA             NA
6:          00000              0           0900   226000013189             NA             NA             NA
>
>   lastValue <- function(x)   tail(x[!is.na(x)], 2)
>   tag2 <- as.data.frame(apply(tag1, 1, lastValue))
> dim(tag2)
[1]     2 56997

A: It is possible to achieve this by using a regular expression:
pat <- "^.*_(.*)_(.*)$"
data.tag <- data.frame(tagid.1 = c("tag id",
                         "00000_0_0900_226000013189",
                         "00000_0_0986_114100005288",
                         "00000_0_0900_226000132078",
                          "00000_0_0900_22600001\a\0048\022LI"))
data.frame(C1 = sub(pat, "\\1", data.tag[,1]),
           C2 = sub(pat, "\\2", data.tag[,1]))

      C1                    C2
1 tag id                tag id
2   0900          226000013189
3   0986          114100005288
4   0900          226000132078
5   0900 22600001\a\0048\022LI

A: We could also do this with strsplit
setNames(do.call(rbind.data.frame, lapply(strsplit(as.character(data.tag[,1]), "_"),
          function(x) if(length(x)==1) rep(x, 2) else tail(x,2))), paste0("C", 1:2))
#     C1                    C2
#1 tag id                tag id
#2   0900          226000013189
#3   0986          114100005288
#4   0900          226000132078
#5   0900 22600001\a\0048\022LI


text:
Q: Ubuntu can't turn off Legion back logo light Is there a way to turn on/off the Legion Slim 7 Logo light on Ubuntu OS? It works by pressing Fn+l on windows; doesn't work on ubuntu.
The keyboard light works perfectly fine.It is just the logo light. Is it possible to code a driver to do so? If so, Where should I start?


text:
Q: 16.04 LTS wifi doesn't resume after disconnecting from vpn New to Ubuntu/Linux and running into some issues connecting/disconnecting from vpn. It took me a little while to figure out how to connect to my work network so that I could remote desktop into my workstation. I ended using openconnect to connect to the network and remmina for the actual remote desktop connection (RDC).
The issue I'm running into is after I disconnect from my RDC and openconnect session, the wifi doesn't automatically connect back to my wifi. I usually can see the wifi symbol has full bars, but the internet does not work. At the moment I have just been restarting my computer, but this is obviously not ideal. I couldn't find any threads with similar problems, but if they exist, please direct me to them!
Here is my wifi chip info:
  *-network
       description: Wireless interface
       product: Wireless 7260
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlp2s0
       version: 6b
       serial: 5c:51:4f:ea:45:0c
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=4.10.0-32-generic firmware=17.459231.0 ip=192.168.168.171 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:46 memory:f1400000-f1401fff

A: Your routing table is the most likely culprit.  It was used to route all your internet packets through your VPN.  There is probably one routing rule to do this and it needs to be replaced.  You will need to open a command line terminal to proceed.  Do the command ip route show and look for the rule or rules that begin with default.  Enter a rule replacement for that default route rule.  Here is the command that should do it for you: sudo ip route default via 192.168.168.171 dev wlp2s0.  Then repeat the command ip route show to verify the change.  Verify you can reach the internet with ping -c 9 8.8.8.8.


text:
Q: Add text in word based on content I have a batch of .doc documents, in the first line of each document I have the name of a person written. I would like to add in each document the email adress of the person, based on a list I have. How can I use python or vba to program something that does the job for me?
I tried to do this vba code, that finds the name of the person and then writes the email, was thinking to loop it over. However even this minumum working example does not actually work. What am I doing wrong?

    Sub email()
    Selection.find.ClearFormatting
    Selection.find.Replacement.ClearFormatting

    If Selection.find.Text = "Chiara Gatta" Then
       With Selection.find
        .Text = "E-mail:"
        .Replacement.Text = "E-mail: chiara.gatta@gmail.com"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
       End With
    Selection.find.Execute replace:=wdReplaceAll
    End If
    End Sub

A: The question lacks minimum details & code required for help. However I am trying to give you a code that would pickup person names & email addresses from one table in a document containing the code. the table should have 3 columns, 1st col contain Name of the person, 2nd col should contain Email address with 3rd column blank for remarks from code. See image
On running the code you would be prompted to select the word files that would be replaced by the email address. On trial use only copy files and may try only a handful of files at a time (if file sizes are large). It is assumed that files will contain Name and  word "E-mail:"  (if "E-mail:" word is not in the file try to modify the code as commented)
Code:
Sub test2()
Dim Fldg As FileDialog, Fl As Variant
Dim Thdoc As Document, Edoc As Document
Dim Tbl As Table, Rw As Long, Fnd As Boolean
Dim xName As String, xEmail As String

Set Thdoc = ThisDocument
Set Tbl = Thdoc.Tables(1)
    Set Fldg = Application.FileDialog(msoFileDialogFilePicker)

    With Fldg
    .Filters.Clear
    .Filters.Add "Word Documents ", "*.doc,*.dot,*docx,*.docm,*.dotm", 1
    .AllowMultiSelect = True
    .InitialFileName = "C:\users\user\desktop\folder1\*.doc*" 'use your choice of folder
     If .Show <> -1 Then Exit Sub
    End With

    'Search for each Name in  Table 1 column 1
    For Rw = 1 To Tbl.Rows.Count
    xName = Tbl.Cell(Rw, 1).Range.Text
    xEmail = Tbl.Cell(Rw, 2).Range.Text
        If Len(xName) > 2 And Len(xEmail) > 2 Then
        xName = Left(xName, Len(xName) - 2)        'Clean special characters in word cell text
        xEmail = Left(xEmail, Len(xEmail) - 2)     'Clean special characters in word cell text

           'open each Document selected & search for names
            For Each Fl In Fldg.SelectedItems
            Set Edoc = Documents.Open(Fl)
            Fnd = False
                With Edoc.Content.Find
                .ClearFormatting
                .Text = xName
                .Replacement.Text = xName & vbCrLf & "E-mail: " & xEmail
                .Wrap = wdFindContinue
                .Execute Replace:=wdReplaceNone
                '.Execute Replace:=wdReplaceOne
                Fnd = .Found
                End With

                'if Word "E-mail is not already in the file, delete next if Fnd Branch"
                ' And use .Execute Replace:=wdReplaceOne instead of .Execute Replace:=wdReplaceNone
                If Fnd Then  ' If Name is found then Search for "E-Mail:"
                Fnd = False
                With Edoc.Content.Find
                .ClearFormatting
                .Text = "E-mail:"
                .Replacement.Text = "E-mail: " & xEmail
                .Wrap = wdFindContinue
                .Execute Replace:=wdReplaceOne
                Fnd = .Found
                End With
                End If

                If Fnd Then
                Edoc.Save
                Tbl.Cell(Rw, 3).Range.Text = "Found & Replaced in  " & Fl
                Exit For
                Else
                Tbl.Cell(Rw, 3).Range.Text = "Not found in any selected document"
                End If
            Edoc.Close False
            Next Fl
       End If
    Next Rw
End Sub

it's operation would be like this. Try to understand each action in the code and modify to your requirement.


text:
Q: Click all see more on a facebook search page using selenium - python Hi I am trying to scrape facebook with selenium and bs4.
I have a function to search the facebook for a search query and then load the page with that search.
I am able to scroll down too.
But now when I am trying to click all see more buttons I am stuck.
Here is the relevant html

See more

See more

2 others

See more

Code I am using to scrape
search()
sleep(2)
click_more = True
see_more_class = '@class,"qi72231t nu7423ey n3hqoq4p r86q59rh b3qcqh3k fq87ekyn bdao358l fsf7x5fv rse6dlih s5oniofx m8h3af8h l7ghb35v kjdc1dyq kmwttqpk srn514ro oxkhqvkx rl78xhln nch0832m cr00lzj9 rn8ck1ys s3jn8y49 icdlwmnq cxfqmxzd pbevjfx6 innypi6y"'
see_more_text = 'text()="See More"'
while click_more:
    sleep(1)
    element = driver.find_element(By.XPATH,f'//div[contains({see_more_class})]')
    if element.is_displayed():
        try:
            if element.text=='See more':
                element.click()
            elif element.text=='2 others':
                pass
        except Exception as e:
            print(e)
    else:
        click_more = False

The code is able to click the first two see more no problem. But I am not able to move ahead of the 2 others button. I don't want to click the 2 others button.
I am quite new to selenium any and all explanation and answers are welcome and appreciated.
Tried giving the see_more_text in the xpath contains but to no avail. I am using a chrome browser.
There might be a chance that the 2 others might have a different text say 13 others. So need a sure shoot solution to how to click all the see more buttons


text:
Q: Three commit references when merging submodules I am merging a branch in a project that uses git submodules. Usually when there is a conflict there are two sets of changes, theirs and ours. Resolving the conflicts is about merging these two into one. But I noticed that for git submodules the diff shows a third value:
diff --cc my_submodule
index dd7404e,e6753b1..0000000
--- a/my_submodule
+++ b/my_submodule
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit dd7404e5f35ee0b0064f0d6ed8201cc39d6ed6b2
 -Subproject commit e6753b1142cf0350608720ff23f7ecf51b813cd9
++Subproject commit 3b4e75fbb7c55cf21e19509bbbbfabfa1fc10630

What do the "- ", " -" and "++' mean?
Note that it's possible that the submodule version actually checked out in the repository before the merge was neither theirs nor ours, would that explain the three hashes?

A: It simply means the submodule gitlink (the special entry in the index of the parent repo) was changed both in source and destination.
(See git diff man page)
++ means one line that was added does not appear in either branch1 or branch2
From Git Tools - Advanced Merging:
You have three SHA1 because in a conflict, Git stores all of these versions in the index under "stages" which each have numbers associated with them.

*

*Stage 1 is the common ancestor,

*stage 2 is your version and

*stage 3 is from the MERGE_HEAD, the version you're merging in ("theirs").

The combined diff format section has all the details:

When shown by git diff-files -c (combined diff of merged files), it compares the two unresolved merge parents with the working tree file
I.e.

*

*file1 is stage 2 aka "our version",

*file2 is stage 3 aka "their version".

  A - character in the column N means that the line appears in fileN but it does not appear in the result.
  A + character in the column N means that the line appears in the result, and fileN does not have that line".

In your case:

*

*A - in the first column means file1, meaning stage 2, meaning "ours" version.

*A - in the second column mean file2, meaning stage 3, meaning "theirs".

*A '++' means an addition which was not in file1 or 2 (each time when compared with the common ancestor from stage 1)


text:
Q: Which type of list is used for android alarm time when the user have to set the alarm time on his phone (HTC for me), there is two listViews, one for hours and the other for minutes.
I would like to reuse this type of lists on my application but I don't know if this is possible or i have to create those lists manually?
Thank you.

A: I think you're looking for the TimePicker.


text:
Q: How to set the NZCV flags to constants in a single ARMv8 instruction I'd like to write a function that takes an ARMv8 instruction containing a condition code, and returns an ARMv8 instruction whose effect is the same as the original but with the condition inverted.
Most cases are easy:

*

*If the condition code is not AL, then just toggle bit 0 of the condition code.

*Otherwise (if the condition code is AL) there is no inverse condition code. Bizarrely NV behaves like AL! Instead we have to rewrite the instruction to pretend that its condition is always false:

*

*If the instruction is a branch, replace it with a no-op.

*If the instruction is CSEL, replace it with MOV.

*If the instruction is CSINC, replace it with ADD.

*If the instruction is CSINV, replace it with MVN.

*If the instruction is CSNEG, replace it with NEG.

*Otherwise it's CCMP or CCMN...

It's the last case that is causing me trouble. It doesn't matter whether the instruction is CCMP or CCMN since the arithmetic operation isn't going to happen anyway. What is needed is a way of setting the N, Z, C and V flags to arbitrary constant values in a single instruction. Is it possible?


text:
Q: How to reference dynamic file within {% static %} call? Django newbie here getting started with my first app...
I need to reference an image within my static assets folder ([project]/static/images/____.jpg) and I've been doing so using the {% static %} template tag similarly to the example in the getting started tutorial:
{% load staticfiles %}

However, I need to reference the image file itself using a variable which is passed in from the view.py file. Of course, this syntax doesn't work but should illustrate what I'm trying to do.

What's the correct syntax for referencing this variable within the static template tag?

A: Give with a try: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#with
{% with "myapp/"|add:imagevariable as filename %}

{% endwith %}

You can also use get_static_prefix: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatetag-get_static_prefix


text:
Q: How do I not duplicate the div from bootstrap datepicker that it generates I have a standard bootstrap datepicker in a bootstrap modal dialog. I create a new modal every time as the content is dynamic, but there is a datepicker every time. Everything works fine. However, I am starting to notice that every time i launch the modal, bootstrap appends it's UI div to the DOM.  After a while, I have plenty of this at the end of my DOM:

...

I have other datepickers on the page so deleting all divs with that class is not feasible.
Is there anyway that I can add an id to that div?  any way to distinguish it from the others?
OR,  is this even a problem?  There is basic security so the session times out after 30 min and the user needs to refresh.  So at most 5 hours before lunch and they need to reload, which solves the problem.
how much of a performance hit am i taking with say 200 of these in the DOM?


text:
Q: For Loop initializing I have a simple question. I am doing an assignment but i have not studied for loop much so i have a question about it
c1=6;
for (i=0; i<7 ; i++)
    {
    for (x=0, x<c1 ,x++)
        {
        cout<<"*";
        }
    x=0;
    c1--;
    }

c1=6;
    for (i=0; i<7 ; i++)
        {
        for (x=0, x<c1 ,x++)
            {
            cout<<"*";
            }
        c1--;
        }

These both are different codes one have x=0 other doesnt..
Does for loop automatically initializes x value to 0 before starting every time?
I need this x=0 in for loop Yes or no? (P.s i have studied while loop alot we need it in while loop)

A: Lets take a simple for loop, like the one you have:
for (i=0; i<7; i++)
{
    // statements...
}

It's equivalent to the following code:
{
    i=0;
    while (i<7)
    {
        // statements...
        i++;
    }
}

This is for all for loops.
So to answer your question: The initialization is done before the for loop always.

A: No, you do not need to reinitialize x = 0 in your code. That's what the x=0 in your for loop is for. The for loop automatically initializes x to the value you set when starting.

A: Yes you do need the x in your for loop. x is initialized inside your for loop. A for loop statement is composed of 3 parts, Variable initialization; your condition; and updating your variable. You will get an error with out it.
for (var initialization; condition; var update)
{
    //code.....
}

the difference between a while loop and a for loop is a while loop you initialize your variable before your while loop and update your variable within the loop it self.
x = 0
while (x < 5)
{
    x++
}

A for loop, it is all contained within the for statement.
for (int x = 0; x < 5; x++)
{
    //code...
}

So in your second for loop statement x is already being initialized to 0 within the for statement.
Also your for loop with the x's should have ; not ,

A: statements are put after you initialize before the for loop. They are put inside the body of the for loop.


text:
Q: Using ArcGIS Desktop to zoom to next selected feature? How could I adapt the following code to enable me to zoom to each individual selected Geometry one after the other?

import arcpy
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()

A: I have a visit tool (in C#, converted from VB.net, which was upgraded from VB6 which was influenced by a tool I wrote in AML)... anyway, the key is to use the Envelope of the geometry in the case of polygon, polyline or multipoint and recentre the map extent.
Here is a very basic start for you:
import arcpy
mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
Envelopes = [] # store extents here

# find the selection set
SelLayer = arcpy.mapping.ListLayers(mxd,data_frame=df)[0] # first layer
fidSet   = arcpy.Describe(SelLayer).FIDSet

if len(fidSet) == 0:
    arcpy.AddMessage("Nothing selected")
else:
    # now cursor through it an get the geometries
    # storing their extents into a list
    with arcpy.da.SearchCursor(SelLayer,"SHAPE@") as SCur:
        for feat in SCur:
            # I'm going to assume polygon/polyline
            Envelopes.append(feat[0].extent) # grab the envelope

    df.extent = Envelopes[0] # first extent
    arcpy.RefreshActiveView()

First you need to check there is a selction against the layer, if there is cursor through the records (remember that if there is a selection against a layer only the selected records are returned) using SHAPE@ to get the geometry object which has an extent as a property, store these in a list and then calling the first one to set the current dataframe extent (also a property).
Note that once the list is made the selection can be changed, this may or may not be what you want. In my case I wanted the extents to remain and be able to edit as I went through the list.

A: You can incorporate your code as above to include the following:

*

*Use arcpy.da.searchcursor() make a python list of those selected features

*Iterate through your python list using a unique ID to create and use an SQL expression letting you Select By Attribute, then zoom to selected features.

Playing around I think something along these lines will work...it is untested at the moment:
import arcpy

mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
# From selection make feature layer (ArcGIS always defaults to using selected features)
LayerList = []
with arcpy.da.SearchCursor("Layer1", "OBJECTID") as Cursor:
    for item in Cursor:
        LayerList.append(item)
        Query = """{0} = {1}""".format("OBJECTID", item)
        #print LayerList
        #print Query
        for rows in LayerList:
            arcpy.SelectLayerByAttribute_management("Layer1", "NEW_SELECTION", Query)
            df.zoomToSelectedFeatures()


text:
Q: Memory management when reading the same file over again I am wondering if linux keeps something in memory (in order to speed up next time) when reading a text file over and over again ?
I am not modifying the text file. Just reading.
Thanks !
Remi

A: Yes, the Linux kernel would allocate unused memory to buffering disk accesses (which is why if you use top you'd see that, under active usage, you normally don't see much free RAM)

A: In a linux kernel, the read() system call loads your data in the page cache, if this data is still around next time your perform read() on the same location, then yes, it will read from this cache and speed up things.
you can read a bit up on it in this tutorial and just by researching it in google and other search engines.


text:
Q: Извлечь строки и числовые значения из текстового файла Имеется текстовый файл:
не нужная текстовая строчка
Иванов
15.1
10е9/л
(4.0 - 1 о.о)

>1

Петров
11.5
10е9/л
(о - 5)

Сидоров
0.8
10е9/л
(о - 2)

Мельников
2
10е9/л
(1 - 8)

Мне необходимо извлечь Фамилии и их числовые значения после пробела. Чтобы на выходе получался вот такой результат:
Иванов: 15.1
Петров: 11.5
Сидоров: 0.8
Мельников: 2

У меня есть уже шаблон с регулярным выражением, но он извлекает значения, не так как мне нужно.
matches_list = re.findall(r'([\w\s]+).+?(\d*\.\d+|\d+)', content, flags=re.DOTALL | re.U)

Помогите, пожалуйста, мне правильно составить регулярное выражение

A: print('\n'.join(f'{x[0]}: {x[1]}'
                for x in re.findall(r'[\r\n]+([\D]+?)\s*?[\r\n](\d*\.\d+|\d+)',
                content,
                flags=re.M|re.S)))

Иванов: 15.1
Петров: 11.5
Сидоров: 0.8
Мельников: 2

UPDATE:
In [7]: %paste
content="""не нужная текстовая строчка
не нужная текстовая строчка

не нужная текстовая строчка
Иванов
15.1
10е9/л
(4.0 - 1 о.о)

>1

Петров
11.5
10е9/л
(о - 5)

Сидоров
0.8
10е9/л
(о - 2)

Мельников
2
10е9/л
(1 - 8)"""

print('\n'.join(f'{x[0]}: {x[1]}'
                for x in re.findall(r'[\r\n]([^\d\r\n]+?)\s*?[\r\n](\d*\.\d+|\d+)',
                content)))

## -- End pasted text --
Иванов: 15.1
Петров: 11.5
Сидоров: 0.8
Мельников: 2


text:
Q: How can i accept argument after invoking a method in transcript on Pharo Smalltalk? I have created a Game class, and I have a method called Board which must accept stdin of 2 integers, and 1 integer will be assigned to the column variable, and the other integer will be assigned to the row variable. So for example, opening up Transcript on pharo and typing this in:
'Game new board 2 3'
should make column=2 and row =3 but I can't figure out how to do this.
Here is my code attempt
 board

| col rows |

col := stdin nextNumber

rows := stdin nextNumber

Transcript cr; show: col asString, rows asString

THIS DOESN'T WORK. I have to create a board game and I cant even figure out how to accept arguments from the transcript/workspace and I'm screwed it's due next monday!!

A: Let me show you the idiomatic way. If you type in your playground

Game newBoardColumns: 2 rows: 3

and then DoIt and go, a debugger will pop up telling you that that #newBoardColumns:rows:message is not understood by the Game. In your debugger, you have a create button that allows you to add that method. If you select to add it on the class side of Game, you can implement it as something like
newBoardColumns: aColumns rows: aRows
    ^self basicNew
    initializeColumns: aColumns rows: aRows;
    yourself

That will return a new instance of the Game class, and initialize it with the columns and rows method. If you save that and restart execution in the debugger, it will complain that it doesn't know #initializeColumns:rows: so you'll have to create that in the same way, this time at the instance side of Game.
initializeColumns: aColumns rows: aRows
    columns := aColumns.
    rows := aRows.
    self initialize.

when trying to save, make sure to add columns and rows as instance variables. Now you can restart execution again and inspect your Game in the inspector pane.
To show something in the Transcript, you could type in your playground

(Game newBoardColumns: 2 rows: 3) show

and DoIt. That will pop up a debugger again, telling you that #show is not understood. You can implement that in Game as
show
    Transcript cr; show: columns asString,' ', rows asString

A: The Transcript is more like a logging stream, not an interactive terminal, but you can evaluate Smalltalk expressions in it (you can also do that in a Workspace/Playground and many other "text boxes"). That means your "input"/evaluated text must be a valid Smalltalk expression. Game new board 2 3 is not.
Rather, your board method should take two arguments, like below:
boardWithColumns: cols rows: rows
    Transcript cr; show: cols asString, rows asString

Note the changed method signature. Unlike in your code, cols and rows are no longer temporary variables, but the arguments of the message send.
You can then evaluate Game new boardWithColumns: 2 rows: 3 to have these dimensions printed to the Transcript.


text:
Q: How to get complete URL of browser in UrlRewriting using C# I have used URL rewriting. I have one question is that I have URL like
http://localhost/learnmore.aspx

This is URL overwriting so I want this complete URL so I have coded like this.
string url=Request.RawUrl;

After this code I got /learnmore.aspx in url variable but I want the complete URL http://localhost/learnmore.aspx
How can I do this?

A: string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost/learnmore.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /localhost/learnmore.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

EDIT: To remove query string items: (found from Get url without querystring)
var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
string path = uri.GetLeftPart(UriPartial.Path);

OR
Uri url = new Uri("http://www.somesite.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme,
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);

OR
string url = "http://www.somesite.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));

A: You can get host and scheme this way :
Request.Url.GetLeftPart(UriPartial.Authority)

With this you will get :

http://localhost/

and then you can append RawUrl

A: you can try to get the base url :
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
    Request.ApplicationPath.TrimEnd('/') + "/";

A: Request.Url.AbsoluteUri would do the trick.


text:
Q: Databinding is initialized in improper order by automatically generated executeBindings Preface
I have a simple app with a viewmodel, a custom UI control, and a TextView. Databinding is setup like this:
LiveData -> control.value -> control.preValue -> TextView
When LiveData is changed, databinding notifies control.value of the new value. control.value setter has a line which also gives the new value to control.preValue. Both properties have calls to their respective databinding listeners to notify databinding that the values have changed and that the UI should be updated. The text value of TextView is bound to control.preValue, so when the listener is notified, the TextView is updated.
This works well at runtime, however there is a problem at initialization.
The Problem
When the UI is first constructed, the LiveData value is not correctly propagated to the TextView. This is because the listeners have not yet been created by the android databinding library, so when control.preValue is set by control.value's setter, the listener is still null.
Diving deeper into executeBindings we can see the cause of the problem.
executeBindings is a function which is part of the *BindingImpl file automatically generated by the databinding library based on the Binding Adapters I have defined. It is responsible for initializing databinding, e.g. creating listeners, registering livedatas, and setting initial values to the UI.
executeBindings starts like this. It initializes variables for all the databound values.
    @Override
    protected void executeBindings() {
        long dirtyFlags = 0;
        synchronized(this) {
            dirtyFlags = mDirtyFlags;
            mDirtyFlags = 0;
        }
        java.lang.Integer viewmodelBpmGetValue = null;
        androidx.lifecycle.MutableLiveData<java.lang.Integer> viewmodelBpm = null;
        int bpmPickerPreValue = 0;
        androidx.lifecycle.MutableLiveData<java.lang.Boolean> viewmodelPlaying = null;
        java.lang.String integerToStringBpmPickerPreValue = null;
        int androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue = 0;
        com.okos.metronome.MetViewModel viewmodel = mViewmodel;

Next, it gets the value of control.preValue property and stores it in the earlier created variable. This is already the core of the problem. At this point control.preValue is still at the default value that is defined in the control's definition class, not the LiveData value which will be assigned to it a bit later.
        if ((dirtyFlags & 0x18L) != 0) {

                // read bpmPicker.preValue
                bpmPickerPreValue = bpmPicker.getPreValue();

                // read Integer.toString(bpmPicker.preValue)
                integerToStringBpmPickerPreValue = java.lang.Integer.toString(bpmPickerPreValue);
        }

Next we get the LiveData value from the viewmodel and register it with databinding
            if ((dirtyFlags & 0x15L) != 0) {

                    if (viewmodel != null) {
                        // read viewmodel.bpm
                        viewmodelBpm = viewmodel.getBpm();
                    }
                    updateLiveDataRegistration(0, viewmodelBpm);

                    if (viewmodelBpm != null) {
                        // read viewmodel.bpm.getValue()
                        viewmodelBpmGetValue = viewmodelBpm.getValue();
                    }

                    // read androidx.databinding.ViewDataBinding.safeUnbox(viewmodel.bpm.getValue())
                    androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue = androidx.databinding.ViewDataBinding.safeUnbox(viewmodelBpmGetValue);
            }

Here it sets control.value to the value of the LiveData in the first if block. This line will trigger the control.value setter, which will set control.preValue, and those setters will both try to call their respective onChange listeners but they will be null because executeBindings hasn't created them yet. They are created in the 2nd if block.
        if ((dirtyFlags & 0x15L) != 0) {
            // api target 1

            this.bpmPicker.setValue(androidxDatabindingViewDataBindingSafeUnboxViewmodelBpmGetValue);
        }
        if ((dirtyFlags & 0x10L) != 0) {
            // api target 1

            com.okos.metronome.view.DialPickerBindingAdapter.setPreValueListener(this.bpmPicker, (com.okos.metronome.view.PrePickerBase.OnValueChangeListener)null, bpmPickerpreValueAttrChanged);
            com.okos.metronome.view.DialPickerBindingAdapter.setValueListener(this.bpmPicker, (com.okos.metronome.view.PrePickerBase.OnValueChangeListener)null, bpmPickervalueAttrChanged);
        }

Finally, the value of the TextView is set, but it is set to the original value of preValue which we cached in a variable in the very first if block. **Not the new value which has been updated to preValue from the LiveData since then.
        if ((dirtyFlags & 0x18L) != 0) {
            // api target 1

            androidx.databinding.adapters.TextViewBindingAdapter.setText(this.tvBpmDisplay, integerToStringBpmPickerPreValue);
        }

This seems like an oversight in the databinding library, and I wonder if anyone has any ideas of getting around this? The fix seems pretty simple to just move the first if block in executeBindings down so integerToStringBpmPickerPreValue is set after the value has been set from LiveData, but because executeBindings is automatically generated, I can't do that. There are some ways of changing the order of execution in executeBindings, like which order the bindings are defined in the xaml, but none of that affects the parts I want to change.


text:
Q: Concat two dataframes and create multi-index from indexes I have two DataFrames df_1 and df_2 are:
df_1 = pd.DataFrame({"A1":"1", "A2":"2", "A3":"3"}, index=[2411])
df_1.index.name = "i_1"
df_2 = pd.DataFrame({"B1":"4", "B2":"5", "B3":"6"}, index=[123122])
df_2.index.name = "i_2"

I want to concat them, so the final DataFrames will look like:
                A1  A2  A3  B1  B2  B3
i_1     i_2
2411    123122  1   2   3   4   5   6

Basicly, that's concatination along axis 1 and mooving the setting a multi-index from indexes.
The most closest to the desired result, that i have done is:
df_1 = df_1.reset_index()
df_2 = df_2.reset_index()
df_f = pd.concat([df_1,df_2], axis=1)
df_f = pd.DataFrame(df_f, index=pd.MultiIndex.from_arrays([float(df_1["i_1"]), float(df_2["i_2"])], names=["i_1","i_2"]))
del df_f["i_1"]
del df_f["i_2"]

But the result is:
A1  A2  A3  B1  B2  B3
i_1 i_2
2411.0  123122.0    NaN NaN NaN NaN NaN NaN

A: I think simpliest is reset_index of both df for default indexes, so concat align data nice and last set_index:
df_f = pd.concat([df_1.reset_index(),df_2.reset_index()], axis=1).set_index(['i_1','i_2'])
print (df_f)
            A1 A2 A3 B1 B2 B3
i_1  i_2
2411 123122  1  2  3  4  5  6

In you solution is problem different indexes, so after concat get 2 rows, because data cannot allign (not same indexes):
df_f = pd.concat([df_1,df_2], axis=1)
print (df_f)
         A1   A2   A3   B1   B2   B3
2411      1    2    3  NaN  NaN  NaN
123122  NaN  NaN  NaN    4    5    6

Then get NaNs because in DataFrame constructor create new Multiindex but data not aligne again - in original df_f are data size (2x6) and want assign to 1,6 structure, also indexes are different.


text:
Q: iOS: Blocks and ivars In a lot of question it is asked if its ok to use self in blocks. The answer is no, to avoid retain cycle.
Now when i use an "ivar" in my block in my UIViewController it should be fine. But when i use:
- (void)viewDidLoad
{
    [_customCell setChangedValueBlock:^{
        if(_object != nil){
            NSLog(@"This is a sample");
        }
    }];
}

The dealloc method never called:
-(void)dealloc{
    NSLog(@"Dealloc");
}

When i remove the if(_object != nil){, the dealloc method is called.
Should i make weak reference to the _object before passing it to the block?

A: Using an ivar (property, whatever) is exactly like using self - you have implicitly used self. You need to do the weak-strong dance.
It would be much better to pass thru a property, though, because it can be made thread-safe and because accessing an instance variable directly on a released weak reference will cause your device to explode.


text:
Q: How to generate sign to pass to transferPreSigned(), contract is not asking for sign while transfer() I'm creating ERC865 token so that users can send tokens without having ether. I followed 1 and 2.
As per 1, sender will sign transaction object while calling transfer() but I'm unable to see any "Sign"! What parameters should be passed to transferPreSigned()? I'm using Metamask and Solidity.


text:
Q: Require.js optimizer - Trouble getting going Good morning,
I have been messing around with the Require.js optimizer this morning and was having trouble getting started.
I am running windows 8, and have created a modular backbone.js application that I am now ready to package for deployment (production).  I would now like to optimizer theses files (concat and minimize), r.js optimizer seems like just the trick.
The problem I am running into is when trying to run the classpath command.
java -classpath path/to/rhino/js.jar;path/to/closure/compiler.jar org.mozilla.javascript.tools.shell.Main r.js main.js

Will throw an error - Error: Could not find or load main class org.mozilla.javascript.tools.shell.Main
I'm confused because I'm not sure where that package is even supposed to be, wouldn't it already be part of the optimizer/compiler?
My directory structure is as follows
build -
compiler.js
js.jar
r.js

app
js -> backbone and application files here
css
images

I'd highly appreciate any light that could be shed on this one, this is the first time I am running the require.js optimizer.

A: The command you used attempts to run r.js with main.js as the entry point, not perform optimization (bear in mind the Optimizer is not the main component of r.js). You probably found the command in the r.js README; the correct command is in the same file, in the "Optimizer" section:
java -classpath path/to/rhino/js.jar;path/to/closure/compiler.jar org.mozilla.javascript.tools.shell.Main r.js -o path/to/buildconfig.js

You'll need a build profile file which should be fairly straightforward in your case. More info directly on RequireJS page.
I can highly recommend using Node.js instead of Rhino, it's much faster and saves setting up Java dependencies/classpath.


text:
Q: Reading a text file line by line and saving to an array (C Language) Here's my issue:
I'm currently working on a project for university. We're suppose to do a program that receives .pbm and .pgm files as input, and then we're suppose to handle them in some ways. But for now the main thing is to successfully receive them.
Each .pbm and .pgm file's first line is a "magic number". A set of characters like P1, P2 (...) P6.
Our goal is to receive a .pbm file as input, save the first line, dynamically allocate a string so it is just as big as its content (P6\n, for example), so we can then detect the magic number. The same applies to every other line. We basically just want a way to save each line into an array, making them just as big as their content.
Me and my project partner are both beginners: file handling, pointers, dynamic memory and headers are still pretty hard to us. Thank you in advance.
---EDIT--- (Forgot the code, as an user pointed out)
int main(int argc, char const *argv[])
{
    readFile(argv[1], "EI_2012-13_ascii.pbm");
    return 0;
}

void readFile (const char* input_file, char* filename){
    char *line_buffer, *line;
    FILE *file_stream = NULL;

    if(!check_extension(filename, ".pbm") &&
     !check_extension(filename, ".pgm") && !check_extension(filename, ".ppm"))
        ERROR(ERR_EXT, "Invalid file extension!\n");

    file_stream = fopen(input_file, "r");
    if (file_stream == NULL)
        ERROR(ERR_EXT, "Couldn't open the file for reading");

    line_buffer = malloc(sizeof(2));
    fscanf(file_stream, "%s", line_buffer);
    //line = strchr(line_buffer, '\n');

    printf("%s\n", line_buffer);
    printf("%d\n", sizeof(line_buffer));

    fclose(file_stream);
}

With this code we were attempting to output a string and its size underneath it. Strangely we keep getting the same output: 4. We needed that the malloc received a proper argument, the size of the line until the '\n'.

A: You can detect the magic number reading the file line by line using Linux function getline() as shown below,
void readFile (const char* input_file, char* filename){
    char *line;
    FILE *file_stream = NULL;
    ssize_t read; size_t len = 0;

    file_stream = fopen(input_file, "r");
    if (file_stream == NULL)
         ERROR(ERR_EXT, "Couldn't open the file for reading");

     while((read = getline(&line, &len, file_stream)) != 1){
        printf("%s", line);
        printf("length of line: %zu\n", read);
     }
     if (line)
        free(line);
     fclose(file_stream);
}


text:
Q: Scroll not moving after adding Text with Javascript I'm adding some text to a textarea by using JS everytime I click on a button. The thing is that everytime the text is added, the scroll goes to top of the textarea and I don't want that. I don't want the scroll to move automatically when I add the content.
This is part of my code:
const textarea = document.getElementById('my_textarea');
let data = "new content added";
textarea.innerHTML = data + textarea.innerHTML;

Could someone please help me out?
Thanks in advance.

A: Just add a particular line in your button event Listener
textarea.scrollTo(0,textarea.scrollHeight)

Overall code will look somewhat similar to this

    const textarea = document.getElementById('my_textarea');

    document.querySelector("button").addEventListener("click",() => {
      let data = "new content added";
      textarea.innerHTML = data + textarea.innerHTML;
      textarea.scrollTo(0,textarea.scrollHeight)
    })

A: I think you could just set your scroll position everytime you click on your button. So you can put this piece of code in another function and call it after your desired text is loaded.
var textarea = document.getElementById('textarea_id');
textarea.scrollTop = textarea.scrollHeight;


text:
Q: convergence test : $\int_{0}^\infty \mathrm 1/(x\ln(x)^2)\,\mathrm dx $ I have to check if   $\int_{0}^\infty \mathrm 1/(x\ln(x)^2)\,\mathrm dx $ is convergent or divergent.
My approach was to integrate the function , hence :  $\int_{0}^\infty \mathrm 1/(x\ln(x)^2)\,\mathrm dx=-\lim_{x \to \infty} 1/\ln(x)+ \lim_{x \to 0} 1/\ln(x)=0 $
Still my book says that it is divergent. Maybe the $\infty$ sign of the integral means to check for $+\infty$ and $-\infty $ or i just overlooked something.  Any help would be appreciated.

A: Look at the following improper integral:
$$
\int_1^2f(x)dx
$$
Certainly, $\lim_{x\to 1^+}(x-1)f(x)=+\infty$ so the Comparison test admits the series is divergent.

A: Let's change the variables:
$$y=\ln {x} \\ dy =\frac{dx}{x}$$
Now the integral becomes:
$$I=\int_0^\infty \frac{dx}{x(\ln{x})^2}=\int_{-\infty}^\infty \frac{dy}{y^2}.$$
Note that the integrand is an even function, ergo(the main goal is to avoid the singularity):
$$I=2\int_0^{\infty} \frac{dy}{y^2}=-\frac{2}{x}\large{|_0^{\infty}}=\infty $$


text:
Q: Google Apps Script: Compare One Cell to Another, then Increment Cell Value I'm not very experienced in programming, but I'm looking to do something specific with my Google Sheets document.  As an example:

*

*I buy fruit buy the box.  Each type of box has a
certain amount of each fruit.

*My customers have standing orders for
differing numbers of certain fruit platters I sell.

*I need to figure
how many of each fruit box I need to buy to fulfil each customer's
order, with a minimum of wastage.

I keep running into circular dependancy errors when I try to work things out with my limited spreadsheet knowledge.  Ideally what I'd like to do is have a script that:

*

*Increments the "Amount to Buy" of Fruit Box #1 by 100 (they come in pallets of 100, I can't buy less)

*If the amount of fruit with the best yield for that box (highlighted in green on the "Fruit Boxes" sheet.  Fruit Box #1 is Cherry) is met, then the sheet moves onto the next fruit box.

At the moment I am able to get the sheet to tell me how much of each fruit box I need to buy to have enough of the "best yield" fruit that box contains, but I need it to take into account that the other boxes I need to buy also may contain some of that fruit.
My example sheet is here >> https://docs.google.com/spreadsheets/d/1tbI89jfY2ddAlyTN5VGaQ3nSRsgJcuR6Ev3I-YIdUoA/edit?usp=sharing
Note:  Bonus points for anyone who can suggest a better way of displaying how many of each platter each customer requires.  At the moment I'm using a very long and clunky IF, THEN statement in the "Required" column for each fruit platter, but I'm sure there must be a better way.
Thanks in advance for any help you can provide.

A: I'm not sure this is a Google Apps script question - are you planning to code a solution in Javascript, or are you happy to just use normal spreadsheet functions? I suspect the later, in which case you may be better off asking in https://webapps.stackexchange.com/questions/tagged/google-spreadsheets
Some functions that may be relevant to explore include SUMIF, SUMPRODUCT, HLOOKUP and VLOOKUP. I'm not sure I fully understand your question so I can't help you more!


text:
Q: 230V/230V AC relay circuit I've built a nice programmable switch basing on Raspberry and a relay board. It's fine for driving common 230V appliances but the relays seem rather flimsy; I wouldn't trust them to run 10A of current through them. I'd like to connect devices that potentially take about much - heaters for my home etc. The obvious solution is next stage relay rated for currents of that order; 230V input from my switch, 230V over some thick wire from a rated socket, the load on output of the relay.

simulate this circuit – Schematic created using CircuitLab
What I'd like to ask - is that enough? I know driving the relay driven by logic pin requires quite a bit of "glue electronics", an optocoupler, a transistor to amplify signal from the optocoupler, protecting diodes, resistors regulating the levels etc. Is anything of that kind required when driving one 230V relay from another? Any extra electronics between them, or can I safely connect them directly like in the schematics above?

A: Due to inductive spikes mainly if the relay contacts open during the peak current portions of the AC cycle, I would suggest an MOV (metal oxide varistor) across the contacts of the first relay. Alternatively you could place it across the load (the coil of the second relay). The MOV should be rated for at least 275Vrms (such as Littelfuse V275LA2P). If the final load is inductive, you should place one there also (or one each across each contact of the second relay).
A snubber is often used when switching AC inductive loads and could be used here as well as (or in place of) the MOV. This is made of a resistor and capacitor in series which will slow the rise time of and attenuate the inductive spikes. Red Lion makes a snubber (SNUB0000) or you can make your own. Note that an MOV will clip the inductive spike while a snubber will also slow the rise-time and thus greatly reduce interference with other equipment. From the Red Lion datasheet:

The R-C Snubber is intended to suppress the "inductive kick" from motors,
  solenoids or relay coils. High energy noise spikes are generated whenever
  current is interrupted through an inductive load. These noise spikes may
  interfere with associated equipment causing erratic operation and may also
  accelerate relay contact wear. Applied across an inductive load, the R-C
  snubber suppresses the noise spikes and extends contact life.

I agree with Andyaka's comment: "Why don't you find a single relay that can do the job?"; although due to your specific circumstances, two relays also make sense.

A: Yes. The first relay effectively isolates the Pi from any mains so no need for opto isolator. The switch rating of the first relay is sufficient to switch the current through the coil of the second so no need for amplification. The only point I would make is that the second relay should be of an AC coil type.
see http://www.ehow.co.uk/about_6498402_difference-ac-dc-relay-coil.html

A: You don't need much to drive a relay from a microcontroller pin - a transistor and a diode is enough. Something like this:

Regarding your question of driving another relay with a relay - you have to use a relay that can be driven by 230V. Something like this would work.

simulate this circuit – Schematic created using CircuitLab

A: The arrangement shown will work fine so long as RLY3's actuation voltage is 230 Volts AC.
Such cascaded relay arrangements are commonly used in practice, for instance in certain electric locomotives which need to switch massive currents under "control-by-wire" (software interface).
Make sure the two relays are not very close to each other, so that they do not interfere with each other.

A: Like Anindo says your RLY3 needs a 230V coil, and these relays may be more expensive. Why can't you use a common 12V or 24V relay for RLY3 and drive it from the RPi with a MOSFET. You won't need RLY1 that way. The RPi can drive any logic level FET, and FETs for drive currents in the order of 100mA or less are easy to find. You may have trouble finding a sturdy relay for PCB mount, but that would also be the case for a 230V relay.


text:
Q: Peskin and Schroeder: derivation of Dirac fields commutator I'm perplexed by the following non numbered equation at page 54 of Peskin & Schroeder, right between $(3.92)$ and $(3.93)$
$$ [\psi_a(x),\overline{\psi}_b(x)]=\int\frac{d^3p}{(2\pi)^3}\frac{1}{2E_\mathbf{p}}\sum_s\left(u_a^s(p) \overline{u}_b^s(p)e^{-ip\cdot(x-y)}+v_a^s(p) \overline{v}_b^s(p)e^{ip\cdot(x-y)}\right)=\\=\int\frac{d^3p}{(2\pi)^3}\frac{1}{2E_\mathbf{p}}\sum_s\left((\not p+m)_{ab}e^{-ip\cdot(x-y)}+(\not p-m)_{ab}e^{ip\cdot(x-y)}\right)=\\=(i\not\partial_x+m)_{ab}\int\frac{d^3p}{(2\pi)^3}\frac{1}{2E_\mathbf{p}}\left(e^{-ip\cdot(x-y)}-e^{ip\cdot(x-y)}\right)=\\=(i\not\partial_x+m)_{ab}[\phi(x),\phi(y)]$$
Where $\psi_a$ are Dirac fields. I have questions both about the notation and the actual content.

*

*What is meant by the subscript $ab$ on operators? E.g. $(\not p +m)_{ab}.$ On the fields I interpreted it as if we had multiple fields with the same Lagrangian, i.e. a total Lagrangian density given by
$$\mathcal{L}=\sum_a \overline{\psi}_a(i\not \partial -m)\psi_a$$
but the two subscripts don't make sense to me written that way.

*Looking at this computation, it seems like $$u_a^s(p) \overline{u}_b^s(p)=(\not p+m)_{ab}$$ (whatever that means) and similar for the antiparticles, but I would've expected $$ u_a^s(p) \overline{u}_b^s(p)=2m\delta_{ab}.$$
How can I resolve this?

A: (1) Recall that the written out form of
$${\not p } + m  = \gamma^\mu p_\mu + m 1_4$$
and so
$$({\not p } + m )_{ab} = (\gamma^\mu p_\mu + m 1_4)_{ab} $$
is just denoting the $ab$ entry of the 4$\times$ 4 matrix.
(2)

$$u_a^s(p) \overline{u}_b^s(p)=(\not p+m)_{ab}$$

Not quite. Rather,
$$\sum_s u_a^s(p) \overline{u}_b^s(p)=(\not p+m)_{ab}.$$
This is shown on page 34 of Fun with Spinor indices. Your concern about thinking that $"u_a^s(p) \overline{u}_b^s(p)=2m\delta_{ab}"$ is also addressed on that page.
Edit So in short $ab$ are, in general, spinor indices meaning that $\psi_a$ is the $a^{th}$ component of the dirac spinor $\psi$, and, say, $\bar{\psi}_a\gamma^\mu_{ab}\psi_b = \bar{\psi} \gamma^\mu \psi$  where the latter is found by usual matrix multiplication.  That is, $ab$ represent the components of a matrix in spinor space.


text:
Q: How to modifie a variable that its inside on a file on C? I'm new in coding, tecnically i started this year to code and i need a lot of practise. Whatever, i tried to modify a variable that is in a file but the browser or CPU didnt found it. When i run the code, it can write the variables and pass it to the file and read it, but it cant modifie a variable that is inside on the file. I tried to use a while and an if but my knowledge couldnt go so far than these.
The problem is on the Delete function, it can read the file or archive but it couldnt reach the "end of file" because apparently it doesnt exist. The code principally read a punch of number and stop when you enter -1 on the scanf. The it read all the number (include -1 twice) and then it modifie the last number converting to a zero. The problem is that the last function repeated infinitely
#include<stdio.h>
void Create(FILE *p){
p=fopen("c:Example", "rb");
if(!p){
    p=fopen("c:Example", "wb");
    printf("El texto fue creado \n");
    } else {
    printf("El texto ya existe \n");
    }
}
void Add(FILE *p){
int a;
p=fopen("c:Example", "ab");
if(p==NULL){
    printf("El texto no se encontro \n");
    } else {
    scanf("%d", &a);
    while(a!=-1){
        fwrite(&a, sizeof(int), 1, p);
        scanf("%d", &a);
        }
    fwrite(&a, sizeof(int), 1, p);
    }
fclose(p);
}
void Read(FILE *p){
int a;
p=fopen("c:Example", "rb");
if(p==NULL){
    printf("El texto no existe \n");
    } else {
    fread(&a, sizeof(int), 1, p);
    printf("%d \n", a);
    while(a!=-1){
        fread(&a, sizeof(int), 1, p);
        printf("%d \n", a);
        }
    }
fclose(p);
}
void Delete(FILE *p){
int a;
p=fopen("c:Example", "wb");
if(p==NULL){
    printf("El texto no existe \n");
    } else {
    fread(&a, sizeof(int), 1, p);
    printf("(1)\n");
    while(a!=-1){
        fread(&a, sizeof(int), 1, p);
        printf("(2)\n");
        }
    a=0;
    printf("(3)\n");
    }
fclose(p);
}

int main(){
FILE *p;
Create(p);
printf("\n");
Add(p);
printf("\n");
Read(p);
printf("\n");
Delete(p);
printf("\n");
Read(p);
printf("\n");
return 0;
}

A: A solution to the problem could be reading the numbers and generate a new file with the last number, which is -1, replaced by 0. Then delete the old file and rename temporary file as the older one. I wrote a solution that works trying to not change much code of yours. I suggest you to better undestand how fread() and fwrite() functions work. After scanf function, I use getchar() function to remove new line, caused when you hit enter, from the buffer. Try also to keep your code clean with spaces and indent.
#include <stdio.h>
#include <stdlib.h>

void Create (FILE *p)
{

    if((p = fopen ("c:Example", "wb")) == NULL) // Check if file opening doesn't fail
    {
        printf ("Can't open file\n");
        exit (-1);
    }

    printf ("File exists\n");

    fclose (p); //Close file pointer
}

 void Add(FILE *p)
{
    int a = 0; // Initialize variable

    p = fopen("c:Example", "ab");

    if (p == NULL) // File opening failed
    {
        printf("El texto no se encontro \n");
        exit (-1); // Program has to terminate
    }
    else
    {

        while(a != -1)
        {
            printf ("Please insert number\n"); //Tell user what to do
            scanf ("%d", &a);
            getchar();
            fwrite(&a, sizeof(int), 1, p);
        }
    }

    fclose(p);
}

void Read(FILE *p)
{
    int a = 0; // Initialize variable
    p = fopen("c:Example", "rb");

    if(p == NULL) // Error opening file
    {
        printf("El texto no existe \n");
        exit (-1); // Program has to termimate
    }
    else
    {
        while(a != -1)
        {
                fread(&a, sizeof(int), 1, p);
                printf("I've read %d\n", a);
        }
    }

    fclose(p);
 }

 void Delete(FILE *p)
 {
     int a = 0;
     p = fopen("c:Example", "r"); //Open for read

     if(p == NULL) // Can't open file
     {
         printf("El texto no existe \n");
         exit (-1); //Exit the program
     }

     else
     {
        FILE *temp;
        if ((temp = fopen ("temp", "ab")) == NULL) //Create a temp file in append mode
         {
             printf ("Error creating temp file\n");
             fclose (p);
             exit (-1);
         }

         while (a != -1)
         {
             fread(&a, sizeof(int), 1, p);

             if (a != -1)
             {
                  fwrite (&a, sizeof(int), 1, temp); // write to temp only if is not -1
             }
         }

         a = 0;
         fwrite (&a, sizeof (int), 1, temp); //Write 0 to last position

         fclose (temp);
         fclose (p);
         remove ("c:Example"); //Remove old file
         rename ("temp", "c:Example"); //Rename new file
         }
  }

  void Read_new (FILE * p)
  {
     int a = -1 // Initialize a as -1;
     p = fopen ("c:Example", "rb");

     while (a != 0)
     {
          fread (&a, sizeof (int), 1, p);
          printf ("I've read %d\n", a);
     }

    fclose (p);
 }

 int main()
 {
    FILE *p;
    Create(p);
    Add(p);
    Read(p);
    Delete(p);
    Read_new(p);
    return 0;
 }


text:
Q: Get user information Youtube v3 api after oauth I am trying to get the user email, that I used to log in with when performing Oauth2 through Youtube in my application. The code is similar to this:
        YouTube client = new YouTube.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory
            .getDefaultInstance(), credential)
            .setApplicationName("app_name").build();

        YouTube.Channels.List channelListByIdRequest = client.channels().list("snippet,contentDetails,statistics");
        channelListByIdRequest.setMine(true);
        ChannelListResponse channelListResponse = channelListByIdRequest.execute();

Here I pull the channel api, that, according to the doc is some kind of similar to the user api in v3. However, neither in Channel nor in any other API I cannot find how to get the email I logged in with. How can that information be accessed?

A: I have done some research and, unfortunately, there is indeed no possibility to fetch the email. As far as I understand, it is against the concept of Youtube and its data API - it deals with channels and multiple of those can be associated with a single email.
Used this for reference:
https://developers.google.com/youtube/v3/getting-started
However, you can use Google plus API scopes along with Youtube scopes to fetch the user info (but we need to take into account that it will be discarded by March 7, 2019)
     GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets,
    Arrays.asList(YouTubeScopes.YOUTUBE_FORCE_SSL, PlusScopes.PLUS_ME, PlusScopes.USERINFO_EMAIL))
    .setAccessType("offline").setApprovalPrompt("force").build();

We will be prompted to select email and channel in Oauth window and will be able to fetch the info.