text:
Q: How do I prevent root access to my docker container I am working on hardening our docker images, which I already have a bit of a weak understanding of.  With that being said, the current step I am on is preventing the user from running the container as root.  To me, that says "when a user runs 'docker exec -it my-container bash', he shall be an unprivileged user" (correct me if I'm wrong).
When I start up my container via docker-compose, the start script that is run needs to be as root since it deals with importing certs and mounted files (created externally and seen through a volume mount).  After that is done, I would like the user to be 'appuser' for any future access.  This question seems to match pretty well what I'm looking for, but I am using docker-compose, not docker run: How to disable the root access of a docker container?
This seems to be relevant, as the startup command differs from let's say tomcat.  We are running a Spring Boot application that we start up with a simple 'java -jar jarFile', and the image is built using maven's dockerfile-maven-plugin.  With that being said, should I be changing the user to an unprivileged user before running that, or still after?
I believe changing the user inside of the Dockerfile instead of the start script will do this... but then it will not run the start script as root, thus blowing up on calls that require root.  I had messed with using ENTRYPOINT as well, but could have been doing it wrong there.  Similarly, using "user:" in the yml file seemed to make the start.sh script run as that user instead of root, so that wasn't working.
Dockerfile:
FROM parent/image:latest

ENV APP_HOME                            /apphome
ENV APP_USER                            appuser
ENV APP_GROUP                           appgroup

# Folder containing our application, i.e. jar file, resources, and scripts.
# This comes from unpacking our maven dependency
ADD target/classes/app ${APP_HOME}/

# Primarily just our start script, but some others
ADD target/classes/scripts /scripts/

# Need to create a folder that will be used at runtime
RUN mkdir -p ${APP_HOME}/data && \
    chmod +x /scripts/*.sh && \
    chmod +x ${APP_HOME}/*.*

# Create unprivileged user
RUN groupadd -r ${APP_GROUP} && \
    useradd -g ${APP_GROUP} -d ${APP_HOME} -s /sbin/nologin  -c "Unprivileged User" ${APP_USER} && \
    chown -R ${APP_USER}:${APP_GROUP} ${APP_HOME}

WORKDIR $APP_HOME

EXPOSE 8443

CMD /opt/scripts/start.sh

start.sh script:
#!/bin/bash

# setup SSL, modify java command, etc

# run our java application
java -jar "boot.jar"

# Switch users to always be unprivileged from here on out?
# Whatever "hardening" wants...  Should this be before starting our application?
exec su -s "/bin/bash" $APP_USER

app.yml file:
version: '3.3'

services:
  app:
    image: app_image:latest
    labels:
      c2core.docker.compose.display-name: My Application
      c2core.docker.compose.profiles: a_profile
    volumes:
      - "data_mount:/apphome/data"
      - "cert_mount:/certs"
    hostname: some-hostname
    domainname: some-domain
    ports:
    - "8243:8443"
    environment:
      - some_env_vars
    depends_on:
    - another-app
    networks:
      a_network:
        aliases:
          - some-network
networks:
  a_network:
    driver: bridge
volumes:
  data_mount:
  cert_mount:

docker-compose shell script:
docker-compose -f app.yml -f another-app.yml $@

What I would expect is that anyone trying to access the container internally will be doing so as appuser and not root.  The goal is to prevent someone from messing with things they shouldn't (i.e. docker itself).
What is happening is that the script will change users after the app has started (proven via an echo command), but it doesn't seem to be maintained.  If I exec into it, I'm still root.

A: As David mentions, once someone has access to the docker socket (either via API or with the docker CLI), that typically means they have root access to your host. It's trivial to use that access to run a privileged container with host namespaces and volume mounts that let the attacker do just about anything.
When you need to initialize a container with steps that run as root, I do recommend gosu over something like su since su was not designed for containers and will leave a process running as the root pid. Make sure that you exec the call to gosu and that will eliminate anything running as root. However, the user you start the container as is the same as the user used for docker exec, and since you need to start as root, your exec will run as root unless you override it with a -u flag.
There are additional steps you can take to lock down docker in general:

*

*Use user namespaces. These are defined on the entire daemon, require that you destroy all containers, and pull images again, since the uid mapping affects the storage of image layers. The user namespace offsets the uid's used by docker so that root inside the container is not root on the host, while inside the container you can still bind to low numbered ports and run administrative activities.

*Consider authz plugins. Open policy agent and Twistlock are two that I know of, though I don't know if either would allow you to restrict the user of a docker exec command. They likely require that you give users a certificate to connect to docker rather than giving them direct access to the docker socket since the socket doesn't have any user details included in API requests it receives.

*Consider rootless docker. This is still experimental, but since docker is not running as root, it has no access back to the host to perform root activities, mitigating many of the issues seen when containers are run as root.

A: You intrinsically can't prevent root-level access to your container.
Anyone who can run any Docker command at all can always run any of these three commands:
# Get a shell, as root, in a running container
docker exec -it -u 0 container_name /bin/sh

# Launch a new container, running a root shell, on some image
docker run --rm -it -u 0 --entrypoint /bin/sh image_name

# Get an interactive shell with unrestricted root access to the host
# filesystem (cd /host/var/lib/docker)
docker run --rm -it -v /:/host busybox /bin/sh

It is generally considered best practice to run your container as a non-root user, either with a USER directive in the Dockerfile or running something like gosu in an entrypoint script, like what you show.  You can't prevent root access, though, in the face of a privileged user who's sufficiently interested in getting it.

A: When the docker is normally run from one host, you can do some steps.
Make sure it is not run from another host by looking for a secret in a directory mounted from the accepted host.
Change the .bashrc of the users on the host, so that they will start running the docker as soon as they login. When your users needs to do other things on the host, give them an account without docker access and let them sudo to a special user with docker access (or use a startdocker script with a setuid flag).
Start the docker with a script that you made and hardened, something like startserver.
#!/bin/bash

settings() {
   # Add mount dirs. The homedir in the docker will be different from the one on the host.
   mountdirs="-v /mirrored_home:/home -v /etc/dockercheck:/etc/dockercheck:ro"
   usroptions="--user $(id -u):$(id -g) -v /etc/passwd:/etc/passwd:ro"
   usroptions="${usroptions} -v/etc/shadow:/etc/shadow:ro -v /etc/group:/etc/group:ro"
}

# call function that fills special variables
settings

image="my_image:latest"

docker run -ti --rm ${usroptions} ${mountdirs} -w $HOME --entrypoint=/bin/bash "${image}"

Adding a variable --env HOSTSERVER=${host} won't help hardening, on another server one can add --env HOSTSERVER=servername_that_will_be_checked.
When the user logins to the host, the startserver will be called and the docker started. After the call to the startserver add exit to the .bash_rc.

A: Not sure if this work but you can try.  Allow sudo access for user/group with limited execution command.  Sudo configuration only allow to execute docker-cli. Create a shell script by the name docker-cli with content that runs docker command, eg docker "$@".  In this file, check the argument and enforce user to provide switch --user or -u when executing exec or attach command of docker. Also make sure validate the user don't provide a switch saying -u root.  Eg
sudo docker-cli exec -it containerid sh (failed)

sudo docker-cli exec -u root ... (failed)

sudo docker-cli exec -u mysql ... (Passed)

You can even limit the docker command a user can run inside this shell script


text:
Q: PHP, CSV columns into separate arrays Basically, i want to make a system where a user can upload a CSV file and pick what columns they want to upload/process
I can do this fine by using fopen and foreach,
but since the number of the column may vary from CSV to CSV....
i can store the picked columns in an array, eg picked[]= "1,2,4";   //from 1,2,3,4 columns
comma separated or anyway i want.
but how can i use something like list(1,2,4) = explode("," , theData[]);
where i can load 1,2,4, in there dynamically, or even 1,2,3,4 and then i can ignore 3.

A: well the csv is sort of a 2 dimensional array as you got the row index and column index.
First you will have to split your line breaks (\n) to split everything in seperate rows. Then each row has to be seperated by comma. For the first row you will have the column names.
All this can easily be coded yourself...
Or you could use the fgetcsv function
Function gets explained on:
http://php.net/manual/en/function.fgetcsv.php

A: You can unset the columns you don't need from each row:
$theData = array(
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' )
    );
$picked = '1, 3, 5';

$totalColumns = count( $theData[0] );
$columns = explode( ',', $picked );
foreach( $theData as $k => &$thisData ) {
    for( $x = 1; $x < $totalColumns + 1; $x++ ) {
        if( ! in_array( $x, $columns ) ) {
            unset( $thisData[$x - 1] );
        }
    }
}

Watch out for the 0-index adjustments in the for loop and the unset - this is because you have used column numbers that are non 0-indexed in your example.

A: You could use array_intersect_key(): "returns an array containing all the entries of array1 which have keys that are present in all the arguments."
http://www.php.net/manual/en/function.array-intersect-key.php
So first you need to process the data line by line, e.g. to an array that looks like
$data[column] = array(entries):

Example:
$data = array(
  1 => array (
    entry1,
    entry2,
    etc
  ),
  2 => etc
);
Then you show the user which columns there are, the user selects the columns he likes to use, e.g.:
$selected = array(1,2,4);

Then do an intersect to get an array with the selected columns:
 $use = array_intersect_key($data, $selected);

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSInteger used in calculation, warning 'local declaration of '' hides instance' I am a beginner. And I was trying to transform arabic numbers to ordinal numbers by having the following class.
num is NSInteger, while, during the calculation, the warning pop out "local declaration of '' hides instance"
#import "ordinalNumberFormatter.h"

@implementation ordinalNumberFormatter

- (NSString*)ordinalNumberFormatter:(NSInteger)num
{
        NSString *ending;
        int ones = num % 10; //Warning came out
        int tens = floor(num / 10); //Warning came out
        tens = tens % 10;
        if(tens == 1){
            ending = @"th";
        }else {
            switch (ones) {
                case 1:
                    ending = @"st";
                    break;
                case 2:
                    ending = @"nd";
                    break;
                case 3:
                    ending = @"rd";
                    break;
                default:
                    ending = @"th";
                    break;
            }
        }
        return [NSString stringWithFormat:@"%d%@", (int)num, ending]; //Warning came out
    }
@end

A: Do you have a class variable called "num" as well?  The warning is just saying that you're using the local variable "num" defined in
- (NSString*)ordinalNumberFormatter:(NSInteger)num

And you might instead want to use the "num" defined as the class variable.  Maybe change the above "num" to another name and use that name in the method.  That'll clear it all up


text:
Q: Find date ranges in one table that do not overlap date ranges in second table I have two tables that each has two date fields - fromdate and todate. Using SQL Server, I need to find all of the rows from table1 that their from-to date range does not overlap the date ranges in table2. I am currently using the following
Select fromdate,
       todate
from table1
Where not exists
    (select fromdate,
            todate
     from table2
     where table1.todate > table2.fromdate
       and table1.fromdate < table2.todate)

However this is very slow (this is only a simplified example). Is there a better way such as using joins or CTE?


text:
Q: Using Page Objects vs Config Files in Selenium I've been using Ruby Selenium-Webdriver for one of the automation scripts I'm developing and I'm being asked to use Page Objects, we use page objects a lot however for this application I am using CSV file instead, I have defined all the xpaths that I'm using in my application in a CSV file and I'm parsing that CSV file in my script to refer to those objects, I would like to know is there much of a difference in using a class for defining Page Objects or using a CSV file instead apart from performance concern? I believe using a CSV file will be an addon for us from configuration standpoint and will make it much easier to maintain, any suggestions on this?
Edit - In our use case, we're actually automating applications built on a cloud based tool, so basically all the applications share same design structure from HTML standpoint so we define xpath patterns in CSV and then we pass certain parameters to some custom methods that we've developed to generate xpath's automatically using the CSV instead of finding those manually as its overhead for us because we already know that all the applications will share similar xpath pattern for all elements.
Thanks

A: I think, POM is better than CSV approach. In POM, you put elements for a page in a separate class file. So, if any change is to make then it's easier to find where to change/maintain. Moreover, it won't get too messy as CSV file and you don't need to use extra utility function to parse those.

A: There is also a pageobjects gem that provides a set of libraries over and above webdriver/watir, simplifying the code.
Plus, why xpaths? Its one of the last recommended ways to identify an element.
As for the frameork aspect, csv should be more of a maintenance problem than PageObjects. Its the basic difference between text and code. You enforce Object oriented approach on your elements in PageObjects but that is not possible with csv.
In the best case scenario, you have created a column/separate sheets defining which page that element xpath belongs to. That sounds like an overhead. As your application / suite grows there can be thousands of elements. Imagine parsing/ manually updating a csv with that kind of data.
Instead in PageObjects, your elements will be restricted to the Page. Any changes to the app will also specify which elements may get impacted. Now, when define your element as an object in PageObject, rather than css, you also dont need to explicitly create your elements by reading the csv.

A: It completely depends on the application and the type of test you might perform.
Since it is an automated test script, you do not have to really worry about the performance of the script (it might take few more milli seconds to parse, which should be OK).
Maintaining all the elements identification properties & corresponding actions in a CSV file will make the maintenance easier and make the framework application independent which are nice. But maintaining your framework is bit difficult to make it more robust. Both approaches have its own pros and cons.
Refer to below posts [examples are in java - but you will get the idea]:

*

*Keyword driven framework

*Advanced Page Objects
Update:
If you like both, you can comeup with your implementation to easily integrate these too.
@ObjectRepository(src="/login.csv")
public class LoginPage{

    private Map<String, WebElement> elements;

    public void login(){
        elements.get("username").sendKeys('');
        elements.get("password").sendKeys('');
        elements.get("signin").click();
    }
}

Ie, define all the elements in a config file like csv/json etc. Let the page object refer to the class for the page elements. All the methods will be part of the page class.


text:
Q: Get current week, month and year records using SQL I have a table having a column which has values like 2017-08-21
See the screencast here.
Now I need to get the values of current week, current month and current year.
How can I achieve this?

A: Current week :
SELECT *
FROM  your_table
WHERE YEARWEEK(`your_date`) = YEARWEEK(CURDATE())

Current month
SELECT *
FROM  your_table
WHERE YEAR(`your_date`) = YEAR(CURDATE())
  AND MONTH(`your_date`) = MONTH(CURDATE())

Current year
SELECT *
FROM  your_table
WHERE YEAR(`your_date`) = YEAR(CURDATE())

A: To select all records in current year
Select *
FROM `table_name`
WHERE YEAR('hit_date') = YEAR(CURDATE());

To select all records in current month
Select *
FROM `table_name`
WHERE MONTH('hit_date') = MONTH(CURDATE())
AND YEAR('hit_date') = YEAR(CURDATE());

To select all records in current week
Select *
FROM `table_name`
WHERE YEARWEEK('hit_date') = YEARWEEK(CURDATE());

Please note regarding YEARWEEK you can specify your week start day depend on mode ( second parameter ) please have a look MySQL YEARWEEK() Function


text:
Q: Mozilla FireFox Addons -> Include external library in main.js I need to import/include a javascript file in my main.js in my FireFox Addon, but as the main.js does not contain a "document" I can not insert it the normal/easy way.
I've tried some stuff but never got it working.
Here is what I exactly want to accomplish:
I use an external timezone detection script (https://bitbucket.org/pellepim/jstimezonedetect/overview). I need to determine the timezone in the main.js to download the Google Calendar File + convert the times to the users timezone. This can not be done later! Until now I just inserted the code manually into the file (copy+paste), but this is not a very nice and clear way of doing this.

A: You would need to create a CommonJS module. Add your .js file inside the addon's lib folder and export all functions that you will be needing via the "exports" directive. Once you do that, you can use the exported functions via the "require" directive.
For example in the module that you will be reusing, you can put:
// REUSABLE MODULE
exports.somefunction = somefunction;

function somefunction() {
    doSomething();
 }

And then in the module that will be using this:
var othermodule = require("reusable_module");
othermodule.somefunction();

Here is the relevant documentation: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/guides/modules.html

A: 2020 update:
As i encountered it myself and as require seems not to work
this does seem to work: (ES6 style import)
Inside the manifest replace the "script" with "page" like this -
"background": {
    "page": "background.html"
  }

create a  background.html file and add
<script type="module" src='./background.js'></script>

now inside your js file you can use other files using ES6 import
import * as [name] from "[location]"


text:
Q: How to verify installed spaCy version? I have installed spaCy with python for my NLP project.
I have installed that using pip.  How can I verify installed spaCy version?
using
pip install -U spacy

What is command to verify installed spaCy version?

A: Use command - python -m spacy info to check spacy version

A: If you ask yourself: How to find any Python pkg version?
This one should be used/ as well, not only for Spacy ofc:
The easiest (if you installed it using pip):
pip show spacy #pip3 if you installed it using pip3

Or:
python -m spacy --version

Or... just run python (with the version that you installed Spacy on) and use the version method
If you want to know the version of any Python pkg (package) you are working with this would work for you every time!
run:
python
>> import spacy
>> print(spacy.__version__)

Or, Either:
python -m spacy --version

or
python3 -m spacy --version #depends where it is install (python or python3)

A: You can also do python -m spacy info. If you're updating an existing installation, you might want to run python -m spacy validate, to check that the models you already have are compatible with the version you just installed.

A: If you installed with pip you can try to find it with pip list and get version info with pip show <name>

A: If you are using python3, you can use your package manager (pip) pip3 list and find spacy's version.
For Python 2.7+ pip list does the job

A:
Simply use !python -m spacy info to get details on Jupyter notebook, remove ! for normal python command check.
Check the above screenshot to see the result details.
Thanks

A: Another way to get versions of Spacy and the dependencies is to use: pip freeze requirements.txt. See this link for the official documentation for both Mac and Windows OSs.
The main benefit I find with this approach is that you get a list of all dependencies plus the versions. Libraries are often times very picky about the versions. Using this method you can just share the requirements.txt with your collaborators and then they are good to go too :)
Edit:
Thanks to hc_dev for the valuable comment.

A: Ways to find the spacy version installed:

*

*pip show spacy

*python -m spacy info

*python -m spacy validate
Below find how the output will be:
pip show spacy

Name: spacy
Version: 3.4.2
Summary: Industrial-strength Natural Language Processing (NLP) in Python
Home-page: https://spacy.io
Author: Explosion
Author-email: contact@explosion.ai
License: MIT
Location: c:\users\shraddha.shetty\appdata\local\programs\python\python310\lib\site-packages
Requires: catalogue, cymem, jinja2, langcodes, murmurhash, numpy, packaging, pathy, preshed, pydantic, requests, setuptools, spacy-legacy, spacy-loggers, srsly, thinc, tqdm, typer, wasabi
Required-by: en-core-web-sm, pyresparser

python -m spacy info

============================== Info about spaCy ==============================

spaCy version    3.4.2
Location         C:\Users\shraddha.shetty\AppData\Local\Programs\Python\Python310\lib\site-packages\spacy
Platform         Windows-10-10.0.19044-SP0
Python version   3.10.5
Pipelines        en_core_web_sm (3.4.1)

C:\Users\shraddha.shetty>python -m spacy validate
    ✔ Loaded compatibility table

    ================= Installed pipeline packages (spaCy v3.4.3) =================
    ℹ spaCy installation:
    C:\Users\shraddha.shetty\AppData\Local\Programs\Python\Python310\lib\site-packages\spacy

    NAME             SPACY            VERSION
    en_core_web_sm   >=3.4.0,<3.5.0   3.4.1     ✔


text:
Q: JEST STYLED COMPONENTS - toHaveStyleRule didn't find property I'm trying to test my styled components.
Therefore i installed jest-styled-components.
I wanted to test, if my component change the opacity after click.
I tried it with toHaveStyleRule. But it says:
Property not found: "opacity"

So here is my styled component:
const ClueAnswer = styled.h3`
  transition: opacity 1s;
  transition-timing-function: ${props => props.reveal ? 'ease-out' : 'ease-in' };
  opacity: ${props => props.reveal ? 1 : 0};
  cursor: pointer;
`;
ClueAnswer.displayName = 'ClueAnswer';
export { ClueAnswer };

And I'm importing it here:
// Vendor
import React, { Component } from 'react';
// Styled Components
import {
  ClueAnswer,
  ClueWrapper
} from '../style/general';

class Clue extends Component {
  constructor(props) {
    super(props);

    this.state = {
      reveal: false
    };
  }

  render() {
    const { clue } = this.props;

    return (
      <ClueWrapper>

Difficulty: { clue.value }

{ clue.question }

        <ClueAnswer
          reveal={ this.state.reveal }
          onClick={ () => this.setState(prevState => { return { reveal: !prevState.reveal } }) }>{ clue.answer }</ClueAnswer>
      </ClueWrapper>
    );
  }
}

export default Clue;

My setupTest.js file looks like this:
// Polyfill
import raf from './polyfill';
// Vendor
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-styled-components';

configure({ adapter: new Adapter() });

And finally my test file:
// Vendor
import React from 'react';
import { shallow } from 'enzyme';
// Component
import Clue from './clue';
// Fixtures
import { clue } from '../data/fixtures';

const props = { clue };

describe('Clue Component', () => {
  const clueWrapper = shallow(<Clue { ...props } />);

  describe('and behavior on click', () => {
    const ClueAnswer = clueWrapper.find('ClueAnswer');
    const revealBeforeClick = clueWrapper.state('reveal');
    let revealAfterClick;

    beforeAll(() => {
      ClueAnswer.simulate('click');
      revealAfterClick = clueWrapper.state('reveal');
    });

    it('toggles reveal state on click', () => {
      expect(revealBeforeClick).not.toBe(revealAfterClick);
    });

    it('changes the opacity on click', () => {
      console.log(clueWrapper.debug());
      console.log(ClueAnswer.props());
      expect(ClueAnswer).toHaveStyleRule('opacity', 1);
    });
  });
});

The debug of clueWrapper.debug() looks like this:

I expected from toHaveStyleRule to get the current value of opacity, but instead i got the described problem.
Anyone have a hint?
Best regards

A: The problem is that ClueAnswer not really rendered when the parent component is rendered just using shallow. Using mount instead should also force ClueAnswer to be rendered


text:
Q: jQuery on a .php file not working on mobile (iOS and Android) but works perfect on computer I have a very interesting problem. I recently created a simple one page static website (.html) based on Bootstrap with some jQuery in it, and is working perfectly on localhost (xampp) and live server (PC and mobiles).
I then added a .php file to the site, which is similar to the html page, but has a script in it. After uploading, everything is fine except on mobile browsers; jQuery doesn't work. The html file working perfect, the php doesn't work. I tried opening in Chrome-Android, Samsung Internet-Android and a Safari-iOS; all not working. I downloaded the .min.js jQuery and Bootstrap files and linked them, not working. Changed CDNs, not working. Changed
$(document).ready(function(){...

to
$(function(){...

you guessed it, not working.
Every time I change, I make sure it is working well on localhost and on PC but on mobiles it wont.
Any help regarding this issue? I'm banging my head on the desk!
My link tags:
<meta http-equiv="Cache-control" content="no-transform" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Sacramento" rel="stylesheet">

My current jQuery:
<script>
    $(function() {
        $("html,window").stop().scrollTop(0);
        $("#mainmenu").stop().fadeIn(0);
        $("#scrollup").stop().fadeOut(0);
        $(window).scroll(function() {
            if ($(this).scrollTop() > ($("#about").position().top + $("#about").height()) / 2) {
                $("#mainmenu").stop().fadeTo('300', 0.5);
                $("#scrollup").stop().fadeTo(0, 1);
            } else {
                $("#mainmenu").stop().fadeTo('300', 1);
                $("#scrollup").stop().fadeTo(0, 0);
            }
        });
        $("#scrollup").click(function() {
            $("html,window").stop().animate({
                scrollTop: 0
            }, 1000, 'swing');
        });
        $("#readmore").click(function() {
            $("html,window").stop().animate({
                scrollTop: $("#projects").position().top
            }, 1000, 'swing');
        });
    });

</script>

I'm using the free plan of 000webhost.com, which I do primarily for testing purposes.
edit: My php script is a simple include() function, and is working without any problems on all devices.
Edit2: After investigating further, I found that the fading in and out functions are working quite well. The functions with scrollTop() are the ones having problems.

A: After a lot of research, head banging and decrease in my lifespan, I found that the problem is not in jQuery itself but rather with specific functions. I noticed that the fadeIn, fadeOut and fadeTo functions work properly, but scrollTop related functions and Bootstrap jQuery weren't working. The fix to scrollTop, referencing this old SO question, was to set overflow to hidden on body and html tags before scrolling, then resetting it. So basically:
CSS:
.fix{
         overflow, overflow-x, overflow-y:hidden; !important
    }

jQuery:
$("body,html").addClass("fix").animate/scrollTop(...).removeClass("fix");

After checking it works on all mobile browsers I have access to. Still though, Bootstrap navbar collapse scripts are not working on mobile browsers, and I am yet to find a solution for it.
UPDATE
After further head banging, I found out that I loaded Bootstrap .css and .js BEFORE loading jQuery:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

A simple trivial and logical change of loading jQuery BEFORE Bootstrap solved all my issues, obviously due to BS scripts using jQuery which must be already loaded:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

Along with the mobile fix for scrolling functions, these 2 solutions fixed all my issues I had on mobile devices.


text:
Q: cannot unpack non-iterable int obj while using get_object_or_404 I'm a new programmer attempting to put in a "submit comment" page in my project using a generic CreateView. The page displays properly when it first loads, but after clicking the form's "submit" button, I get a "TypeError at /blog/blog/4/create   -  cannot unpack non-iterable int object."
Here is the generic view in question:
class BlogCommentCreate(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'blog/comment_create_form.html'
    fields = ['content',]

    def get_context_data(self, **kwargs):
        context = super(BlogCommentCreate, self).get_context_data(**kwargs)
        context['blogpost'] = get_object_or_404(BlogPost, pk = self.kwargs['pk'])
        return context

    def form_valid(self, form):
        form.instance.comment_author = self.request.user
        form.instance.blogpost = get_object_or_404(BlogPost, self.kwargs['pk'])
        return super(BlogCommentCreate, self).form_valid(form)

    def get_success_url(self):
        return reverse('blogpost-detail', kwargs={'pk': self.kwargs['pk'],})

Here are the relevant url patterns. "comment_create" is the create page that is giving me issues with form submission, and "blogpost-detail" is where I'm trying to redirect to:
urlpatterns = [
    path('blog/<int:pk>', views.BlogPostDetailView.as_view(), name='blogpost-detail'),
    path('blog/<int:pk>/create', views.BlogCommentCreate.as_view(), name='comment_create')
]

And finally, here is the comment model:
class Comment(models.Model):
    date_created = models.DateField(blank=False, default = date.today)
    content = models.TextField(max_length=200)
    comment_author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    blogpost = models.ForeignKey('BlogPost', on_delete=models.CASCADE)

    def __str__(self):
        return self.content

Things I have tried:
1. Renaming parameters in my get_object_or_404 call that might overlap with built-in django keywords (as suggested in another thread here)
2. Renaming model fields and playing with capitalization in the views. Ran makemigrations before and after this step
3. (After trying 1 and 2) Wiping and recreating my blogpost objects
4. Getting rid of the parameters in super(), as it seems like they might not be necessary?
The only thing that the error text makes me think of is that the context might be receiving **kwargs as a list instead of a bunch of individual parameters. But I don't know enough about the get_context_data or form_valid methods to fix this, as I am just going off of the Django docs and code snippets I found.

A: You should specify the pk in get_object_or_404 as a named parameter:
form.instance.blogpost = get_object_or_404(BlogPost, pk=self.kwargs['pk'])
or perhaps it is simpler, to just pas the primary key as blogpost_id:
form.instance.blogpost_id = self.kwargs['pk']
You can pass positional parameters to get_object_or_404, but these are Q objects [Django-doc], for example to do more sophisticated filtering.


text:
Q: This is not work Flask Rq Queue with SqlAlchemy database table I Have a Flask project. Process are work normal. Database is PostgreSql. Everything is working on this Database. But when I Can use Python Rq I dont reach tables with SqlAlchemy. My project is on heroku. How can i solve this problem.
Note:( queuing operations are working normally except database)
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

import os
import redis
from rq import Queue
from worker import conn
#from models import User, Processed, Wallet,LogsRecord

# init SQLAlchemy so we can use it later in our models
db = SQLAlchemy()
q = Queue(connection=conn)

def create_app():
    app = Flask(__name__) # creates the Flask instance, __name__ is the name of the current Python module

    app.config['SECRET_KEY'] = '****' # it is used by Flask and extensions to keep data safe
    #app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' #it is the path where the SQLite database file will be saved

    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****@e****.compute**.m**.com:5432/**'

    #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:*****' #local

    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # deactivate Flask-SQLAlchemy track modifications

    db.init_app(app) # Initialiaze sqlite database

    # The login manager contains the code that lets your application and Flask-Login work together
    login_manager = LoginManager() # Create a Login Manager instance
    login_manager.login_view = 'auth.login' # define the redirection path when login required and we attempt to access without being logged in
    login_manager.init_app(app) # configure it for login
    from models import User
    @login_manager.user_loader
    def load_user(user_id): #reload user object from the user ID stored in the session
        # since the user_id is just the primary key of our user table, use it in the query for the user
        return User.query.get(int(user_id))
    # blueprint for auth routes in our app
    # blueprint allow you to orgnize your flask app
    from auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)
    # blueprint for non-auth parts of app
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    app.register_blueprint()

    return app

Worker.py
import os

import redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']

redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')

conn = redis.from_url(redis_url)

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

Main.py
@main.route('/test') # profile page that return 'profile'
def test():

    if request.args.get("n"):

        job= q.enqueue(background_task, request.args.get("n"))

    return render_template('test.html',veri=job.get_id)

def background_task(n):

    user_check = User.query.get(1)
    if(user_check):
        n=int(n)
        email=user_check.email
        start = time.time()
        for i in range(n):
            print("sayı sayıyor:",i," Kul:",email)
            time.sleep(1)
        end = time.time()
        sure = (end-start)
    return f"Son Sayı {n} İşlem şu kadar sürdü {sure}"

bash (heroku logs --tail) code Error result
2021-07-08T22:09:07.034922+00:00 app[worker.1]: 22:09:07 Traceback (most recent call last):
2021-07-08T22:09:07.034947+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1008, in __call__
2021-07-08T22:09:07.034949+00:00 app[worker.1]: return self.registry[key]
2021-07-08T22:09:07.034949+00:00 app[worker.1]: KeyError: <greenlet.greenlet object at 0x7f60ec8853b0 (otid=0x7f60ec890f80) current active started main>
2021-07-08T22:09:07.034951+00:00 app[worker.1]:
2021-07-08T22:09:07.034952+00:00 app[worker.1]: During handling of the above exception, another exception occurred:
2021-07-08T22:09:07.034952+00:00 app[worker.1]:
2021-07-08T22:09:07.034952+00:00 app[worker.1]: Traceback (most recent call last):
2021-07-08T22:09:07.034953+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/worker.py", line 1031, in perform_job
2021-07-08T22:09:07.034953+00:00 app[worker.1]: rv = job.perform()
2021-07-08T22:09:07.034954+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/job.py", line 749, in perform
2021-07-08T22:09:07.034955+00:00 app[worker.1]: self._result = self._execute()
2021-07-08T22:09:07.034955+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/job.py", line 772, in _execute
2021-07-08T22:09:07.034956+00:00 app[worker.1]: result = self.func(*self.args, **self.kwargs)
2021-07-08T22:09:07.034957+00:00 app[worker.1]: File "/app/main.py", line 43, in background_task
2021-07-08T22:09:07.034957+00:00 app[worker.1]: user_check = User.query.get(1)
2021-07-08T22:09:07.034958+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 552, in __get__
2021-07-08T22:09:07.034958+00:00 app[worker.1]: return type.query_class(mapper, session=self.sa.session())
2021-07-08T22:09:07.034959+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 129, in __call__
2021-07-08T22:09:07.034959+00:00 app[worker.1]: return self.registry()
2021-07-08T22:09:07.034960+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1010, in __call__
2021-07-08T22:09:07.034960+00:00 app[worker.1]: return self.registry.setdefault(key, self.createfunc())
2021-07-08T22:09:07.034961+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 4089, in
__call__
2021-07-08T22:09:07.034961+00:00 app[worker.1]: return self.class_(**local_kw)
2021-07-08T22:09:07.034961+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 174, in __init__
2021-07-08T22:09:07.034962+00:00 app[worker.1]: self.app = app = db.get_app()
2021-07-08T22:09:07.034962+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 1042,
in get_app
2021-07-08T22:09:07.034963+00:00 app[worker.1]: raise RuntimeError(
2021-07-08T22:09:07.034964+00:00 app[worker.1]: RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
2021-07-08T22:09:07.034964+00:00 app[worker.1]: Traceback (most recent call last):
2021-07-08T22:09:07.034965+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1008, in __call__
2021-07-08T22:09:07.034965+00:00 app[worker.1]: return self.registry[key]
2021-07-08T22:09:07.034965+00:00 app[worker.1]: KeyError: <greenlet.greenlet object at 0x7f60ec8853b0 (otid=0x7f60ec890f80) current active started main>
2021-07-08T22:09:07.034966+00:00 app[worker.1]:
2021-07-08T22:09:07.034966+00:00 app[worker.1]: During handling of the above exception, another exception occurred:
2021-07-08T22:09:07.034967+00:00 app[worker.1]:
2021-07-08T22:09:07.034967+00:00 app[worker.1]: Traceback (most recent call last):
2021-07-08T22:09:07.034967+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/worker.py", line 1031, in perform_job
2021-07-08T22:09:07.034968+00:00 app[worker.1]: rv = job.perform()
2021-07-08T22:09:07.034968+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/job.py", line 749, in perform
2021-07-08T22:09:07.034969+00:00 app[worker.1]: self._result = self._execute()
2021-07-08T22:09:07.034969+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/rq/job.py", line 772, in _execute
2021-07-08T22:09:07.034969+00:00 app[worker.1]: result = self.func(*self.args, **self.kwargs)
2021-07-08T22:09:07.034970+00:00 app[worker.1]: File "/app/main.py", line 43, in background_task
2021-07-08T22:09:07.034970+00:00 app[worker.1]: user_check = User.query.get(1)
2021-07-08T22:09:07.034971+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 552, in __get__
2021-07-08T22:09:07.034971+00:00 app[worker.1]: return type.query_class(mapper, session=self.sa.session())
2021-07-08T22:09:07.034972+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/scoping.py", line 129, in __call__
2021-07-08T22:09:07.034972+00:00 app[worker.1]: return self.registry()
2021-07-08T22:09:07.034972+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/util/_collections.py", line 1010, in __call__
2021-07-08T22:09:07.034973+00:00 app[worker.1]: return self.registry.setdefault(key, self.createfunc())
2021-07-08T22:09:07.034973+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/sqlalchemy/orm/session.py", line 4089, in
__call__
2021-07-08T22:09:07.034974+00:00 app[worker.1]: return self.class_(**local_kw)
2021-07-08T22:09:07.034974+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 174, in __init__
2021-07-08T22:09:07.034974+00:00 app[worker.1]: self.app = app = db.get_app()
2021-07-08T22:09:07.034981+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/flask_sqlalchemy/__init__.py", line 1042,
in get_app
2021-07-08T22:09:07.034982+00:00 app[worker.1]: raise RuntimeError(
2021-07-08T22:09:07.034982+00:00 app[worker.1]: RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

A: The error is not with redis or database. The error says

No application found. Either work inside a view function or push an application context
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that
needed to interface with the current application object in some way.
To solve this, set up an application context with app.app_context().

In your case you have to use
with app.app_context():
    user_check = User.query.get(1)
if(user_check):
    [...]

For this you need to import your app, In your case, It is main as I see the route \test so  you have to use main in place of app, with main.app_context():

A: I did this for solution. Note to history for those who get the same error :) magic code "app.app_context().push()"
app = create_app()
**app.app_context().push()**
if __name__ == '__main__':
    db.create_all(app=create_app())
    app.run(debug=True) # run the flask app on debug mode


text:
Q: Removing a duplicate JQuery library in wordpress I have a wordpress site which uses a plugin allowing the easy addition of popup windows from the click of a button. Was working fine but now I get an error each time the popup button is clicked. In addition to the error, the popup no longer appears. Instead the scroll bar disappears and the page freezes. It's as if an invisible popup has loaded.
I hit f12 and captured an error when the button was clicked:
Uncaught TypeError: f.getClientRects is not a function
at r.fn.init.offset (jquery-3.2.1.min.js?ver=4.8.2:4)
at Object.getWithinInfo (position.min.js?ver=1.11.4&nocache=1:11)
at r.fn.init.a.fn.position (position.min.js?ver=1.11.4&nocache=1:11)
at r.fn.init.reposition (site.min.js?defer&ver=1.6.6&nocache=1:1)
at r.fn.init.e.fn.popmake (site.min.js?defer&ver=1.6.6&nocache=1:1)
at r.fn.init.open (site.min.js?defer&ver=1.6.6&nocache=1:1)
at r.fn.init.e.fn.popmake (site.min.js?defer&ver=1.6.6&nocache=1:1)
at HTMLButtonElement.<anonymous> (site.min.js?defer&ver=1.6.6&nocache=1:2)
at HTMLDocument.dispatch (jquery-3.2.1.min.js?ver=4.8.2:3)
at HTMLDocument.q.handle (jquery-3.2.1.min.js?ver=4.8.2:3)

I believe the issue relates to duplicate JQuery libraries installed but I wonder if anyone could point me in the direction of how I can either remove the duplicate library in my wordpress installation or produce a work around?

A: I think you can remove this js https://code.jquery.com/jquery-3.2.1.min.js?ver=4.8.2.


text:
Q: How to get all the dependencies using NPM for your Angular Application i have installed NPM
also i had saved it as given in GITshowing the result after npm install
and i even installed gulp and when i checked its not been installedgulp error
**The template that i downloaded reads as follows : **

     to automaticaly populate bower styles dependencies -->

<!-- build:css({.tmp/serve,src}) styles/app.css -->
<!-- inject:css -->
<!-- css files will be automaticaly insert here -->

in the body section :
<!-- build:js(src) scripts/vendor.js -->
<!-- bower:js -->
<!-- run `gulp wiredep` to automaticaly populate bower script dependencies -->
<!-- endbower -->
<!-- endbuild -->

<!-- build:js({.tmp/serve,.tmp/partials,src}) scripts/app.js -->
<!-- inject:js -->
<!-- js files will be automaticaly insert here -->
<!-- endinject -->

<!-- inject:partials -->
<!-- angular templates will be automatically converted in js and inserted here -->
<!-- endinject -->
<!-- endbuild -->

and finally i tried cashing everything i supposed to be relevant in my localhost but again it failed to run.

A: It seems like you forgot to initialize your working directory: npm init.
Do the same for bower.
When you install a package with npm you can pass --save or --save-dev as parameters so npm will track the name and the version of the package in the package.json file.This allow to any one who clone your repo to run npm install and get all the packages been listed on the package.json file. If you want to use bower then you need to install it with npm install bower --save-dev and then install packages the same way as with npm. e.g: bower install jquery -S. So bower will track the dependencies of your project on a bower.json file. It is posible to add a preinstall and postinstall key on the scripts section of the package.json file so npm will run the those commands before of after installing your dependencies:
//package.json
{
  "scripts": {
    "postinstall": "bower install"
  }
}

To replace the scripts and links styles you'll need to create a task on your gulp file


text:
Q: XRDP stopped working! All of a sudden when I try to login I get this message:
xrdp_mm_processes_login:login failed

Anyone know how to fix this?
It's been working for months without any issues.. Then tonight I had a power outage and now this morning this happens..
Using Ubuntu Desktop 14.04

A: Basic troubleshooting would be...

*

*restart xrdp service ?

*restart the computer completely ?

If this is still failing, maybe you have a orphaned "X session". To check this, perform the following actions
in terminal console, type the following

*

*cd /tmp/.X11-unix

*ls -l

if you see a session associated with your name, delete that session
Restart xrdp and try again
If this is not fixing your issue, then try the following,
in Terminal console, type
vncserver
if you have a message like
Warning: Head-Node:1 is taken because of /tmp/.X11-unix/X1
Remove this file....
you have an orphaned X session and you need to delete the file....
Say yes on the screen...
Hope this help
Till next time
See ya


text:
Q: Flex: Impossible to resize the external loaded SWF's content I have an application where I try to load an external SWF. So, we have:

*

*My application: The Stage's dimensions are 768x1280. ScaleMode = EXACT_FIT.

*External SWF: It's another application where its stage is: 800x600. ScaleMode = EXACT_FIT.

The problem is that the external SWF does not modify its size although I apply "scaleX, scaleY", change its width and so on.
I also tried to insert it into a Canvas container (as "How to resize an external SWF to fit into a container?" ) but it didn't solve my problem.
The interesting piece of code is when the external SWF is loaded by my application:
private function onLoadedApp( evt:Event ):void{
     stage.scaleMode = StageScaleMode.EXACT_FIT;
     trace("Loading Application..");
     var loaderInfo:LoaderInfo = evt.target as LoaderInfo;
     loaderInfo.removeEventListener( Event.COMPLETE, onLoadedApp);
     trace(loaderInfo.loader.content);
     var swfApplication:SpriteUIComponent = new SpriteUIComponent(evt.target.loader.content );
     if( SWFContainer.width < swfApplication.explicitWidth ){
            var coef:Number = SWFContainer.width/swfApplication.explicitWidth;
            swfApplication.scaleX = coef;
            swfApplication.scaleY = swfApplication.scaleX;
      }
       SWFContainer.addElement(swfApplication);
}

I also tried to do it through SWFLoader, but the external.swf's content doesn't change its original size although I add the "scaleContent" parameter.
Visual results I got:
The external SWF is loaded on the suitable position and it "seems" to have 320x240 dim. But its width is a bit cropped, since if I stretch the Flash Player I achieve to see the rest of the external swf's stage. Besides, the external SWF never is resized although I shrink/stretch the Flash Player. It always remains fixed (if I trace its dimensions, I always get 800x600, although I visually see 320x240)- If I increase the stage's width of the main application, this little clip dissapear.
Discussion:
I know the original Stage's dimensions are 800, and this is greater than the original stage of my application (768), but I think, when I do the resizing, external SWF's Stage have to be fitted in the container. It is fitted, but a part of the external SWF is not seen. It's like Flash Player remembered that the external SWF Stage's width were greater than my application's one...
Thanks in advance.

A: Even with scaleContent set to "true" you still need to set an exact height and width to the SWFLoader control for it to even try resizing the internal SWF.  All scaleContent does is instead of showing the SWF at regular or stretched sizes, it also up-scales the SWF if needed, and if not just scales it to retain the ratio of the original SWF.

A: I don't think the issue is with your ScaleMode. There can only be one Stage per flash player. The "stage" property of your 'external' SWF references the Stage of your 'application' SWF after it's added to the display list. If the SWF is loaded and not added to the display list, the loaded SWF's 'stage' property will equal 'null'. Setting the stage scaleMode inside your external SWF won't dictate how it scales once loaded into another SWF.
Also, you're probably resizing the SWFContainer, not the SWF itself...thats why the SWF width and height properties are always 800x600. I'm not sure if this is what you're asking for, but from what I'm understanding, you may need to create a stage resize event listener.

A: Have you tried to use a scale effect on "External SWF"?
Scale Effect


text:
Q: ruby and gem how do i roll them back or can i downgrade? i am working a project that has been giving me a headache on my desktop PC, im using Aptana Studio 3 Workspace. and i tried to run 'rake db:migrate' and gives me this:
    rake aborted!
    LoadError: cannot load such file -- sqlite3/sqlite3_native
    LoadError: cannot load such file -- sqlite3/2.1/sqlite3_native
now, i tried somethings and nothing worked other people in my course havent seen this so i pushed what i had to github and pulled to my laptop and i ran the same command and it worked. i noticed that GEM version on my laptop was 2.0.15 and ruby version was 2.0.0p598. my desktop is running GEM v2.2.2 and ruby version 2.1.5p273. i have a hunch this is the issue. can i rollback so that my desktop is using the same versions as my latop ?

A: You need to first specify the gem version you want to install on your Gemfile.
gem "foo", "~> 0.3.4"

Then run bundle update foo
Then run git diff Gemfile.lock
To see what was changed.


text:
Q: How to add a WHERE condition in a Lucene query I have the following code for searching a "Keyword" in the student_table using Lucene query.
public List search(String search, LONG studentCity) {
   FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
   QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Spot.class).get();
   Query luceneQuery = qb.keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1).onFields("name", "description", "address").matching(search).createQuery();

I got all the rows in the student_table that contain the "Keyword", but I need to add a condition such:" where student_table.city_id= studentCity"
So I can restrict the result of the query by the City Id.
Thank you.

A: To add the city_id=studentCity contition, you're going to need a TermQuery (and the appropiate field type when you index your document)
After that you'll have to wrap your fuzzy query and the TermQuery in a BooleanQuery with both occurrence conditions set to MUST.
That'll be the query you pass to your IndexReader / IndexSearcher.
Hope that helps!


text:
Q: How do I get Slick carousel to work? I know this has been asked a lot but I've read through loads of other threads related to Slick yet none of the suggested fixes seem to be working for me.
I've followed the instructions on http://kenwheeler.github.io/slick/ but am just left with a page that has three images stacked on top of each other and doesn't remotely resemble a carousel. I have a feeling that it's because I haven't added anything to my main css stylesheet but have no idea how I'm supposed to style it to turn it from three static images into a carousel!  Does anyone have any ideas? The code from the html page is below. Does anyone know what I need to do to the 'fade' div class in order to get it working? Or is not a stylesheet issue?
Any help would be massively appreciated. Thank you!
<!doctype html>

    <meta charset="utf-8">
    <title>Title will go here</title>
    <meta name="description" content="Description">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="shortcut icon" href="favicon.ico" />
    <link rel="stylesheet" type="text/css" href="slick/slick.css" />

    <link rel="stylesheet" type="text/css" href="slick/slick-theme.css" />

A: Load your page and 'View Source', try to see if any of your  files or  stylescripts are missing. Just click on the links and see if it brings you to the source files.
If you're missing any of them that explains your problem. You can try what Samar mentioned.
If all the files are present and linked, check your JavaScript console and if there are any errors, maybe that would be a hint to your problem. Otherwise, I can't find anything glaring in your markup.


text:
Q: How does stackoverflow code the comments to work that way? I'd like to create a feature similar to what stackoverflow does for comments on this site.  Essentially allow the person who wants to post a line of text, to write it in, hit submit, and immediately see if posted on the page without having to leave the page.
Must be ajax, but Im curious how I might do this with javascript - or by using jquery, or by using...
Any thoughts?  Feel free to comment here to see how it works

A: You are correct. Take a look at a complete tutorial here:

*

*http://net.tutsplus.com/tutorials/php/asynchronous-comments-with-jquery-and-json/
Go to the Javascript part to see how it's done on the client side.

A: SO definitely does use jquery, whether or not that effect is a direct result of it I don't know
this looks like it might be useful (just in reverse)
http://davidwalsh.name/animated-ajax-jquery

A: I'm not sure it is implemented like this but there is a simple way:
1) User fills the comment textbox and hits "Publish" button
2) A javascript function updates the User HTML with the new comment so a refresh is not needed
3) A javascript function makes an AJAX request so the database is also updated
Simple like that :)

A: I don't know exactly how stackoverflow does it, but here is a pretty simple way.

*

*When you generate your question/answer level entries, tag them with an attribute (maybe _postId="..." or something).

*Have a comment box that expands into view or whatever you choose, and a container to hold comments in. Give these things so that you can find them in the DOM using a combination of the post ID and the class name.

*When submitted, send an XML HTTP Request (XHR). Let's say for simplicity (you'll need to make it more secure) that the XHR sends the user ID, post ID that's being commented on, and the text body.

*Have the server respond with confirmation when the request is complete. Now you can create the comment HTML with Javascript and append it to your comments container for the appropriate box.

A: This is simple ajax stuff.
Juste see there :

*

*Ajax tutorial

*Ajax example


text:
Q: when I try my lambda by assuming role tried to access s3 bucket in different account. I get GetObject operation: Access Denied I have a question regarding how s3 and roles work across accounts.
I have a situation where I have a lambda function with a role in account A and a bucket in account B that the lambda function needs to access. The role from account A has s3:* permissions on the bucket in account B. We set the principal on the bucket in account B to accept the role from account A. The bucket policy also allows s3:* on the bucket. Something like below.
Account A Role:
{
    "Action": [
        "s3:*"
    ],
    "Resource": [
        "arn:aws:s3:::bucket/*",
        "arn:aws:s3:::bucket"
    ],
    "Effect": "Allow"
}

Account B Bucket Policy:
{
    "Effect": "Allow",
    "Principal": {
        "AWS": "arn:aws:iam::account:role/role"
    },
    "Action": "s3:*",
    "Resource": ["arn:aws:s3:::bucket/*","arn:aws:s3:::bucket"]
}

The problem we are running into is that the role in account A is able to do all LIST actions on the bucket in account B, but when we try any GET actions we get access denied. Which doesn't make sense because we have s3:* permissions on both sides.
Is there something that we missed in the setup of the bucket or IAM policy that would get this working as we expect? We tried an assume role with the same policy as the role in account A , but in account B and had no issues with LIST or GET actions on the bucket in account B. So there is a work around, but we would like to see if we can get the original setup working.
This is the error message I am getting.
botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

A: Here is the response I got from AWS....
In s3, we have Bucket Owner who owns the bucket and Object Owner who owns the object. Unless the Object Owner grants permission to the object no one apart from the Object owner has access to it. As bucket owner or anyone who has been granted permission to the bucket can LIST the bucket, but read / write operations would result into 403 Access Denied for the objects.
An object owner could grant permissions to the bucket owner using --acl bucket-owner-full-control which is what I see for this S3 object in question.
When you objects NOT owned by the bucket owner, bucket policies do not inherit. In such case, the bucket owner  may copy over the object to gain the ownership. Once this is done, Account C or X which are granted access by the Bucket Policy would have access to the object.
Here is my work around for that. Create a role "XXX" in Account B. And grant access to read from s3 bucket in account B.
import boto3
sts_client = boto3.client('sts')
assumed_role_object = sts_client.assume_role(
        RoleArn="<ARN of role XXX>",
        RoleSessionName="AssumeRoleSession1"
    )
# From the response that contains the assumed role, get the temporary
# credentials that can be used to make subsequent API calls

credentials = assumed_role_object['Credentials']
s3_client = boto3.client(
    service_name='s3',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken']
)
response = s3_client.get_object(Bucket=self.bucket, Key=file_name)
file_content = response['Body'].read().decode('utf-8')


text:
Q: MFMailComposeViewController change to recipients Hi I would like to enable the user to send e-mail to different e-mail address it depends on the bout ton selected in the table view - All from same view.
My problem is changing the e-mail address of the recipient each time i tried a few things like putting the e-mail address in a String which updates depending on the bout ton pressed but i was not able to get the e-mail address to the to: Tab in the composer.
I am able to fix a spesific e-mail address but i want the to: tab to change each time it is a different recipient.
Any help would be appreciated -
My current code which returns blank e-mail address is below.
(Mail is my String receiving the correct e-mail address each time).
-(void)displayComposerSheet
{
    MFMailComposeViewController *mailComposerVC = [[MFMailComposeViewController alloc] init];
    mailComposerVC.mailComposeDelegate = self;

    [mailComposerVC setSubject:@"Iphone App"];

    NSArray *toRecipients = [NSArray arrayWithContentsOfFile:mail];

    [mailComposerVC setToRecipients:toRecipients];

    NSString *BodyText = @"My Name Is:    \n My Phone Number Is:     \n Please Help With:    \n";
    [mailComposerVC setMessageBody:BodyText isHTML:NO];

    [self presentModalViewController:mailComposerVC animated:YES];
}

A: What is your toRecipients?
Why don't you just do:
NSString *email1 = @"Person1@gmail.com"

NSString *email2 = @"Person2@gmail.com"

//if logic
NSArray *toRecipients = [NSArray arrayWithObject:email1];
//if logic
NSArray *toRecipients = [NSArray arrayWithObject:email2];


text:
Q: Ruby ri file - Nothing known about File error I tried installing a gem first gem install rdoc-data
After it successfully installed, I tried rdoc-data --install However, I get the error:
Your ruby version 2.1.1 is not supported, only 1.8.7, 1.9.2, 1.9.3, 2.0.0
Does this mean I have to downgrade to Ruby 2.0.0?

I tried running ri File to read the documentation however all I get is the message: Nothing known about File.
Did some research into older Stack Overflow posts and someone suggested running rvm docs generate however all I get is "Currently 'rvm docs ...' does not work with non-rvm rubies.

A: Install ri documentation first:
rvm docs generate-ri

A: I used
gem install rdoc-data
gem rdoc --all --ri --no-rdoc

Don't forget to open a new terminal window, then ri "test" ri "if" etc should thereafter.
These commands came from here and here


text:
Q: Register with Geodatabase greyed out I'm having trouble registering a table with a Geodatabase in an SDE, the option is greyed out. This is a weekly task for me and I have never had this happen before.
I receive a new table weekly from our accounts department and have to check if there is any new entities in it to add to my parcel database. When I right click on the table and go to mange the option to register with database is greyed out.
I checked for locks on the table and there are none. I previewed the table and it appears to be the same as every week
I am the only one working off the database at the moment, has anyone run into similar problems before? Any suggestions on things to try?

A: Well in the end it was completely user error. After geoprocessing the table every week I need to delete it, for whatever reason I forgot to delete the table the previous week meaning it was still registered with the geodatabase.
In the end I deleted the table and will have to wait till next week to run the scripts on it!
Thanks


text:
Q: Concept of In Memory Database and how to see if my data is being populated in HSQL DB? I am using HSQL in memory database for test purpose of my application and using SQL Server as main database, now when am doing test then HSQL Database is being populated with same data that I have in my SQL Server, now I am trying to test particular service which is retrieving data from Database(it would query MS Server if directly service is run or it will query HSQL Database if called from test)
I am able to see data from MS Server when I run the query but HSQL Db does not return any data if am running same query on it. My hunch here is that HSQL DB is not being populated with the data, is there a way where in I can go and look in what tables I have in HSQL DB and how data is being populated in HSQLDB, i want to see data and i do not have any gui client to see how HSQL Database is populated and what data goes in what table. Do we have a good client for the same and how can I connect to HSQL Database using it and also how can I actually see things happening under HSQL Cover rather than just assuming that HSQL is being populated properly with what we have in SQL Server?
Any suggestions would go long way?

A: The best way to use HSQLDB for development is running a Server instance (which could store data purely in memory). While the server is on, you can connect from multiple clients, including GUI, to test and browse the data.
The URL form jdbc:hsqldb:hsql://localhost is used to access the server, while the server itself is using jdbc:hsqldb:mem:test as its internal memory database. The server must be started first with a command like this:
java -cp ../lib/hsqldb.jar org.hsqldb.Server -database.0 mem:test

A: Here I add a detailed steps of
How To Running a memory-only HSQLDB in server mode?
1) Download the latest version hsqldb-2.2.5.zip
2) unzip it,open the bin folder
3) modify the runServer.bat like
cd ..\data
@java -classpath ../lib/hsqldb.jar org.hsqldb.server.Server -database.0 mem:aname -dbname.0 aliasdb
   and click the runServer.bat to start server
4) run the runManager.bat, select Server type, enter the url
jdbc:hsqldb:hsql://localhost/aliasdb,connect, create some test table and test data
5) run the runManager.bat again to start another client,select Server type, enter the url jdbc:hsqldb:hsql://localhost/aliasdb, connect, you will find the data you created.

A: You can use Derby In-memory-database and H2 in-memory-database. They are good.but H2 has a better performance. H2 has a web console GUI and Derby has eclipse plugin GUI. You can try it. I have used them in the project. H2 Database has a tag in SO and its auther will support you in SO. I think fredit is right for using server mode instead of embed mode. But his url doesn't seem to be right. At least it should use mem. For Derby, the url is jdbc:derby://myhost:1527/memory:myDB;create=true. This is  the exmple url for H2 jdbc:h2:tcp://localhost/mem:db1.
You need to use server mode, so client can connect to it from network.
One thing you need take care is ,in memory mode, since it's in memory, when your java process is over,the JVM is not there, the data in DB is also lost. But for testing,it becomes an advantage. You don't need to clear the test data.
H2 has a very good feature for test purpose.It has SQL support which runs compatibility SQL for IBM DB2, Apache Derby, HSQLDB, MS SQL Server, MySQL, Oracle, and PostgreSQL. Which means even you use special SQL in  MS SQL Server can get the same result in H2. I believe you will like it.
the links

*

*H2

*Derby
I know HSQL has in memory mode, but i haven't used it.
Good luck.
UPDATE
I believe if you instead write query in your test case, it will return results. I have done this a lot in my test case. Even in embed mode as long as you create your JDBC connection in your test case. If you feel this is inconvenient, you can even dump the data output to files.But you must load the data into the HSQL in your test case, you can use BeforeClass to do it.If you cannot do this,You have to use server mode.
The hsql seems to be a bit different in JDBC url for server memory mode
for details refer to
http://hsqldb.org/doc/guide/guide.html#N108D2 Connections
You have to deal with some server configs.
@Rachel, I Finally find a link to help you set up server mode with in memory mode.
Look at this. It's a bit complex.
"Running a memory-only HSQLDB in server mode"

*

*http://www.ramuenke.de/archives/34

*How to run a HSQLDB server in memory-only mode
NOTE
The second link didn't tell in detail how to connect correctly.
So try the first one.


text:
Q: Does OkHttp's enqueue method implement AsyncTaskLoader? I am pretty new to android programming. I've written a code to perform API query using the OkHttp Library.
My question is, once the OkHttp's enqueue process has started, and the user immediately rotates the phone, thereby destroying and restarting the activity, does that cause a second enqueue process to occur, thereby causing the code to perform 2 OkHttp Api query in parallel?
I know that if we are using httpUrlConnections with AsyncTask (instead of OkHttp), this is a known issue. And we can bypass it by using an AsyncTaskLoader, which has a separate life cycle from our MainActivity. But I am just wondering of OkHttp also takes that into account.
Thank you! An example of my code is shown below if that helps in anyway.
private void performApiCall(String url) {
    mLoadingPb.setVisibility(View.VISIBLE);
    // is network available?
    if (NetworkUtility.isNetworkAvailable(MainActivity.this)) {
        // create new OkHttp client
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build(); // building the request
        Call call = client.newCall(request);

        // Asynchronous task
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                alertUserAboutError();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mLoadingPb.setVisibility(View.INVISIBLE);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "OkHttp, onResponse received");
                // perform data download
                if (response.isSuccessful()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLoadingPb.setVisibility(View.INVISIBLE);
                        }
                    });

                    String jsonData = response.body().string(); // this is the raw data in json format
                    Log.v(TAG, jsonData);

                    try {
                        if (mMovieData == null) {
                            saveMovieData(jsonData);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mCurrentPage++;
                                    setRecyclerView();
                                    Log.d(TAG, "OkHttpCall completed");
                                }
                            });
                        } else {
                            appendMovieData(jsonData);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    mCurrentPage++;
                                    updateRecyclerView();
                                    Log.d(TAG, "OkHttpCall completed");
                                }
                            });
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e(TAG, "Exception caught: ", e);
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLoadingPb.setVisibility(View.INVISIBLE);
                        }
                    });

                    alertUserAboutError();
                }

            }
        });
    } else {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLoadingPb.setVisibility(View.INVISIBLE);
            }
        });

        alertUserNetworkUnavailable();
    }
}

A:
My question is, once the OkHttp's enqueue process has started, and the user immediately rotates the phone, thereby destroying and restarting the activity, does that cause a second enqueue process to occur, thereby causing the code to perform 2 OkHttp Api query in parallel?

If your activity is automatically calling enqueue() when it is created, then yes.

And we can bypass it by using an AsyncTaskLoader, which has a separate life cycle from our MainActivity.

Note that the Architecture Components' support for view-models and LiveData is Google's current direction for addressing the problems that loaders tried to address.


text:
Q: How to map stat_function aesthetics to data in ggplot2? I want to add a stat_function layer to a plot with an aesthetic mapped to the state of some variable that identifies a set of parameters. I have manually created the two stat_function lines in the minimal working example below. That's generally what the result should look like.
p <- ggplot(data.frame(x = -1:1), aes(x = x))
p + stat_function(fun = function (x) 0 + 1 * x, linetype = 'dotted') +
  stat_function(fun = function (x) 0.5 + -1 * x, linetype = 'solid')

My best guess at how to accomplish this is
params <- data.frame(
  type = c('true', 'estimate'),
  b = c(0, 0.5),
  m = c(1, -1),
  x = 0
)

linear_function <- function (x, b, m) b + m * x
p + stat_function(data = params,
                  aes(linetype = type, x = x),
                  fun = linear_function,
                  args = list(b = b, m = m))

This form works if I use constants like args = list(b = 0, m = 1), but when I try to get the values for the parameters out of the params data frame it's unable to find those columns. Why is this not working like I expect and what's a solution?

A: Unfortunately, nothing positive to add here; the fact stands: stat_function does not support this functionality.
The alternative is to either use for loops to make layers, as demonstrated in this question, or generate the grid data yourself, which is what was suggested as a closing comment to a feature request discussion about adding this functionality.


text:
Q: Is this code undefined behavior? I came across this piece of code:
#include <iostream>

int main()
{
int m = 44;
std::cout << "m = " << m << ", m++ = " << m++ << ", ++m = " << ++m <<
std::endl;

return 0;
}

My first thought was, this is undefined behavior, but it turns out this code was part of an exam in my university, so I'm not so sure now.
The question on the exam is: what is the output of this program?
I also heard that C++11 or C++14 changed the rules about UB in some way, so it might be defined now.
Anyway, the output is (on gcc in windows)
m = 46, m++ = 45, ++m = 46

Is that output correct?


text:
Q: How to customize dropdown item in react semantic-ui-react? I'm using dropdown from semantic-ui-react.
I am dynamically creating a dropdown option, and I want to change the background color of the item dynamically.
How can I fill the background color to 100%?

Campaign

import {
  Dropdown,
  Menu,
} from "semantic-ui-react";
//make customize option
  getCustomerGroupOptions = () => {
    let options = [
      {
        text: "none",
        key: "none",
        value: {},
      },
    ];
   for (let tag of this.props.tags || []) {
      options = [
        ...options,
        {
          text: tag.label,
          key: tag.id,
          value: tag,
          content: (
            <div
              className="item"
              style={{ backgroundColor: tag.color, color: "#fff" }}
            >
              {tag.label}
            </div>
          ),
        },
      ];
    }
}

//Dropdown
                  <Dropdown
          error={errors.recipientFlag}
          placeholder={I18n.get(
            `${scope}.normalModal.title3.group.placeholder`
          )}
          className="mb-5 width-75 max-width-350px"
          name="recipient"
          value={campaign.recipient ? campaign.recipient : null}
          selection
          options={groupOptions}
          onChange={onChange}
        />

A: If you use inspector, you'll find that the css you're overriding is only set to the div.item.text element. It's a lot easier to get what you want if you just set the css to div.item created by semantic-ui-react.
Use Dropdown.Item and set your css to that component. I've removed some stuff for which you didn't provide logic, but you can interpolate from something like this:
import {
    Dropdown
  } from "semantic-ui-react";
const Campaign = (props) => {
    const getCustomerGroupOptions = () => {
      let options = [
      ];
     for (let tag of props.tags || []) {
        options = [...options,
              <Dropdown.Item
                style={{ backgroundColor: tag.color, color: "#fff"}}
              >
                {tag.label}
              </Dropdown.Item>
        ];
      }

      return options;
  }

  return (
         <Dropdown
            className="mb-5 width-75 max-width-350px"
            placeholder='Select Friend'
            name="recipient"
            selection
          >
              <Dropdown.Menu>
                {getCustomerGroupOptions()}
              </Dropdown.Menu>
          </Dropdown>
    );
}

export default Campaign;


text:
Q: Is it possible to create table-valued *methods* in a SQL CLR user-defined type? I have a CLR UDT that would benefit greatly from table-valued methods, ala xml.nodes():
-- nodes() example, for reference:
declare @xml xml = '<id>1</id><id>2</id><id>5</id><id>10</id>'
select c.value('.','int') as id from @xml.nodes('/id') t (c)

I want something similar for my UDT:
-- would return tuples (1, 4), (1, 5), (1, 6)....(1, 20)
declare @udt dbo.FancyType = '1.4:20'
select * from @udt.AsTable() t (c)

Does anyone have any experience w/ this? Any help would be greatly appreciated. I've tried a few things and they've all failed. I've looked for documentation and examples and found none.
Yes, I know I could create table-valued UDFs that take my UDT as a parameter, but I was rather hoping to bundle everything inside a single type, OO-style.
EDIT
Russell Hart found the documentation states that table-valued methods are not supported, and fixed my syntax to produce the expected runtime error (see below).
In VS2010, after creating a new UDT, I added this at the end of the struct definition:
[SqlMethod(FillRowMethodName = "GetTable_FillRow", TableDefinition = "Id INT")]
public IEnumerable GetTable()
{
    ArrayList resultCollection = new ArrayList();
    resultCollection.Add(1);
    resultCollection.Add(2);
    resultCollection.Add(3);
    return resultCollection;
}

public static void GetTable_FillRow(object tableResultObj, out SqlInt32 Id)
{
    Id = (int)tableResultObj;
}

This builds and deploys successfully. But then in SSMS, we get a runtime error as expected (if not word-for-word):
-- needed to alias the column in the SELECT clause, rather than after the table alias.
declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]

Msg 2715, Level 16, State 3, Line 2
Column, parameter, or variable #1: Cannot find data type dbo.tvm_example.
Parameter or variable '@this' has an invalid data type.

So, it seems it is not possible after all. And even if were possible, it probably wouldn't be wise, given the restrictions on altering CLR objects in SQL Server.
That said, if anyone knows a hack to get around this particular limitation, I'll raise a new bounty accordingly.

A: You have aliased the table but not the columns. Try,
declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]

According to the documentation, http://msdn.microsoft.com/en-us/library/ms131069(v=SQL.100).aspx#Y4739, this should fail on another runtime error regarding incorrect type.

The SqlMethodAttribute class inherits from the SqlFunctionAttribute class, so SqlMethodAttribute inherits the FillRowMethodName and TableDefinition fields from SqlFunctionAttribute. This implies that it is possible to write a table-valued method, which is not the case. The method compiles and the assembly deploys, but an error about the IEnumerable return type is raised at runtime with the following message: "Method, property, or field '' in class '' in assembly '' has invalid return type."

They may be avoiding supporting such a method. If you alter the assembly with method updates this can cause problems to the data in UDT columns.
An appropriate solution is to have a minimal UDT, then a seperate class of methods to accompany it. This will ensure flexibility and fully featured methods.
xml nodes method will not change so it is not subject to the same implemetation limitations.
Hope this helps Peter and good luck.


text:
Q: Get android seekbar value and display it on screen I'm trying to get the value of the seek bar whenever it changes and display it underneath. I'm using the onclick method on my seekbar to call this method.
public void getNumber(View view)
{
    SeekBar seek = (SeekBar) findViewById(R.id.seekBar1);
    int seekValue = seek.getProgress();
    String x = "Value: " + Integer.toString(seekValue);
    ((TextView) findViewById(R.id.level)).setText(x);
}

A: Here some extra help:
import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidSeekBar extends Activity {
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState)
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       SeekBar seekBar = (SeekBar)findViewById(R.id.seekbar);
       final TextView seekBarValue = (TextView)findViewById(R.id.seekbarvalue);

       seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    // TODO Auto-generated method stub
    seekBarValue.setText(String.valueOf(progress));
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
   }
       });
   }
}

use the OnProgressChanged event to check the progress of the seekbar, you can return that int to use it somewhere else in your app.


text:
Q: Adding more than one input to a structural directive I've been following along with an example of how to use structural directives here - but one thing I'd like to be-able to do would be to pass in some data from the card.component class into the delay.directive.ts. How do I do this?
export class DelayContext {
  /**
    - Line below demonstrated passing into an array of functions that can be called in the HTML
  */
  // constructor(private loadTime: number, private myFunc: Array<Function>) {}
  constructor(private loadTime: number, private delayService: DelayService) {}
}

@Directive({ selector: '[delay]'})
export class DelayDirective {
  constructor(
    private templateRef: TemplateRef<DelayContext>,
    private viewContainerRef: ViewContainerRef
  ) { }

  @Input('delay')
  set delayTime(time: number) {
    setTimeout(
      () => {
        let embedView = this.viewContainerRef.createEmbeddedView(
          this.templateRef,
          // new DelayContext(performance.now(),[this.foo,this.bar])
          new DelayContext(performance.now(), new DelayService())
        );
        console.log(embedView);
      },
      time);
  }
}

I've tried defining another input parameter like so:
@Input('foo')
  set fooParameter(parameters) {
    console.log(parameters);
  }

and then attempted to pass it data in the HTML several different ways, of which none worked. Here's what I've tried:
 <card *delay="500 * item; let loaded = loadTime; foo: 'test'">

          <button>{{item}}</button>

{{loaded | number:'1.4-4'}}

      </card>

This throws an error - Can't bind to 'delayFoo' since it isn't a known property of 'card' I didn't expect this error because we are in the binding parts for the delay directive.
Can this directive take any more input?
EDIT
Thanks to Gunter for answering the first part of the question. But if I define an object in the card.component.ts like this:
bar: Object = {
        val: 'Some Value'
    };

and then attempt to pass it to the directive:
<card *delay="500 * item; let loaded = loadTime; foo: bar">

this always prints undefined:
 @Input('delayFoo')
  set setFoo(obj) {
    console.log(obj)
  }

Are we outside the context of card here? Also - the complete card component:
import { Component } from '@angular/core';
import { DelayService } from './delay.service';

@Component({
    selector: 'card',
    template: `
      <ng-content select=".main"></ng-content>
    <ng-content select=".sub"></ng-content>`,
    styles: [
        `
        :host {
      display: inline-block;
      font-family: 'Helvetica', sans-serif;
      font-weight: 300;
      margin: 1rem;
      animation: fade-in 2s;
    }

    :host >>> .main {
      padding: 2rem;
      background: #e3f2fd;
      font-size: 2rem;
      text-align: center;
    }

    :host >>> .sub {
      padding: 0.4rem;
      background: #ef5350;
    }
    @keyframes fade-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
        /* Firefox < 16 */
        @-moz-keyframes fade-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
        /* Safari, Chrome and Opera > 12.1 */
        @-webkit-keyframes fade-in {
          from { opacity: 0; }
          to   { opacity: 1; }
        }
        `
    ]
})
export class CardComponent {
    bar: Object = {
        val: 'Some Value'
    };
    ngOnInit() {}
}

EDIT
A working plunker can be found here

A: Rename it to
@Input('delayFoo')

Inputs in structural directives need to include the selector.


text:
Q: Error Getting Device Information on Different Android Hardware/OS I'm using the following plugin on my Cordova project:

com.vliesaputra.deviceinformation

Here is a sample of my code:
var deviceInfo = cordova.require('cordova/plugin/DeviceInformation');
deviceInfo.get(GotDeviceInfo, function () {
    alert('error');
}

function GotDeviceInfo(result) {
    var data = JSON.parse(result);
    alert(data.phoneNo);
    alert(data.simNo);
}

On my Samsung Galaxy S5 SM-G900F (Android 5.0) I'm getting accurate information on the phone and sim numbers, but on my TomTom PRO 8275 (Android 4.3) I get TM.ERROR for both values. I assume TM means TelephonyManager, but apart from that, I have no definite reason why this works on one Android device and not on the other.
I have activated sims in both devices and have tested mobile data which again works just fine. So I know the sim is working in both devices. Is it just the hardware doesn't support it? The OS version?
Does anyone have any definitive solutions or ideas on how to get this to work or at least why it doesn't?

A: Probably it's because the manufacturer does not provide these values to be accessable by the android framework. Several android functionalities are manufacturer related and could return different results on different devices.


text:
Q: CRM Dynamics Plugin on Update not Working? I have a CRM Dynamics plugin that fires on an Update of a boolean change, it fails to fire when I select Yes on the Two Option control, Please find my code below and advice where I may be going wrong.
namespace WebCall.Plugin
{
  public class WebCallTrigger : IPlugin
  {
    /// <summary>
    /// Plugin to initiate a web call from CRM using MaruSip API
    /// </summary>
    /// <param name="serviceProvider"></param>
    public void Execute(IServiceProvider serviceProvider)
    {

        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

        if (context == null)
        {
            throw new ArgumentNullException("localContext");
        }

        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

        IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            //initaialize Entity
            Entity phoneCallEntity = (Entity)context.InputParameters["Target"];

            if (phoneCallEntity.LogicalName != Contact.EntityLogicalName)
                return;

            //ensure that the Plugin fires on a create operaton
            if (context.MessageName == "Update")
            {
                try
                {
                    if (phoneCallEntity.Attributes.Contains("new_dialnumber"))
                        phoneCallEntity["new_dialnumber"] = true;

                    string NumberToCall;                // = phoneCallEntity.Contains("telephone1") ? phoneCallEntity["telephone1"].ToString() : null;

                    if (phoneCallEntity.Contains("telephone1"))
                    {
                        NumberToCall = phoneCallEntity.Attributes["telephone1"].ToString();
                    }

                    else
                    {
                        NumberToCall = phoneCallEntity.Attributes["mobilephone"].ToString();
                    }

                    string ReceiveCallOn = phoneCallEntity.Contains("new_receivecallon") ? phoneCallEntity["new_receivecallon"].ToString() : null;
                    string apiKey = phoneCallEntity.Attributes.Contains("new_apikey") ? phoneCallEntity.Attributes["new_apikey"].ToString() : null;
                    int fId = phoneCallEntity.Attributes.Contains("new_fid") ? (int)phoneCallEntity.Attributes["new_fid"] : 0;

                    //service.Update(phoneCallEntity);

                    //Create a new instance of the WebCallService and call the webcall method
                    WebCallService webCallService = new WebCallService();

                    webCallService.WebCall(NumberToCall, ReceiveCallOn, apiKey, fId);
                }

A: In case telephone1 or mobilephone fields were not updated - target you are referring would not contain mentioned fields. My suggestion to get that data from pre-Image. You can check this article - https://deepakexploring.wordpress.com/2011/02/04/preentityimages-and-postentityimages-in-crm-5-0-2011/

A: If you registered the plugin on update of the Phone Call entity and you are comparing its logical name to "Contact" your plugin will never fire.
Review this line from your code:
if (phoneCallEntity.LogicalName != Contact.EntityLogicalName)
                return;


text:
Q: mongo db filter the result in array of objects product schema has an array field of  productDetails .
const ProductSchema = new Schema(
  {
    title: [{ lang: { type: String, upperCase: true }, value: String, _id: false }],
    attributes: [
      {
        attributeGroup: { type: mongoose.Types.ObjectId, ref: 'AttributeGroup' },
        att: [{ type: mongoose.Types.ObjectId, ref: 'Attribute' }]
      }
    ],
    shop: {
      type: mongoose.Types.ObjectId,
      ref: 'Shop'
    },
    promotion: {
      percent: Number,
      discountFrom: Date,
      discountTo: Date
    },
    preparationTime: Number,
    description: [{ lang: { type: String, upperCase: true }, value: String, _id: false }],
    photoUrl: [String],
    productDetails: [
      {
        size: {
          enum: ['SMALL', 'MEDIUM', 'LARGE'],
          type: String
        },
        price: Number,
        stock: { type: Number, min: 0, default: 0 },
        afterDiscountPrice: Number
      }
    ],
    reqCarTypes: [
      {
        type: mongoose.Types.ObjectId,
        ref: 'ReqCarType'
      }
    ],
    isDeleted: { type: Boolean, default: false }
  },
  { timestamps: true }
)

for example I have a product document like this:
{
    "_id" : ObjectId("60aa201525d6cd24d873d5dc"),
    "photoUrl" : [
        "http://lorempixel.com/640/480",
        "http://lorempixel.com/640/480"
    ],
    "reqCarTypes" : [],
    "isDeleted" : false,
    "shop" : null,
    "promotion" : {
        "percent" : 36,
        "discountFrom" : ISODate("2021-01-23T09:27:49.623Z"),
        "discountTo" : ISODate("2021-12-25T09:27:49.624Z")
    },
    "title" : [],
    "attributes" : [],
    "description" : [],
    "productDetails" : [
        {
            "price" : 40,
            "afterDiscountPrice" : 12,
            "_id" : ObjectId("60aa201525d6cd24d873d5dc"),
            "size" : "SMALL"
        },
        {
            "price" : 50,
            "afterDiscountPrice" : 12,
            "_id" : ObjectId("61aa201525d6cd24d873d5dc"),
            "size" : "MEDIUM"
        }
    ],
    "createdAt" : ISODate("2021-05-23T09:27:49.641Z"),
    "updatedAt" : ISODate("2021-05-23T09:27:49.641Z"),
    "__v" : 0
}

then I want all the fields to return except those that I haven't set the productDetails id.
I can get productDetails id from frontend and I expect to returns something like this:
{
    "_id" : ObjectId("60aa201525d6cd24d873d5dc"),
    "photoUrl" : [
        "http://lorempixel.com/640/480",
        "http://lorempixel.com/640/480"
    ],
    "reqCarTypes" : [],
    "isDeleted" : false,
    "shop" : null,
    "promotion" : {
        "percent" : 36,
        "discountFrom" : ISODate("2021-01-23T09:27:49.623Z"),
        "discountTo" : ISODate("2021-12-25T09:27:49.624Z")
    },
    "title" : [],
    "attributes" : [],
    "description" : [],
    "productDetails" : [
        {
            "price" : 40,
            "afterDiscountPrice" : 12,
            "_id" : ObjectId("60aa201525d6cd24d873d5dc"),
            "size" : "SMALL"
        }
    ],
    "createdAt" : ISODate("2021-05-23T09:27:49.641Z"),
    "updatedAt" : ISODate("2021-05-23T09:27:49.641Z"),
    "__v" : 0
}

check out productDetails fields.
I use nodejs and typescript .

A: I think this query will work for your collection and gives your desired result as per my understanding
db.collection.aggregate
([
{$match:{_id:PRODUCT_ID}},
{$project:{
    _id:'$_id',
    productDetails:{
        $filter: {
           input: "$productDetails",
           as: "productDetails",
           cond: { $eq: [ "$$productDetails._id", PRODUCT_ID ] }
        }
     },
    photoUrl :"$photoUrl",
    reqCarTypes : "$reqCarTypes",
    isDeleted : "$isDeleted",
    shop : "$shop",
    promotion : "$promotion",
    title : "$title",
    attributes : "$attributes",
    description : "$description",
    createdAt : "$createdAt",
    updatedAt :"$updatedAt",
}},
])


text:
Q: SQL Server Reporting Services Upgrade/Migration I couldn't find any documentation on this. I'm currently doing a dry run of SSRS 2005 to SSRS 2008 R2 upgrade/migration. I've backed everything up (encryption key and configuration files) and did a native backup then restore on the new server.
As it's restoring, I see "Converting database 'ReportServer' from version 611 to the current version 661.
Does this mean the server is doing all the heavy lifting of the upgrade in the background. After the restore, I am able to bring the service up and going rather quickly. Is this "upgrade" documented anywhere?