text:
Q: Splitting data from a txt file I am new to Python.
What I am trying to do is to split what I got from a txt file to select just the Aperture and the ShutterSpeed values.
This is how my data looks like (30 different values of Aperture and Shutter Speed) :
======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF
Aperture                        : 2.2
Shutter Speed                   : 1/1806
======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF
Aperture                        : 2.2
Shutter Speed                   : 1/510
======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF
Aperture                        : 2.2
Shutter Speed                   : 1/374
======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF
Aperture                        : 2.2
Shutter Speed                   : 1/1884

I need to make my code select only the float values (2.2, and 1/1884 for example from all the data).
This is the code I am trying to do (with the help of some people here) :
filename='/home/stagiaire/Bureau/datatest.txt'
with open(filename) as f:
    data = f.read()
data = data.split('\n')

Fnumber      = [float(row.split(':')[0]) for row in data]
ShutterSpeed = [float(row.split(':')[1]) for row in data]

Any suggestions?

A: You can use slice operator(:) to filter out the text you need, something like this :
# -*- coding: utf-8 -*-
data = [
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF Aperture : 2.2 Shutter Speed : 1/1806",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF Aperture : 2.2 Shutter Speed : 1/510",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF Aperture : 2.2 Shutter Speed : 1/374",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF Aperture : 2.2 Shutter Speed : 1/1884"
       ]
for node in data :
    node_lst = node[node.index('Aperture : '):].split()
    Fnumber = node_lst[2]
    ShutterSpeed = node_lst[6]
    print(Fnumber, ShutterSpeed)

Alternatively, you can do this without having to use .split() on your data :
# -*- coding: utf-8 -*-
data = [
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF Aperture : 2.2 Shutter Speed : 1/1806",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF Aperture : 2.2 Shutter Speed : 1/510",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF Aperture : 2.2 Shutter Speed : 1/374",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF Aperture : 2.2 Shutter Speed : 1/1884"
       ]

for node in data :
    Fnumber_txt = node[node.index('Aperture : ') + len('Aperture : '):]
    Fnumber = Fnumber_txt[:Fnumber_txt.index(' ')]
    ShutterSpeed = node[node.index('Shutter Speed : ') + len('Shutter Speed : '):]
    print(Fnumber, ShutterSpeed)

Both of the above code snippets will produce this result :
2.2 1/1806
2.2 1/510
2.2 1/374
2.2 1/1884

Edit : As you have data at three different indexed for one entity, you can use step of slice operator to fetch it and process, something like this :
# -*- coding: utf-8 -*-
data = [
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/1806",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/510",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/374",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/1884"
       ]

fns = [float(fn.split(":")[-1].strip()) for fn in data[1::3]]
sss = [ss.split(":")[-1].strip().split("/") for ss in data[2::3]]

for i, elems in enumerate(sss) :
    Fnumber = fns[i]
    Shutter = elems[0]
    Speed = elems[1]

    print(Fnumber)
    print(Shutter)
    print(Speed)

This will result in :
2.2
1
1806
2.2
1
510
2.2
1
374
2.2
1
1884

Alternatively, you can format your final result like this :
# -*- coding: utf-8 -*-
data = [
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/1806",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/510",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/374",
        "======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF",
        "Aperture                        : 2.2",
        "Shutter Speed                   : 1/1884"
       ]

fns = [float(fn.split(":")[-1].strip()) for fn in data[1::3]]
sss = [ss.split(":")[-1].strip().split("/") for ss in data[2::3]]
print(list(map(lambda x: [float(x[0]), float(x[1][0]), float(x[1][1])], list(zip(fns, sss)))))

This will result in :
[[2.2, 1.0, 1806.0], [2.2, 1.0, 510.0], [2.2, 1.0, 374.0], [2.2, 1.0, 1884.0]]

A: Seems like you're practically achieve your goal. This is a header of your code snippet:
filename='/home/stagiaire/Bureau/datatest.txt'
with open(filename) as f:
    data = f.read()
list_of_strings = data.split('\n')

Now you're get the list of strings each one has a distinctive pattern inside. Let's split it up onto the chunks and dissect these flakes:
for i in list_of_strings:
    # now split it into 2 parts and get the tail:
    gist=row.split('Aperture:'[-1].strip()
    print("This is a gist out of string:", gits)
    # split and get the head of result:
    aperture=float(gist.split()[0])
    print("Aperture:", aperture)
    # and now the speed:
    shutter_speed = gist.split()[-1]
    print("Shutter speed:", shutter_speed)

This is for Python 3.x If you're using the second version - just re-style the print function

A: Take a look at my approach with regex:
import re

string = r"======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF Aperture : 2.2 Shutter Speed : 1/1806 ======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF Aperture : 2.2 Shutter Speed : 1/510 ======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF Aperture : 2.2 Shutter Speed : 1/374 ======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF Aperture : 2.2 Shutter Speed : 1/1884"

aperatures = re.findall(r'Aperture : \d*\.\d*', string)
aperatures_float = [float(aperature.split(sep=':')[1].strip()) for aperature in aperatures]
shutter_speeds = re.findall(r'Shutter Speed : \d*\/\d*', string)
shutter = [shutter.split(sep=':')[1].strip() for shutter in shutter_speeds]

And output for provided string:
In[332]:
shutter
Out[332]:
['1/1806', '1/510', '1/374', '1/1884']
type(shutter[0])
Out[333]:
str

In[328]:
aperatures_float
Out[328]:
[2.2, 2.2, 2.2, 2.2]
aperatures_float[0]
Out[329]:
2.2
type(aperatures_float[0])
Out[330]:
float

Since there is '/' in shutter value I left it as a string.
Some explanations:
re.findall(r'Aperture : \d*\.\d*', string)

this line finds all occurrences of character sequences (using regex expression) that start with literal 'Aperature : ' and is followed by any number of digits, then a dot and then any number of digits again.
For shutter speeds code works exactly the same.

A: I have found a solution using this module. Here is the code:
import re

re.findall(r"[-+]?\d*\.\d+|\d+", "======== /home/stagiaire/Bureau/Photos Test
Luxmetes/Position 2 (au sol à l'ombre)/0033/IMG_170407_083601_0004_RED.TIF
Aperture : 2.2 Shutter Speed : 1/1806 ======== /home/stagiaire/Bureau/Photos
Test Luxmetes/Position 2 (au sol à
l'ombre)/0033/IMG_170407_083600_0003_NIR.TIF Aperture : 2.2 Shutter Speed :
1/510 ======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position 2 (au
sol à l'ombre)/0033/IMG_170407_083601_0004_REG.TIF Aperture : 2.2 Shutter
Speed : 1/374 ======== /home/stagiaire/Bureau/Photos Test Luxmetes/Position
2 (au sol à l'ombre)/0033/IMG_170407_083600_0003_RED.TIF Aperture : 2.2
Shutter Speed : 1/1884")


text:
Q: Do you recognize this password hashing format? I'm trying to reverse-engineer a password scheme on a legacy PHP application, so I can port the passwords to a new system which will be replacing it. The application has passwords stored in two formats, a newer and an older one. The newer one simply uses crypt() with salt. The older one doesn't seem to have any supporting code any more (at least not in version control), and no hint of what may have been used. I have one account in the old style for which I may know the password, but I don't know how to check it.
The password is stored in the following format:
$1$f1KtBi.v$nWwBN8CP3igfC3Emo0OB8/

It appears to be three fields, delimited by $: 1, f1KtBi.v, and nWwBN8CP3igfC3Emo0OB8/. The first field is always 1. The second and third fields always match the regular expression [a-zA-Z0-9/.]+. The second field always has 8 characters, the third field always has 22.
Have you seen this password storage scheme before? Any idea what hashing mechanism might have been used?

A: This is the output of the crypt()[docs] function.
The 1 means that it used the MD5 algo internally.

A: That's most likely produced with crypt(), especially with MD5:

CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$

Good luck finding the salt.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php multiple variables into one So Ive got a couple of statements using a list of variables and it seems i am always adding another column to the database so i wanted to make one list of variables and contain it somehow so i can just change it once if i need to instead of half a dozen times.
    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($a, $b, $c, $d, $e, $f, $g);

$stmt->fetch();

$stmt->close();

But I want to make something like this:
    varList="$a, $b, $c, $d, $e, $f, $g";

    $stmt = $mysql->prepare("SELECT * FROM table WHERE id =? LIMIT 1");

$stmt -> bind_param('i', $id);

$stmt->execute();

$stmt->bind_result($varList);

$stmt->fetch();

$stmt->close();

A: What you can do is make an array (of references to variables), and then use call_user_func_array to call bind_result.
Example:
$varList = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); // variable names.
$params = array(); // list of params

foreach($varList as $v){
    $params[] = &$$v; // store a reference to the vars in $params
}

call_user_func_array(array($stmt, 'bind_result'), $params);

You may not need that foreach loop, you may also be able to do this:
$varList = array(&$a, &$b, &$c, &$d, &$e, &$f, &$g); // variable references

call_user_func_array(array($stmt, 'bind_result'), $varList);

Based off this answer: https://stackoverflow.com/a/966717/206403


text:
Q: How to apply formatting to content of a span With CkEditor, When I create an A tag and later apply some custom formatting (like color text for instance), the resulting source looks like this:

some text

As you can see, the formatting is around the text but INSIDE the A tag.
I have a personal plugin that outputs a SPAN tag with a specific class. In the wysiwyg editor, when I select the text and apply the same formatting, I get this:

Some text

This time, the formatting is not simply around the text. It is applied around the SPAN tag.
How can I control this behaviour? I would like to get this result instead:

Some text

Thanks

A: Unfortunately there is no ability to control the order of inline styles (based on span tags) inside editor's instance. The only sensible way to achieve desired result is to start with applying text color and then apply your custom style.
However there are two methods to convert output of the editor to the correct format. The first is to add custom handler to editor's data processor via toDataFormat event to check ancestors of span.command3d and swap them in places if necessary. However it's a little bit troublesome as you must traverse through all content, therefore it's easier way: add element callback to editor's filter. Example.


text:
Q: How read the first and the last line of a file in scala I am reading a file that contain the following:
16,44,34
16,47,18
22,44,28
22,47,24

but I just want to read the first and the last line of the file,
In this moment I am reading the file as an Iterator:
 while (in2.hasNext) {
        val s  = in2.next(',').toInt
        val p = in2.next(',').toInt
        val o  = in2.next('\n').toInt
 }

but I am reading the whole file, exist a way in scala to do it?

A: Well, you can write it a little nicer, and save on not having to parse every line in the file, but you will still have to read them all, unless you are willing to do some acrobatics with random access files and binary data (probably, not worth the effort, unless the file is truly huge).
   val lines = Source.fromFile("input_file.csv").getLines
   val firstLine = if(lines.hasNext) Some(lines.next) else None
   val lastLine = lines.foldLeft(Option.empty[String]) { case (_, line) => Some(line) }
   val spos: Seq[Seq[Int]] = (firstLine ++ lastLine).map(_.split(",").map(_.toInt))

   // next line will fail if there are fewer than two lines in the file
   // or if either first or last line doesn't have exactly three comma-separated fields
   // I am just putting it here to illustrate how you could extract the parsed data

   val Seq(Seq(s1, p1, o1), Seq(s2, p2, o2)) = spos

Update
Ok, if you really don't want to have to read through the entire file, you can try something like this (this is a crude approach, based on the fact that your lines are all short, so I can be sure that if I land somewhere ~1000 bytes from the end of the file, I'll definitely be well before the start of the last line.
   val file = new RandomAccessFile("input_file.csv", "r")
   val firstLine = Option(file.readLine)
   if(file.length > 1024 + firstLine.fold(0)(_.length))
      file.skipBytes(file.length - 1024)
   val lastLine = Iterator.continually(file.readLine)
     .takeWhile(_ != null)
     .foldLeft(Option.empty[String]) { case (_, line) => line }

(the rest of the earlier snippet can stay the same).


text:
Q: How to add elements to array in object property I have the following array and object I would like to 'match'
const items = [
  { key: 1, name: 'A', owner: 'Alex', },
  { key: 2, name: 'B', owner: 'Barb', },
  { key: 3, name: 'C', owner: 'John', },
  { key: 4, name: 'D', owner: 'Barb', },
  { key: 5, name: 'E', owner: 'Alex', },
];

const owners = {
  'Alex': { 1: [], 5: [] },
  'John': { 3: [], },
  'Barb': { 2: [], 4: [] },
}

I would like to have the following end result:
const ownersWithName = {
  'Alex': [{ key: 1, name: 'A', }, { key: 5, name: 'E' }],
  'Barb': [{ key: 2, name: 'B', }, { key: 4, name: 'D' }],
  'John': [{ key: 3, name: 'C', }, ],
}

So far my solution is this:
function matchOwners (items, owners) {
  const ownersWithName = {};
  for (const item of items) {
    if (owners[item.owner]) {
      if (ownersWithName[item.owner]) {
        ownersWithName[item.owner] = [ ...ownersWithName[item.owner], item];
      } else {
        ownersWithName[item.owner] = [item];
      }
    }
  }
  return ownersWithName;
}

This solution works, but i feel it's too verbose. i tried to use the spread operator without the if condition, but this needs the array to exist already, otherwise i get the error ownersWithName[item.owner] is not iterable. Is there a better way to do this?

A: Something like (completely untested):
ownersWithName = items.reduce((result, item) => {
  if (owners[item.owner]) {
    if (!(item.owner in result)) {
      result[item.owner] = [];
    }
    result[item.owner].push({key: item.key, name: item.name});
  }
  return result;
}, {})

A: You can also simply achieve this by using Array.forEach() along with the Object.keys() method.
Live Demo (Descriptive comments has been added in the below code snippet) :

// Input array
const items = [
  { key: 1, name: 'A', owner: 'Alex', },
  { key: 2, name: 'B', owner: 'Barb', },
  { key: 3, name: 'C', owner: 'John', },
  { key: 4, name: 'D', owner: 'Barb', },
  { key: 5, name: 'E', owner: 'Alex', },
];

// Input object which should be used to match.
const owners = {
  'Alex': { 1: [], 5: [] },
  'John': { 3: [], },
  'Barb': { 2: [], 4: [] },
};

// Declare an object which will store the final result.
const resultObj = {};

// Iterating over an items array to manipulate the data and make the final result set.
items.forEach(obj => {
  resultObj[obj.owner] = !resultObj[obj.owner] ? [] : resultObj[obj.owner];
  Object.keys(owners[obj.owner]).forEach(key => {
    if (key == obj.key) {
      resultObj[obj.owner].push({
        key: obj.key,
        name: obj.name
      });
    }
  });
});

// Final output
console.log(resultObj);


text:
Q: Tracking changes to Django Model instances When you create or modify an object instance in Django's admin, a changelog entry is created. This is really nice for fairly obvious reasons.
However my model's instances created by a normal user outside of the admin interface. No changelog is recorded to note its creation (not a huge issue) but I would like to track edits the user makes.
I also want to show the user this full log (user+admin edits) in the frontend so I need a way to pull the changelog out.
My question: how? Is there a one-line switch I can flick to enable full logging or do I have to dig in and do something on my user's edit form logic?

A: django-reversion is an app designed to help with that.


text:
Q: How to create Feed section in wordpress for homepage I am trying to do is, when a user post something from his account it will directly need to show on homepage on wordpress site. This will be for all user's role.
Here i want to build a feed page like LinkedIn.
Thanks in advance.

A: I'm assuming you have some knowledge...
You could just add a loop restricted to a specific author... or user by grabbing the user ID. You could do something like this:

<?php
// 'post_type' => 'any' ... to display all post and custom post type related to the author or user
// You should restrict the number of post, you don't want your site crashing by loading all posts available
// I'm letting your imagination take over
$authID = get_the_author_meta( 'ID' );
$query = new wp_query( array( 'author' => $authID,'post_type' => 'any', 'post_status' => 'publish', 'posts_per_page' => '3' ) );  if ( $query->have_posts() ): ?>

Discover your feed

<?php while ( $query->have_posts() ): $query->the_post(); ?>

<a aria-label="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php endwhile; else: ?>

Your feed is empty

<?php endif; ?>

Should be working just tested it.
Regards. Stackoverflow, World Wide Web support x)


text:
Q: List of strings between regex matches How do I find all the strings between a regex pattern?
For example,
>>> s="123 asd 12 456 sfd g 789"
>>> reg=re.compile("\d{3}")
>>> reg.findall(s)
['123', '456', '789']

I want to find:
[' asd 12 ', ' sfd g ']

A: Use the .split() method instead of .findall():
>>> reg.split(s)
['', ' asd 12 ', ' sfd g ', '']

It includes all results in between the matches, including the empty strings at the start and end. You can filter those out:
>>> filter(None, reg.split(s))
[' asd 12 ', ' sfd g ']

although on Python 3 you'd need to use list(filter(None, reg.split(s))), or iterate over the result of filter().

A: Use re.split instead of re.findall.

A: You could try something like:
>>> reg = re.compile(r'(?:\d{3})?(.*?)\d{3}')
>>> reg.findall("123 asd 12 456 sfd g 789")
[' asd 12 ', ' sfd g ']

Since .findall() won't find overlapping matches, you need to specify the first group of numbers as being an optional match.  In the end, it might be better to take a different approach than regexes alone for a more robust solution.

A: >>> s = "123 asd 12 456 sfd g 789"
>>> filter(None, re.compile("\d{3}").split(s))
[' asd 12 ', ' sfd g ']


text:
Q: How Does Integrating the Derivative of this Approximation for Tangent Increase its Accuracy? In this answer, Raymond Manzoni uses a beautiful method to find the Taylor Series of $\tan x$, which is recursively defined as $x_{n+1}=\int1+x_n^2dx$, which comes from the fact that $\frac d {dx}\tan x=\sec^2x=1+\tan^2x$. Why does this work and are there any other series that can be derived recursively like this?

A: This is just the Picard iteration for the initial value problem $y'=f(x,y)=1+y^2$, $y(0)=y_0=0$. In general,
$$
y_{n+1}=y_0+\int_0^x f(s,y_n(s))\,ds
$$
and the theorem of Picard-Lindelöf tells us that under rather general assumptions this converges locally.
If $f$ is polynomial or analytical, then if one replaces $y_n$ with its truncated power series, then the evaluation of $f(s,y_n(s))$ will also be a truncated power series that can then be integrated. When $y_n=y(x)+O(x^{n+1})$, then $$f(x,y_n(x))=f(x,y(x))+f_y(x,y_n)O(x^{n+1})=y'(x)+O(x^{n+1})$$
and integration of this will give
$$
y_{n+1}(x)=y_0+\int_0^x (y'(s)+O(s^{n+1}))\,ds=y(x)+O(x^{n+2}),
$$
that is, the truncation degree increases and the coefficient of $x^{n+1}$ will be known and correct.
For instance, the most trivial non-trivial polynomial is $f(x,y)=y$ which in its integration gives term-for-term the exponential series.


text:
Q: libssh2: How to send data through libssh2_channel_write EDIT:
Here's the complete code. modified the code to work with a router but the use case is same. Once i issue the password using libssh2_channel_write() subsequent libssh2_channel_read() fails with LIBSSH2_ERROR_SOCKET_RECV. Not sure why. I am unable to send subsequent commands to the remote device and get their output.
Logic was to execute a command on the remote device ( libssh2_channel_exec ). This command execution would throw a password to be entered by the client. Now read the stream via libssh2_channel_read() and ensure that the password is being asked and write the password to the channel via libssh2_channel_write(). Ensure the password is accepted on the remote device by doing subsequent reads [ THIS IS WHERE THE LIB IS FAILING WITH ERROR_SOCKET_RECV ] and then send the command to be executed via libssh2_channel_write() and read the command output. Am i missing something ?
    for( ;; )
    {
        /* loop until we block */
        int rc;
        do
        {
            char buffer[0x4000];
            rc = libssh2_channel_read( channel, buffer, sizeof(buffer) );

            if( rc > 0 )
            {
                int i;
                char *enable = "check-password\n";
                int ret;
                bytecount += rc;
                fprintf(stderr, "We read [%d] bytes:\n", bytecount);
                fputc('[', stderr);
                for( i=0; i < rc; ++i )
                    fputc( buffer[i], stderr);
                fputc(']', stderr);

                if ( strstr(buffer, "Password:") != NULL ){
                    fprintf(stderr, "Sending the password now\n");
                    while((ret = libssh2_channel_write(channel, enable, strlen(enable))) == LIBSSH2_ERROR_EAGAIN) {
                        printf("ERROR_EAGAIN - sending password again\n");
                    }

                    fprintf(stderr, "Wrote [%d] bytes: \n", ret);
                    flag = 1;
                    continue;
                }
                if (!flag){ // start
                    char *cmd = "show clock\n";
                    int ret;
                    fprintf(stderr, "THIS Fetching show clock command now\n");
                    while((ret = libssh2_channel_write(channel, cmd, strlen(cmd))) == LIBSSH2_ERROR_EAGAIN) {
                        printf("ERROR_EAGAIN - sending show clock again\n");
                    }
                    flag = 1;
                } // end
            }
            else {
                if(rc != LIBSSH2_ERROR_EAGAIN)
                    fprintf(stderr, "libssh2_channel_read returned [%d]:\n ", rc);
            }
        }
        while( rc > 0 );

        /* this is due to blocking that would occur otherwise so we loop on
           this condition */
        if( rc == LIBSSH2_ERROR_EAGAIN )
        {
            int check;
            check = waitsocket(sock, session);
        }
        else
            break;
    }


text:
Q: Equivalent of Eclipse 'Show in' project explorer for Android studio In Eclipse is was always easy to search for a file int he project explorer.  Right click in the java file and do 'show in'.

this would reveal the file in the explorer for me instead of me hunting for it.  Where is the android studio's way of doing the same thing ? I've tried typing the name of the file in the project explorer but it doesn't seem to work.


text:
Q: Unix script, find current directory #!/bin/sh

Dir1=$1
Dir2=$2

if [ $# -lt 1 ]
then
    echo  "`find -type f | wc -l` ordinary `find -type f -executable | wc -l` executable     `find -type l | wc -l` links `find -type d | wc -l` directories"
else
    if [ $# -eq 1 ]
    then
        echo "$Dir1: `find $Dir1 -type f | wc -l` ordinary `find $Dir1 -type f -executable | wc     -l` executable `find $Dir1 -type l | wc -l` links `find $Dir1 -type d | wc -l` directories"
    else
    fi
fi

For this code, what i am trying to do is that, if i have a script called find.sh, when i type in find.sh without any directory, it will just find files that are in current directory, if a directory is given for example, find.sh test, it will find all the files in test directory, problem is i am not sure if the first part of the code is right, not sure if its finding the current directory or not.

A: You don't seem to be using Dir2 there.
I would do
if [ -z $1 ]
then
   Dir1=$(/bin/pwd)
else
   Dir1=$1
fi

for your variable detection. then you just need:
number=$(find $Dir1 -type f |wc -l)
echo "$Dir1 has $number files"

and same job for your executable.

A: Here is the fix
#!/usr/bin/env bash

dir1=${1:-.}
dir2=${2:-.}
echo $dir1 $dir2

for dir in $dir1 $dir2
do
  ordinary=$(find $dir -type f | wc -l )
  executable=$(find $dir -type f -executable | wc -l)
  directories=$(find $dir -type d | wc -l)
  links=$(find $dir -type l | wc -l)
  echo "$dir: $ordinary $executable $links $directories"
done

Explanation

*

*dir1=${1:-.} assign $1 to dir1 if $1 is exist, otherwise, give the default value . . . means current directory.


text:
Q: IP Address dotted decimal to /8 or /16 notation using bash,sed or awk? I have an input file that contains a list of ip addresses and the ip_counts(some parameter that I use internally.)The file looks somewhat like this.
202.124.127.26  2135869
202.124.127.25  2111217
202.124.127.17  2058082
202.124.127.16  2014958
202.124.127.20  1949323
202.124.127.24  1933773
202.124.127.27  1932076
202.124.127.22  1886466
202.124.127.18  1882955
202.124.127.21  1803528
202.124.127.23  1786348
119.224.129.200  1776592
119.224.129.211  1639325
202.124.127.19  1479198
119.224.129.201  1145426
202.49.175.110  1133354
119.224.129.210  1119525
68.232.45.132  1085491
119.224.129.209  1015078
131.203.3.8   857951
202.162.73.4   817197
207.123.58.125   785326
202.7.6.18   762603
117.121.253.254   718022
74.125.237.120   710448
68.232.44.219   693002
202.162.73.2   671559
205.128.75.126   611301
119.161.91.17   604393
119.224.129.202   559930
8.27.241.126   528862
74.125.237.152   517516
8.254.9.254   514341

As you can see the ip addresses themselves are unsorted.So I use the sort command on the file to sort the ip addresses as below
cat address_count.txt | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n > sorted_address.txt
Which gives me an output with ip addresses in the sorted order.The partial output of that file is shown below.
4.23.63.126    15731
4.26.254.254   320705
4.27.8.254    25174
8.12.129.50   176141
8.12.223.125    11800
8.19.32.65    15854
8.19.240.53    11013
8.19.240.70    11915
8.19.240.72    31541
8.19.240.73    23304
8.20.213.28    96434
8.20.213.32   108191
8.20.213.34   170058
8.20.213.39    23512
8.20.213.41    10420
8.20.213.61    24809
8.26.195.253    28568
8.27.152.253   104446
8.27.233.125   115856
8.27.235.126    16102
8.27.235.254    25628
8.27.238.254   108485
8.27.240.125   169262
8.27.241.126   528862
8.27.241.252   197302
8.27.248.125    14926
8.254.9.254   514341
12.129.210.71    89663
15.192.45.21    20139
15.192.45.26    35265
15.193.0.148    10313
15.193.113.29    40318
15.201.49.136    14243
15.240.238.52    57163
17.250.248.95    28166
23.33.125.13    19179
23.33.125.37    17953
31.151.163.60    72709
38.99.42.37   192356
38.99.68.180    41251
38.99.68.181    10272
38.104.237.74    74012
38.108.112.103    37034
38.108.112.115    69698
38.108.112.121    92173
38.108.112.122    99230
38.112.63.238    39958
38.119.130.62    42159
46.4.28.22       19769

Now I want to parse the file given above and convert it to aaa.bbb.ccc.0/8 format and aaa.bbb.0.0/16 format and I also want to count the number of occurences of the ip's in each subnet.I want to do this using bash.I am open to using sed or awk.How do I achieve this.
For example
8.19.240.53    11013
8.19.240.70    11915
8.19.240.72    31541
8.19.240.73    23304
8.20.213.28    96434
8.20.213.32   108191
8.20.213.34   170058
8.20.213.39    23512
8.20.213.41    10420
8.20.213.61    24809

The about input portion should produce 8.19.240.0/8 and 8.20.213.0/8 and similarly for /16 domains.I also want to count the occurences of machines in the subnet. For example In the above output this subnet should have the count 4 in the next column beside it.It should also add the already displayed count.i.e (11013 + 11915 + 31541 + 23304) in another column.
8.19.240.0/8 4 (11013 + 11915 + 31541 + 23304) 8.20.213.0/8 6 (96434 + 108191 + 170058 + 23512 + 10420 + 24809)
It would be great if someone could suggest some way to achieve this.

A: If your gawk-foo is strong, you can probably replace this whole thing with a single awk script, but I found this easier to hack together.
while read; do
    ipcalc $(awk '{print $1}' <(echo "$REPLY")) |
    awk '/^Network:/ {print $2}'
done < sorted_address.txt

Obviously, it relies on ipcalc, but parsing that is going to be less painful than trying to do your own parsing in Bash.


text:
Q: Replacing fragments dynamically? Now I know this is a very simple question and was asked many times, but non of the solutions provided previously has worked for me.
I have an activity with a FrameLayout as follows:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/replace_me"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

</android.support.constraint.ConstraintLayout>

And in my MainActivity class I have the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        replaceFragment(new ChooseLevelFragment(), false);
    }
}

public void replaceFragment(Fragment fragment, boolean addToBackStack) {
    FragmentTransaction replace = getSupportFragmentManager().beginTransaction().replace(R.id.replace_me, fragment);
    if (addToBackStack) {
        replace.addToBackStack(null);
    }
    replace.commit();
    Log.d(TAG, "Fragment replaced!");
}

The first fragment is being shown correctly. However, when the user clicks on an item from the menu and logs in, the app should replace the current fragment with the new one
private void showAuthenticationDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

    Fragment fragmentByTag = getSupportFragmentManager().findFragmentByTag(AuthenticationDialogFragment.TAG);

    if (fragmentByTag != null) {
        fragmentTransaction.remove(fragmentByTag);
    }
    fragmentTransaction.addToBackStack(null);

    AuthenticationDialogFragment authenticationDialogFragment = AuthenticationDialogFragment.newInstance(() -> {
        replaceFragment(new ParentControlPanelFragment(), true);
    });
    authenticationDialogFragment.show(fragmentTransaction, AuthenticationDialogFragment.TAG);

}

The new fragment is not being replaced even after the commit. I can see my log message but not the new fragment. I'm not quite sure where the problem is.

A: The problem was that I was trying to replace the fragment before I dismiss the dialog.
The correct approach is to dismiss the dialog first then try to replace the fragment.


text:
Q: Is there a way to access the files of application cache of safari using javascript? I looked at certain options to access the files that are cached in the browser, but I could not get one. Only thing which I ended up was counting the number of files being cached by listening the caching events.
Here is the code:
var cacheStatusValues = [];
cacheStatusValues[0] = 'uncached';
cacheStatusValues[1] = 'idle';
cacheStatusValues[2] = 'checking';
cacheStatusValues[3] = 'downloading';
cacheStatusValues[4] = 'updateready';
cacheStatusValues[5] = 'obsolete';
var cache = window.applicationCache;
cache.addEventListener('cached', logEvent, false);
cache.addEventListener('checking', logEvent, false);
cache.addEventListener('downloading', logEvent, false);
cache.addEventListener('error', logEvent, false);
cache.addEventListener('noupdate', logEvent, false);
cache.addEventListener('obsolete', logEvent, false);
cache.addEventListener('progress', logEvent, false);
cache.addEventListener('updateready', logEvent, false);
var count=0;
function logEvent(e) {
    var online, status, type, message;
    online = (navigator.onLine) ? 'yes' : 'no';
    status = cacheStatusValues[cache.status];
    type = e.type;
    message = 'online: ' + online;
    message+= ', event: ' + type;
    message+= ', status: ' + status;
    if (type == 'error' && navigator.onLine) {
        message+= ' (prolly a syntax error in manifest)';
    }
    console.log(message);
    if(type=='progress') {
       count++;
    }
    if(type=='cached') {
//count-1 is bcoz the "progress" events starts from 0
        alert("Count of files Cached: "+count-1);
        //alert(cache.mozItems());
    }
}

I could not find a way to traverse the cached files. On searching in net I got the answers as somewhat like this,
"There is no direct Javascript interface for checking the contents of the browser's cache. It would be a security hazard if you were able to probe the contents of the users' file system. " in http://www.codestyle.org/javascript/faq-Browser.shtml.
But still I was wondering if there can be a possible way using javascript, preferably or any other language supported for iOS. It would be of great help if a solution is posted in this thread. Thanks in advance.


text:
Q: Spring Boot @RequestBody parses only 0/null values? I have a POJO "Problem" object:
import lombok.Data;

@Data
public class Problem {
    int capacity;
    int weights[];
    int values[];
}

Which I am trying to parse in a Rest controller in Spring Boot:
@RequestMapping(value = "/calculate", method = RequestMethod.POST)
public SolutionResponse calculateSolution(@RequestBody Problem problem) {
// problem = Problem(capacity=0, weights=null, values=null) ??
// Goes on ..
}

I am posting the following with cURL:
curl -d '{"problem": {"capacity": 60, "weights": [5, 2, 22], "values": [2, 5, 30]}}' -H "Content-Type: application/json" -X POST http://localhost:8088/endpoint/calculate

Looking into debug mode, it is indeed parsed, but as:
problem = Problem(capacity=0, weights=null, values=null)

So, it's wrong as they should have the values that I posted.
What could be the issue?

A: Json you are sending from curl is not correct.
It should be
{"capacity": 60, "weights": [5, 2, 22], "values": [2, 5, 30]}


text:
Q: How to fix Loading the Google Maps JavaScript API without a callback is not supported How to fix the following console errors.

*

*Loading the Google Maps JavaScript API without a callback is not supported

*InvalidValueError: not an instance of HTMLInputElement
Because of the above errors, my jobs are not showing in Google search results.
I'm not a developer, so I need suggestions to fix this problem. I will incorporate the necessary changes in my WordPress website.

A: I actually created a noop function so I could keep track of when it was called.
function gmNoop() { console.log('GMap Callback') }

Then added it to my Google map API resource request.
https://maps.googleapis.com/maps/api/js?key='.GOOGLEMAPSKEY.'&callback=gmNoop

The reason I needed this was because my application calls initMap() after  other prerequisites. Calling initMap() prior to these other resources would load a map without markers.

A: TL;DR
Use Function.prototype as a noop callback to quickly get rid of the error message.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=Function.prototype

Full Explanation
According to the Google Maps API documentation, the callback parameter has been required for a very long time. In practice, however, Google has only recently (within the past few days) begun enforcing this requirement.
While it doesn't seem to break anything, it now shows an ugly error message in the console...

Loading the Google Maps JavaScript API without a callback is not supported.

How can I fix it?
The short answer is to specify a callback value. Set the name of the JavaScript function that you would like to trigger once the external API library has finished loading.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=FUNCTION_NAME

Be warned, you must specify a real function name! Otherwise you'll trigger an "is not a function" error message, and simply be trading one error message for another.
But I don't have/need a callback function!
If you don't actually have a callback function to run immediately after the library loads, you can use Function.prototype as a noop stand-in.
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=Function.prototype

The Function.prototype method is native to JavaScript, and does absolutely nothing... It's exactly what you need in a situation like this!
For more information about Function.prototype, see this unrelated SO thread...

A: I just found this yt video which may help you:
https://www.youtube.com/watch?v=1asukrHEqMM&ab_channel=KnowledgeBase
It didn't help me much as my problem is slightly different, but gave me an idea of what way to go. Hopefully it helps you. Good luck
::::::::::E D I T::::::::::
Basically what you have to do to get rid of this error is to declare the function (aka initMap) before running the script where you make the API call.
The initMap function is the function where the google map is created and given the characteristics and all that.
initMap function looks like this:
function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

The API call is the script line where we put the API-KEY.

I found two ways to do it, the first way is: have a module that you only have to call before the API with a src script.
Example:

Dentro de google.js es donde guardo mi funcion de initMap()

The second way is: write all the code inside a script tag before making the API call.
Example:

Note that I use defer so that the code loads at the bottom of the
page, this is just my style because I like to declare everything in the
head element.


text:
Q: C compile errors: stray '\200' in program and expected ')' before numeric constant I copied this program and am having trouble with the void downFrequency function (I think).
This is for Arduino Uno. Here are the compiler errors:
Compiling 'MY_dds' for 'Arduino Uno'
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : stray '\342' in program
MY_dds.ino : stray '\200' in program
MY_dds.ino : stray '\223' in program
MY_dds.ino : : In function 'void downFrequency()':
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
MY_dds.ino : expected `)' before numeric constant
Error compiling

Here is the program:
#include <stdio.h>
#include <dds.h>
#include <LiquidCrystal.h>

#define RESET 13
#define data_pin 12
#define load_pin A5
#define clock_pin A4
#define clock_hz 120000000LL
#define calibrationValue -0.0400000 // This is a value we change to calibrate
                                    // our particular chip more accurately
#define buttonPin A0

// chip, data_pin, load_pin, clock_pin, clock_hz
dds ddschip(DDS9850, data_pin, load_pin,  // Set my dds up with 120 MHz
            clock_pin, clock_hz);         // onboard crystal

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// Some variables to use in our program
long toFrequency = 14070000;
long currentFrequency;
long maxFrequency = 40000000;
long minFrequency = 0;
int incrementNumber = 6;
int maxprogramnumber = 6; // Don't forget to increase the menu numbers here!!
int programnumber = 1;

void setup()
{
  Serial.begin(9600);
  Serial.println("Beginning Setup");

  // Set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("T.Robb V0.1b "); // Print a little message
  lcd.setCursor(0, 1);
  lcd.print(" DDS Sine wave ");
  delay(2000);

  // Set up pins
  pinMode(RESET, OUTPUT);
  pinMode(data_pin, OUTPUT);
  pinMode(load_pin, OUTPUT);
  pinMode(clock_pin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);

  ddschip.calibrate(calibrationValue); // This is a value we change to calibrate
                                       // our particular chip more accurately
  ddschip.setfrequency(toFrequency);
  lcd.clear();
}

void loop()
{
  if(toFrequency >= maxFrequency)
  {
    (toFrequency = maxFrequency);
  }

  if(toFrequency <= minFrequency)
  {
    (toFrequency = minFrequency);
  }

  ddschip.setfrequency(toFrequency);
  currentFrequency = toFrequency;

  switch(incrementNumber)
  {
    case 0:
      Serial.println("increment amount is 1 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 1 Hz");
      break;

    case 1:
      Serial.println("increment amount is 10 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 10 Hz ");
      break;

    case 2:
      Serial.println("increment amount is 100 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 100 Hz ");
      break;

    case 3:
      Serial.println("increment amount is 1 000 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 1 kHz");
      break;

    case 4:
      Serial.println("increment amount is 10 000 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 10 kHz");
      break;

    case 5:
      Serial.println("increment amount is 100 000 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 100 kHz");
      break;

    case 6:
      Serial.println("increment amount is 1 000 000hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 1 MHz");
      break;

    default:
      Serial.println("increment amount is 100 Hz");
      lcd.setCursor(0, 0);
      lcd.print("Change By 100 Hz ");
      break;
  }

  lcd.setCursor(0, 1);
  lcd.print("Freq is "); // Print to LCD
  lcd.setCursor(8, 1);
  lcd.print(currentFrequency);

  Serial.println(incrementNumber); // Temporary for debugging delete me

  Serial.print("Current frequency is set to: ");
  Serial.println(currentFrequency);

  while((analogRead(buttonPin))>=1000) // Do nothing while no buttons pressed to chill out
  {
  }

  delay(5);
  if (analogRead(buttonPin)>=100 && analogRead(buttonPin) <= 200) // We have pushed up
  {
    upFrequency();
    delay(300);
  }

  if(analogRead(buttonPin)>=200 && analogRead(buttonPin) <= 400) // We have pushed down
  {
    downFrequency();
    delay(300);
  }

  if ((analogRead(buttonPin)) <= 50) // We have pushed right
  {
    incrementNumber++;
    delay(300);
  }

  if(analogRead(buttonPin) >= 400 && analogRead(buttonPin)<=600) // We have pushed left
  {
    incrementNumber–;
    delay(300);
  }

  if(incrementNumber > 6) // This is where the menu goes around and around
  {
    incrementNumber = 0;
  }
  if(incrementNumber < 0)
  {
    incrementNumber = 6;
  }

  delay(100);
  lcd.clear();
}

void upFrequency()
{
  Serial.println("Going UP Frequency");
  switch(incrementNumber)
  {
    case 0:
      toFrequency = (toFrequency + 1);
      break;

    case 1:
      toFrequency = (toFrequency + 10);
      break;

    case 2:
      toFrequency = (toFrequency + 100);
      break;

    case 3:
      toFrequency = (toFrequency + 1000);
      break;

    case 4:
      toFrequency = (toFrequency + 10000);
      break;

    case 5:
      toFrequency = (toFrequency + 100000);
      break;

    case 6:
      toFrequency = (toFrequency + 1000000);
      break;

    default:
      toFrequency = (toFrequency + 10);
      break;
  }

}

void downFrequency()
{
  Serial.println("Going DOWN Frequency");
  switch(incrementNumber)
  {
    case 0:
      toFrequency = (toFrequency – 1);
      break;

    case 1:
      toFrequency = (toFrequency – 10);
      break;

    case 2:
      toFrequency = (toFrequency – 100);
      break;

    case 3:
      toFrequency = (toFrequency – 1000);
      break;

    case 4:
      toFrequency = (toFrequency – 10000);
      break;

    case 5:
      toFrequency = (toFrequency – 100000);
      break;

    case 6:
     toFrequency = (toFrequency – 1000000);
     break;

    default:
      toFrequency = (toFrequency – 10);
      break;
  }

}

A: Probably your double quote symbols (") were wrong. Please check if they are actually ", and not " .

A: You've somehow ended up with "en dash" characters, rather than normal minus signs, in the downFrequency function.
Make sure you're editing using a text editor, not a word processor; and for each of these:
toFrequency = (toFrequency – 1);
                           ^

delete the marked character, and retype as a normal minus sign.
(If you're interested in the gory details, the "dash" character is Unicode 2013, encoded in UTF-8 as three bytes with octal values 324,200,223, which is why you see those numbers in the error messages.)

A: The compiler is complaining that there are non-ASCII characters in your source file.
My octal fu is rusty, but it looks like UTF-8 to me. 342 200 223 is 0xE2 0x80 0x93 which is Unicode code point "EN DASH." This code was given a minus sign makeover by a text editor with a degree in cosmetology.

A: Simple copy always mess up the source code.
One can check the "stray" problem via cat -A yoursrc.c.
To me, I usually reformat the code by Vim in two steps.
vim yoursrc.c
:%!tr -cd '[:print:]\n'

Then compile, gcc yoursrc.c.


text:
Q: Lambda function to make simple HTTP request I want to use AWS lambda to make a cronjob-style HTTP request. Unfortunately I don't know Python.
I found they had a "Canary" function which seems to be similar to what I want. How do I simplify this to simply make the HTTP request? I just need to trigger a PHP file.
from __future__ import print_function

from datetime import datetime
from urllib2 import urlopen

SITE = 'https://www.amazon.com/'  # URL of the site to check
EXPECTED = 'Online Shopping'  # String expected to be on the page

def validate(res):
    '''Return False to trigger the canary

    Currently this simply checks whether the EXPECTED string is present.
    However, you could modify this to perform any number of arbitrary
    checks on the contents of SITE.
    '''
    return EXPECTED in res

def lambda_handler(event, context):
    print('Checking {} at {}...'.format(SITE, event['time']))
    try:
        if not validate(urlopen(SITE).read()):
            raise Exception('Validation failed')
    except:
        print('Check failed!')
        raise
    else:
        print('Check passed!')
        return event['time']
    finally:
        print('Check complete at {}'.format(str(datetime.now())))

A: This program will "simply make the HTTP request."
from urllib2 import urlopen

SITE = 'https://www.amazon.com/'  # URL of the site to check

def lambda_handler(event, context):
    urlopen(SITE)

A: You can use Requests (http://docs.python-requests.org/en/master/) to work with the response in a easier way.
import requests

URL = 'https://www.amazon.com/'
def lambda_handler(event, context):
    requests.get(URL)

A: I found out a way to do requests in AWS Lambda.
Courtesy of https://stackoverflow.com/a/58994120/129202 - this answer has a couple of other solutions too, that could be worth checking out. The below one worked for me.
import urllib.request
import json

res = urllib.request.urlopen(urllib.request.Request(
        url='http://asdfast.beobit.net/api/',
        headers={'Accept': 'application/json'},
        method='GET'),
    timeout=5)

print(res.status)
print(res.reason)
print(json.loads(res.read()))


text:
Q: Owl carousel : change slide on hover dots I´m using dots to navigate the owl carousel 2.
I like to change the navigation from click to hover.
So when I hover the second dot, the carousel jumps to the second slide.
Couldn't find something like this in the documentation.
Are there any easy solutions for this?

A: The easiest solution would be something like this:
$('.own-carousel .dot').hover(function() {
    $(this).click();
}, function() {});

This simply triggers the click events on hover. I am not sure about the classes own-carousel and dot, better check those.


text:
Q: why flatten and collect_list error in scala? with cannot resolve symbol I have a dataset that I am trying to flatten using scala.
+---------+-----------+--------+
|visitorId|trackingIds|emailIds|
+---------+-----------+--------+
|     a   |       666b|      12|
|     7   |       c0b5|      45|
|     7   |       c0b4|      87|
|     a   |  666b,7p88|        |
+---------+-----------+--------+

I am trying to achieve a dataframe which is grouped by the visitorID. Below is the format
+---------+---------------------+--------+
|visitorId|   trackingIds       |emailIds|
+---------+---------------------+--------+
|     a   |       666b,666b,7p88|   12,87|
|     7   |       c0b4,c0b5     |      45|
+---------+---------------------+--------+

My code:
object flatten_data{

  def main(args: Array[String]): Unit = {

    val spark = SparkSession
      .builder()
      .master("local[5]")
      .appName("Flatten_DF")
      .enableHiveSupport()
      .getOrCreate()

       val df =  spark.read.format("csv")
      .option("header","true")
      .option("delimiter",",")
      .load("/home/cloudera/Desktop/data.txt")
    print(df.show())
    val flattened = df.groupBy("visitorID").agg(collect_list("trackingIds"))
  }
}

I am using IntelliJ Idea and I am getting an error at "collect_list".
I read through many solution on stackoverflow where people have asked on how to flatten and groupbykey and have used the same collect_list. I am not sure why this is not working for me. Is it because of IntelliJ?

A: I reworked on your code and this seems to be working:
import org.apache.spark.sql.SparkSession
   import org.apache.spark.sql.functions._

   object flatten_data{

   def main(args: Array[String]): Unit = {

    val spark = SparkSession.builder().master("local").appName("test").getOrCreate()
    import spark.implicits._
    val someDF = Seq(
      ("a", "666b",12),
      ("7", "c0b5",45),
      ("7", "666b,7p88",10)
    ).toDF("visitorId","trackingIds","emailIds")

    someDF.groupBy("visitorID").agg(collect_list("trackingIds")).show()
        }
    }

A: collect_list is a method defined in the org.apache.spark.sql.functions object, so you need to import it:
import org.apache.spark.sql.functions.collect_list

Alternatively, you can import the entire object, then you'll be able to use other functions from there as well:
import org.apache.spark.sql.functions._

Finally, the approach I personally prefer is to import functions as f, and use qualified calls:
import org.apache.spark.sql.{functions => f}

agg(f.collect_list(...))

This way, the global namespace inside the file is not polluted by the entire host of functions defined in functions.


text:
Q: Android Retrofit - Callback vs no call back I am analyzing retrofit on android and had a question on callbacks vs not using them.  I am under the impression that callbacks are only used for success and failure responses a client might desire.  Otherwise i would omit it.  Here is an example of a retrofit interface without a callback:
 public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

and here is an example with a callback (i hope i have it right):
   public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user,Callback<Repo> cb);
}

Im confused on two things:

*

*The return value in the interface is List but to me it should be void because retrofit will use gson to convert the json response to a Repo POJO. All i have to do is create the Repo POJO so i would expect the last piece of code to be like this instead:
public interface GitHubService {
@GET("/users/{user}/repos")
void listRepos(@Path("user") String user,Callback cb);
            }
What is the purpose of the return value?

*my second question is : is the callback only necessary to know if the request was a success or failure as i see from the docs that callback has two methods: failure and success.

A: I want to try and answer your question
1. You are correct, the return value should be void, as you will get the response from the Callback
2. Yes it is, the Callback is needed to check whether the request is successful or not, also it is there to grab the server response.
Hope this is useful, cheers!

EDIT : You can use direct return value or use callbacks to get the response. Quoting from the retrofit documentation site :

*

*A method with a return type will be executed synchronously.

*Asynchronous execution requires the last parameter of the method be a Callback.

So I guess the documentation answers it really, Callback is needed if you want the execution to be asynchronous :D


text:
Q: How to express $(142536)$ as string of $(13456)$ and $(132)$ in $S_6$? Suppose that $r=(13456)$ and $s=(132)$ be two permutations in $S_6,$ the group of all permutations of the symbols in $\{1,2,3,4,5,6\}$.
Let $\alpha=(142536)$. I am willing to express $\alpha$ as a string of $r,s$ as $$\alpha=r^{m_1}s^{m_2}r^{m_3}s^{m-4}\cdots$$
where $m_1, m_2, \cdots$ will be integers.
I do not know if there is any general procedure to determine $m_1, m_2, \cdots$ manually.
If any such method exists, please share the link or please tell me how to solve it.
Thanks in advance. Please feel free to edit my question if necessary

A: You can't do this at all. $(142536)$ is an odd permutation, so you cannot write it in terms of even permutations $(13456)$ and $(132)$. Any product of even permutations is itself even.


text:
Q: Why can't we perform joins in a distributed database like Bigtable? From this answer to "What database does Google use?":

Bigtable is not a relational database. It does not support joins nor does it support rich SQL-like queries.

Is this obvious? I do not understand why.

A: Bigtable doesn't use SQL (a query language) so SQL can't be used directly to query the database. And Bigtable doesn't have "relations" in the same way as relational databases, it's more like bare tables.
If you want to get data from two tables, you have to do two lookups, and combine the result set in the application code. In other words the "join" operation is not built-in in the database, so you have to do that kind of operations in the application, if needed.
The fact that Bigtable doesn't support SQL and JOIN operations has nothing to do with that it is a distributed database system. There are distributed databases that has support for SQL. E.g. VoltDB and MySQL Cluster. There are also many databases that aren't distributed and doesn't use SQL e.g. Kyoto Cabinet.


text:
Q:  won't submit form on first click if  field uses  I'm having an issue with the following form:
<h:form>
    <p:outputPanel autoUpdate="true">
        <p:panelGrid columns="2">
            <f:facet name="header">
                <h:outputText value="Edit a Recycler"/>
            </f:facet>

            <p:outputLabel value="Recycler Name" for="recyclerName"/>
            <p:inputText id="recyclerName" value="#{RecyclerAdmin.editItem.company.companyName}" required="true" requiredMessage="You must name the recycler.">
                <p:ajax async="true" />
            </p:inputText>

            <p:outputLabel value="Zip Code" for="zipCode"/>
            <p:inputText id="zipCode" value="#{RecyclerAdmin.editItem.company.primaryAddressId.zip}" required="false">
                <p:ajax event="blur" async="true" update="citystate" listener="#{RecyclerAdmin.zipCodeChanged}"/>
            </p:inputText>

            <p:outputLabel value="City/State"/>
            <c:choose>
                <c:when test="${RecyclerAdmin.editItem.company.primaryAddressId.city != null and RecyclerAdmin.editItem.company.primaryAddressId.city.length() > 0}">
                <h:outputText id="citystate" value="#{RecyclerAdmin.editItem.company.primaryAddressId.city}, #{RecyclerAdmin.editItem.company.primaryAddressId.state}"/>
                </c:when>
                <c:otherwise>
                    <p:spacer id="citystate"/>
                </c:otherwise>
            </c:choose>

            <f:facet name="footer">
                <p:commandButton id="updatebutton" action="#{RecyclerAdmin.update()}" value="Save" ajax="false"/>
                <p:commandButton id="cancelbutton" action="#{RecyclerAdmin.cancel}" value="Cancel" ajax="false" immediate="true"/>
            </f:facet>

        </p:panelGrid>
    </p:outputPanel>
</h:form>

If I make a change to the "Recycler Name" text field, and then immediately click on the save button, the button click highlighting activates, and remains active, but the form does not submit until the button is clicked a second time. If I click somewhere else before clicking on the save button, everything works, and if I remove the ajax async="true" from the recyclerName field, the form also will submit normally, but I need the ajax reference otherwise any changed values in the field are erased when the zipCode field is manipulated.
Any ideas?

A: try different event
try removing async=true
p:ajax event="keyup"

http://www.primefaces.org/showcase/ui/ajax/event.xhtml

A: The problem was caused by the outputPanel autoUpdate="true" tag. i have added specific update field references to the individual ajax tags and the problem is now gone.


text:
Q: How to Print Unicode Emojis from Dictionary's Value New to Python, been wracking my brain on this all day.
I am working with emojis' unicode values
Printing the unicode values works as expected:
print("\U0001f600")

Yields
>>>

However, my use-case is a bit more complicated. I've imported and formatted a large set of emojis using panda and dataframes. Through a probably more-complecated-than-need-be sequence of .tolist() and zipping, I've landed on what I thought was the dictionary format that I needed.
Example .tolist() with a small dataset:
emoji_list = ['#⃣', '*⃣', '0⃣', '1⃣']

grouped_code_list = [['00000023', '0000FE0F', '000020E3'], ['0000002A', '0000FE0F', '000020E3'], ['00000030', '0000FE0F', '000020E3'], ['00000031', '0000FE0F', '000020E3']]

short_name_list = ['keycap: #', 'keycap: *', 'keycap: 0', 'keycap: 1',]

keyword_list = ['keycap', 'keycap', 'keycap', 'keycap']

I formatted the above four lists into my target dictionary:
# list into a list of lists
def extractDigits(list):
    keyword_list_list =[]
    for keyword in list:
        sub = keyword.split(', ')
        keyword_list_list.append(sub)

    return (keyword_list_list)

# implement extractDigits(list)
listed_keyword_list = extractDigits(keyword_list)

description_list = list(zip(short_name_list, listed_keyword_list))

emoji_code_list = list(zip(grouped_code_list, description_list))

emojiDictionary = dict(zip(emoji_list, emoji_code_list))

The above code gives me a dictionary comprised of the following key/value pairs:
Key: an emoji from emoji_list as a key
Value: a tuple of 1. the unicode value/s (from grouped_code_list) that represent that emoji and 2. a second tuple containing the emoji CLDR Short Name and a list of associated keywords (from description_list)
Printing that dictionary looks like this:
print(emojiDictionary)
>>> {'#⃣': (['00000023', '0000FE0F', '000020E3'], ('keycap: #', ['keycap'])), '*⃣': (['0000002A', '0000FE0F', '000020E3'], ('keycap: *', ['keycap'])), '0⃣': (['00000030', '0000FE0F', '000020E3'], ('keycap: 0', ['keycap'])), '1⃣': (['00000031', '0000FE0F', '000020E3'], ('keycap: 1', ['keycap']))}

Printing it to look a bit more nice looks like this:
for key in emojiDictionary:
    print("")
    print ("key: " + key)
    for values in emojiDictionary[key]:
        print ("value: " + str(values))

>>> key: #⃣
>>> value: ['00000023', '0000FE0F', '000020E3']
>>> value: ('keycap: #', ['keycap'])

>>> key: *⃣
>>> value: ['0000002A', '0000FE0F', '000020E3']
>>> value: ('keycap: *', ['keycap'])

>>> key: 0⃣
>>> value: ['00000030', '0000FE0F', '000020E3']
>>> value: ('keycap: 0', ['keycap'])

>>> key: 1⃣
>>> value: ['00000031', '0000FE0F', '000020E3']
>>> value: ('keycap: 1', ['keycap'])

The Problem
My goal is to be able to print the unicode values from the dictionary, joined if there are more than one, and with the added "\U" to print the emoji itself.
Here is the code to do almost all of that:
print_first_emoji = str(r'\U' + r'\U'.join(emojiDictionary["#⃣"][0]))

yields
>>> \U00000023\U0000FE0F\U000020E3

By comparison:
print("\U00000023\U0000FE0F\U000020E3")

yields
>>> #⃣

I've tried quite a few different things, mostly involving different ways of escaping/not escaping out the backslash.
For example, If I add in the "\U" to the source dataframe before .tolist(), the resulting list adds a "\" to escape the "\" out. So, my grouped_code_list would look like this:
grouped_code_list = [['\\U00000023', '\\U0000FE0F', '\\U000020E3'], ['\\U0000002A', '\\U0000FE0F', '\\U000020E3'], ['\\U00000030', '\\U0000FE0F', '\\U000020E3'], ['\\U00000031', '\\U0000FE0F', '\\U000020E3']]

I've considered printing with the CLDR short name, but the point in using the unicode is that I can typically print emojis' that would throw this error:
"SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-19: unknown Unicode character name"
I prefer to have the option of building certain emojis with multiple unicode values when necessary, rather than throwing out hundreds of emojis because the CLDR short name isn't recognized.
Does anyone have a solution, one way or another? I am I must missing something with the way these print?

A: str(r'\U' + r'\U'.join(emojiDictionary["#⃣"][0])) - almost there, but you don't need str (it already is a string), you need ast.literal_eval:
from ast import literal_eval
print(literal_eval(r'"\U' + r'\U'.join(emojiDictionary["#⃣"][0])+'"'))

The main question, however, is why? You already have the emoji as the key, why not just print it? What is this whole emojiDictionary for?

A: It looks like the values are a list of 32-bit numbers represented in hex format.
This might help you out in understanding unicode.
>>> a = ['00000023', '0000FE0F', '000020E3'] # list of values
>>> b = [int(i, 16) for i in a] # convert them to integers, base 16 since they were hex strings
>>> b
[35, 65039, 8419]
>>> c = [chr(i) for i in b] # get the characters for them
>>> c
['#', '', '⃣']
>>> print(''.join(c)) # join those characters
#⃣
>>> print(''.join(chr(int(i, 16)) for i in a)) #concise
#⃣
>>>


text:
Q: MQTT broker publisher-side or subscriber-side? I'm trying to implement a communication between two entities (we will say a controller and a device). The controller is a Windows application running on Windows 10 and the device is an embedded system. I would like to use MQTT protocol to transmit messages between them. The problem is the location of the broker. Should I implement the broker in the embedded system considering that it could be have more devices connected to the controller in the future, or should I use an existing broker application as proposed by Mosquitto ?
Thank you in advance,
Best regards


text:
Q: CSS Animation in React JS
In React JS , If i press that arrow button it should rotate 90deg and the arrow should face down if i again click it, the arrow should come back to normal position and vice-versa. please help me in solving this question. Thanks in advance!


text:
Q: Is it possible to make a page's publishing schedule mandatory? As opposed to a page just being published as soon as it's approved - I need to make the schedule (the setting of the start and expiry date) of the publishing mandatory. Can it be done?

A: If you're using SharePoint 2010 you can use List validation:

*

*Make sure your Page layouts include "Scheduling Start Date"

*Go to the Pages library

*Select List settings in the Library tab of the Ribbon

*Select Validation Settings

*Enter a formular like =[Scheduling Start Date]>TODAY()

*Enter an appropriate user message like "Page must be scheduled into the future"

As this probably needs to be done on multiple sites it could be a good idea to put it into a Feature which is included in/stapled onto the Site definition

A: You need to enable versioning in the Pages Document library . More info on this Link


text:
Q: SQL for Joining tables after concatination I have two tables, Table A and Table B.
Table A
Col1
----------
one.1.1
two.2.2
three.2.2
one.1
one.3

Table B
| Col1   | Col2 | Col3 |
+----------------------+
| one    | 1    | 1    |
| two    | 2    | 2    |
| three  | 2    | 1    |
| three  | 2    | 2    |

I wanted a left join in which it displays the values which are present in table A but not in table B.
I need to concatenate the Table B columns it can be both in formats "Col1.Col2" or "Col1.Col2.Col3"
Here's my query:
SELECT Col1
FROM TableA AS A
    LEFT JOIN TableB AS B ON A.Col1 = B.Col1+'.'+B.Col2+'.'+B.Col3
WHERE A.Col1 IS NOT NULL
     AND B.Col1+'.'+B.Col2+'.'+B.Col3 IS NULL

A: If you use left joined  table's column in where condition this work as an inner join  .. keep the condition in on clause
In your case is you need  the rows that don't match just use them
SELECT Col1 FROM TableA AS A
LEFT JOIN TableB as B ON A.Col1 = B.Col1+'.'+B.Col2+'.'+B.Col3
WHERE B.Col1+'.'+B.Col2+'.'+B.Col3 IS NULL

A: This MySQL query (SQLFiddle) will do what you want. Note that in MySQL you use CONCAT or CONCAT_WS to join strings. Also note you only need to check if B.col1 is NULL.
SELECT A.Col1
FROM TableA A
LEFT JOIN TableB B
ON A.Col1 = CONCAT_WS('.', B.Col1, B.Col2, B.Col3) OR
   A.Col1 = CONCAT_WS('.', B.Col1, B.Col2)
WHERE B.Col1 IS NULL

Output:
Col1
one.3


text:
Q: Is that possible to embed a Blob URL image in markdown? I want to embed a Blob URL image in my Github README.md file. When I tried ![image](blob:https://{...}) it failed. Is that possible to embed this format in markdown file?

A: Unfortunately github doesnt allow either blob or data uri's as image source.
source : https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#images


text:
Q: Can't find interface declaration for my IOS view controller I'm getting this error: "Cannot find interface declaration for 'BaseViewController', superclass of 'ViewController'. Here's the situation:
AppDelegate:

*

*Subclass of NSObject

*In the header file:
#include UIApplicationDelegate
BaseViewController

*

*Subclass of UIViewController

*In the header file:
#import "AppDelegate.h"
ViewController

*

*Subclass of BaseViewController
#import "BaseViewController.h"
The error doesn't make sense, as BaseViewController is imported in ViewController's header file. What is the problem here?

A: Cannot find interface declaration for 'BaseViewController'
That error means that the compiler can't find the line that looks like this:
@interface BaseViewController : UIViewController
But I think it CAN find the BaseViewController.h (Or it would complain about that specifically)
I'd check that the spelling is the same including upper/lowercase?
Other than that, it should work as you'd expect.

A: Also check for infinite loops in your import statements

A: Try adding
#import <UIKit/UIKit.h>


text:
Q: Add new point to bullet points I have question. I want to save path to the file from disk to the

 under

.
I want to choose for example 2 files from <import> and get

1path

2path

 and after that for example i want add 2 next files and show them in new

 to get paths to those 4 files. Is there any possibility to do that?

A: <initiating bad question translator>

*

*You have an <input type="file" multiple /> element

*You also have a

*You want it so that when a file or files are selected, they appear as items in the list.

<Computing answer>
Bind an event listener for the change event of your file input. Read the files property of the input element. This will be an array of files. You should then be able to get the filenames. For each filename, create a new
 element, put the filename in it, and append to your list.
Give this algorithm a try, and come back with some code if you have further problems :)


text:
Q: How to sort part of the table? I have a table with column "ActionDate" that has 2 types of dates:

*

*some different real dates and

*constant values '1980-01-01'

I need to sort data in such a way that real dates should come first in ascending order and constant values should come after.
The data sample:
1) The current state:
ActionDate

2014-01-03
2014-01-01
2014-01-02
1980-01-01
2014-01-04
2014-01-05
1980-01-01

2) The desired state:
ActionDate

2014-01-01
2014-01-02
2014-01-03
2014-01-04
2014-01-05
1980-01-01
1980-01-01

A: Use a CASE statement to create an order
SELECT ActionDate
FROM [Your_Table]
ORDER BY CASE WHEN ActionDate = '01-01-1980' THEN 1 ELSE 0 END, ActionDate

The CASE statement checks the date, when it is your reference date it assigns the value 1. When used in the OREDER BY it means rows marked 0 will be before those marked 1.
The second part of the ORDER BY uses the natural date ordering to sort them from oldest to newest.
SQL Fiddle which includes the sort order field to help you see what is happening.

A: SELECT * , 'OrderDate' = CASE ActionDate
WHEN '01-01-1980' THEN 2
ELSE 1
END
FROM YourTable
ORDER BY OrderDate, data

In my solution, I created a column OrderDate which has values 1 or 2 , 1 for all the real datas and 2 for  '01-01-1980' then you can sort them after that column and after the data column.

A: Something like this would probably do it:
SELECT ActionDate
FROM dbo.MyTable
WHERE ActionDate <> '01/01/1980'
ORDER BY ActionDate

UNION ALL

SELECT ActionDate
FROM dbo.MyTable
WHERE ActionDate = '01/01/1980'

A: Since 1980-01-01 is the timestamp start value, I suppose that your date is generated automatically to store the 'today date' when the action occur, in other words, there is no date lower than 1980-01-01 and in this case, a simple order by can do the task (and it's much more faster)
SELECT ActionDate
FROM [Your_Table]
ORDER BY ActionDate DESC


text:
Q: Finding if a word ends with a certain suffix in python I've trying to make it work without if statement with python in which it does work most of time until it reaches a word like 'celebration'. I'm not understanding what's causing this to happen.
common_suffix = ['ly', 'ion', 'ed', 'able']
def ends_in_common_suffix(word):
    for suffix in common_suffix:
        last_word = word[-len(suffix)]
        return last_word < suffix


text:
Q: REST API versioning using AWS After going trough this link on API versioning, i am trying to adapt the version through the headers and deploy it of AWS, but it looks like AWS does not support any custom verndor specific MIME types(link here)
Any idea how to achieve the versioning in this scenario where you do not have control over the MIME type...or any insights on how to do API versioning when using AWS?

A: My suggestion for cloud based service is "v1.api.mysite.com". It provides good flexibility. More details and reasoning here - http://timanovsky.wordpress.com/2013/01/28/api-versioning-scheme-for-cloud-rest-services/


text:
Q: JQuery plugin for infinite up scrolling? I actually wanted to ask if a front-end plugin is really necessary for implementing infinite scroll?  and relatedly I wanted to ask if anyone knows if any of the JQuery based infinite scroll plugins support scrolling up to retrieve more content.  Would implementing infinite scrolling to load data when the user scrolls up, rather than down, just be a setting in some plugin, or the some specification of the horizontal point that the user has to scroll to, in order to load content?
Sorry if this seems obvious to everyone else, this is the first time that I would be implementing it.


text:
Q: Process finished with exit code -1073741515 (0xC0000135) while using SDL2 in CLion I am trying to set up SDL2, but it returns with Process finished with exit code -1073741515 (0xC0000135). Any idea? I can only imagine there is some mistake in my CMakeLists.txt, but the cmake compiles and the project builds properly.
Here is a simple code using SDL that I tested:
#include <SDL2/SDL.h>

int main()
{
    // retutns zero on success else non-zero
    SDL_Window* win = SDL_CreateWindow("GAME",
                                       SDL_WINDOWPOS_CENTERED,
                                       SDL_WINDOWPOS_CENTERED,
                                       1000, 1000, 0);

    return 0;
}

And here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.15)
project(SDL_project)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIR})

add_executable(SDL_project main.cpp)

target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARY} -lmingw32 -mwindows)
add_definitions(-DSDL_MAIN_HANDLED)


text:
Q: Unwanted lines appearing in html5 canvas using tiles I'm drawing a map on a canvas using squares 40px * 40px.
All is well until I, by offsetting the canvas (using transform), scroll the map. Then, out of nowhere, lines apear between the tiles. See images below.
Why?

A: This looks like floating-point positioning (e.g. you've scrolled to 100.5, 100.5) combined with bilinear filtering most browsers use to display images on the 2D canvas.
Basically, if you drawImage() an image between pixels, every pixel is smoothed over two pixels, which means the edges draw at 50% alpha over the background.  This breaks tiling, because the next tile's edge is the same, and draws at 50% alpha over the other tile's 50% alpha, which adds up to 75% alpha.  This will appear lighter or darker (depending on the background color) than the rest of the tile.  So you get "seams" along the edges of the tiles.
To fix: Math.round() your image co-ordinates, as well as any calls to translate() (since translating by half a pixel has the same effect).  This guarantees everything is drawn to a pixel-aligned grid and never seams.


text:
Q: How to extract log details using grok expression Below is our log entry and we want extractct below highlighted values using
Grok expression -http://grokdebug.herokuapp.com/discover

sys tmp usr var Purging cache - END (PID: 4477, QN: 51/51, ET:
  0) anaconda-post.log bin dev etc home lib lib64 lost+found media mnt opt

Required help to get above values ing Grok expression

A: This works for me:
QN: %{NUMBER:QN1}/%{NUMBER:QN2}, ET: %{NUMBER:ET}

Results in the following output:
{
  "QN1": [
    [
      "51"
    ]
  ],
  "BASE10NUM": [
    [
      "51",
      "51",
      "0"
    ]
  ],
  "QN2": [
    [
      "51"
    ]
  ],
  "ET": [
    [
      "0"
    ]
  ]
}


text:
Q: Delete If Present at Destination, Copy To Destination If Error Move to Next I have VBScript that I wrote a long while back to identify PDF based on the file name. It then appended data to the file name and moved it to the proper directory. I did it as a Select Case in order for it to loop for many file names. I am now attempting to modify the script to check if the file with the new name is already at the destination directory, and if so, delete the old file, and copy the new one (also if the file is open and can't be overwritten, ignore and move to the next). I've been searching on many forums, and have been able to find pieces of what I am attempting, but have been unable to successfully integrate the processes into my script. Here is what I have for my select case, this section is what gets repeated with the "VariableAddedtoFileName" changed.
Select Case Pname
    Case "FileName"
        sDestinationFolder = "\\Server\FileDir\"
        sDestinationName = "VariableAddedtoFileName"
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        sSourceFile = objStartFolder & "\" & objFile.Name
        sDestinationFile = sDestinationFolder & "\" & Pname & " " & _
            sDestinationName & Right(objFile.Name, 4)

        If oFSO.FileExists(sDestinationFile) Then
            Set oFSO = Nothing
        Else
            oFSO.MoveFile sSourceFile, sDestinationFile
            Set oFSO = Nothing
        End If
    Case "StatementScriptTest"
    Case Else
End Select

So if I change theSet oFSO line in the If oFSO.FileExists group to oFSO.DeleteFile sDestinationFile It deletes the file, but won't copy the new one. If Rerun, it then copies the file, since it is no longer there. I have tried multiple combinations of attempting to manipulate the if statements and then with no luck. I also attempted to delete the file prior to the if section with no avail. Any assistance would be greatly appreciated.
If the full script is needed I can provide, I only listed this section as it is the part that gets rerun numerous times. Also I am aware that there are multiple posts similar to this, but I want to figure out how to update my code to work.
Update: I have fixed the overwriting by using CopyFile:
 If oFSO.FileExists(sDestinationFile) Then
    oFSO.CopyFile sSourceFile, sDestinationFile, True
Else
    oFSO.CopyFile sSourceFile, sDestinationFile, True
    Set oFSO = Nothing
End If

But I am still getting errors if the file is open when the attempt to overwrite is made.

A: First, you won't need the IF statement if you will have the same code in each branch. Just use the oFSO.CopyFile sSourceFile, sDestinationFile, True and it will do the work for you.
Second, in order to catch the error, you will have to use On Error Resume Next declaration before the copy command and check if some error triggered:
On Error Resume Next ' this tells VB to not throw errors and to populate the Err object when an error occurs

oFSO.CopyFile sSourceFile, sDestinationFile, True

IF Err.Number <> 0 Then
    ' do something when error occurs
    ' ...

    Err.Clear ' clears the error so it will not trigger this on the loop if no more errors occur
End IF

' When you want to stop ignoring the errors
On Error GoTo 0


text:
Q: Ionic cordova build android ERROR Quiero hacer un build de mi app Ionic en mi dispositivo Android, y en consola sale este error:

En Android Studio, tengo instalados los siguientes SDK:

Tengo instalado los build-tools de Android, de hecho tengo instalado, según lo que dice Android Studio: "Android SDK Build-Tools 30-rc2", y también tengo instalado el "Android SDK Platform-Tools".
Mis variables de entorno, para mi usuario son:
-ANDROID_HOME: C:\Users\Fabio\AppData\Local\Android\Sdk
-ANDROID_SDK_ROOT: C:\Users\Fabio\AppData\Local\Android\Sdk
-CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL: https://services.gradle.org/distributions/gradle-4.1-all.zip
-GRADLE_USER_HOME: C:\Users\Fabio\.gradle
-JAVA_HOME: C:\Program Files\Java\jdk1.8.0_241

En la variable PATH incluí todas estas variables:

En el archivo package.jsonde mi proyecto tengo instalados los siguientes paquetes, y que tienen que ver con toda esta posibilidad de utilizar los dispositivos Android para ejecutar la aplicación, y manejar cosas como el login con Facebook, con Google+, usar Google Maps, etc.:
"@ionic-native/core": "^4.20.0",
"@ionic-native/facebook": "^5.22.0",
"@ionic-native/google-maps": "^4.21.0",
"@ionic-native/google-plus": "^5.22.0",
"@ionic-native/splash-screen": "4.20.0",
"@ionic-native/status-bar": "4.20.0",
    "cordova-android": "^8.1.0",
    "cordova-plugin-facebook4": "^6.4.0",
    "cordova-plugin-file": "^6.0.2",
    "cordova-plugin-googlemaps": "^2.6.2",
    "cordova-plugin-googleplus": "^8.4.0",
    "ionic": "^3.20.0",
    "ionic-angular": "3.9.9",
    "ionic-native": "^2.9.0",
    "rxjs": "^6.5.4",
    "rxjs-compat": "^6.5.4",

Probé las siguientes soluciones que busqué en Internet:

*

*Borrar la carpeta node_modules y hacer npm install.

*Corregir las variables de entorno correspondientes y ejecutar el
comando ionic cordova build android.

*Actualizar el paquete ionic-native a la última versión (o a una versión específica, como
está descripto en la lista de dependencias    de arriba.

*Ejecutar el comando ionic cordova platform rm android, y luego ionic cordova platform add android
Ejecuté el comando ionic requirements -l, y obtuve el siguiente resultado:

Debido a lo de arriba, probé las soluciones mencionadas arriba, incluso borrar Android Studio, e instalar de nuevo todo (el build-tools y el platform-tools, y los SDK), y no hubo caso.
No sé qué es lo que me falta instalar o qué es que tengo mal.

A: el error de No installed build tools found se debe al a version "Android SDK Build-Tools 30-rc2"
Esa versión no es estable, en Android Studio ve hacia Tools, SDK Manager y selecciona la pestaña de SDK TOOLS, ahi desmarca la casilla "Hide obsolte Packages" e istala el Android SDK Tools (obsolete).
Luego de ahí selecciona la casilla que dice Package details y despliega el SDK Build-tools 30-rc2 elimina esa versión e instala cualquiera que no sea rc.
Por ese lado estarías bien.


text:
Q: Where do I instantiate my Objects in CRUD n-Tiered WinForm App? Say I have a WinForm CRUD(like) application.  I want to follow best practices on this so I try and make it follow OOP and a n-Tiered design.
Unfortunately I am familar with the words but not the practice of them.  So lets go with the following example:  My CaseNote program.  I have a tabbed application where you go to the search tab to find a member and then one of the options is to go to the CaseNote tab to create a new case note, look at existing CaseNotes, or create a follow up CaseNote to a Parent Note.  All of this is for the member you selected from the search tab.
So if I am creating objects and passing them around to be used by different forms where should I be instantiating them?  I had thought I would have 3 layers; UI, Object, DAL.  Where I fall flat is where I instance tho objects.  I can't instance them in the object layer, can I?  Also, if I instance them on the form how do I pass them from form to form in a quite large app?
CaseNotes Screen Shot

A: If you want to look at some more words around this problem you want to look at MVP and MVC. (These stand for Model View Controller and Model View Presenter). Some people will shoot me down for saying this but they are quite similar in concept.
The aim of MVP and MVC is to allow you to design your application logic without even having to think about your application apperance. It also allows you to define your user interactions without implementing an actual GUI. Esentially your model is your application logic, your data, your classes which actually do stuff like talk to your database. Your presenter or controller is what interacts with your model and what controls your user interface and reacts to user operations on the interface. Finally your View is your winforms design or your web page.
I'm sure you will be able to find plenty of material on the web about this but to give you some concrete help with this problem should serve to inform and illustrate your reading.
The first thing you need to do is start creating your objects that represent your data. So you will have a CaseNote object which is contains the casenote data. You will have a case note data container of some sort such as a case note database. You can define the logical operations and properties of these as if they where real items.
Then you would move on to define your presenter or controller which will define the operations that you want to support from the GUI. At the same time you should define an Interface that will define for the presenter/controller what operations is can perform on the GUI. So for instance your presenter may expose a method called SearchForCaseNote which takes a string parameter. Your view Interface will expose a method called DisplayCaseNote. When a user clicks on the search button the view will pass through the command to the presenter which will then call the model to get the data. The presenter may format the data at this point, i.e. convert DateTime object to a string and then pass the data back to the view through the interface define method called DisplayCaseNote.
You don't have to use the View interface, you could call into the view directly, but having the interface means you can have many different view implementations.
One last thing i need to mention is where you create these different parts of your application. My view is everything thing should fall out from the presenter/controller. So when you application starts it creates the presenter/controller object which then create and displays your view passing itself as a variable to the view. The presenter/controller can then either create the initial models by loading them from disk or ideally discover them through a dependency injection container like unity. In fact using unity to discover the view implementation is probably a better idea again as it gives you true seperation between view and presenter/controller. When you come to move to another view, (i.e. open another window), your presenter/controller should expose a method such as DisplayDetailPage which the view calls when a button is clicked. This would create the presenter/controller for the next view which would in turn create the view and get a reference to the model.
Hope this helps.

A: I think you should use the RocketFramework


text:
Q: What to pass when asked for "missing required parameters for [Route:..." I am trying to apply a ::post function to a route with the where filter. It works without the where filter. What's missing?
This works:
Route::post('/actors/Chelsea_Handler', [
    'uses' => 'StarsController@infoupdate',
    'as' => 'infoupdate',
]);

This does NOT work but why?
Route::post('/{type}/Chelsea_Handler', [
    'uses' => 'StarsController@infoupdate',
    'as' => 'infoupdate',
])->where(['type' => 'actors']);

The function in the controller then updates some database table.
public function infoupdate(Request $request, $type){

    if(Auth::guest()){
        return redirect('login');
    }
    elseif(Auth::user()->id == 1){

        DB::table('stars')->where('id', $request->id)->update(['info' => 'test']);

        return back();

    }else{
        return redirect('login');
    }
  }

A: Have you already tried this?
Route::post('/{type}/Chelsea_Handler', [
    'uses' => 'StarsController@infoupdate',
    'as' => 'infoupdate',
])->where('type', 'actors');

A: You could possibly have another similar route.
App is trying to find /{type} route.
Route::post('/{type}/Chelsea_Handler', [
    'uses' => 'StarsController@infoupdate',
    'as' => 'infoupdate',
])->where(['type' => 'actors']);

But you can have something like this in your routes file:
Route::post('/{anythingElse}/something', ['uses' => 'SomeController@foo']);

I would not recommend first segment to have curly brackets, app will use first route with this pattern.

A: the where in a route is meant to be a constraint in the url, and by no means as a query, such as where(['id' => '[0-9]+', 'name' => '[a-z]+']);
if you need to query you can use it in the controller like below
$actors = Model::where('type','actors')->get();


text:
Q: How to insert record with many belongsTo relations in Laravel Eloquent I am trying to insert record in Eloquent way.
It is clear in basic cases. For example if I have a Blog with Posts and each post belongs to a User I can do this:
$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);

But how should I do this if my Post belongs to User, Category and Group at the same time?
My first idea was to do it this way:
$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
$group->posts()->associate($post);
$cat->posts()->associate($post);

But it doesn't work, because group id and category id are null when I save it to the DB and it is not allowed.
What I am doing now is:
$post = new Post;
$post->content = 'Post content';
$post->group = $group->id;
$post->category = $cat->id;
$user->posts()->save($post);

But I don't think it is the right way.
Could someone point me in the right direction?

A: You're using associate the wrong way around. You have to call it on the belongsTo relation side not the hasMany.
Try this:
$post = new Post;
$post->content = 'Post content';
$post->category()->associate($cat);
$post->group()->associate($group);
$user->posts()->save($post);


text:
Q: Swift: NSMutableAttributedString foregroundColor not setting properly I need the first character of my UILabel to be a different color than the rest of the label. I'm using the following code:
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: cell.label.text!)
        attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 1))
        cell.label.attributedText = attributedString

This is just causing the first character to vanish. A print statement for attributedString looks like this (apparently correct):
■{NSForegroundColor = "UIExtendedSRGBColorSpace 1 0 0 1";} restOfText{}

What am I doing wrong?

A: The problem is the NSRange value with length 1. For Swift strings use the dedicated NSRange initializer taking the String.Index range and the target string
let string = cell.label.text!
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: string)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(...string.startIndex, in: string ))

A: The code as written works no problem. I accidentally overwrote cell.label.text later. Whoops


text:
Q: How does Athena match data to the correct fields when creating a table from Amazon S3? I'm still getting to grips with Athena, so apologies if this question doesn't make sense. I'm trying to create a table in Athena from a csv file I have uploaded to my Amazon S3 bucket. During the table creation process on Athena, I need to define field names and datatypes. How are these fields matched with those stored in the Amazon S3 bucket? Is it just the order in which they appear in the csv?

A: Yes indeed depending on the order.
https://docs.aws.amazon.com/athena/latest/ug/csv-serde.html

A: This depends on the data format and the serde used. For CSV data, columns are mapped by index. The same goes for the regex and grok serde, as well as ORC. JSON, Avro, and Parquet is instead mapped by name.
Grok, ORC and Parquet can be configured to be either index or name, but the above are the defaults.


text:
Q: Installed as a dual boot ubuntu 13.04 alongside win8 and no grub? i previously had windows 7 on my machine when i bought it i installed win8 now but i wanted to try out ubuntu so i installed alongside win8 but there was no grub screen to choose ubuntu.. if anyone knows of a way to fix this please let me know !! THANK YOU

A: Boot up a live cd that is the same version and bit as your Ubuntu OS. Use boot-repair to reinstall grub. Here is how first open up a terminal in put in this code.
Installing boot-repair
sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
than
sudo apt-get install -y boot-repair && (boot-repair &)

Opening boot-repair
sudo boot-repair

Using boot-repair

Then puss "Recommended repair" and before that, you need to make sure the default setting is right for your system, so just look over the Advanced options.
After you have done that reboot your computer and you will see grub again!

source :
https://help.ubuntu.com/community/Boot-Repair

A: You could download EasyBCD for Windows, and add Grub2 to the Windows bootloader (only works for Vista or newer visions of Windows). You may have to manually specify which partition Grub2 is located on.


text:
Q: Disallow identity search Azure DevOps We have an Azure DevOps environment(online dev.azure.com/aaaa). Here we have multiple projects. Each project has multiple users.
I would like to avoid users from project A being able to mention users from project B due to privacy.
Is this possible?

A: There is the concept of "project scoped users".

To limit the identity selection to just those users and groups added to a project, perform the following procedure for your organization and projects.

*

*Enable the Limit user visibility and collaboration to specific projects preview feature for the organization.

*Add the users to your project(s) as described in Add users to a project or team. Users added to a team are automatically added to the project and team group.

*Open Organizations Settings>Security>Permissions and choose Project-Scoped Users. Choose the Members tab. Add all users and groups that you want to scope to the project(s) you've added them to.


text:
Q: Grub menu doesn't appear I'm using windows 7 and I installed Ubuntu 12.04 along side with it by creating a new 60 GB partition. It installed perfectly and then I restart the PC. I can't see the grub menu that let me to choose the operating systems. My monitor shows

unsupported input

Please help me.

A: This post is a bit old, but I was having a similar issue, and it seems the OP never got an answer which helped.  Like I said, my situation was similar, but my monitor reported that it was not optimal, and displayed nothing.
The menu was there, I know because I could arrow down and press Enter and the boot up would be different (i.e. 4 down was Windows on my PC).  I did a little research and ended up updating /boot/grub/grub.cf setting the line as follows:
FROM (was):
set gfxmode=auto

TO:
set gfxmode=1024x768

Saved and rebooted. The menu now shows. Hope this helps.
Note: You have to sudo to edit the file.

A: You can select operating systems before you get to the grub menu, or at least you should be able to.  On my wubi install I have to select Ubuntu at boot before grub appears.  Just select windows 7 before you get to grub.

A: Try this:

*

*Boot into Ubuntu.

*Go to the Terminal by searching "Terminal" in the dash.

*Type sudo gedit /etc/default/grub in the terminal and type your password if prompted.

*Locate the line GRUB_TIMEOUT=0.  Change the value from 0 to 10 then save the file and close it.  GRUB will now let you choose the Operating system for 10 seconds when you boot your computer.  You should see GRUB_TIMEOUT=10 instead of 0.

*Go back to the terminal window (you didn't close that, didn't you?) and type sudo update-grub in the terminal.  Type your password if prompted, then wait until the task had been processed.

*Reboot and test!