text:
Q: Adding rows for missing year by group in pandas I have a dataframe which looks like this
pd.DataFrame({'A': ['C1', 'C1', 'C1', 'C1', 'C2', 'C2', 'C3', 'C3'],
   ...:                    'date': [date(2019, 12, 31), date(2018, 12, 31), date(2017, 12, 31), date(2016, 12, 31), date(2017, 12, 31), date(2016, 12, 31), date(2018, 12, 31), date(2016, 12, 31)],
   ...:                    'value': [9, 9, 8, 4, 8, 3, 6, 4]})
Out[13]:
    A        date  value
0  C1  2019-12-31      9
1  C1  2018-12-31      9
2  C1  2017-12-31      8
3  C1  2016-12-31      4
4  C2  2017-12-31      8
5  C2  2016-12-31      3
6  C3  2018-12-31      6
7  C3  2016-12-31      4

first_year = date(2016, 12, 31)
last_year = date(2019, 12, 31)

For each group I need to add the missing years for each group in column 'A' and take the 'value' of the previous year. I would like to say via input variable what my first and last year should be. my resulting dataframe should look like this
     A        date  value
 0  C1  2019-12-31      9
 1  C1  2018-12-31      9
 2  C1  2017-12-31      8
 3  C1  2016-12-31      4
 4  C2  2019-12-31      8
 5  C2  2018-12-31      8
 6  C2  2017-12-31      8
 7  C2  2016-12-31      3
 8  C3  2019-12-31      6
 9  C3  2018-12-31      6
10  C3  2017-12-31      4
11  C3  2016-12-31      4

following logic applies (by group in column A)
C1 = all years between 2016 and 2019 available already
C2 = years 2018 and 2019 missing, need to be added and get value from last available year in 2017 value = 8
C3 = year 2017 missing, gets value from year 2016. and year 2019 missing, gets value from 2018

A: IIUC, you can it do it like this:
idx = pd.MultiIndex.from_product([df['A'].unique(),
                                  pd.date_range(first_year,
                                                last_year,
                                                freq='A')],
                                 names=['A','date'])

df.set_index(['A','date'])\
  .reindex(idx)\
  .groupby(level=0)\
  .ffill()\
  .sort_index(level=[0,1], ascending=[True, False])\
  .reset_index()

Output:
     A       date  value
0   C1 2019-12-31    9.0
1   C1 2018-12-31    9.0
2   C1 2017-12-31    8.0
3   C1 2016-12-31    4.0
4   C2 2019-12-31    8.0
5   C2 2018-12-31    8.0
6   C2 2017-12-31    8.0
7   C2 2016-12-31    3.0
8   C3 2019-12-31    6.0
9   C3 2018-12-31    6.0
10  C3 2017-12-31    4.0
11  C3 2016-12-31    4.0

Create a product of your 'A' and date range, using pd.MultiIndex.from_product.  Using that index, set the index of or your dataframe and reindex with the created index from the product.  Lastly, ffill forward fill and resort the dataframe then reset_index.

A: Another possible idea using groupby + groupby.apply along with reindex + ffill:
i = pd.date_range(first_year, last_year, freq='Y', name='date')
df = df.set_index('date').groupby('A',group_keys=False)\
       .apply(lambda s: s.reindex(i).ffill()).reset_index()

Result:
         date   A  value
0  2016-12-31  C1    4.0
1  2017-12-31  C1    8.0
2  2018-12-31  C1    9.0
3  2019-12-31  C1    9.0
4  2016-12-31  C2    3.0
5  2017-12-31  C2    8.0
6  2018-12-31  C2    8.0
7  2019-12-31  C2    8.0
8  2016-12-31  C3    4.0
9  2017-12-31  C3    4.0
10 2018-12-31  C3    6.0
11 2019-12-31  C3    6.0


text:
Q: Can a Self Extracting Zip File read a registry entry? I'm trying to get my website to talk to a friend's program. Think ITunes - one main program with hundreds of thousands of little things installed into it. We don't want to have to create an InstallShield install program for each of those hundreds of thousands of little things.
We have the files grouped into the folder sub-structure.
We have a .REG file for what registry entry needs to be added to see the new folder group.
But is there a way to do a self extracting zip file that reads a registry entry so we know where they installed the original program to be able to dump the new files there as well? I want them to double-click the EXE and click Finish and for everything to work.
(I've been looking into INF and CAB files through IExpress.exe, but haven't found the answer. I remember Package for the Web didn't have an option to read a registry entry, but did let you modify the suggested install path.)
Thanks so much.
Best wishes,
Andrea

A: Have you tried Inno Setup toolchain? It's a bit better than a bare Self-Extracting ZIP file, it's a setup creation utility. I'm convinced it has got something to put some entry in the Registry, look also at the plugins.
Basically, a self-extracting executable that alters the registry, it's a setup program. So why don't you go for a proper one?
Website: http://www.jrsoftware.org/isinfo.php

A:
But is there a way to do a self extracting zip file that reads a registry entry so we know where they installed the original program to be able to dump the new files there as well? I want them to double-click the EXE and click Finish and for everything to work

Well, yes and no. There are self-extractors that can run a program after extracting all files. DotNetZip, for example, can produce an SFX which can do this.
Just an aside: a normal SFX is just a zip file, with a "stub" executable merged with it. The stub exe can do anything it wants to do, but the most basic thing it does is extract the files in the zip. When you use DotNetZip to produce an SFX, it embeds its particular stub into the zip. That stub knows how to extract files, and also knows how to invoke a program after extracting. You can also produce your own stub that can do other more exotic things.
So you could use an SFX for your purpose. When run, it would extract, then invoke it's extra program. The program could look in the registry, then move or relocate the extracted files to the appropriate place. Then terminate.
For a different twist, the SFX might have just two files: the program-to-run (the one that reads the registry, and another embedded zip. Then when the SFX runs it generates 2 files. Then it invokes the program-to-run, which reads the registry, then unpacks the contained zip and puts the files into the desired place.
Ok, so you could do it.
Should you?
mmm, maybe.  This really is an installer, so, you should decide whether you want to use a zip as an installer.  Don't forget, if you use an SFX as an installer, there's no good way to uninstall.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reverse current frying a boost converter? AFAIK, most boost converters incorporate a diode or some mechanism for ensuring that current flows from the battery to the output. For instance, TPS61030's datasheet says that

This device however uses a special circuit which takes the cathode of the backgate diode of the high-side PMOS and disconnects it from the source when the regulator is not enabled (EN = low).

MPC6140's datasheet says that

With the EN pin pulled low, the output of the MCP1640B is isolated or disconnected from the input by turning off the integrated P-Channel switch and removing the switch bulk diode connection. This removes the DC path that is typical in boost con- verters, which allows the output to be disconnected from the input.

Does that mean if current tries to flow from output, these chips (at least these two?) won't be damaged at all? That is, for instance, there are two possible power sources connected in parallel, boosted to 5V. If only one is hooked up, would the current flowing into the other booster in reverse fry it?
What if both could be hooked up?


text:
Q: Password decryption with known salt and dictionary We are migrating a company we acquired a lot of kiosk hardware assets from that are in the field. Since the company was suffering, we are stuck with some issues in migrating the locations fingerprints, usernames and passwords without any implementation docs. Luckily, most of the passwords used are numeric 4-6 PIN or a common used word. I'm stuck with trying to figure out what format the password is hashed in and hopefully can decipher it from there using a dictionary for the majority of the passwords. I have the following format:
"password": "ce62f0002776890507c4050a3b76c064d3d24328aea52a08633b726d352532dc",
"salt": "JUQLSPOYGFURMGSDRYWIWBIWP",

The password above is "password". Hopefully this helps in finding the format.

A: If it is a hash, looks like a hash, possibly HMAC-SHA256 from the length, you need to run a password cracking program. You should be able to recover well over 90% but most likely not all.
On my laptop I can run a 20 byte password through SHA-512 and compare in under 1us so with just a SHA-512 hash I can try 1,000,000 passwords a second.
You can make a list to check but there are already good lists, see below.
For more information see:
Password list at SecLists.
Infosec password-cracking-tools
Arstechnica How I became a password cracker.

A: You can implement the old hashing method in your new code. When the password matches (i.e. the one the partner sends) you can then store it in your new format (essentually accepting both). This saves you the need to crack the existing passwords.
For this to work you do need to know how the passwords are hashed and what formatis used, lucikly this seems to be fairly easy (Java sample):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write("password".getBytes(StandardCharsets.US_ASCII));
bos.write("JUQLSPOYGFURMGSDRYWIWBIWP".getBytes(StandardCharsets.US_ASCII));

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] out = md.digest(bos.toByteArray());

System.out.println("hex = " + new HexBinaryAdapter().marshal(out).toLowerCase());

Produces (i.e. concatenate password bytes and salt bytes, non-iteratively calculate SHA256 and convert to hex) the expected hash:
hex = ce62f0002776890507c4050a3b76c064d3d24328aea52a08633b726d352532dc


text:
Q: Angular $templateCache Does Not Work in Internet Explorer I am having an issue with Angular's $templateCache in ie10 specifically, but is also an issue in ie11. It works in Firefox, Chrome and Safari.
Here is my template definition, in templates.js:
angular.module('app').run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('/views/page.html',
    "
\n" +
    "
\n" +
    "    {{pageTitle}}\n"
    ...
  );
}]);

I include the templates.js at the top of the page in the , like:

And finally I consume the templates in my routes definition, here:
angular.module('app', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/', {
      redirectTo:'/page'
    })
    .when('/page', {
      controller: 'pageController',
      templateUrl:'/views/page.html'
    })
    .otherwise({
      redirectTo:'/'
    });
}]);

Again, it all works fine in Chrome, Firefox and Safari, but not IE10. The only other information I can think to provide is that the app is not at the root level, it is http://example.com/app. but the templates are indeed stored in http://example.com/views.
Any ideas?
EDIT: Here is a JSFiddle which actually works in IE, but I'm not sure if that's because of how JSFiddle handles the browser frame. If you copy and paste the code into an index.html, and run it on your server, it will not work in IE.
http://jsfiddle.net/v9sv7jdL/2/

A: In this case we actually had special logic in our app for IE. It adds a ?ts= to the end of our requests, which of course, does not exist in the templateCache.


text:
Q: Creating web service (not web service client) from WSDL file I have a requirement, according to which i have to create an Axis2 Web service based on a wsdl file. I already got the wsdl file. I have been using wsdl2java earlier to create web service client but i don't know how to create web service using the given wsdl file. Can somebody please help me in giving the correct command or options to be used.
Also, i need to publish it on WAS 6.1 and JBoss 5.1.0 GA, what all should be done for that.

A: I am able to get the answer. Updating here for other's reference.
Starting with WSDL, Creating and Deploying a Service
We start with a WSDL, however if you do not have a WSDL and need to create a WSDL from a java class, please use the Java2WSDL tool to create the WSDL. As you might already know, a WSDL description of a service provides a precise definition of that web service. Axis2 can process the WSDL and generate java code that does most of the work for you. At the server side, we call them Skeletons, and at the client side, Stubs.
This method of writing a Web service with Axis2 involves four steps:

*

*Generate the skeleton code.

*Add business logic.

*Create a *.aar archive (Axis Archive) for the Web service.

*Deploy the Web service.

Step1: Generate Skeleton Code
To generate the skeleton and required classes, you can use the WSDL2Java tool provided in Axis2. This tool is located in the bin directory of the distribution and can be executed using the provided scripts (.bat or .sh). The tool's parameter list can be found in the Axis2 Reference Document.
The parameters for the wsdl2java tool in our example are as follows. Please note that, for this example, we are using xmlbeans as the data binding framework, and the generated code will be placed in a "samples" directory.
wsdl2java.sh -uri ../samples/wsdl/Axis2SampleDocLit.wsdl -ss -sd -d xmlbeans
-o ../samples -p org.apache.axis2.userguide
This will generate the required classes in the "sample/src" directory, and the schema classes in the "samples/resources/schemaorg_apache_xmlbeans" directory. Note that these are not source files and should be available in the class path in order to compile the generated classes.
Step 2: Implement Business Logic
Now you should fill the business logic in the skeleton class. You can find the skeleton class -Axis2SampleDocLitServiceSkeleton.java- among the generated classes in the "samples/src/org/apache/axis2/userguide directory. Let's fill the echoString(..) method in the skeleton as shown below. Our sample WSDL-Axis2SampleDocLit.wsdl in "samples/wsdl" directory has three operations: echoString, echoStringArray, echoStruct. To see how the others will look when they are filled up, see Code Listing For Axis2SampleDocLitService Service
public org.apache.axis2.userguide.xsd.EchoStringReturnDocument
    echoString(org.apache.axis2.userguide.xsd.EchoStringParamDocument param4) throws Exception {
    //Use the factory to create the output document.
    org.apache.axis2.userguide.xsd.EchoStringReturnDocument retDoc =
           org.apache.axis2.userguide.xsd.EchoStringReturnDocument.Factory.newInstance();
    //send the string back.
    retDoc.setEchoStringReturn(param4.getEchoStringParam());
   return retDoc;

Step 3: Create Archive File
An Axis2 service must be bundled as a service archive. The next step is to package the classes in an .aar (axis2 archive) and deploy it in Axis2. There is an ant file generated with the code; it will generate the Axis2 service archive for you. However, if you do not want to use ant, you can create an archive with the following steps :
Compile the generated code.
Copy "resources/schemaorg_apache_xmlbeans" xmlbeans classes to your class folder.
Among the generated files, there will be a services.xml file, which is the deployment descriptor for Axis2 service.[learn more about it]. Copy the resources/service.xml to META-INF/services.xml
(To write your own service.xml file, see the sub section in Writing Web Services Using Axis2's Primary APIs )
Create the archive using content of the class folder. Change the directory to the class folder and run jar -cf service-name.aar to create the archive.
Step 4: Deploy Web Service
The service can be deployed by simply dropping the ".aar" file into the "services" directory in "/webapps/axis2/WEB-INF" of your servlet container. We recommend using Apache Tomcat as the servlet container. Please Note that the services directory is available only after axis2.war has been exploded by Tomcat. However, the easiest way to do it is to start Tomcat after axis2.war is copied to the webapps directory (if you have not already started it). Check the "Services" link on the Home page of Axis2 Web Application (http://localhost:8080/axis2) and see whether the Axis2SampleDocLitService is displayed under the deployed services.

We recommend using the exploded configuration to deploy Axis2 WAR in WebLogic and WebSphere application servers to support the hotupdate/hotdeployment features of Axis2. See Application Server Specific Configuration Guide for details.
Note: Axis2 provides an easy way to deploy Web Services using the "Upload Service" tool in the Axis2 Web Application's Administration module. (See the Web Administration Guide for more information)
See the following link for full article: http://axis.apache.org/axis2/java/core/docs/adv-userguide.html


text:
Q: Error while setting up an indexer on tsv data I have a data in tsv format & I want to index it using azure search. So I have set up my indexer accordingly, and provided /t as delimiter.
I get following error:
Import configuration failed, error creating Indexer: "Error with data source: Row '1' in document 'mapping/v1/subscriptions.tsv' is malformed. Reason: Line 1 cannot be parsed using the current Delimiters.  Please adjust your data source definition in order to proceed."
I wanted to check following
1) are tsv files supported by indexer? (I think yes)
2) How should one provide delimiter if so?


text:
Q: Delete comment from database php I am trying to delete comments from my comment system but the code I have is not working. I want to be able to delete each comment from my table including the parent comments. At the moment my code does not get the parameter of the comment from the delete button link.
function.php:
<?php
function getComments($row) {
    echo "
";
    echo "
" . $row['author'] . "
";
    echo "
" . $row['comment'] . "
";
    echo "
" . $row['created_at'] . "
";
    echo "Edit Song";
    echo " ";
    echo "Delete Song";
    $q = "SELECT * FROM threaded_comments WHERE parent_id = ".$row['id']."";
    $r = mysql_query($q);
    if(mysql_num_rows($r)>0)
        {
        echo "
";
        while($row = mysql_fetch_assoc($r)) {
            getComments($row);
        }
        echo "
";
        }
    echo "
";
}
?>

delete.php:
<?php
    include 'includes/config.php';

    $deleteid = $_GET['id'];

    mysql_query("DELETE FROM threaded_comments WHERE id='$deleteid'");

    echo "Song has been deleted!";
    header ('Location: index.php');
?>

I have added the index.php and post_comment page page. Also the delete function still doesn't work when I made the changes.
index.php:
<?php
include("config.php");
include("functions.php");
?>

<title>Multi-Lyric Collaboration System</title>

    MultiLyric Collaborator

<?php
$q = "SELECT * FROM threaded_comments WHERE parent_id = 0";
$r = mysql_query($q);
while($row = mysql_fetch_assoc($r)):
    getComments($row);
endwhile;
?>

    <form id="comment_form" action="post_comment.php" method='post'>
    Name:
    <input type="text" name="name" id='name'/>

    Enter Song:
    <textarea name="comment_body" id='comment_body'></textarea>
    <input type='hidden' name='parent_id' id='parent_id' value='0'/>

        <input type="submit" value="Add comment"/>

</form>

post_comment.php:
<?php
include("config.php");
$author = mysql_real_escape_string($_POST['name']);
$comment_body = mysql_real_escape_string($_POST['comment_body']);
$parent_id = mysql_real_escape_string($_POST['parent_id']);
$q = "INSERT INTO threaded_comments (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysql_query($q) or die(mysql_error());
if(mysql_affected_rows()==1) {
    header("location:index.php");
}
else {
    echo "Comment cannot be posted. Please try again.";
}
?>

A: From the "SELECT" statement in getComments(), it looks like what you need to do is:
mysql_query("DELETE FROM threaded_comments WHERE parent_id ='$deleteid'");

It is 'parent_id' not 'id'.


text:
Q: Material-UI FormControl InputLabel display problem
In the picture, you can see that my label is behind the outline but I don't know why it is. I didn't give any kind of style I just gave a minWidth that's it but still, it's one kind of broken I mean the label is behind the line. Here is the code:
import React, { Component } from "react";
import {
  Container, Grid, FormControl,
  InputLabel, Select, MenuItem
} from "@material-ui/core";
import { withStyles } from "@material-ui/core/styles";

const styles = (theme) => ({
  formControl: {
    minWidth: 180
  }
});

class Account extends Component {
  constructor() {
    super();
    this.state = {
      age: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (event) => this.setState({ age: event.target.value });

  render() {
    const { classes } = this.props;
    const { age } = this.state;
    return (
      <React.Fragment>
        <Container>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
              <FormControl
                className={classes.formControl}
                variant="outlined"
                size="small">
                <InputLabel>Age</InputLabel>
                <Select value={age} onChange={this.handleChange}>
                  <MenuItem value="">
                    None
                  </MenuItem>
                  <MenuItem value={10}>Ten</MenuItem>
                  <MenuItem value={20}>Twenty</MenuItem>
                  <MenuItem value={30}>Thirty</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        </Container>
      </React.Fragment>
    );
  }
}

export default withStyles(styles, { withTheme: true })(Account);

A: The "Select" did not have enough space. To proof the theory I have added a
 break to create some extra space. Now it displays the age above the Select Field. Please adjust the Margin Top.

A:
import React, { Component, createRef } from "react";
import { Container, Grid, FormControl,
         InputLabel, Select, MenuItem } from "@material-ui/core";
import { withStyles } from "@material-ui/core/styles";

const styles = (theme) => ({
  formControl: {
    minWidth: 180
  }
});

class Account extends Component {
  constructor() {
    super();
    this.state = {
      age: '',
      labelWidth: 0
    };
    this.handleChange = this.handleChange.bind(this);
    this.inputLabel = createRef();
  }

  handleChange = (event) => this.setState({ age: event.target.value });

  componentDidMount() {
    this.setState({ labelWidth: this.inputLabel.current.offsetWidth });
  }

  render() {
    const { classes } = this.props;
    const { age, labelWidth } = this.state;
    return (
      <React.Fragment>
        <Container>
          <Grid container spacing={2}>
            <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
              <FormControl
                className={classes.formControl}
                variant="outlined"
                size="small"
              >
                <InputLabel ref={this.inputLabel}>Age</InputLabel>
                <Select
                  value={age}
                  onChange={this.handleChange}
                  labelWidth={labelWidth}
                >
                  <MenuItem value="">
                    None
                  </MenuItem>
                  <MenuItem value={10}>Ten</MenuItem>
                  <MenuItem value={20}>Twenty</MenuItem>
                  <MenuItem value={30}>Thirty</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        </Container>
      </React.Fragment>
    );
  }
}

export default withStyles(styles, { withTheme: true })(Account);


text:
Q: How to save modified mesh at runtime? In my game, I modify mesh at runtime using a damage algorithm.
After that, I would like to save them.
I get all meshes with:
MeshFilter[] meshfilters = MyObject.GetComponentsInChildren<MeshFilter>();

then i modify single mesh.
How to save that in my original FBX file ?
Thanks

A: Unity's internal mesh type is not the same as an FBX, FBX is a file storage format, while Unity uses a different internal structure at runtime, for greater efficiency.
As far as I know there is no standard way to save out a runtime mesh as an FBX (this is a feature of 3D modelling software, not a game engine)
You can save your deformations somehow and re-apply them when you reload the model, when I did a similar thing (custom generated terrain meshes at runtime) I would generate a mesh at runtime, then save the data required to generate that mesh, then pass it into the same flow I used to generate the mesh in the first place.
It is possible to serialise meshdata in the unity editor as meshdata is actually a different format from FBX (Unity reads an FBX, then generates a mesh asset from the FBX's data, then associates that mesh with the FBX) You do this by playing with AssetDatabase.CreateAsset() https://docs.unity3d.com/ScriptReference/AssetDatabase.CreateAsset.html
But I don't think this is what you're intending to do.
If you want the full FBX suite of features (skinning, animation, use in other unity projects) and you want them at runtime, you don't really have any options that I know of. Short of implementing your own FBX serialisation library (not really a reasonable solution)


text:
Q: move_uploaded_file failure Can someone help me understand why this is returning false?
if ((move_uploaded_file($_FILES[$field]['tmp_name'], $path))) {

As in, potential causes. I have checked the variables are correct and I have checked permissions on the destination folder which is 777.
Cheers!
For those wanting to see var_dump ($_FILES);
array(1) { ["image"]=>  array(5) { ["name"]=>  string(14) "accountile.png"
["type"]=>  string(9) "image/png" ["tmp_name"]=>  string(14) "/tmp/php28IQhv"
["error"]=>  int(0) ["size"]=>  int(394) } }

A:
I have checked the variables

Do not check variables but check error messages.
It's the only thing you need.
Add these lines at the top of your code
ini_set('display_errors',1);
error_reporting(E_ALL);

and see what it says.
If move_uploaded_file failed, it will always raise an error with detailed explanation.
You won't believe it, but reading error messages is way more efficient way to find a problem than guesswork you tried before
I can't believe noone mentioned it already.

A: With move_uploaded_file you don't need 777 permissions.  What is the output of $path?  Have you verified that $path exists?  Have you verified that $field exists?
Either $field or $path don't exist, or open_basedir is in effect is my guess.
Is open_basedir restriction enabled?  That could prevent the destination of the uploaded file from being written to.  Look in your php.ini for open_basedir, if there's a path specified then it is enabled and you want to see if the destination path of your uploaded file is within this path.  If it is, that's why it's failing.
update
$path cannot be a URL, it must be a local path such as /home/user/public_html/

A: Don't use
$path = "http://www.barbadostravelbuddy.co.uk/demo/images/carhire
    /accountile10420103260403000000pm.png"

but
$path = "/home/sites/barbadostravelbuddy.co.uk/public_html/demo/images/carhire/
    accountile10420103260403000000pm.png"

It needs to be a path on the system, not an URL.

A: Did you edit your php.ini to make sure upload_tmp_dir points to a temporary directory?

A: Check:
enctype="multipart/form-data"

Inside the form itself, without it file upload won't work at all.

A: Basic debugging steps:

*

*What does a print_r($_FILES) look like?

*Does the source file actually exist?

*Is the "error" flag of the file upload zero (will be visible when doing the print_r)

*What does the target $path look like?

*Are you specifying a full file name in the target path?

My guess is that $path is only a path to a folder, not to a full file name.

Update: You need to specify a filesystem path as $path.

A: Did you check permission on the temporary upload folder?
What does php tell you if you do:
var_dump($_FILES);

A: Loïc Février, thank you, you've saved me a lot of time!
Here is my part...
printing possible errors during upload.
First create directory Uploader/UploadedFiles
Then use code below...
$destination=$_SERVER[DOCUMENT_ROOT]."/Uploader/UploadedFiles/" . $_FILES["file"]["name"];

if(move_uploaded_file($_FILES["file"]["tmp_name"],  $destination)){
   echo ("Stored in".$_SERVER[DOCUMENT_ROOT]."/Uploader/UploadedFiles/".$_FILES["file"]["name"]);
}else{
   $html_body = '
File upload error!
';
   switch ($_FILES[0]['error']) {
   case 1:
      $html_body .= 'The file is bigger than this PHP installation allows';
      break;
   case 2:
      $html_body .= 'The file is bigger than this form allows';
      break;
   case 3:
      $html_body .= 'Only part of the file was uploaded';
      break;
   case 4:
      $html_body .= 'No file was uploaded';
      break;
   default:
      $html_body .= 'unknown errror';
   }
   echo ($html_body);
}

A: $path has to be a file name and not a path to a directory.

A: I was facing the same problem.
If your error says "Failed to open stream: Permission Denied" it means the PHP Server is not being capable of creating the new file inside your destination directory.
Once you have set the Linux permissions on the directory (wich sounds like you did by making it 777) you should give that special permission to the PHP Server.
If your folder is named "uploads", you should cd to the previous directory and use the next command:
chcon -R -t httpd_sys_rw_content_t uploads

That definetly solved my problem.
Hope it helps.


text:
Q: Python - Selenium (find elements by CSS selector) How do I access the first element of an array using a CSS selector in python?
For Example:
css=('.od-FieldEditor-fieldTitle.ms-Label.is-required') returns an array of 6 labels. I want to access the innerText attribute of the first label.
Image shows the array of labels

A: Try this:
elements = driver.find_elements_by_css_selector('selector_required')

# if you want to navigate through
for e in elements:
    # do some stuffs with 'e'

# to access a single object
e = elements[0] # will return the first element of a list


text:
Q: Retrieve the commit hash I'm currently working on a deployment script to run as part of my GitLab CI setup. What I want is to copy a file from one location to another and rename it.
Now I want to be able to find what commit that file was generated with, so I'd like to add the hash of the commit to it.
For that to work I'd like to use something like this:
cp myLogFile.log /var/log/gitlab-runs/$COMMITHASH.log

The output should be a file named eg.
/var/log/gitlab-runs/9b43adf.log

How is this possible to achieve using GitLab CI?

A: In your example you used the short git hash that you would get with the predefined variable CI_COMMIT_SHA by building a substring like this:
${CI_COMMIT_SHA:0:8}

or by using the short sha directly
$CI_COMMIT_SHORT_SHA

A: The variable you are looking for is CI_COMMIT_SHA (formerly CI_BUILD_REF in GitLab 8.x and earlier)  which one of the predefined variables.
All predefined variables are listed here.

A: Since GitLab v11.7 you can use $CI_COMMIT_SHORT_SHA which returns the first eight characters of CI_COMMIT_SHA.


text:
Q: how answer a phone call with python through serial port? I've been trying to answer a phone call using a serial port, but i only get 'RING\r\n' and after a while 'NO CARRIER'. is there any command to answer a call?
import serial
ser = serial.Serial()
ser.port='COM3'
ser.baudrate=9600
ser.open()
while True:
    lectura = ser.readline()
    if lectura == "RING": ser.write("OK") # To answer the call.

A: You just have to send the ACK character.
ser.write(b'\x06')


text:
Q: Alternative to scanning AWS DynamoDB? I understand that scanning DynamoDB is not reccomended and is bad practice.
Let's say I have a food ordering website and I want to do a daily scan of all users to find out who hasn't ordered food in the last week so I can send them an email (just an example).
This would put some very spikey demand on the database, especially with a large user base.
Is there an alternative to these scheduled scans that I'm missing? Or in this scenario is a scan the best tool for the job?

A: There are a lot of different possible answers to this question. As so often all of this begins with the simple truth that the best way to do something like this, depends on the actual specifics and what you are trying to optimise for (cost, latency, duration etc.).
Since this appears to be a "once a week" thing I guess latency and "job" duration are not high on the priority list, but cost might be.
The next important thing to consider is implementation complexity. For example: if your service only has 100 users, I would not bother with any of the more complex solutions and just do a scan. But if your service has millions of users, this is probably not a great idea anymore.
For the purpose of this answer I am going to assume that your user base has become too large to just do a scan. In this scenario I can think of two possible solutions:

*

*Add a separate index that allows you to "query" for the last order date easily.

*Use a S3 backup
The first should be fairly self explanatory. As often described in DynamoDB articles, you are supposed to define your "access patterns" and build indexes around them. The pro here is that you are still operating within DynamoDB, the con is the added cost.
My preferred solution is probably to just do scheduled backups of the table to S3 and then process the backup somewhere else. Maybe a custom tool you write or some AWS service that allows processing large amounts of data. This is probably the cheapest solution but processing time might not be "super fast".
I am looking forward to other solutions to this interesting question.


text:
Q: Django Unique Together (with foreign keys) I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here's the intermediary model:
class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    class Meta:
        unique_together = (("userprofile", "extension"),
                           ("user", "extension"),
                           # How can I enforce UserProfile's Client
                           # and Extension to be unique? This obviously
                           # doesn't work, but is this idea possible without
                           # creating another FK in my intermediary model
                           ("userprofile__client", "extension"))

and here's UserProfile:
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    client = models.ForeignKey(Client)

Thanks.

A: You can't.
The unique_together clause is directly translated to the SQL unique index. And you can only set those on columns of a single table, not a combination of several tables.
You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.
Docs: http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.validate_unique

A: From django 2.2+ versions, it is suggested to use constraint & Index as model class meta option:
https://docs.djangoproject.com/en/3.2/ref/models/options/#django.db.models.Options.unique_together
https://docs.djangoproject.com/en/3.2/ref/models/options/#django.db.models.Options.constraints
class UniqueConstraintModel(models.Model):
    race_name = models.CharField(max_length=100)
    position = models.IntegerField()
    global_id = models.IntegerField()
    fancy_conditions = models.IntegerField(null=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                name="unique_constraint_model_global_id_uniq",
                fields=('global_id',),
            ),
            models.UniqueConstraint(
                name="unique_constraint_model_fancy_1_uniq",
                fields=('fancy_conditions',),
                condition=models.Q(global_id__lte=1)
            ),
            models.UniqueConstraint(
                name="unique_constraint_model_fancy_3_uniq",
                fields=('fancy_conditions',),
                condition=models.Q(global_id__gte=3)
            ),
            models.UniqueConstraint(
                name="unique_constraint_model_together_uniq",
                fields=('race_name', 'position'),
                condition=models.Q(race_name='example'),
            )
        ]

A: You need to call Models.full_clean() method to call validate_unique for foreignKey. You can override save() to call this
class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    def save(self, *args, **kwargs):
        self.full_clean()
        super().save(*args, **kwargs)

    class Meta:
        unique_together = (("userprofile", "extension"),
                       ("user", "extension"),
                       # How can I enforce UserProfile's Client
                       # and Extension to be unique? This obviously
                       # doesn't work, but is this idea possible without
                       # creating another FK in my intermediary model
                       ("userprofile__client", "extension"))

A: from django.core.exceptions import ValidationError

.....

class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    def validate_unique(self, *args, **kwargs):
        super(UserProfileExtension, self).validate_unique(*args, **kwargs)
        query = UserProfileExtension.objects.filter(extension=self.extension)
        if query.filter(userprofile__client=self.userprofile.client).exists():
            raise ValidationError({'extension':['Extension already exits for userprofile__client',]})

The first query is to filter all records in UserProfileExtension model which has the same extension we are putting in the current record.
Then we filter the query returned to find if it already contains userprofile__client which we are passing in the current record.

A: My 2 cents, complementing the accepted response from @Wolph

You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.

This is a working example code someone could find usefull.
from django.core.exceptions import ValidationError

class MyModel(models.Model):

    fk = models.ForeignKey(AnotherModel, on_delete=models.CASCADE)

    my_field = models.CharField(...)  # whatever

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.\
                filter(fk=self.fk, my_field=self.my_field).\
                exists():
            raise ValidationError(
                message='MyModel with this (fk, my_field) already exists.',
                code='unique_together',
            )

A: My solution was to use Django's get_or_create.  By using get_or_create, a useless get will occur if the row already exists in the database, and the row will be created if it does not exist.
Example:

extension = Extension.objects.get(pk=someExtensionPK)
userProfile = UserProfile.objects.get(pk=someUserProfilePK)
UserProfileExtension.objects.get_or_create(extension=extension, userprofile=userProfile)

A: Another possible solution is to add this on your save method from your Model:
def save(self, *args, **kwargs):
    unique = self.__class__.objects.filter( extension =self.extension, userprofile=self.userprofile )
    if unique.exists():
        self.id = unique[0].id
    super(self.__class__, self).save(*args, **kwargs)


text:
Q: Is there any reason to replace JavaScript with JScript in Internet Expolorer? So when JScript is different from JavaScript, how does IE interpret jQuery, and all the other JavaScript-s ?
Is it better to replace the JavaScript with JScript for IE? Are there any performance diferences?

A: JScript and JavaScript are the same. They're just aliases for each other:
(via Wikipedia)

As explained by JavaScript guru Douglas Crockford in his talk entitled The JavaScript Programming Language on YUI Theater, "[Microsoft] did not want to deal with Sun about the trademark issue, and so they called their implementation JScript. A lot of people think that JScript and JavaScript are different but similar languages. That's not the case. They are just different names for the same language, and the reason the names are different was to get around trademark issues."

The only scripting differences between the 2 will be in cross-browser differences.

A: As the other people said JavaScript and JScript are one and the same. IE interprets JQuery as any other JavaScript code. If fact JQuery implements workarounds for most browser inconsistencies, including those in IE.
About the performance - IE JScript/JavaScript performance is awful compared to all other modern browsers. Awful as in more then 10 times worse.
Unfortunately, there is nothing you can do to speed it up, besides trying to persuade your visitors to use another browser.

A: You can insert an extra script for IE browsers only-
<script type="text/jscript" src="jsforie.js"></script>

It will boost the performance of the other browsers.


text:
Q: What does (interactive) mean in an Emacs Lisp function? Emacs Lisp function often start like this:
(lambda () (interactive) ...

What does "(interactive)" do?

A: (interactive) is for functions meant to interact with the user, be it through M-x or through keybindings.
M-x describe-function RET interactive RET for detailed info on how to use it, including parameter to catch strings, integers, buffer names, etc.

A: Just to clarify (it is in the quoted docs that Charlie cites) (interactive) is not just for key-bound functions, but for any function. Without (interactive), it can only be called programmatically, not from M-x (or via key-binding).
EDIT: Note that just adding "(interactive)" to a function won't necessarily make it work that way, either -- there could be many reasons functions are not interactive. Scoping, dependencies, parameters, etc.

A: I means that you're including some code for the things you need to make a function callable when bound to a key -- things like getting the argument from CTRL-u.
Have a look at CTRL-h f interactive for details:

    interactive is a special form in `C source code'.
    (interactive args)

    Specify a way of parsing arguments for interactive use of a function.
    For example, write
      (defun foo (arg) "Doc string" (interactive "p") ...use arg...)
    to make ARG be the prefix argument when `foo' is called as a command.
    The "call" to `interactive' is actually a declaration rather than a function;
     it tells `call-interactively' how to read arguments
     to pass to the function.
    When actually called, `interactive' just returns nil.

    The argument of `interactive' is usually a string containing a code letter
     followed by a prompt.  (Some code letters do not use I/O to get
     the argument and do not need prompts.)  To prompt for multiple arguments,
     give a code letter, its prompt, a newline, and another code letter, etc.
     Prompts are passed to format, and may use % escapes to print the
     arguments that have already been read.

A: Furthermore it's worth mentioning that interactive's main purpose is, in an interactive context (e.g. when user calls function with key binding), let user specify function arguments that otherwise could be only given programmatically.
For instance, consider function sum returns sum of two numbers.
(defun sum (a b)
  (+ a b))

You may call it by (sum 1 2) but you can do it only in a Lisp program (or in a REPL). If you use the interactive special form in your function, you can ask the user for the arguments.
(defun sum (a b)
  (interactive
   (list
    (read-number "First num: ")
    (read-number "Second num: ")))
  (+ a b))

Now M-x sum will let you type two numbers in the minibuffer, and you can still do (sum 1 2) as well.
interactive should return a list that would be used as the argument list if function called interactively.

A: One of the "gotchas" that this clarifies is that the argument to interactive is actually a kind of mini-formatting language (like for printf) that specifies the following (for the surrounding function's input):

*

*schema (number of arguments and their type)

*source (e.g., marked-region in buffer and/or user input, etc.)

For example,

'r'
Point and the mark, as two numeric arguments, smallest first.

means that the interactive-annotated function needs exactly two arguments.
e.g. this will work
(defun show-mark (start stop)
  (interactive "r")
  (print start)
  (print stop))

This will break:
(defun show-mark (start)
  (interactive "r")
  (print start))

Wrong number of arguments: ((t) (start) (interactive "r") (print start)), 2


text:
Q: count with where clause and where condition should take from textBox How to count with where clause and where condition should take from textBox
select Count(SRNO) from [Visitor_Customer] where [month]= & me.textBox1.text

this code is not working
please help....

A: Try this
"select Count(SRNO) from [Visitor_Customer] where [month]= "& me.textBox1.text


text:
Q: Proper way to return data from VC without losing scope I have solved my problem, but I don't know if there is some better way of doing that.I am making a workout log. From VC1 I want to select a date and push the VC 2 to select an exercise and then return the exercise to VC1. I am getting the returned data using delegation like that.
VC1
//Here the date of the new Workout. I have to get the exercise first.
func addButtonInSectionDidClick(date:NSDate) {

   //Delegate will call exerciseSelectionDismissedWithExerciseName
   exerciseSelectionWireframe!.dismissDelegate = self

   //Push the VC 2 for exercise selection
   exerciseSelectionWireframe!.presentExerciseSelection()

 }

func  exerciseSelectionDismissedWithExerciseName(name:String) {

        //Returned but I can't use the var date anymore.

    }

There is the problem. I can not use the var date, in the delegation method, but I need to.
My workaround is using a completion block as private var.
    private var completionBlock: (() -> Void)?

    //Here the date of the new Workout. I have to get the exercise first.
    func addButtonInSectionDidClick(date:NSDate) {

       //Delegate will call exerciseSelectionDismissedWithExerciseName
       exerciseSelectionWireframe!.dismissDelegate = self

       //Push the VC 2 for exercise selection
       exerciseSelectionWireframe!.presentExerciseSelection()

       completionBlock = {
          var myDate = date
      }

 }

    func  exerciseSelectionDismissedWithExerciseName(name:String) {

        if let completionBlock = completionBlock {
                     completionBlock()
        }

    }

Is there some other predefined way of doing this? I don't like having that completionBlock var there.

A: Use a share preference or use a singleton, something like:
import Foundation
class ConstantData {
var myDate:NSDate    = NSDate()
}

let sharedDateAccess = ConstantData()

So you can change the variable value and you can access it from anywhere:
func addButtonInSectionDidClick(date:NSDate) {
   //Delegate will call exerciseSelectionDismissedWithExerciseName
   exerciseSelectionWireframe!.dismissDelegate = self

   //Push the VC 2 for exercise selection
   exerciseSelectionWireframe!.presentExerciseSelection()

   sharedDataAccess.myDate = date

 }


text:
Q: how to show pop up alert message without blocking the page to render and how to refresh chart in each 30 sec i want to show pop up if value is less than 3 . i used alert function but when this alert event is fired page is not rendering. how to show popup without blocking the page to display , and how to refresh the chart every 30 sec.

A: Javascript modals will always block page. You need to implement your own popup code or use library for example bootstrap modal
http://getbootstrap.com/javascript/
Another way you can think of if you are doing just simple notifications is using something called toastr (or growl) - there are libs for this also.
For updating fussioncharts look at this example
http://www.fusioncharts.com/dev/using-with-javascript-libraries/jquery/updating-chart-properties-using-jquery.html#changing-the-data-for-an-existing-chart


text:
Q: Passing collection from backgroundworker DoWork to backgroundworker Completed and perform a foreach My goal here is:

*

*User types full or partial computername into combobox

*button click event starts background worker passing computername to DoWork method

*DoWork method searches ActiveDirectory for computername and passes the collection to WorkerCompleted method

*WorkerCompleted method adds each computername to the combobox items.

My error is at the foreach loop in my backgroundWorker_RunWorkerCompleted method.

*

*"foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'"

If I do a MessageBox.Show(results.First().ToString()); in the DoWork method, I can view the first computername in the collection.
If I do a MessageBox.Show(e.Result.ToString()); in the DoWork and WorkerCompleted method, I get this:

*

*"System.DirectoryServices.AccountManagement.PrincipalSearchResult`1[System.DirectoryServices.AccountManagement.Principal]"

Any guidance on this would be greatly appreciated!
    private void button1_Click(object sender, EventArgs e)
    {
        //Saves computername entered by user to pass into DoWork method
        string PCName = comboBox1.Text;

        //Start background thread passing computer to the Dowork method
        backgroundWorker1.RunWorkerAsync(PCName);
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
        {
            //Setup Filter
            ComputerPrincipal computer = new ComputerPrincipal(ctx);
            computer.Name = "*" + e.Argument + "*";

            //Search for PC
            PrincipalSearcher ps = new PrincipalSearcher();
            ps.QueryFilter = computer;

            //Get Results
            PrincipalSearchResult<Principal> results = ps.FindAll();

            //results will be passed to RunWorkerCompleted
            e.Result = results;
        }
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //Add each computername to combobox
        foreach (object PC in e.Result) // <--------------- ERROR HERE!
        {
            comboBox1.Items.Add(PC.ToString());
        }
    }
}

A: You should cast the object to IEnumerable or the type that you know it is
  var collection = (PrincipalSearchResult<Principal>) e.Result;
  foreach (var PC in collection)
    {
        comboBox1.Items.Add(PC.ToString());
    }

A: You have to cast e.Result in Completed handler from object to PrincipalSearchResult<Principal> in order to iterate through it.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //Add each computername to combobox
    PrincipalSearchResult<Principal> results = (PrincipalSearchResult<Principal>)e.Result;
    foreach (Principal PC in results)
    {
        comboBox1.Items.Add(PC.ToString());
    }
}

Edit:
PrincipalSearcher can't be used in Background Worker, because it's uses of COM component that requires Single-threaded Apartment (STA). Background Worker thread runs in multithreaded apartment (MTA). ApartmentState can be set using Thread.SetApartmentState, but it must be called before thread starts (so it can't be used to change ApartmentState of BackgroundWorker's working thread).


text:
Q: How to sync files programmatically to Azure storage in a way like Dropbox? I upload medical images to Azure storage. I used MS DICOM Server APIs and JS libraries provided by Microsoft to upload files to Azure Blob Storage. But they are not that fast. I expected to find something like dropbox method. Files synchronization is fast and resumable. What is the best method to run this? I expected very high traffic on my web application. Tens of clients will upload to my cloud storage at the same time.
Thank you

A: •   You can use Azure AzCopy utility for this purpose and you can use the following commands regarding Azcopy from powershell to sync the files from local storage to azure blob storage.
Syntax: -
'azcopy sync '' 'https://.blob.core.windows.net/' –recursive'
Example: -
azcopy sync 'C:\myDirectory' 'https://mystorageaccount.blob.core.windows.net/mycontainer' –recursive
•   You can also sync files between to and from a container and a local resource such that any modification to any file in the storage resources like deletion will be replicated to the other destination storage resource as well. You will have to add the '—delete-destination' parameter to 'true' or 'prompt' for the files to be deleted from the destination storage resource.
•   For periodical syncing of data between the resources, you can create a windows task scheduler job to be run every 2 hours with the azcopy script to be invoked and run for syncing purposes. Also, please refer the below links for more information on various parameters to be used with azcopy for performing specific operations.
https://learn.microsoft.com/en-us/azure/storage/common/storage-use-azcopy-blobs-synchronize
https://learn.microsoft.com/en-us/azure/storage/common/storage-ref-azcopy-sync


text:
Q: How do I finish a css animation with loading a new URL? I have in mind a few fade-ins, then a fade-out, and ending in a new page being load (target=self).
From some googling, it seems css animation doesn't foresee the last step (fetching a new URL).
Is there a simple way to do that? The starting page will be loading jquery.
Somehow the new URL has to wait until the animation ends.
Update
In the end, I used this css animation tutorial to make a 5-second animation, inserted all css in the <head> and pasted the images in the page in base64 (no further HTTP requests), checked the resulting file size (11Kb), checked Google Analytics to see my average page load times for files that size (less than 1 second) then added to the page <META http-equiv="refresh" content="8; url=page2.html">. Feels like something from the 1990s, but it works.

A: It depends if your animation is powered by CSS or jQuery, a question raised by a few others, too. If it is CSS-based, you can listen to the animationend event (with appropriate vendor prefixes added to maximize cross-browser compatibility):
$(ele).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function() {
    // Load new URL
    window.location.href = newURL;
});

See demo fiddle here: http://jsfiddle.net/teddyrised/pqxsj8v9/

If your animation is jQuery powered, i.e. using the .animate() method, simply use the callback function:
$(ele).animate({
    // Animate stuff
}, duration, function() {
    // Load new URL
    window.location.href = newURL;
});

See demo fiddle here: http://jsfiddle.net/teddyrised/ad0vtqyt/

A: If the animation time is always the same, you can handle the excact time of animation, and load the page after this time.

A: how are you firing the animation, you mentioned jquery, so if you are using jquery for the animation you can always use the callback to load your page or set a timeout etc
$('.someElement'.animate({}, timeFrame, function () {

    // fire cod ein here or set a timeout for when the whole animation is done
    setTimout(function () {
        //code here
    }, timeForAnimationToFinish):

});

jquery animate docs
if you are adding classes and using css3 transition, you could always do:
$('#someThing').addClass('animateMeFor30Seconds', function () {
    var someThing = $(this);
    setTimeout(function () {
        //next animation
    }, 30000);
});

It's not the greatest, but it will pass your unit tests and allow you to refector :-)


text:
Q: compare day with getDay from a Date object in a JSON API output I am working with some data being outputted from a JSON API. I have a loop that is pulling bits and pieces from the API and I would like to compare the day in a date object.  I am not 100% sure if the date in the output is an object but it looks like this, example: 2021-09-27T02:15:00-07:00.
What I am trying to compare is the day which is 27 in the above example and once the day in the look changes to 28 then I want to do something.
I do have the index in my loop so I think my best bet is compare with the previous day in the last index with i - 1, but it doesn't look I can compare the date value like this because this compares the whole date value including the time 02:15:00, so this cannot be accurate:
if (data[i].PresentationDate !== data[i - 1].PresentationDate)

and it doesn't look I can getDay() from PresentationDate like this:
if (data[i].PresentationDate.getDay() == data[i - 1].PresentationDate.getDay()) {...}

when I try to do so then I get this error:
Uncaught TypeError: data[i].PresentationDate.getDay is not a function.
What am I doing wrong and what's the best and most accurate way to get the Day in this loop and compare it with the previous index?

A: Assuming data[i].PresentationDate is a String (as your error somewhat alludes to), parse it to a Date object first, then compare the year/month/day and take the action you need based on the outcome:
var currentDate = new Date(data[i].PresentationDate);
var prevDate = new Date(data[i-1].PresentationDate);

if (currentDate.getDay() == prevDate.getDay() && currentDate.getMonth() == prevDate.getMonth() && currentDate.getYear() == prevDate.getYear()) {
    // same day
} else {
    // different day
}


text:
Q: RegEx for a multiple line search and replace using sed I need to have a RegEx that finds a \n in the middle of a line as a start point, anything before is random, and replace after 15 digits and 49 alpha on the second line. I need to replace all that by blanks, but the second line needs to join with the first one.
Attempt
sed -r -e '{N;s/\n[[:digit:]]{15}[[:space:]]{49}//}'

Input
QC HOH 0H0 CA
:70:NOFX TRADE TR
100000100200621                                                 ADE RELATED WOOD                                                                                PURCHASE

What needs to be removed is the linefeed after TRADE TR and bring the ADE RELATED to the TR so it spells TRADE.
Desired Output
QC H0H 0H0 CA
:70:NOFX TRADE TRADE RELATED WOOD                                                                                PURCHASE

A: This might work for you (GNU sed):
sed -E 'N;s/\n[[:digit:]]{15}[[:space:]]{49}//;P;D' file

This opens up a two line window and amends the second of them if the substitute command matches. It always prints the first of the two lines and then removes it.

A: With GNU sed:
$ sed -Ez 's/\n[[:digit:]]{15}[[:space:]]{49}//' file
QC J0B 2Y0 CA
:70:NOFX TRADE TRADE RELATED WOOD                                                                                PURCHASE


text:
Q: `tee` and `bash` process substitution order I'd have supposed this code would have printed "oof" first:
echo foo | tee >(rev) | ( sleep 1 ; cat ; )

Output:
foo
oof

Increasing the sleep time doesn't change the order.  Why doesn't that work?

Note that other tools do work as supposed, e.g.: echo foo | pee rev 'sleep 1 ; cat'.

A: In
echo foo | tee >(rev) | (sleep 1; cat)

In bash like in ksh, but unlike zsh, the stdout of rev also is the pipe to (sleep 1; cat).
echo, tee, rev and the (...) subshell are started at the same time, but tee writes foo\n to stdout before the pipe to rev, so in any case, rev will write oof to the pipe after tee writes foo, so oof can only come last. Delaying cat has no incidence.
If you wanted the output of rev not to go through the pipe to (sleep 1; cat), you'd use zsh or do:
{ echo foo 3>&- | tee >(rev >&3 3>&-) 3>&- | (sleep 1; cat) 3>&-; } 3>&1

Note that zsh also has a builtin tee in its multios feature, so you can do:
echo foo > >(rev) > >(sleep 1; cat)

However in:
echo foo > >(rev) | (sleep 1; cat)

The output of rev would go through cat (confusingly considering it doesn't in the echo foo >(echo bar) | (sleep 1; cat) case).

A: Using two bash process substitutions, (instead of just one, then a pipe), then dumping the STDOUT to /dev/null, works as expected:
echo foo | tee >(rev) >( sleep 1 ; cat ; ) > /dev/null ; sleep 1

Output:
oof
foo

Notes:

*

*the 2nd sleep prevents "foo" from being printed after the command prompt.

*reducing the sleep delay number to some optimum ought to be better, but I'm not sure what that number should be.  1 is a bit slow, but always seems to work; .01 doesn't always work, (that is, the output is sometimes in the wrong order), .1 seems to work well.


text:
Q: Flutter doctor --android-licenses stuck at some point So ive been trying to install flutter into my laptop. When i was in the process of installing flutter, using this command line flutter doctor --android-licenses does not give me the exact correct process that i need.
Instead of showing 7 out of 7 licenses it only shows 6 out of 7 hence making the process stuck at some point. Does any one know the reason for this issue ?

A: Not sure what is the problem but when i tried the recommendation by @Benyamin to open VPN and all of the sudden everything just works like a charm. Thank you once again.


text:
Q: Serving static assets via flatironjs Is there a built-in way for serving static assets (images/css/js) via flatironjs? Or do we need to write custom routes to do this? Couldn't find any examples for any built-in way.

A: flatiron now has a plugin for static file serving.
app.use(flatiron.plugins.static, { root: __dirname });

Example at: flatiron/examples/static-app/app.js

A: Union supports connect middleware so just add require("connect").static to the middleware stack


text:
Q: mov edx overwrites cx register I'm trying to print Hi 10 times. This is my code.
section .data

msg db "Hi"

section .text

global _start

_start:

    mov cx, 10

    L1:
    mov eax, 4
    mov ebx, 1
    mov ecx, msg
    mov edx, 3
    int 0x80

    dec cx
    jnz L1

    mov eax, 1
    mov ebx, 0
    int 0x80

gdb reports that mov edx, 3 overwrites the cx register to some crazy value and so the loop keeps going forever.
What am i doing wrong? Is it because they are the same register?
How does one program in assembly with so few registers?
Compiling on centos with nasm and ld
Thanks

A: You're looking at the wrong line.  The problem is "mov ecx, msg".  ECX is the extended register of which CX is the lower part, so you're writing over it.
It's best to save your loop counter on the stack, because who knows that the 'int' call might change.  Add 'push cx' (or ecx) after 'L1:'. and 'pop cx' after the 'int' call to preserve the contents of the register.

A: This code fixes it:
section .data

msg db "Hi"

counter dw 10

section .text

global _start

_start:

    L1:
    mov eax, 4
    mov ebx, 1
    mov ecx, msg
    mov edx, 2
    int 0x80

    mov cx, [counter]
    dec cx
    mov [counter], cx

    jnz L1

    mov eax, 1
    mov ebx, 0
    int 0x80

move the value into a variable and then dec it then put it back


text:
Q: Serial number of certs in BasicOCSPResponse is not the same with the certificate I want to know how a browser check the validity of a certificate with OCSP stapling, to make sure the certificate is not expired or revoked.
I used wireshark to capture tls packets with bing.com.
Looked into Server hello packet Server Hello, Certificate, Certificate Status, Server Key Exchange, Server Hello Done.
Looked into certificate status field, and I can see OCSP response, which is what I need.
Went into BasicOCSPResponse, its structure (rfc6960) is:
   BasicOCSPResponse       ::= SEQUENCE {
      tbsResponseData      ResponseData,
      signatureAlgorithm   AlgorithmIdentifier,
      signature            BIT STRING,
      certs            [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }

So I clicked into certs, is looks like this:

I have highlighted serial number, which should be the serial number of the bing certificate, but I cannot match it with the certificates I downloaded from bing (see them here), the public key is different  either.

I don't know why there is no one certificate match with it, so I am not sure which certificate is signed by its CA. Hope someone can help me with it. Thank you!


text:
Q: SharePoint Online : Permission to list based on user How can we setup list permission based on following scenario:
- Administrator and SP Group A should be able to see records of all users
- SP Group B should be able to see records where department = "ABC"
- Other users should be able to see only records where Manager = [ME]
We are using SharePoint online.

A: I think you can manage this scenario using Target Audience as the following

*

*Besides all items view, Create additional two views, one filtered by Department and the other filtered by the manager.

*Create a page to show all three views,

*Add a list view web part, and select your current view.

*Repeat the above steps for each view.

*Edit the list view web part, and at Target Audience section, set your group name based on your requirements.


text:
Q: Get variable in scope without closure / wrapping function If I have a variable that is changing over time and I want to preserve a particular instance of it I have to wrap it in a closure like so:

function test(){
 var x = Math.random();
 // Is there an alternative to using the following closure:
 var printnum = (function(num){
  return function(){
   console.log(num);
  }
 })(this.x); // Because I think this is ugly

 return printnum;
}

var a = test();
var b = test();

a(); //number
a(); //same as above
b(); //different number
b(); //same as above

In PHP you would use use like so:
$a = rand();
function () use ($a) {
  echo($a);
}

I really appreciate this because you immediately see which variable is being injected, it's not listed at the very bottom like in js: (function(b){})(a); Also there aren't an excessive amount of brackets. I tried experimenting with .apply() and .call() and but they both execute the function, I just want to inject a variable in a certain state.
I think I'm just asking for a language feature that doesn't exist, but please prove me wrong. Any ideas?

A: a simple way using .bind() (ES5) to remove the wrapper functions and avoid closure:
function test(){
  return console.log.bind(console, Math.random());
}

A: I personally like the IIFE, but "One man's garbage..." Anyway, you really just need to pass a copy of the number so that you don't get caught up in the closure variable.

function test(){
  // Because you are working with a number and JavaScript passes all arguments by value
  // a copy of the number will be passed to helper, allowing helper to "disconnect"
  // from using the number in the parent scope
  return helper(Math.random());

  function helper(num){
    return function(){ console.log(num); }
  }
}

var a = test();
var b = test();

a(); //number
a(); //same as above
b(); //different number
b(); //same as above

A: Can you use es6? If so, an arrow function will give the same result, but is more concise:

function test(){
 var x = Math.random();

 var printnum = x => () => console.log(x);
 return printnum(x);

    // OR you can invoke immediately:
    // var printnum = (x => () => console.log(x))(x);
    // return printnum;
}

var a = test();
var b = test();

a(); //number
a(); //same as above
b(); //different number
b(); //same as above

AFAIK, in javascript, you'll have to pass the x into the function one way or another to avoid it printing something else if x's value is later changed.

A: There's no need for the printnum function. Just return the inner anonymous function.
This is essentially the same as the PHP, but it doesn't need the use() declaration to list variables to inherit into the closure (PHP needs this because the default is to not allow any access to outside variables).

function test() {
  var x = Math.random();
  return function() {
    console.log(x);
  }
}

var a = test();
var b = test();

a(); //number
a(); //same as above
b(); //different number
b(); //same as above


text:
Q: Partition elimination in Greenplum I have a scenario like this:
SELECT * FROM PACKAGE WHERE PACKAGE_TYPE IN ('BOX','CARD')

The table is partitioned by PACKAGE_TYPE field. Assume that there are twenty possible values for PACKAGE_TYPE field. So there are twenty partitions including BOX, CARD and DEFAULT partitions. When the above query is run, partition elimination happens correctly and only the BOX and CARDpartitions get scanned. The result is quick.
However, when the same query is written like this:
SELECT * FROM PACKAGE WHERE PACKAGE_TYPE IN (SELECT PACKAGE_TYPE FROM PACKAGE_LIST_TABLE), where the column PACKAGE_TYPE in PACKAGE_LIST_TABLE contains two values BOX and CARD.
When the above query is run, all the 20 partitions are being scanned. It degrades the performance.
It seems that the compiler is failing to identify the second query correctly and as a result all the partitions are getting accessed.
Any workarounds to overcome this?
Thanks in advance.

A: The Postgres manual page on Partitioning includes this caveat

Constraint exclusion only works when the query's WHERE clause contains constants (or externally supplied parameters). For example, a comparison against a non-immutable function such as CURRENT_TIMESTAMP cannot be optimized, since the planner cannot know which partition the function value might fall into at run time.

In order to eliminate a seek on a partition, Postgres must know when creating a query plan that no rows from that partition are relevant. In your query, this occurs only after the sub-query has completed, so the query would have to be split into two, with the second part planned only after the first completes.
If the partitions include an index on the partitioned column (PACKAGE_TYPE) as well as a constraint, the planner may elect to use an index scan on each partition, leading to the incorrect partitions being reasonably efficiently eliminated at runtime anyway. (That is, there would be 20 index scans, but each would require very little resource.)
An alternative would be to split the query yourself, and build the SQL dynamically. Since the SELECT PACKAGE_TYPE FROM PACKAGE_LIST_TABLE can only ever return up to 20 distinct values, you could select those into an array/set in your application or a user-defined function. Then you can pass these in as literals in the IN ( ... ) clause as in your first example (or equivalently = ANY(array_expression)), and achieve the partition elimination.


text:
Q: How do you create a gtk window in python and also have code running in the background? I am trying to create a GUI window with a web address inside (a video stream in this case) while also having some additional code running in the background that communicate with the GPIO ports on a Raspberry Pi. I can get the window to work but the background code only starts when the window is closed. Or if I reverse the order of the code the GPIO code stops working when the window is open. Here is some example code.
import gtk

import webkit

import gobject

import RPi.GPIO as GPIO

from time import sleep

import os

ip = raw_input("Enter the last 3 digits of IP address: ")

awesome = "http://192.168.0." + ip + ":9090/stream"

print awesome

os.system("sudo uv4l -nopreview --auto-video_nr --driver raspicam --encoding mjpeg --width 640 --height 480 --framerate 30 --server-option '--port=9090' --server-option '--max-queued-connections=30' --server-option '--max-streams=25' --server-option '--max-threads=29'")

gobject.threads_init()

win = gtk.Window()

win.connect('destroy', lambda w: gtk.main_quit())

bro = webkit.WebView()

bro.open(awesome)

win.add(bro)

win.show_all()

gtk.main()

GPIO.setmode(GPIO.BOARD)

GPIO.setup(38, GPIO.OUT)

GPIO.setup(40, GPIO.OUT)

GPIO.setup(37, GPIO.OUT)

GPIO.setup(35, GPIO.OUT)

GPIO.output(38, GPIO.HIGH)

GPIO.output(40, GPIO.LOW)

GPIO.output(37, GPIO.LOW)

GPIO.output(35, GPIO.HIGH)

sleep(2)

A: gtk.main() runs till you close window (it is call "main loop" or "event loop" and it does everything in GUI program - get key/mouse event, send it to widgets, redraw widgets, run functions when ypu press button, etc.).
You have to use Threading to run (long-running) code at the same time or use some Timer class in GUI to execute some code periodically.


text:
Q: Does using inequality (<>) or NOT in where clause lead to SQL ignoring the index? I found this article that talks about avoiding using <> operator in where clause because optimizer ignores the index.
https://www.mssqltips.com/sqlservertutorial/3203/avoid-using-not-equal-in-where-clause/
Is this absolutely true?
What is the best way to handle this? How to avoid using <> ?

A: A <> X predicate is sargable.
SQL Server can convert it to two range seeks (on < X or > X).
Unless the index is covering for the query however you may well not see this. The tipping point for a query using a non covering index and look ups is typically very low. (at most selectivity of a single digit percent).
So unless, say, 99% of the table does have value X the <> will match too many rows for that plan to be chosen.
Even in this case likely you should be considering a filtered index only containing the 1% of rows that don't match X rather than a full index including the highly unselective value.
Unless the domain of possible values is entirely fixed and quite small you don't really have a choice between using <> X or writing it as IN(all,values,that,are,not_x) - you need to choose the one with the correct semantics for all possible values.


text:
Q: Two different AJAX forms not working Hello I'm working on rails and have been trying to make ajax requests when submiting forms for comments so the result is appended to the list of comments. I've got it to work thanks to this video: https://www.youtube.com/watch?v=K-sns5tNdTY .
Later I decided to add answers to my comments, which I implemented with a new model and made a coffeescript on each comment to show me the answers and a form to answer to that specific comment. It was kind of a pain in the ass but got it to work finally.
Now I've got my answers working just fine, but the comment form is not working through AJAX, the comments are getting posted, but not appended to the comment list.
What I get is a console error when inspecting on chrome:
jquery.self-bd7ddd3….js?body=1:10255 POST http://localhost:3000/comentarios 500 (Internal Server Error)
This is how I render the comments and the form (sorry for it being in spanish):

Comentarios

                            <%= render @comentarios %>

                    <% if @comentarios.count <= 0 %>

 Aún no hay comentarios. Haz uno!

                    <% end %>
                    <% if usuario_signed_in? %>

                        <%= render :partial => 'comentarios/form' %>

                    <% end %>

This is the form for my comments (views/comentarios/form):
<%= form_for @comentario , remote: true do |f| %>

    <%= f.hidden_field :favor_id, value: @favor.id%>

            <%= f.label :texto, "Escribe un comentario:" %>

            <%= f.text_area :texto, required: true,class: "form-control", style: "width: 99%; max-width: 99%"%>

            <%= f.submit "Comentar", :class=>'btn btn-primary'%>

<% end %>

And this is the create.js.erb for that inside views/comentarios
$('#comentarios').append($("<%= j render @comentario %>").hide().fadeIn(500));
$('#comentario_texto').val("");

Then for each comment I render this:

                                <% if Usuario.find(comentario.usuario_id).foto.presence %>
                                <%= image_tag Usuario.find(comentario.usuario_id).foto, title:"FotoUsuario", class:"img-sm"%>
                                <% else %>
                                <%= image_tag "foto_stock.png", title:"FotoUsuario", class:"img-sm"%>
                                <% end %>

<%= link_to Usuario.find(comentario.usuario_id).nombre.capitalize+" "+Usuario.find(comentario.usuario_id).apellido.capitalize, usuario_path(:id => comentario.usuario_id)%>

 <%= comentario.created_at.strftime("%d/%m/%Y %H:%M") %>

<%= comentario.texto%>

                    <% if (current_usuario.id == comentario.usuario_id)%>
                    <%= link_to "Eliminar", comentario, method: :delete, data: {confirm: '¿Esta seguro de eliminar este comentario?'}, class: 'btn btn-danger btn-xs' %>
                    <% end%>

                    <a class= "respuestas-link btn btn-primary btn-xs" data-section-id="respuestas-seccion-<%=comentario.id%>" href="#">
                        Respuestas

                <section id="respuestas-seccion-<%=comentario.id%>" style="display: none">

                            <% respuestas = comentario.answers %>
                            <div id="respuestas-<%=comentario.id%>">
                                <%= render respuestas %>

                            <%= render :partial => 'answers/form', :locals => {:coment => comentario}  %>

where I render each answer and this form for each comment:
<%= form_for @respuesta , remote: true do |f| %>

    <%= f.hidden_field :comentario_id, value: coment.id%>
            <%= f.label :texto, "Escribe una respuesta:" %>

            <textarea required="required" class="form-control" style="width: 99%; max-width: 99%" name="answer[texto]" id="answer_texto_<%=coment.id%>"></textarea>

            <input type="submit" name="commit" value="Enviar" class="btn btn-primary btn-xs">

<% end %>

And get it working through ajax through this create.js.erb in /views/answers/create.js.erb
$('#respuestas-' + <%= @respuesta.comentario.id %>).append($("<%= j render @respuesta %>").hide().fadeIn(500));
$('#answer_texto_' + <%= @respuesta.comentario.id %>).val("");

Finally I would like to say that I've tried removing the
<%= render :partial => 'answers/form', :locals => {:coment => comentario}  %> line in views/comentarios/_comentario.html.erb and the comment form  works just fine.
I find it weird as there are many forms for answers in the page and all of them are working simultaneously without interfering with each other, except for the comments form.
Thanks for your time and hope you can help!

A: I worked it out by inspecting with chrome in Network, XHR where I had a better explanation of the error:
ArgumentError in Comentarios#create

Showing /app/views/answers/_form.html.erb where line #1 raised: First
  argument in form cannot contain nil or be empty

It was messing up with the @respuesta I used for other forms, so I added a @respuesta.new somewhere in the controller for Comentarios and that did the trick!


text:
Q: Could not find or load main class - Under unusual circumstances Alright, I know this is a very common, very simple question, but mine comes with rather unusual circumstances. (Circumstances which I was unable to find a solution to elsewhere on the internet.) So, I have some source code which I am programmatically compiling via JavaCompiler. I then attempt to execute the compiled code with Runtime. (That is, Runtime.getRuntime().exec(String[]).) However, when I attempt to execute said code, I get Could not find or load main class. The source code in question follows this base-model:
package compiledCode;
public class Compiled
{
    public Compiled(){}
    public static void main(String[] args)
    {
        System.out.println("Hello!! ;D");
    }
}

Even that code won't execute. I still get the same error. Thanks in advance for your help. :)
*Edit:
The steps I take in detail are as follows:

*

*I start with the code mentioned above in a String called code. I then make a File object (in this case, Compiled.java.)

*I use a custom method of mine which I have tested and have ensured it works to compile the file (and optionally get a Class object from it, though, for specific reasons, I can't do it that way for this.) into a .class file. (Using the JavaCompiler API.)

*I then use Runtime.getRuntime.exec(new String[]{"java",[location of .class file]}); to execute it.
It is at this point that I get an error.
The exact code I am using, as requested, is this..
ClassFileHelper.toClass(src, "C:/Users/Steven/Desktop/ /Eclipse/Workspace/RoccedGame/ServiceCoder", "ServiceCoder");
System.out.println("java "+src.getAbsolutePath().substring(0,src.getAbsolutePath().lastIndexOf(".java"))+".class");
final Process p = Runtime.getRuntime().exec(new String[]{"java",src.getAbsolutePath().substring(0,src.getAbsolutePath().lastIndexOf(".java"))+".class"});

The String manipulation in the 3rd line is a bit messy, but I've triple-checked to ensure that it works - which it does. If you would like to see the code for the .toClass() bit, go here.

A: You're not passing the correct parameters to Runtime.exec().
You pass the actual location of the compiled classfile. However, you should be passing a class name, and if your class is in a package you'll also need to pass the root of the package hierarchy as a -classpath parameter.
This is described in the JDK documentation: http://docs.oracle.com/javase/6/docs/technotes/tools/windows/java.html


text:
Q: $concat string with $cond in mongodb aggregation [
{
    "user_id" : 12453,
    "profile_type" : "demo_type_1",
    "records" : [
        {
            "type" : "typ_11",
            "value" : {
                "high" : 115,
                "low" : 78
            },
            "_meta" : {
                "data_type" : "text"
            }
        },
        {
            "type" : "type_1",
            "files" : [
                {
                    "title" : "path_prescription_1",
                    "url" : "/file_name.extension"
                },
                {
                    "title" : "path_prescription_2",
                    "url" : "/file_name__1.extension"
                }
            ],
            "_meta" : {
                "data_type" : "file"
            }
        }
    ]
},
{
    "user_id" : 12455,
    "profile_type" : "demo_type_1",
    "records" : [
        {
            "type" : "typ_11",
            "value" : {
                "high" : 115,
                "low" : 78
            },
            "_meta" : {
                "data_type" : "text"
            }
        },
        {
            "type" : "type_1",
            "files" : [
                {
                    "title" : "path_prescription_1",
                    "url" : "/file_name.extension"
                },
                {
                    "title" : "path_prescription_2",
                    "url" : "/file_name__1.extension"
                }
            ],
            "_meta" : {
                "data_type" : "file"
            }
        }
    ]
},
...
]

i want to append prefix the url value to make it an absolute path while retrieving from the database only when the _meta fields data_type is file not for text. The is stored in the above format and retrieved in the same format only with the appended url.
is there any way to do this by using aggregation pipeline ?

A: You can try using $addFields like this:
db.getCollection('test').aggregate(

[

{
    $unwind: {
        path:"$records",

        preserveNullAndEmptyArrays: true
        }
},

{
    $unwind: {
        path:"$records.files",

        preserveNullAndEmptyArrays: true
        }
},

{
    $addFields: {
        "records.files.url":{
             $cond: {
                    if: {
                      $eq: ['$records.files', undefined]
                    },
                    then: null,
                    else: {$concat: ["some_prefix", "$records.files.url"]}
              }

            }
        }

    }

]

)

This will give you:
/* 1 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "typ_11",
        "value" : {
            "high" : 115.0,
            "low" : 78.0
        },
        "_meta" : {
            "data_type" : "text"
        },
        "files" : {
            "url" : null
        }
    }
}

/* 2 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_1",
            "url" : "some_prefix/file_name.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 3 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508520"),
    "user_id" : 12453.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_2",
            "url" : "some_prefix/file_name__1.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 4 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "typ_11",
        "value" : {
            "high" : 115.0,
            "low" : 78.0
        },
        "_meta" : {
            "data_type" : "text"
        },
        "files" : {
            "url" : null
        }
    }
}

/* 5 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_1",
            "url" : "some_prefix/file_name.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

/* 6 */
{
    "_id" : ObjectId("5b6c484b9a8ea6a11c508521"),
    "user_id" : 12455.0,
    "profile_type" : "demo_type_1",
    "records" : {
        "type" : "type_1",
        "files" : {
            "title" : "path_prescription_2",
            "url" : "some_prefix/file_name__1.extension"
        },
        "_meta" : {
            "data_type" : "file"
        }
    }
}

But remember to ignore records.files.url field when the record is type text.


text:
Q: Cypress get the ID of some element I am trying to obtain the ID of some element in Cypress. Because it's ID randomly changes (yes it is strange but it is angular).
E.g. I have a <button id="dropdown-1" class="someclass"><span>Click here</button>
As I can't rely on that ID, because after I do some actions on the page it becomes to dropdown-2 etc., I want to know, what is the current ID name.
I tried something like:
cy.get('button > span').contains('Click here').find("id");

but seems that is not the correct way.
I also tried:
  cy.get('button > span').contains('Click here')
  .invoke('attr', 'id')

this works not as well.

A: You can use a combination of text and a selector which has the non-changing part of your id value. Something like:
cy.contains('button[id*="dropdown-"]', 'Click here').invoke('attr', 'id')

Now you can use use the id value in two ways.

*

*Directly after extraction:

cy.contains('button[id*="dropdown-"]', 'Click here')
  .invoke('attr', 'id')
  .then((id) => {
    cy.log(id) //prints id
  })

*Save it in alias .as and use it later:

cy.contains('button[id*="dropdown-"]', 'Click here')
  .invoke('attr', 'id')
  .as('idValue')
cy.get('@idValue').then((idValue) => {
  cy.log(idvalue) //prints id
})


text:
Q: meta keyword tag not showing in browser source Fist of all I already look these questions Meta Keywords does not appear and Magento meta keywords tag not showing but my question answer is not listed there.
I am using Magento 1.9 CE in my_theme>default>template>page>html head.phtml when I change keywords name to keywords1 like
<meta name="keywords1" content="this keyword, what keyword" />

I can see this in browser source but when I back change to keywords like
<meta name="keywords" content="this keyword, what keyword" />

Magento engine despairs the whole tag.
So there is not the problem if cache etc problem is clear that Magento engine deliberately removing keywords meta tag if anyone knows why it is doing this???
or any solution

A: Credit goes to @tahir-yasin mention this is due to Creare SEO, but you don't need to uninstall this extension. Go to your Settings>Configuration>
In CREARE SEO find General Settings and change "
Disable Meta Keywords Tag and Empty Meta Description Tags?" to "No" your problem will be solved..


text:
Q: Evaluating a numerical integral at a point Can we evaluate a numerical integration at a point? Consider the following example:
g = NIntegrate[(1 - 2/Sqrt[4 + r^2])/Sqrt[1 + (4 + r^2)^2 (1 - 2/Sqrt[4 + r^2])^2],{r,0,u}];

Since I know that Mathematica can not solve this integral analytically, I ask it to solve this integral numerically (for example, I solve this integral for $1/2<r< 5/2$). Now I need a list of data that contains the value of g for each different values of u. How can I get this list?

A: Is this what you want?
v =
  Table[
    {u,
     NIntegrate[
       (1 - 2/Sqrt[4 + r^2])/Sqrt[1 + (4 + r^2)^2 (1 - 2/Sqrt[4 + r^2])^2],
       {r, 1, u}]},
    {u, 1, 2, .05}];
Column[v]

A: I am guessesing they want something like this
f[to_] :=
 NIntegrate[(1 - 2/Sqrt[4 + r^2])/
   Sqrt[1 + (4 + r^2)^2 (1 - 2/Sqrt[4 + r^2])^2], {r, 1, to}, Method -> "TrapezoidalRule"]

data = Table[{r, f[r]}, {r, 1, 2, .1}];

ListStepPlot[data, Frame -> True, GridLines -> Automatic,
 GridLinesStyle -> LightGray,
 FrameLabel -> {{"Integral vale", None}, {"r",
    "Showing integral as r increases"}}, BaseStyle -> 14, PlotStyle -> Red]


text:
Q: open conditional python files but read data from one I want to open and read a file depending on a condition, read only if condition met true. I wrote the following scriptlet:
def bb(fname, species):
     if species in ('yeast', 'sc'):
         pm =  open('file.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)
    elif species in ('human', 'hs'):
         pm =  open('file2.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)

Is there a proper pythonic way, where I don't have to repeat/write the same lines (line3 to 10) over and over again ? Thanks !

A: You can put the filename value in a variable
def bb(fname, species):
    if species in ('yeast', 'sc'):
        fname2 = 'file.txt'
    elif species in ('human', 'hs'):
        fname2 = 'file2.txt'
    else:
        raise ValueError("species received illegal value")

    with  open(fname2, 'rU') as pm:
        for line in pm:
            line = line.split()
            with open(fname, 'rU') as user:
                for e in user:
                    e = e.split()
                    if e[0] in line:
                        print(line)

or define another function
def bb(fname, species):
    if species in ('yeast', 'sc'):
        read_file('file.txt', fname)
    elif species in ('human', 'hs'):
        read_file('file2.txt', fname)

def read_file(fname1, fname2):
    with  open(fname1, 'rU') as pm:
        for line in pm:
            line = line.split()
            with open(fname2, 'rU') as user:
                for e in user:
                    e = e.split()
                    if e[0] in line:
                        print(line)

A: Since you seem to be doing the exact same thing regardless of the condition, you could just collapse everything?
def bb(fname, species):
     if species in ['yeast', 'sc', 'human', 'hs']:
         pm =  open('file.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)

Either that or you've made a mistake copying the code. If you want to do something different depending on the case, then you could make a function that takes that argument, or do the conditional statement first and use it to set a certain string or value.
E.g.
if species in ('yeast', 'sc'):
    permissions = 'rU'

etc.

Edit: Ah, with your edited question the answer would be as above but then
if species in ('yeast', 'sc'):
    file_name = 'file.txt'
elif species in ('human', 'hs'):
    file_name = 'file2.txt'

A: Just put opening of file in if else case rest will be done in a similar manner and same code block as well.
def bb(fname, species):
    if species in ('yeast', 'sc'):
             pm =  open('file.txt', 'rU')
    elif species in ('human', 'hs'):
             pm =  open('file2.txt', 'rU')
         for line in pm:
             line = line.split()
             with open(fname, 'rU') as user:
                 for e in user:
                     e = e.split()
                     if e[0] in line:
                         print(line)


text:
Q: sort_index() function in Armadillo library gives wrong result I am trying to use the sort_index() function in the Armadillo C++ library (link here).
Here is my code:
#include <armadillo>
#include <iostream>
using namespace arma;
using namespace std;

int main()
{
    vec test = {2, 5, 1};
    test.print();
    sort_index(test).print();
    cout<<"===\n";
    sort_index(test, "descend").print();

    return 0;
}

And the result is:
2.0000
5.0000
1.0000
    2
    0
    1
===
    1
    0
    2

I think the descend order is correct but the ascend order is wrong. It seems just like a reflect version of descend order. Is this a bug? If two result are both correct, what does sort_index() actually do?

A: sort_index(test, "descend").print();
Will print in descending order (highest first).
sort_index(test, "ascend").print();
Prints in ascending order (smallest first, a reflection of descending order) This is used by default when the function is called.
What seems to be wrong with that? Check out the documentation for sort_index() here.

A: The result is correct. The function sort_index works as same as Python's numpy.argsort. It yields the indices of the original list to make a sorted list.
>>> import numpy as np
>>> x = np.array([2, 5, 1])
>>> idx = np.argsort(x); print(idx)
[2 0 1]
>>> x_sorted = x[idx]; print(x_sorted)
[1 2 5]


text:
Q: Перелистывание html (WebView) Как реализовать аналог gallery для изображений, где вместо изображений будет WebView?
В галерею не запихивается (или у меня не получилось) использование конструкции:
<HorizontalScrollView
        android:id="@+id/hS"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        >
        <LinearLayout
            android:id="@+id/lL"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content">
            <WebView
                android:id="@+id/wV1"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                 >
                </WebView>
            <WebView
                    android:id="@+id/wV2"
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    >
            </WebView>

            </LinearLayout>
        </HorizontalScrollView>

Не помогает, при открытии html. На экране ничего не отображается. Задача в том, чтобы перемещаться между двумя страницами путем перелистывания влево-вправо.

A: Как варианты предложу следующие примеры:

*

*Хорошая реализация с помощью ViewPager. Можно применить любые UI элементы. (коммент, как сделать наподобие Gallery).

*С того же хабра, реализация с помощью ViewFlipper. Также немного переработать и сделать с WebView.

*Ну и на всякий пара примеров: 1 и 2.