text:
Q: Illegal Operation On Bound Member Function C++ So I'm trying to make an event class to mirror C# events. I have seen several implementations that are too involved for what I need. I've come up with the following which fits my purposes:
template <typename TFunc>
class Event;

template <class RetType, class... Args>
class Event<RetType(Args...)> final
{
    typedef typename std::function<RetType(Args ...)> Closure;
  public:
    void operator+=(Closure c)
    {
      observers.push_back(c);
    }

    void operator()(Args... args)
    {
        for (auto closure : observers)
            closure(args...);
    }

  private:
    std::vector<Closure> observers;
};

This can be used as expected:
void Dosomething()
{
    cout << "Did something" << endl;
}
int DosomethingCrazy(int i)
{
    cout << "Did something Crazy " << i << endl;
    return i;
}

int main()
{
    Event<void()> e1;
    Event<int(int)> e2;
    e1 += Dosomething;
    e2 += DosomethingCrazy;
    e1();
    e2(5);
}

But, if I try to subscribe a function within an object I get the error: '&': illegal operation on bound member function expression i.e.:
class Myclass
{
public:
int num;
Myclass(int i) : num(i) { }
void Dosomething()
{
    cout << "Did something" << num << endl;
}
int DosomethingCrazy(int i)
{
    num = i;
    cout << "Did something Crazy " << num << endl;
    return i;
}
};

int main()
{
Myclass a(0);
Myclass b(10);

Event<int(int)> e1;
Event<int(int)> e2;
e1 += &(a.DosomethingCrazy);  //Error
e2 += &b.DosomethingCrazy;  //Same Error

e1(10);
e2(0);

return 0;
}

I have since decided that: even if I were able to accomplish this, it's probably a bad idea to allow external code to subscribe an object's internal methods.
However, I am curious what exactly is disallowing this and why. Also,is there a way to accomplish this, and my syntax is just wrong?
NOTE: This could certainly be achieved with static functions and qualifying the function with the class, but I needed to be able to specifically reference the object. As in the example, 'a' and 'b' should end up with swapped integer values.


text:
Q: THREE.js loading .OBJ files - why do some render flat? I am using the same general purpose code to load basic mesh objects (no textures) from OBJ files (obtained free from sites on the web).
Some objects render OK in that different faces reflect light with different intensities towards the camera.  But other objects just render a uniform matt color and so their form cannot be seen.
I have looked inside the files and noticed various differences.  For example one successful file contains records with the following initial characters v, vt, vn, f, s (vertex, vertext texture,  vertex normal, face, smooth).  An example of an unsuccessful file has these initial characters: v, vt, f.
Here is the code which I am using.
function F_Load_OBJ_Model ( givenFilespec, givenName, givenScene, givenHexColorStr, posX, posY, posZ,  rotX, rotY, rotZ, scaleX, scaleY, scaleZ )
{

var OBJLoader = new THREE.OBJLoader();

OBJLoader.load( givenFilespec, F_make_LoadedOBJ_Handler ( givenName, givenScene, givenHexColorStr, posX, posY, posZ,  rotX, rotY, rotZ, scaleX, scaleY, scaleZ ) );

}

function F_make_LoadedOBJ_Handler( givenName, givenScene,     givenHexColorStr, posX, posY, posZ, rotX, rotY, rotZ, scaleX, scaleY, scaleZ )
{
    //... See Tapio's answer (callback factory for use in loops)
    //... at http://stackoverflow.com/questions/10920372/associate-loaded-json-files-with-a-name-for-later-access
    //... This is useful in case have a loop loading multiple objects asynchronously.

return function ( object )
{
    //... Note that <object> is a THREE Object3D which can have 1 or more child meshes.
    //... But I will assume that there is only one child mesh.

    //var material = new THREE.MeshBasicMaterial();
    //eval( givenName + " = new THREE.Mesh( geometry, material );" );
    //eval ( " var thisMeshOb =" + givenName );
    //eval( givenName + " = object.children[0];" ); //....OK alias

    eval( givenName + " = object.children[0].clone();" );//... also OK

    //object.delete(); //... not possible or neccy, javascript will delete any object which cannot be referred to again.

    eval ( " var thisMeshOb =" + givenName );//... alias used for following common local commands

    thisMeshOb.position.set( posX, posY, posZ );
    thisMeshOb.rotation.set( rotX, rotY, rotZ );
    thisMeshOb.name = givenName;
    thisMeshOb.scale.set( scaleX, scaleY, scaleZ );
    givenScene.add( thisMeshOb );
    //xxx thisMeshOb.material.type = THREE.MeshLambertMaterial();

    thisMeshOb.material.color.setHex( givenHexColorStr ) ;//...("0xff0000");

    thisMeshOb.geometry.computeFaceNormals(); //...no effect
    thisMeshOb.geometry.normalsNeedUpdate = true; //... no effect

    //... for PHONG ... floorGeometry.computeVertexNormals();

    thisMeshOb.updateMatrix(); //... without this the next is not effective!?
    xxx = SOW_F_grob_Add_to_Target_Set( thisMeshOb );
};

}//... EOF F_make_LoadedOBJ_Handler.

I guessed that it might be something to do with missing vertex normals.  But adding the code to update them had no effect on the end result.
So is there a problem with the files or can I do something in THREE.js to make them render properly?

A: You've found correctly that the flat-looking files have no "vn" info.
"vn" means "vertex normal" -- that is, the direction that the (smoothed) normal is facing.
You can try calling something like thisMeshOb.geometry.computeFaceNormals(); and possibly follow it with thisMeshOb.geometry.computeVertexNormals(); -- then set thisMeshOb.geometry.normalsNeedUpdate = true; -- this will calculate a new set of normals directly inside THREE.
You only need to call this once per session, at read-in time, btw -- no need to recalculate every frame.

redpajama_set_name: RedPajamaStackExchange


text:
Q: scroll page then at certian position scroll element I am at a bit of a loss for how how to do this.
I have a web page. I want a user to scroll down, then at a specific distance from the top I want the mouse scroll to effect an elements position (making it appear as thought that element is scrolling). then when that element hits a position (ie top: -500) I want the scroll to apply to the main webpage again. Any thoughts on how I can do this?
Im working on a fiddle now but not having any luck, I will post when I have something to show
Edit: The beginning of a solution/sudo code https://jsfiddle.net/vk0jk37v/23/
Attached is an image of one area in which I am applying this.
//pageFeature.style.backgroundPosition = "0px " + parseInt(-y / 6) + 'px');

var element = document.getElementById('container').getBoundingClientRect();
var elementTop = element.top //distance from top 720;

// variable to stop function from being replayed on scroll when scrolling image
var isScrollingImage = false;

// disables scroll on body
var disableScroll = function() {
    document.body.style.overflow='hidden';
}
// enables scroll on body
var enableScroll = function() {
    document.body.style.overflow='auto';
}
//change position of background along y axis with scroll
var scrollImage = function() {
    console.log("called");
   isScrollingImage = true;
   var pageFeature = document.getElementById("inner");
   var pageFeaturePosition;
   pageFeature.style.backgroundPositionY=parseInt(-scrollY / 10) + "px";
    //if (background is scrolled to bottom) {
    //    enableScroll();
    // }
}

//when element gets to center of viewport and animation is scroll is not on element
//call scrollImage()
function checkPosition() {
    if (scrollY > 720 && !isScrollingImage) {
        disableScroll();
        scrollImage();
    }
    //isScrollingImage = false;
}

//once out of view port will have to bring the image back down,
//scroll image will only happen on the way down

document.addEventListener('scroll', checkPosition);

A:     var thresholdY = 150;
    var thresholdCounter = 0;
    var speed = 4;
    var element = document.getElementById('yourElement');

    window.onscroll = function(event) {
      if(scrollY > thresholdY) {
        window.scrollTo(0, thresholdY);
        element.setAttribute('style', 'transform:translate3d(0,' + (--thresholdCounter * speed) + 'px,0);');
        return false;
      }
      return null;
    };

Here's a demo: https://jsfiddle.net/pkt6xnb5/
The idea here is that you keep the window in place when the user reaches a certain threshold Y position. Also at that time we transform the element along it's Y axis in the opposite direction the user is scrolling to make it move up as they scroll further down. Is that what you're looking for?


text:
Q: A regex that validates a web address and matches an empty string? The current expression validates a web address (HTTP), how do I change it so that an empty string also matches?
(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

A: If you want to modify the expression to match either an entirely empty string or a full URL, you will need to use the anchor metacharacters ^ and $ (which match the beginning and end of a line respectively).
^(|https?:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$

As dirkgently pointed out, you can simplify your match for the protocol a little, so I've included that for you too.
Though, if you are using this expression from within a program  or script, it may be simpler for you to use the languages own means of checking if the input is empty.
// in no particular language...
if input.length > 0 then
    if input matches <regex> then
        input is a URL
    else
        input is invalid
else
    input is empty

A: Put the whole expression in parenthesis and mark it as optional ("?" quantifier, no or one repetition)
((http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)?

A: Use expression markers ^$ around your expression and add |^$ to the end. This way you're using the | or operator with two expressions showing that you have two different match cases.
^(https?:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$|^$

The key here is that |^$ means "or match blank".
Also, that expression with only work in javascript if you use a template string.

A: Expr? where Expr is your URL matcher. Just like I would for http and https: https?. The ? is a known as a Quantifier -- you can look it up. From Wikipedia:

? The question mark indicates there is zero or one of the preceding element.


text:
Q: Rest API plugin wordpress disable default routes Hello guy's Please help me i install REST API plugin WP and i adding some specific route and any things it's work fine as i wont. But I want to disable default route exemple :
/wp-json/
/wp-json/wp/v2/posts

A: You can use this on your plugin for remove all default route.
remove_action( 'rest_api_init', 'create_initial_rest_routes', 0 );

A: As of Wordpress 4.7 it seems to be the following (noting 99 instead of 0):
remove_action('rest_api_init', 'create_initial_rest_routes', 99);

However this will also remove any custom content type routes. So instead you may choose to use:
add_filter('rest_endpoints', function($endpoints) {

    unset( $endpoints['/wp/v2/users'] );
    // etc

    return $endpoints;
});


text:
Q: AJAX validation script doesn't execute before login PHP script I'm trying to use AJAX to validate my form, but it isn't working and I have no idea why. It is still executing login_action.php instead of the AJAX validation. I've created a modal login form and want the error message to be displayed inside that popup. Now it is still redirecting to the login_action.php file first.
Script:

Login popup:

        <form class="loginform animate" action="login_action.php" id="loginform" method="post" onsubmit="return do_login();">

                ×

                E-mailadres
                <input type="email" placeholder="E-mailadres" name="email" id="emailid" >
                Wachtwoord
                <input type="password" placeholder="Wachtwoord" name="password" id="passwordid" >
                <input type= "submit" class="loginbtn"  value="Inloggen" name="submitter" id="submitter">
                Klik hier om een account aan te maken

        </form>

PHP login_action
<?php
session_start();
include('sslsecurity.php');
include('file:///var/www/configure.php');

if(isset($_POST['submitter'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];

    // de gebruiker moet natuurlijk wel iets invullen
    if(!empty($_POST['email'])) {

        // de query in SQL
        $query = $conn->prepare("SELECT role, email, pass FROM WebsiteUsers WHERE email = ? AND pass = SHA1(?) ");

        $query->bindValue('1', $email);
        $query->bindValue('2', $password);
        $query->execute();
        // user id van de user achterhalen

        // resultaat met waarden
        $count = $query->rowCount();
            if($count==1)
            {
                while($row=$query->fetch(PDO::FETCH_ASSOC))
                {
                    if($row['role'] == 'admin')
                    {
                        $_SESSION['loginright'] = $row['role'];
                    }
                    else
                    {
                        $_SESSION['loginright'] = $row['role'];
                    }
                }

                // session variable om de user te herkennen aanmaken
                $_SESSION['email'] = $email;

                // terug naar de index pagina

                echo "ok";

            }
            else
            {
                echo "fail";
            }

    }
}

?>

<?php
$conn = null;

?>

I've been searching on the internet a while but couldn't find an answer that worked for me.
I tried event.preventDefault();, but that doesn't work as well.
Thank you

A: It doesn't appear that you actually have an even listener on your submit button:
    $("#submit").click(function(event){
        //execute validation and ajax here.
        event.preventDefault();
});


text:
Q: Email Reports through Jenkins I have a pdf generated by Dynamic Reports.I want to add this pdf as an attachment in the mail feature of Jenkins for each and every build of the project.Is It possible to achieve this.Is there any another way in which I can mail my reports through Jenkins.

A: Use Email-ext plugin for Jenkins. It provides more configuration options than "standard Jenkins" emails. Also it gives you opportunity add attachments to your emails:

Attachments
New to version 2.15 is the ability to add attachments using the Ant pattern matching syntax used in many places in Jenkins. You can set a maximum total attachment size in the global configuration page, or it will be unlimited.


text:
Q: PHP move_uploaded_file() function not working Got a form to add a product to a web store. You can upload up to 10 images, the minimum is 1 image. Even though it inserts the name of the file to the MySQL database perfectly, the files won't move to the right folder.
I'm using a shared web host, PHP 5.2, the file has write permissions. Talked to the web host already and it's not a permissions problem.
<form action="" method="post" enctype="multipart/form-data">

                    Image 1
                    <input required type="file" class="form-control" name="img1" placeholder="Image 1 (name of the first image, upload it as instructed)">

                    Image 2
                    <input type="file" class="form-control" name="img2" placeholder="Image 2 (name of the first image, upload it as instructed)">

                    Image 3
                    <input type="file" class="form-control" name="img3" placeholder="Image 3 (name of the first image, upload it as instructed)">

                    Image 4
                    <input type="file" class="form-control" name="img4" placeholder="Image 4 (name of the first image, upload it as instructed)">

                    Image 5
                    <input type="file" class="form-control" name="img5" placeholder="Image 5 (name of the first image, upload it as instructed)">

                    Image 6
                    <input type="file" class="form-control" name="img6" placeholder="Image 6 (name of the first image, upload it as instructed)">

                    Image 7
                    <input type="file" class="form-control" name="img7" placeholder="Image 7 (name of the first image, upload it as instructed)">

                    Image 8
                    <input type="file" class="form-control" name="img8" placeholder="Image 8 (name of the first image, upload it as instructed)">

                    Image 9
                    <input type="file" class="form-control" name="img9" placeholder="Image 9">

                    Image 10
                    <input type="file" class="form-control" name="img10" placeholder="Image 10">

image part of the form ^
    <?php

    if(isset($_POST['name'])){
        $img1 = $_FILES['img1']['name'];
        $img2 = $_FILES['img2']['name'];
        $img3 = $_FILES['img3']['name'];
        $img4 = $_FILES['img4']['name'];
        $img5 = $_FILES['img5']['name'];
        $img6 = $_FILES['img6']['name'];
        $img7 = $_FILES['img7']['name'];
        $img8 = $_FILES['img8']['name'];
        $img9 = $_FILES['img9']['name'];
        $img10 = $_FILES['img10']['name'];

        move_uploaded_file($_FILES['img1']['tmp_name'],"../assets/img/carousel/");
        move_uploaded_file($_FILES['img2']['tmp_name'],"../assets/img/carousel/$img2");
        move_uploaded_file($_FILES['img3']['tmp_name'],"../assets/img/carousel/$img3");
        move_uploaded_file($_FILES['img4']['tmp_name'],"../assets/img/carousel/$img4");
        move_uploaded_file($_FILES['img5']['tmp_name'],"../assets/img/carousel/$img5");
        move_uploaded_file($_FILES['img6']['tmp_name'],"../assets/img/carousel/$img6");
        move_uploaded_file($_FILES['img7']['tmp_name'],"../assets/img/carousel/$img7");
        move_uploaded_file($_FILES['img8']['tmp_name'],"../assets/img/carousel/$img8");
        move_uploaded_file($_FILES['img9']['tmp_name'],"../assets/img/carousel/$img9");
        move_uploaded_file($_FILES['img10']['tmp_name'],"../assets/img/carousel/$img10");

The part that gets the name of the files & moves them to the right folder.
Instead of the files moving to the carousel folder, the files are just not moving anywhere at all:
[Thu Apr 18 18:53:34.249395 2019]
[cgi:error] [pid 13994]
[client 172.69.130.13:32306] AH01215: PHP Warning:  move_uploaded_file():
Unable to move '/tmp/phpOjN6YW' to '../assets/img/carousel/download (2).jpg'
in /home/seniorte/public_html/admin/add.php
on line 338: /usr/local/cpanel/cgi-sys/ea-php56
Error log ^

A: This is definitely either a permissions problem or a path problem.  Destination directory must exist and be writable by your PHP process.  For destination, use absolute path, not relative as you are using or if you are using relative make sure that you are using dirname(FILE) . '/../assets'
Assuming all of the above is correct then it will work for you!

A: So what cherrysoft said is correct; its almost certainly a permissions issue, or its not going to the path you think it is going to.
I am going to use this opportunity to help you improve your code though. Your example could be streamlined to allow the addition of more than 10 images more easily, and be more maintainable. Here is a better alternative to your current code:
if(isset($_POST['name'])){
    foreach($_FILES as $key => $file) {
        move_uploaded_file($file['tmp_name'],"../assets/img/carousel/{$file['name']}");
    }
}

In this way your code is not so repetitive. There are ways to improve this even further, but I don't want to get carried away.


text:
Q: Mockito TooManyActualInvocations I'm using Junit and Mockito to test forward.
Here is part of PortalServletTest class:
@SuppressWarnings("serial")
@BeforeClass
public static void setUpTests() {
    when(request.getRequestDispatcher(Mockito.anyString())).thenReturn(rd);
    when(request.getSession()).thenReturn(httpSession);
    when(httpSession.getServletContext()).thenReturn(servletContext);
    when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
    when(configurationManager.getConfiguration()).thenReturn(configuration);
    List<List<String>> mandatoryHeaders = new ArrayList<List<String>>();
    mandatoryHeaders.add(new ArrayList<String>() {
        {
            add("HTTP_XXXX");
            add("http-xxxx");
        }
    });

    List<List<String>> optionalHeaders = new ArrayList<List<String>>();
    optionalHeaders.add(new ArrayList<String>() {
        {
            add("HTTP_YYYY");
            add("http-yyyy");
        }
    });

    when(configuration.getIdentificationHeaderFields()).thenReturn(mandatoryHeaders);
    when(configuration.getOptionalHeaderFields()).thenReturn(optionalHeaders);

}

@Test
public void testMissingHeadersRequest() throws IOException {
    when(request.getHeader(Mockito.anyString())).thenReturn(null);
    target().path("/portal").request().get();
    Mockito.verify(response, times(1)).sendError(HttpServletResponse.SC_USE_PROXY, PortalServlet.MISSING_HEADERS_MSG);
}

@Test
public void testSuccesfulRequest() throws IOException, ServletException {
    Mockito.doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            String headerName = (String) args[0];
            return headerName;
        }
    }).when(request).getHeader(Mockito.anyString());
    target().path("/portal").request().get();
    verify(rd).forward(Mockito.any(ServletRequest.class), Mockito.any(ServletResponse.class));
}

The PortalServlet code:
RequestDispatcher rd = request.getRequestDispatcher("index.html");
        rd.forward(mutableRequest, response);

The problem is that when testing the class, I'm getting the error message:

requestDispatcher.forward(, );
  Wanted 1 time:
  -> at xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140)
But was 2 times. Undesired invocation:
  -> at xxx.PortalServlet.addRequestHeaders(PortalServlet.java:144)
at xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140)

If I run each test individually they pass OK.
Looks like the forward from PortalServlet is count twice for each test.
Any suggestion how to solve this issue?
Thanks in advance.

A: In addition to what @GhostCat wrote, I think you should reset all mocked objects before tests:
@Before
public void before() {
   Mockito.reset(/*mocked objects to reset*/)
   // mock them here or in individual tests
}

A: You are using @BeforeClass to configure your mock objects.
That method is called once before your @Tests in your test class go executed.
You could simply try to change that to @Before!
In other words: before doing any tests, you configure your mocks to allow for one call. But then you are running multiple tests. If you assume that your mocks are all used the same way, you simply re-configure them each time for each @Test method.
Given your comment: does this
verify(rd, times(2)).forward ...

work/help?

A: If you are using Mockito BDD, then do it as below.
then(empRepository).should(times(3)).findById(emp.getId());


text:
Q: Python detect a python script's name in the list of processes I know I can use psutil to get a list of running processes' names like this
import psutil

for i in psutil.pids():
    print(psutil.Process(i).name())

However, If i run a python script with python, psutil only will show me that I have an instance of python running.
So, my question is - if I run a python script:
python script_name

is it possible to detect script_name by psutil?

A: Look at psutil.Process(i).cmdline() docs.  Your example would return
['python', 'script_name']

A: The psutil documentation states that the cmdline() method returns the command line of the process. If the command line is python script_name, the second word will be the actual script name. To get this information I'd change psutil.Process(i).name() to psutil.Process(i).cmdline().

A: You will need to read the script name from the command line arguments:
import psutil
for proc in psutil.process_iter():
    try:
        if "python" in proc.name():
            print(proc.cmdline[1])
    except:
          pass


text:
Q: REST URI's and caching for GET requests when the list to be returned depends on the rights of the user
*

*It is a multi-tenant serverless system.

*The system has groups with permissions.

*Users derive permissions based on the groups they are in.

*If it makes a difference, we are using Cognito for authentication and it is a stateless application.

For example:

*

*GET endpoint for sites   (so sites that the logged-in user has access to based on the groups they are in)

*GET endpoint for devices  (so sites that the logged-in user has access to based on the groups they are in)

In REST APIs. "The idea is that the data returned by an endpoint should depend solely on the parameters passed meaning two different users should receive the same result for the identical request.
"
What should the REST URI look like to ensure the above-stated idea? Since the deciding factor for the list here is "groups" and thus effective permissions, I was thinking we could pass the groups a user in, in the URI in sorted order to leverage caching on GET endpoints as well, Is there a better way to do it?

A:
In REST APIs. "The idea is that the data returned by an endpoint should depend solely on the parameters passed meaning two different users should receive the same result for the identical request. "

No this is not strictly true. It can be a desirable property, but absolutely not needed. In fact, if you build a proper hypermedia REST api, you would likely want to hide links/actions that the current user is not allowed to use.
Furthermore, a cache will never store responses and send to different users if an AUthorization header is present on the request.
Anyway, there could be other reasons to want this.. maybe it's a simpler design for your case, and there is a pretty reasonable solution.
What I'm inferring from your question is that you might have two endpoints:
/sites
/devices

They return different things depending on who's accessing. Instead of using those kind of routes, you could just do:
/user/1234/sites
/user/1234/devices

Now every user has their own separate 'sites' and 'devices' collection. The additional benefit is that if you ever want to let a user find the list of sites or devices from another user, the API is ready to support that.

A:
The idea is that the data returned by an endpoint should depend solely
on the parameters passed

This is called the statelessness constraint, but if you check the parameters always include auth parameters because of this. The idea is keeping the session data on the client side, because managing sessions becomes a problem when you have several million users and multiple servers all around the world. Since the parameters include auth data, the response can depend on this data, so you can use here the exact same endpoints for users with different permissions.
As of the responses you might want to send back hyperlinks, which represent the available operations. The concept is the same here, if the user does not have permission for the actual operation, then they won't get a hyperlink for that operation and in theory they should never get a 403 status either, because you must follow the hyperlinks you got from the service instead of hardcoding URI templates into your client. So you have to handle less errors and junk requests, and another reason here that you can change your URI templates without breaking the clients. This is called hypermedia as the engine of application state, it is part of the uniform interface constraint.


text:
Q: How do I make my scroll always in the end of the page in HTML CSS. I want my scroll to always be at the end of the page I am making a chat with HTML and CSS but every time the chat reaches the end of the page or auto scroll down every there's a new message. Here is my current code. I can use javascript but not sure what to do. Can someone give me code for that implemation and/or probably fix my HTML CSS formation a bit? It's also very unformatted.
<link
  href="https://fonts.googleapis.com/css2?family=Varela&display=swap"
  rel="stylesheet"
/>
<title>Chatapp-shit</title>

    Chatapp Room

    Chat with friends in a comfortable way!

    <input type="text" id="message" placeholder="Message" />
    <button onclick="sendMessage()">Send</button>

```

A: Here is a quick demo of how to use vanilla javascript to make the messages div scroll to the bottom.
You'll presumably want to call scrollDown() every time a new message has been added.

function scrollDown() {
  const messagesElem = document.querySelector('#messages');
  messagesElem.scrollTop = messagesElem.scrollHeight - messagesElem.clientHeight;
}
#messages {
  height: 300px;
  overflow-y: scroll;
  border: 1px solid black;
}
<button onclick="scrollDown()">Scroll Down</button>

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a

  a


text:
Q: 'The resource cannot be found' only in firefox I have an asp.net project with asp buttons. It successfully runs in IE11. But, in firefox, when i click the button it says 'The resource cannot be found.HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. '
Little bit help would be appreciated.
Thanks.


text:
Q: Very basic C++ compiling problem with header file I just don't get the problem with this very simple code... I'm despairing.
testLib.h
#ifndef testLib
#define testLib

int mal2(int wert); // works properly
int abc; // throws: multiple definition of `abc'

#endif

testLib.cpp
#include "testLib.h"

int mal2(int wert) {
  return wert*2;
}

main.ino
#include <testLib.h>

int ergebnis = mal2(5);

// int abc; // throws: error: redefinition of 'int abc'
// abc = 1; // throws: error: 'abc' does not name a type

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:

}

Why is abc multiple defined if I don't use it in main.ino - shouldn't #ifndef prevent exactly that? If it is already multiple defined, why can't I use one of the other two lines then?
Thanks in advance for any light you bring into my darkness...!

A: well it is pretty obvious, you are defining int abc in both main.ino and testlib.h. they are in the same namespace hence the naming collision
modified the answer. this is what your code looks like right now
int mal2(int wert); // works properly
int abc; // throws: multiple definition of `abc'

int mal2(int wert) {
  return wert*2;
}

int ergebnis = mal2(5);

// int abc; // throws: error: redefinition of 'int abc'
// abc = 1; // throws: error: 'abc' does not name a type

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:

}


text:
Q: Listar todos os triggers no SQL Server Existe algum comando, que liste todas as triggers de um banco no SQL Server?

A: Seria isso que você está procurando?
SELECT Object_Name(parent_id) AS [Nome Objeto],
       type_desc              AS Tipo,
       modify_date            AS [Data Modificação]
FROM   sys.triggers

A: Você pode usar o select abaixo.
SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'

Ele retorna além do nome da trigger a tabela que a usar.
Documentação com select do objeto trigger.

A: SELECT * FROM sys.triggers

Coloquei no GitHub para referência futura.
Documentação.


text:
Q: Does Wasteland 2 physical DVD includes Steam copy? I would like to have a box copy of Wasteland 2 for aesthetical reasons, but actually I prefer pure Steam in usage. So can I play Wasteland 2 with just a Steam with no disc, after initial installation?

A: Yes, they do. The game is published by Deep Silver / Koch Media from Germany and all of their recent games are Steamworks. Watch out for the publisher when buying in Russia or Asia though. Could be a different one.
Developer confirming this:
http://steamcommunity.com/app/240760/discussions/0/613936673505002461/#c613936673505223836

Also, the disc apparently does not include the game, but only the Steam Client:

A: To add up to accepted answer. The publisher in ex-USSR is "Бука", but seems like their role is purely nominal, and except for box redesign:

all statements in answer are fully applicable to this version too.


text:
Q: How to limit the number of votes in 'acts_as_votable' gem I'm currently using the rubygem acts_as_votable as the voting system in my project, but I want to limit the total votes of every user (which I used rubygem devise)
The target of the vote is a model called Pin:
class Pin < ActiveRecord::Base
   acts_as_votable
end

Should I use a method and put it in the before_action: to make sure that the vote your making won't let your total votes exceed say like 10?
Updated: 8/18/2015
Now I popped up with a new question:
I created another model group, and declaim the relationship:
(group.rb)
has_many: pins

(pin.rb)
belongs_to: group

So, here comes up the question, if I want to limit the votes in every group, say like: 10 in group 1, 10 in group 2, 10 in group 3....
How can I accomplish it?

A: You can do something like this:
def upvote
  @pin = Pin.find(params[:id])
   # check for user's total votes
  if current_user.find_voted_items.size < 10
    @pin.vote_by :voter => current_user
  else
    ..... #your code
    flash[:notice] = "your total votes exceed"
    redirect_to pins_path
  end
end


text:
Q: Incompatible units: 'rem' and 'px' - Bootstrap 4 and Laravel Mix I just installed a fresh Laravel 5.4, and bootstrap 4 alpha 6. Laravel mix wont compile SASS:
Here is one error:
    Module build failed: ModuleBuildError: Module build failed:
$input-height:                   (($font-size-base * $input-line-height) + ($input-padding-y * 2)) !default;
                                ^
      Incompatible units: 'rem' and 'px'.
      in /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/bootstrap/scss/_variables.scss (line 444, column 34)
    at runLoaders (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/webpack/lib/NormalModule.js:192:19)
    at /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:364:11
    at /Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:230:18
    at context.callback (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
    at Object.asyncSassJobQueue.push [as callback] (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/lib/loader.js:57:13)
    at Object.<anonymous> (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:2262:31)
    at apply (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:20:25)
    at Object.<anonymous> (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:56:12)
    at Object.callback (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/sass-loader/node_modules/async/dist/async.js:944:16)
    at options.error (/Volumes/HDD/nicolae/Dev/htdocs/test/node_modules/node-sass/lib/index.js:294:32)

 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss

Someone passed this? And how?

A: Just change the
$font-size-base: 14px;
to
$font-size-base: 0.875rem;
and run
npm run dev

A: I just fixed this on my side, what worked for me was moving the @import "bootstrap.scss.." and other variables to the top of the app.scss file, it seems it was overwritten and that is what caused the issue.

A: Solved

*

*remove the bootstrap entry from package.json and replace it with
"bootstrap": "4.0.0-alpha.6", in resources/assets/sass/app.scss,

*comment out the import of variables. change the path of bootstrap to
@import "node_modules/bootstrap/scss/bootstrap.scss";

*in resources/assets/js/bootstrap.js, look for require('bootsrap-sass');
and change it to require('bootstrap');

Link!

A: It happened to me too, it's like you said, the override of some variables is the cause of this error.
To fix this just comment this line in resources/assets/sass/_variables:
$font-size-base: 14px;
In the variables if you need are using other variables that laravel provides.
reference: https://github.com/twbs/bootstrap/issues/18368


text:
Q: Google SDK API - update Workspace user profile data by service account (Not Authorized to access this resource/api) I am trying to sync our user profiles from our internal SaaS to Google Workspace user profiles. Especially (gender, phone, jobTitle, department).
After a long reading, I found out that it is not possible to do by OAuth in the Google cloud project, but it is necessary to create a service account. I have created it, but I am still getting responses Not Authorized to access this resource/api.

*

*The Domain-wide Delegation is enabled.

*Admin SDK API is enabled.

*API client access with scope "https://www.googleapis.com/auth/admin.directory.user" is enabled in Workspace security.

Permission of service account:

Code:
        $config = __DIR__ . '/project-users.json';

        $client = new \Google\Client();
        $client->setApplicationName('project-users');
        $client->setAuthConfig($config);
        $client->addScope(Google_Service_Directory::ADMIN_DIRECTORY_USER);
        $client->setSubject('admin@domain.com');
        $client->setAccessType('offline');

        $gsdService = new \Google\Service\Directory($client);

        $googleUser = new \Google\Service\Directory\User();
        // Gender
        $gender = new \Google\Service\Directory\UserGender();
        $gender->setType('male');
        // Phone
        $phone = new \Google\Service\Directory\UserPhone();
        $phone->setType('mobile');
        $phone->setValue('123456789');
        $googleUser->setPhones([$phone]);
        // jobTitle and department
        $organization = new \Google\Service\Directory\UserOrganization();
        $organization->setPrimary(TRUE);
        $organization->setTitle('Lead Developer');
        $organization->setDepartment('Dev');
        $googleUser->setOrganizations([$organization]);

        $gsdService->users->update('fname.lname@domain.com', $googleUser);

A: When using a service account with domain-wide delegation you need to impersonate a user who has the necessary authorization

*

*The Directory API method users.update can only be executed by domain admins with the respective role / permissions.

*See how to make a user an admin.

*If in doubt, you can test with the [Try this API](Try this API) authorized as 'admin@domain.com' to verify either this user has the necessary permissions.


text:
Q: echo html contents with some css I have been trying to echo html with some css styles in it but those css destroys my main html layout with some other css.
How am I suppose to do that without destroying my main layout

A: Try this
echo '';
echo '

';


text:
Q: Hibernate Criteria returns duplicate entries ( No joins)     Criteria cr = session.createCriteria(ProductId.class);

    List<ProductId> policyCount2 = cr.list();
    System.out.println(policyCount2.size());

    for(ProductId x : policyCount2) {
        System.out.println(x.getPRODUCT_TEMPLATE_ID());
    }

there are 8 ProductId rows in the table.... Hibernate is able to find 8 records. however, it returns same product templates 8 times.. like this ...
1
1
1
1
1
1
1
1

This is a straight forward select from the table ProductId. there is no JOINS involved in this program.
Here is the ProductId template table
PRODUCT_ID  PRODUCT_TEMPLATE_ID
FDC140012   1
FDC140012   2
FDC140012   3
FDH140012   5
FDH140012   6
FDH140012   12
FDH140012   10
FDH140012   11

Here is the ProductId POJO...
public class ProductId {

private String PRODUCT_ID;
private int PRODUCT_TEMPLATE_ID;

public String getPRODUCT_ID() {
    return PRODUCT_ID;
}
public void setPRODUCT_ID(String pRODUCT_ID) {
    PRODUCT_ID = pRODUCT_ID;
}
public int getPRODUCT_TEMPLATE_ID() {
    return PRODUCT_TEMPLATE_ID;
}
public void setPRODUCT_TEMPLATE_ID(int pRODUCT_TEMPLATE_ID) {
    PRODUCT_TEMPLATE_ID = pRODUCT_TEMPLATE_ID;
}
public String getSTATE_LIST() {
    return STATE_LIST;
}
public void setSTATE_LIST(String sTATE_LIST) {
    STATE_LIST = sTATE_LIST;
}
}

Here is my Mapping file....
<hibernate-mapping>
    <class name="model.ProductId" table="PRODUCT_ID">
        <id name="PRODUCT_ID" type="java.lang.String">
            <column name="PRODUCT_ID" />
            <generator class="assigned" />
        </id>
        <property name="PRODUCT_TEMPLATE_ID" type="int">
            <column name="PRODUCT_TEMPLATE_ID" />
        </property>
        <property name="STATE_LIST" type="java.lang.String">
            <column name="STATE_LIST" />
        </property>
    </class>
</hibernate-mapping>

A: The reason is you don't have an unique id. All ProductId have FDC140012 as id.
This means that you have only one column PRODUCT_ID as id.
<id name="PRODUCT_ID" type="java.lang.String">
  <column name="PRODUCT_ID" />
  <generator class="assigned" />
</id>

Hibernate gets all other objects from a cache.


text:
Q: How to install Rpy2 for Python 2.6 on WINDOWS XP I download the rpy2-2.2.3 , and try to : python setup.py install on my windows xp computer with R: 2.12.2 , Python: 2.6.1 , after copying some files, it shows below error msg. How to fix ?
Traceback (most recent call last):
  File "setup.py", line 441, in <module>
    [os.path.join('doc', 'source', 'rpy2_logo.png')])],
  File "D:\Python\lib\distutils\core.py", line 152, in setup
    dist.run_commands()
  File "D:\Python\lib\distutils\dist.py", line 975, in run_commands
    self.run_command(cmd)
  File "D:\Python\lib\distutils\dist.py", line 995, in run_command
    cmd_obj.run()
  File "D:\Python\lib\distutils\command\install.py", line 577, in run
    self.run_command('build')
  File "D:\Python\lib\distutils\cmd.py", line 333, in run_command
    self.distribution.run_command(command)
  File "D:\Python\lib\distutils\dist.py", line 995, in run_command
    cmd_obj.run()
  File "D:\Python\lib\distutils\command\build.py", line 134, in run
    self.run_command(cmd_name)
  File "D:\Python\lib\distutils\cmd.py", line 333, in run_command
    self.distribution.run_command(command)
  File "D:\Python\lib\distutils\dist.py", line 994, in run_command
    cmd_obj.ensure_finalized()
  File "D:\Python\lib\distutils\cmd.py", line 117, in ensure_finalized
    self.finalize_options()
  File "setup.py", line 144, in finalize_options
    rversion = get_rversion(r_home)
  File "setup.py", line 186, in get_rversion
    rversion = m.groups()[0]
AttributeError: 'NoneType' object has no attribute 'groups'

R: 2.12.2 , Python: 2.6.1

A: *

*Latest is rpy2-2.2.7.

*rpy2-2.3.0beta is in fact the latest

*No official support for Win32 (or Win64) but it might build with the latest rpy2


text:
Q: Android video filter I'm trying to create an app where I am able to add filters to a recorded video. Basically, I want to replicate the functionality that exists in Instagram video, or Viddy.
I've done research and I can't piece it all together. I've looked into using GLSurfaceView to play the recorded video and I know I could use NDK to do the pixel manipulation and send it back to the SurfaceView or save it somehow. The problem is, I don't know how to send the pixel data because there seems to be no function to access it. This idea came from the Camera function "onPreviewFrame". The function returns a byte array allowing me to manipulate the pixels and display it.
Another idea is to use GLSurfaceView and use OpenGL to render the filter. GLSurfaceView has a renderer you can set, but I'm not very familiar with OpenGL. But again, this goes back to actually getting the pixels of each video frame. I also read about ripping each frame as a texture and then manipulating the texture in OpenGL but the answers I've come across are not very detailed.
Lastly, I've looked into JavaCV. Trying to use FFmpegFrameGrabber, but I haven't had much either. I wanted to just grab one frame, but when I try to write the frame's ByteBuffer to an ImageView, I get a "buffer not large enough for pixels" error.
Any guidance would be great.

A: From Android 4.3 you can use a Surface as the input to your encoder. http://developer.android.com/about/versions/android-4.3.html#Multimedia
So you can use GLSurfaceView and apply the filters using fragment shaders.
You can find some good examples here. http://bigflake.com/mediacodec/

A: It is good to use the exoplayer filter library and this one will do your work but in order to merge the filtered layered with the video you have to do an extra work.
Link for exoplayer filter is there for you : ExoplayerFilter
You have to se the exoplayer for this but follow their instructions you'll be able to do  the task. Ping me if something comes up.


text:
Q: Correct code not compiling (in Texmaker): Due to dependencies? My original goal was to create table with certain properties and I got a good answer here: What I wanted. Unfortunately, running it in Texmaker did give me a fatal error. The code itself is correct though as I tried it in some Online LaTeX editor. I'm not sure why it doesn't compile. The code is the following:
\documentclass[12pt]{article}
\usepackage[letterpaper,margin=1in]{geometry} % set page parameters suitably
\usepackage{booktabs}
\usepackage{siunitx} % for 'S' column type
\newcolumntype{T}[1]{S[table-format=#1]} % handy shortcut macro

\begin{document}

\noindent
\begingroup % localize scope of the next instruction
\setlength\tabcolsep{0pt} % let LaTeX figure out intercol. sapce
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}
    c *{3}{T{2.1}T{2.1}T{3.0}} }
\toprule
$N_p$ & \multicolumn{3}{c}{Isotropic}
      & \multicolumn{3}{c}{Inpainting Once}
      & \multicolumn{3}{c}{Inpainting Twice} \\
\cmidrule{2-4} \cmidrule{5-7} \cmidrule{8-10}
& {error} & {correlation} & {time} &
  {error} & {correlation} & {time} &
  {error} & {correlation} & {time} \\
\midrule
10 & 13.6 & 98.4 & 113 & 12.4 & 98.7 & 285 & 12.3 & 98.7 & 411 \\
15 &  8.4 & 99.4 & 135 \\
20 &  6.2 & 99.7 & 140 \\
\bottomrule
\end{tabular*}
\endgroup

\end{document}

Any suggestions are welcomed.
First error line:
Package: l3keys2e 2020-02-14 LaTeX2e option processing using LaTeX3 keys
)
\l__siunitx_tmp_box=\box48
\l__siunitx_tmp_dim=\dimen159
\l__siunitx_tmp_int=\count183
! LaTeX3 Error: '\tl_to_lowercase:n' deprecated on 2018-03-05. Use
(LaTeX3) '\tex_lowercase:D '.
Type <return> to continue.
...
l.318 \tl_to_lowercase:n
{
LaTeX does not know anything more about this error, sorry.

A: By analysing the OPs log file we find that MikTeX is loading an extra folder in which there is a siunitx version that identifies it self as
Package: siunitx 2012/07/16 v2.5f A comprehensive (SI) units package

which of course is not compatible with modern versions of the expl3 packages.
If that extra root folder is not needed, then disable the extra root folder in the MikTeX settings.
In case there are stuff in the extra foloder that are needed, then rename the super old version of siunitx.sty in there.


text:
Q: How to install Snappy on Hadoop 2.7.6? I'm trying to install snappy1.1.3 on my hadoop 2.7.6 cluster, and following the guide https://code.google.com/archive/p/hadoop-snappy/.
However, after I finished every step from the guide, I ran the command "hadoop checknative", it showed that "Snappy:False". I already vim the hadoop-env.sh and core-site.xml, and restarted the hadoop cluster, but nothing changed.
Is there anyone who can give me some installation guide, with links or help? I would really appreciate that. Or, do I need to compile the source code of hadoop with snappy library, as some docs showed in some webs, but not official guide. Really hope that some one who installed snappy on hadoop successfully can give me some guidance!
Btw, I already insatlled gcc, g++ (both are 4.8.5), libtool, autoconf, automake,  cmake, and JDK 1.8, Java8. Would the version of JDK and Java affect the installation?
Really hope someone could help me. I've already been in this trouble for the whole week and struggled for it.
Update:
I already followed the guide from https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-common/NativeLibraries.html,
and after the compilation I could find the snappy library in the path $ hadoop-dist/target/hadoop-2.9.1/lib/native. But I ran the command "hadoop checknative", the snappy still is false. Does anyone know what should I do after the compilation of hadoop source code?

A: I also have this problem on hadoop 2.7.6 and when change my version to 2.7.7, it solved. I didn't go more to check why this happened, but I also try different ways to solve it on 2.7.6 but finally I didn't find solution except upgrading to 2.7.7


text:
Q: MacVIM on Lion - Command-T opens new tab instead of finding files I have installed MacVim and I'm trying to learn it. But one of the most useful commands for me, the Command-T plugin, doesn't work correctly on Lion. If I type COMMAND-T, it opens a new tab on my macvim! Just like it opens a new tab on safari, terminal, etc!
I googled around, but it seems that I'm the only one with this problem.
I tried \t, but nothing happened as well.
Thanks!

A: The default for Command-T window list is <leader>t not <D>t (the "D" modifier is the Apple Command key) and the default leader for vim is \. So \t should work.
First see if you can execute
:CommandT

If that doesn't work check if your vim has support for ruby by running:
:version

In the :version output be sure that you can see +ruby.
See Troubleshooting section of Command-T for more: http://amix.dk/blog/post/19501:


text:
Q: Может ли Zabbix мониторить данные в базе MySQL? Здравствуйте!
Мой вопрос связан с тем, что хотелось бы мониторить некоторые вычисляемые значения в базе MySQL сторонней программы. Например, необходимо мониторить в базе данных подобное значение:
SELECT SUM(`column1`) FROM `table` where `column2` = "text"

Можно ли в zabbix реализовать что-то подобное?

A: Не хватает подробностей,
возможно это поможет:
zabbix 3.0 docs
заббикс - мощный инструмент для мониторига, если у вас есть, например, готовое консольное решение(bash, python, ruby script...) для получения данных по сабжу, то внедрить в заббикс - дело времени.


text:
Q: porque display flex me arruina mi posicionamiento en el @media? Mi pagina web tiene un conjunto de cartas que en computadora quiero que se vean 2 row de 3 cartas y una row mas de 1 carta , pero para celulares quiero que se vea como 3 columns una arriba de la otra, así viéndose como una gran column de 7 cartas.
El problema es que si pongo el display:flex en .project-first-row (en el css para computadora) luego no me deja en el @media poner project-first-row{ flex-direction: column;} pero solo en la primer columna, porque para proyect-second-row y para proyect-second-row si me deja.
Ahora, si le saco directamente el display:flex al css para computadora, si me deja poner column en el media, pero ya no se vería bien en la computadora (pero si en el celular). Espero que se entienda. Que puedo hacer?

background-color:white;
width: 100%;
padding-top: 75px;
height: 45em;
text-align: center;

}
#project-text {
  width: 500px;
  margin-left: 380px;
  margin-top: -20px;
}
#project,
.project-line-one .project-line-two .project-line-three {
  font-size: 20px;
}
.project-first-row {
  flex-direction: row;
  justify-content: space-around;
  margin-top: 30px;
  display: flex;
  /*este es el que luego en el media no me dejara cambiar a column el flex-direction, pero si se lo saco, si me deja en el media, pero ya no se ve bien en el css para computadora*/
}
.project123 {
  width: 350px;
  height: 350px;
  border-radius: 5%;
  border-style: solid;
  border-width: 1px;
  border-color: #d1d1e9;
}
.project123:hover {
  border-style: solid;
  border-width: 1px;
  border-color: #b172ff;
}
.project123 .portfolio-pic,
.generator-pic,
.match-pic {
  margin-left: -4px;
  max-width: 330px;
  max-height: 300px;
  margin-top: 3px;
}
.project-second-row {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 30px;
}
.project456 {
  width: 350px;
  height: 350px;
  border-radius: 5%;
  border-width: 1px;
  border-style: solid;
  border-color: #d1d1e9;
}
.project456:hover {
  border-style: solid;
  border-width: 1px;
  border-color: #b172ff;
}
.project456 .expenses-pic,
.admin-pic {
  margin-left: -4px;
  max-width: 300px;
  max-height: 300px;
  margin-top: 3px;
}
.project456 .app {
  display: flex;
  flex-direction: column;
  margin-left: 35px;
  max-width: 290px;
  max-height: 290px;
  margin-top: 20px;
}
.project-third-row {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 30px;
}
.project7 {
  width: 350px;
  height: 350px;
  border-radius: 5%;
  margin-left: -841px;
  border-width: 1px;
  border-style: solid;
  border-color: #d1d1e9;
}
.project7:hover {
  border-style: solid;
  border-width: 1px;
  border-color: #b172ff;
}
.project7 .movie-pic {
  margin-left: -4px;
  max-width: 300px;
  max-height: 300px;
  margin-top: 3px;
}

/*CSS el @media estilandolo para un celular*/
height: fit-content;
width: 100%;
flex-direction: column;
background-color: red;

}
#project strong {
  margin-left:-21%;
}
#project-text {
  margin: 0;
  width: 60%;
  margin-left: 10%;
}
project-first-row {
  flex-direction: column;
  /*esto no me lo toma por culpa del display:flex del css anterior, si se lo saco, ahi si me toma este, pero ya no se veria bien para computadoras*/
  height: fit-content;
  background-color: greenyellow;
}
.project123 {
  width: 290px;
  height: 340px;
  margin-top: 10%;
  margin-left: 0.6%;
  background-color: orange;
}
.project123 .portfolio-pic,
.generator-pic,
.match-pic {
  margin-left: 0;
  max-width: 285px;
  max-height: 285px;
}
.project-second-row {
  flex-direction: column;
  height: fit-content;
  margin-top: 0;
}
.project456 {
  width: 290px;
  height: 340px;
  margin-top: 10%;
  margin-left: 0.6%;
}
.project456 .expenses-pic,
.admin-pic {
  margin-left: 0;
  max-width: 285px;
  max-height: 285px;
}
.project-third-row {
  flex-direction: column;
  height: fit-content;
  margin-top: 0;
}
.project7 {
  width: 290px;
  height: 340px;
  margin-top: 10%;
  margin-left: 0.6%;
}
.project7 .movie-pic {
  margin-left: 0;
  max-width: 285px;
  max-height: 285px;
}

    Porfolio

    Meme Generator

    Match3

      Expenses Tracking

      Meeting Planner

      All about Apps

      Movie search

A: Hola espero te sea de ayuda.

body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

main {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
}

.bandas{
    margin-top: 10px;
    background-color: rgb(202, 191, 202);
    display:flex;
    border-radius: 5px;
    align-items: center;
    justify-content: center;
    margin: 10px;
}

.card{
    background-color: orange;
    height: 300px;
    width: 230px;
    margin: 0px 5px 0px 5px;
    border-radius: 5px;
}

@media only screen and (max-width: 480px) {
    .bandas{
        flex-direction: column;
    }
    .card{
        margin: 5px 0px 5px 0px;
    }
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./styles.css">


text:
Q: Why are there CSS rules using -9999px On the Twitter site, I found the following CSS rules:
.ProfileCanopy-headerBg img {
  position: absolute;
  left: 0;
  right: 0;
  top: -9999px;
  bottom: -9999px;
  margin: auto 0;
  width: 100%;
}

What could be the reason for the limit -9999px?

A: It's a way to hide an element that still allows screen readers (and similar technologies) to read the contents, unlike if you were to use, say, display: none.
The value 9999px is arbitrary. Can be any negative number really but I guess it feels safer to really shove it far away :P


text:
Q: Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\teller\fungsi.php on line 2 i get a notice
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\teller\fungsi.php on line 2
Notice: Use of undefined constant status - assumed 'status' in C:\xampp\htdocs\teller\fungsi.php on line 17
Notice: Use of undefined constant status - assumed 'status' in C:\xampp\htdocs\teller\fungsi.php on line 20

in my code. I try this function in the old my sql version was success. but in my sql versi 5.5.16 it doesn't work.
this is my source code :
<?php
session_start();
function ver_user($username,$password)
{
    mysql_connect('localhost', 'root', '');
    mysql_select_db('teller');
    if (!empty($username))
        {
            $query="SELECT * FROM `user` WHERE `username`='$username'";
            $action=mysql_query($query);
            $data=mysql_fetch_array($action);
            $passmd5=md5($password);
            if ($data['password']==$passmd5)
                {
                    $_SESSION['username']=$username;
                    $_SESSION['password']=$password;
                    if ($data[status]==1){
                        $data['0']="valid";
                    }
                    if ($data[status]==2) {
                        $data['0']="valid1";
                    }
                    return $data;
                }
            else
                {
                    $data['0']="invalid";
                    return $data;
                }
        }
}
function logout()
{
    session_destroy();
}
?>

A: The second and third warning are because
$data[status]

should be
$data['status']

There isn't enough information in the question to explain why you get the warning about session_start(). You need to check more of the code to find where you're calling session_start() before this.


text:
Q: Java Generics: "Nested" type parameters? EDIT: Yes, this may be a duplicate. But whereas the other question is akin to "What is a chainsaw and how do I use it?" mine is more like "I am trying to drill a hole with this machine here and it doesn't work - what's up?". Of course the answer is "Don't use a chainsaw!" and easily found once you know you are dealing with a chainsaw.
But I didn't even know that my question was related to "raw types vs. wild cards" and therefore didn't find that question - so maybe this question is still useful for others like me.
ORIGINAL QUESTION: Let's say I have the following data structure which represents an item in my user interface:
public static abstract class RowItem<T> {

    public final T value;

    public RowItem(T value) {
        this.value = value;
    }
}

Now, I would like to do the following:
public static abstract class EpgRowItem<T> extends RowItem<Pair<String, T>> {

    public EpgRowItem(Pair<String, T> value) {
        super(value);
    }
}

public static final class EpgRowProgramItem extends EpgRowItem<Program> {

    public EpgRowProgramItem(Pair<String, Program> value) {
        super(value);
    }
}

public static final class EpgRowOtherDateItem extends EpgRowItem<LocalDate> {

    public EpgRowOtherDateItem(Pair<String, LocalDate> value) {
        super(value);
    }
}

So, in words: An EpgRowItem is a RowItem that contains a Pair, of which the first member is always a String and the second member can be anything. Furthermore, an EpgRowProgramItem is an EpgRowItem in which the second member of the pair is a Program. Likewise, an EpgRowOtherDateItem is an EpgRowItem in which the second member of the pair is a LocalDate.
This seems to work until I have this at some other place in my code:
List<OverlayPresenter.EpgRowItem> programs = ...;
OverlayPresenter.EpgRowItem epgRowItem = programs.get(0);
String channelId = epgRowItem.value.first; // DOESN'T COMPILE?!

I feel the compiler should know that epgRowItem.value must ALWAYS be a Pair<String, ?>, and consequently epgRowItem.value.first must ALWAYS be a String.
Actually, it doesn't even seem to know the first part, i. e. the following doesn't compile either:
Pair<String, ?> pair = epgRowItem.value; // epgRowItem.value is an Object?!

What am I doing wrong? Am I just asking too much of Java's generics?

A: You get into trouble because you are using the raw type EpgRowItem (a raw type is a parameterized type for which you do not specify type parameters; these exist because of backward compatibility with Java 1.4 and older):
List<OverlayPresenter.EpgRowItem> programs = ...;
OverlayPresenter.EpgRowItem epgRowItem = programs.get(0);

See: What is a raw type and why shouldn't we use it?
Use a type parameter, or at least a wildcard:
List<OverlayPresenter.EpgRowItem<?>> programs = ...;
OverlayPresenter.EpgRowItem<?> epgRowItem = programs.get(0);
String channelId = epgRowItem.value.first;  // OK


text:
Q: How to Send Bulk Email Using ASP.Net C# I need send once a month automatic login and password to the registered users on our web page to facilitate access on our products and services.
But I'm afraid to generate spam on the net and I thought about sending the message for single user in a block of email e.g. 25 messages for each time.
Possible query mysql code:
Select CustomerID,ContactName,Address,Phone,Email from customers
Where email_sent = 0 LIMIT 25;

For each time the field email_Sent is update to 1 for the 25 users email and then the next 25 users.
How to realize this idea with c# asp net?
I'd greatly appreciate any suggestions.
Thanks!

A: I recommend to write a windows console and then schedule to run from  task schedule of windows. in task schedule set trigger monthly.
in mail server:
first you should know that dkim and spf for email are ok.
you can send an email to a gmail account for testing. then in gmail go to "show original" and see they are pass.
image to show spf and dkim pass
if you can add ptr record. it will help to prevent spam
in body of email:
you should write address and unsubscribe link in email.
in code:
you should set email is bulk.in c# sample code:
 var mailtest = new System.Net.Mail.MailMessage()
                {
                    From = new System.Net.Mail.MailAddress("", ""),
                    Subject = toSend.DirecMessageSubject,
                    IsBodyHtml = true
                };

mailtest.Headers.Add("Precedence", "bulk");`


text:
Q: Read chunks in a disk (kernel programming) I want to read the first(s) chunks of my disk.
I'm currently developing a driver and i want to stock (and retrieve) some meta data (the number of time each chunks is consulted) in the firsts chunk of my disk
I've see  How to read a sector using a bio request in Linux kernel
and then i start writing the code for the read part :
struct bio *bio = bio_alloc(GFP_NOIO, 1);
struct page *page =  alloc_page(GFP_KERNEL)
struct completion event;
bio->bi_bdev = conf->disks[0].rdev;
bio->bi_sector = (sector_t) 0;
bio_add_page(bio, page, (sizeof(struct nuda_table)) * conf->nbr_chunk, 0);
init_completion(&event);
bio->bi_private = &event;
bio->bi_end_io = readComplete;

submit_bio(READ | REQ_SYNC, bio);
wait_for_completion(&event);
bio_put(bio);

But then i don't know where the data that i have read are stored.
In the struct page ?
Little other question : there is a parameter length in bio_add_page() is this suppose to be bytes ? or chunks ? or other things ?
Thank you in advance

A: page_address will return a pointer (void*) that you can use to read or write the content of the page. However, if it is a page in high memory it will only work if the page is mapped.
Using kmap may be preferable, as it will do that check for you :
void *kmap(struct page *page)
{
        might_sleep();
        if (!PageHighMem(page))
               return page_address(page);
        return kmap_high(page);
}


text:
Q: Display string array macOS Xamarin application I have a generic collection List<(my own type)>.
How can I display a simple array of strings to not define my own cells (NSCollectionViewItem)?
Which control is best for this?


text:
Q: MySQL not equal doesn't work I have the following MySQL code:
SELECT db.chr FROM jp_lists_kanji db, (SELECT list.chr,
                                     FLOOR(1 + RAND() * x.m_id) 'rand_ind'
                                FROM jp_stats_kanji list,
                                     (SELECT MAX(t.id) - 1 'm_id'
                                        FROM jp_stats_kanji t) x
                               WHERE user_id = '12345678'
                                 AND chr != '〇'
                            ORDER BY rand_ind
                               LIMIT 17) random WHERE db.id = random.chr

How is it possible that the result is 〇? Shouldn't AND chr != '〇' prevent that?

A: The join condition for the field returned is WHERE db.id = random.chr. Unless db.id always =  db.chr, '〇' is a valid result.


text:
Q: Custom ImageView is not showing images I am trying to implement an imageview with a diagonal cut at the bottom that I will user to display images on my app. This is the approach I take

*

*I create a custom class that extends the ImageView.

*I then override the onDraw method to draw the shape(This is where I'm not sure if I'm doing the correct thing

My custom imageview class

public class DiagonalSquare extends ImageView {

private Context mContext;
Paint paint ;
Path path;

public DiagonalSquare(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.mContext = context;
    setWillNotDraw(false);
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
}

@Override
protected void onDraw(Canvas canvas) {

    int w = getWidth(), h = getHeight();
    paint.setStrokeWidth(2);
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    paint.setAntiAlias(true);

    path = new Path();
    path.setFillType(Path.FillType.EVEN_ODD);

    path.moveTo(w,h*3/4);
    path.lineTo(w,h);
    path.lineTo(0,h);
    path.close();
    canvas.drawPath(path, paint);
  }
}

This is what I end up getting - blue section is the imageview. Here is the xml for that
  <com.noel.CustomShape.DiagonalSquare
            android:id="@+id/background_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax"
            android:src="@drawable/bebe" />

A: You are missing a call to super.onDraw(canvas);

A: In addition to @Dimezis answer: If you want to have transparent effect on the ImageView background you have to clear hardware layer type and also set  Xfermode for pain like in following example:
package com.j2ko.customviews;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.widget.ImageView;

public class CustomImageView extends ImageView {
    private Context mContext;
    Paint paint ;
    Path path;

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        setWillNotDraw(false);
        //Move to XML if needed
        setBackgroundColor(Color.TRANSPARENT);
        setLayerType(LAYER_TYPE_HARDWARE, null);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int w = getWidth(), h = getHeight();
        paint.setStrokeWidth(2);
        paint.setColor(Color.WHITE);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        paint.setAntiAlias(true);

        path = new Path();

        path.setFillType(Path.FillType.EVEN_ODD);

        path.moveTo(w,h*3/4);
        path.lineTo(w,h);
        path.lineTo(0,h);
        path.close();
        canvas.drawPath(path, paint);
    }
}

This will give the following results:


text:
Q: Changing fonts (and related settings) in wordpress theme I am using wordpress for my blog/site. I am using Freshnews theme from woothemes as the theme for the blog.
Here is the link:
http://demo.woothemes.com/freshnews/
The font is not that good and it is way too small and the spacing is bad (too congested).
How do I change the fonts, size, spacing (line and paragraph) throughout the blog.
I know I would have to change it somewhere in the stylesheet. But where exactly and how?
And what are the ways to get this done?
Should I install a font somewhere?
Should I use webfonts (like google webfonts)?
What is the advantage in using this?
or what are the other ways?

A: Freshnews is one of woothemes older templates but should come with a custom.css file in your root folder. This file is used to override styles in your themes style sheet. You will want to use chrome developer tools or firebug to determine which fonts you want to adjust.
I assume you wan to change your p tags, to adjust the font family, size, and line-height to so in custom.css put the following. Note that there are many styles to edit to get all the font sizes adjusted. Your best bet is to use chrome developer tool or firebug to find the class and ID's of the styles you want to edit.
.entry p {
font-size: 1.2em;
}
p {
font-size: 1.2em;
}


text:
Q: A couple unrelated questions from Jech's "Set Theory" We are taking a course in set theory and the book we are working with is Jech's Set Theory. This is not my first course in set theory. I know the concepts of union, intersection, induction, transfinite induction, power sets, ordinals, and basic notions about cardinals.
In first class we studied about first ten axioms. I am supposed to do the exercises of chapter one. My problem is, that, the statements look too obvious to prove. For example:

Exercise 1.1: Verify (1.1): Axiom of extensionality: If $X$ and $Y$ have the same elements, then, $X = Y$.

My answer: $a \in X \Rightarrow a \in Y$ and $a \in Y \Rightarrow a \in X$ Therfore $X \subseteq Y$ and $Y \subseteq X$ therfore $X = Y$.
Is this ok?

Exercise 1.2: There is no set $X$ such that $P(X) \subset X$

I know that $|P(X)|=2^{|X|}$  but I guess I can't use that? So, what can I use?

A: I think the (1.1) referenced in that problem is the one in the section "Pairing." It doesn't make sense to ask you to verify an axiom, and the "Pairing" section doesn't prove the statement (1.1) that $$(a,b)=(c,d)\iff a=c\land b=d$$
For the second one, you get the Russell paradox if $\mathcal P(X)\subset X$. Define $V=\{U\in\mathcal P(X)\mid U\notin U\}$.  $V$ is a  subset of $\mathcal P(X)$. If $\mathcal P(X)\subset X$, then we also have $V\subset X$, and hence $V\in P(X)$. Is $V\in V$?


text:
Q: wordpress enqueue admin scripts on specific page I wrote a plugin that requires some js and css file on the admin side.
I enqueue them like this:
function checkin_page_files() {
    if ( is_page('/admin.php?page=reports_Systems')) {
        wp_enqueue_style( 'checkin-page-style', content_url() . '/plugins/reports/includes/checkin_page/style.css' );
        wp_enqueue_script( 'checkin-page-js', content_url() . '/plugins/reports/assets/js/checkinPageJavascripts.js', array(), false, false );
        wp_enqueue_script( 'checkin-live-validation-js', content_url() . '/plugins/reports/assets/js/liveValidation.js', array(), false, false );
    }
}

add_action( 'admin_enqueue_scripts', 'checkin_page_files', 0 );

and, as you can see, I am trying to specify that I'd like to include them only if the page is /admin.php?page=reports_Systems, but that doesn't seem to work.
Without the if statement, the files are included properly, so it's not a path error.
How can I achieve this?
All the examples I saw online used the if statement to provide a page like admin.php, or post.php, without the ?.
I think that the reason why mine doesn't work is because of the ? and I wasn't able to find examples like this.
Thanks in advance

A: Here you can check for the $_GET variable 'page'. Wordpress has a built in method get_query_var() to get the $_GET variable from the url.
if(get_query_var('page') == reports_Systems){
//enqueue your scripts
}


text:
Q: How can i transfer a database in SQLyog? I use SQLyog Ultimate ver11.11 on windows8.1. I need to transfer a database from another machine (which it uses SQLyog Ultimate ver11.11 too). What is easiest way for do it?(I mean how can i detach an already existing database in another machine and then attach it to mine?!)
Thanks in advance.

A: Follow below steps :
1) Export database from old system SQLyog. (You can find export option on right click of database)
2) Create database in second system with same name.
3) Import database to second system SQLyog.
Note : I would recomment to use mysql command line.
Just for your information.
For export : mysqldump databaseName > databaseName.sql
For import : mysql databaseName < databaseName.sql
Note : Make sure, you have created your database before importing, otherwise it will give you error with message database not found.

A: If you can connect to both databases then you can use SQL-Yogs copy database command, just right-click on the database to copy in the database list.


text:
Q: Adding and remove layers in cartodb I've been trying to follow the documentation for cartodb for a while to figure this out, but haven't found it very clear. All I'm trying to do is hide one layer and then show another layer upon button click.
However, I have no idea of the syntax and the documentation wasn't much help.
$(document).ready(function() {

var map2 = new L.Map('attribute_map', {
center: [39.8282,-98.5795],
zoom: 4,

})
var map2;
$('#load_2').click(function() {

$('#load_2').css("display","none");
$ ('#attribute_map').css("height","520px");

 var mapURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png'
L.tileLayer(mapURL, {

}).addTo(map2);
 cartodb.createLayer(map2, 'https://jonmrich.cartodb.com/api/v2/viz/50366df6-afed-11e4-ab33-0e853d047bba/viz.json', { https: true,legends: true,cartodb_logo:false,layerIndex:1 })
.addTo(map2)

});
$('#load_3').click(function() {

 cartodb.createLayer(map2, 'https://jonmrich.cartodb.com/api/v2/viz/0a63ff26-ad47-11e4-bebb-0e4fddd5de28/viz.json', { https: true,legends: false,cartodb_logo:false, })
.addTo(map2)
 });
  });

Can someone point me in remotely the right direction? In this example, I'm trying to add visualizations based on different tables. I also tried doing it for multiple layers in the same visualization, but couldn't figure that out either.

A: You should load both sublayers through createLayer, then turn off the one you want to hide initially.
The following works if you have two tables in the visualization you created in CartoDB Editor. If you want to add layers without having a viz.json link, you can create the layers at runtime.
// Instantiate map
var map = L.map('map', {
            center: [39.8282,-98.5795],
            zoom: 4
           });

// basemap url
var mapURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png'

// add basemap tiles to map
L.tileLayer(mapURL, {
        attribution: '© OpenStreetMap contributors, © CartoDB'
    }).addTo(map);

// add cartodb data layers to map
cartodb.createLayer(
    map,
    'https://jonmrich.cartodb.com/api/v2/viz/50366df6-afed-11e4-ab33-0e853d047bba/viz.json',
    {
        https: true,
        legends: true,
        cartodb_logo:false,
        layerIndex:1
    })
.addTo(map)
.done(function(layer) { // when successful, do this stuff

    var sublayer0 = layer.getSubLayer(0);
    var sublayer1 = layer.getSubLayer(1);

    // hide sublayer1
    sublayer1.hide();

    $("#load_3").on('click', function() {
    // turn on layer off, turn off layer on
        sublayer0.toggle();
        sublayer1.toggle();
    });
})
.error(function(err) { // when error, do this
    console.log("error: " + err);
});


text:
Q: PHP: exec weirdness This is my code:
        $command = 'path to some script';
        echo "Running command:\n $command ";
        $result = array ();
        exec ($command, $result);

Which results in the following:
Running command:
[here go some warning printed by the command itself]
path to some script
I.e. the error output of the script, is somehow inserted in the middle (!) of an echo command preceding it.
Ideas?

A: This will be down to buffered vs non-buffered io. The error output will be stderror, and the other will be stdout. Stdout is generally buffered - so if you were to force it to flush before running the script you would get the result you want.
Try this http://php.net/manual/en/function.flush.php

A: This is because exec does not capture standard error (stderr), per example:
exec ('/bin/echo foo > /dev/stderr', $result);

Will output foo, even though exec shouldn't output anything. You can force it to by doing:
exec ($command.' 2>&1', $result);

The reason it appears in the middle is probably because of output buffering (as @Danny explained above). The output buffer may exhaust before the end of command and therefore is flushed automatically, and a new one is started. Hence the error appearing in the middle.


text:
Q: create procedure please hep, I am trying to create a procedure that will  display 4 parameters whenever I enter a parameter. This is my code below
CREATE PROCEDURE sp_emp_info
(       @EmployeeID         INT,
        @EmployeeID         INT             OUTPUT,
        @LastName           VARCHAR(30)     OUTPUT,
        @FirstName          VARCHAR(15)     OUTPUT,
        @Phone              VARCHAR(10)     OUTPUT      )
AS
SELECT @EmployeeID,
      @LastName,
     @FirstName,
     @Phone
FROM    Employees
WHERE   EmployeeID = @EmployeeID
GO

This is bringing this error

The variable name '@EmployeeID' has already been declared. Variable names must be unique within a query batch or stored procedure.
Must declare the scalar variable "@LastName"

I have EmployeeID as both input and output. When I tried to remove the output  by running the below :
CREATE PROCEDURE sp_emp_info
(       @EmployeeID         int,
        @LastName           VARCHAR(30)     OUTPUT,
        @FirstName          VARCHAR(15)     OUTPUT,
        @Phone              VARCHAR(10)     OUTPUT      )
AS
SELECT @EmployeeID,
    @LastName,
    @FirstName,
    @Phone
FROM    Employees
WHERE   EmployeeID = @EmployeeID
GO

that worked, but the  procedure wont run . eg I ran
EXECUTE sp_emp_info 7

It brough this error:

Procedure or function 'sp_emp_info' expects parameter '@LastName', which was not supplied.

What do you think I am doing wrong? Thank you .

A: You need to set a default value for the optional parameters. In this case I set them to NULL.
CREATE PROCEDURE sp_emp_info
    (       @EmployeeID         int      )
    AS
    SELECT EmployeeID
        LastName,
        FirstName,
        Phone
    FROM    Employees
    WHERE   EmployeeID = @EmployeeID
    GO

A: Okay, I was going about this the complex way. this simple coding:
CREATE PROCEDURE sp_emp_info
(       @EmployeeID         int     )
AS
SELECT  EmployeeID,
        LastName,
        FirstName,
        Phone
FROM    Employees
WHERE EmployeeID = @EmployeeID
GO
solved my problem.
Thank you everyone.Much appreciated


text:
Q: Sharing specific text on Facebook I have a quiz page, where the outcome can be 1 of 10 possibilities.
I then have a share link for Facebook, to share a link to the page and also to share the results from the quiz.
I believe I could alter the og tags in the header so that og:description became the desired text, however as Facebook caches pages, this would only be correct the first time being shares and all other shares would be this same one and not the updates og:description tag.
Using JavaScript, is there any other way that I can achieve this?

A: The best way to achieve this is not to change OG tags but use FB.ui
            var obj = {
                method: 'feed',
                picture: image.png,
                name: 'name text',
                caption: 'caption text',
                description: 'description',
                link: 'link',
            };

            function callback(response) {
                console.log("Post ID: " + response['post_id']);
            }
            FB.ui(obj, callback);

This is covered in https://developers.facebook.com/docs/sharing/reference/feed-dialog/v2.5 you will need a Facebook APP + FB JS in your HTML.


text:
Q: What are the permissions necessary for an 'Always-On-Display' app? I would like to make an AOD (always on display) app using Flutter.
I just want to know what are the permissions that my app requires in order to be functional.
I didn't start the proj. yet, therefore I don't even have any code to share.
Would start the proj. after I get my answers.

A: Always on display,you can achieve it by using this package
https://pub.dev/packages/wakelock
you can easily call like this and achieve your goal.like follows
import 'package:wakelock/wakelock.dart';
// ...

// The following line will enable the Android and iOS wakelock.
Wakelock.enable();

// The next line disables the wakelock again.
Wakelock.disable();


text:
Q: Python TCP Client to Client message forwarding I am looking for a short example in python of a TCP server passing an incoming client message to another new client. All I could find was examples on echo server/clients.
Cheers,
dhpizza

A: Here's a basic example using only standard libraries:
import SocketServer
import threading

class Handler(SocketServer.StreamRequestHandler):

    def handle(self):
        print self.client_address,'connected'
        self.server.add_client(self.request)
        while 1:
            data = self.request.recv(1024)
            if not data: break
            self.server.send(self.request,data)
        self.server.remove_client(self.request)

class Server(SocketServer.ThreadingTCPServer):

    def __init__(self,*args,**kwargs):
        SocketServer.ThreadingTCPServer.__init__(self,*args,**kwargs)
        self.clients = []
        self.lock = threading.Lock()

    def add_client(self,c):
        with self.lock:
            self.clients.append(c)

    def remove_client(self,c):
        with self.lock:
            self.clients.remove(c)

    def send(self,sender,data):
        with self.lock:
            for c in self.clients:
                if c is not sender:
                    c.sendall(data)

s = Server(('',8000),Handler)
s.serve_forever()


text:
Q: How can I track the total amount of memory used during runtime? I want to find out during runtime, how much (heap) memory my c++ program is currently using. Can I achieve this by overloading the new/delete operators? Is there a library which provides this functionality?
I know that tools like valgrind can give me a lot of information about my memory usage, but that information is not available during runtime and thus cannot be used by the program.
Background
I am writing a scientific program. I.e., I can assume that the program may use basically all the memory available on the machine on which it is running (or a predefined, fixed amount). I have to deal with large amounts of data which may or may not fit into the available memory. In case of insufficient memory the program may take countermeasures (e.g. store data to disk or recalculate data instead of storing them). To be able to do that I need to track how much memory has been used.


text:
Q: combine and append dataframe as list of dictionarys to a response object I have a dataframe in below format:

daily_dates
registered
attended

02/10/2022
0
0

02/09/2022
0
0

02/08/2022
1
0

And my response object is of this format:
response = {"registered":[], "attended":[]}

I am looking to combine daily_dates with registered and attended column to result in below response object.
response = {"registered":[{"02/10/2022":0},{"02/09/2022":0},{"02/08/2022":1}], "attended":[{"02/10/2022":0},{"02/09/2022":0},{"02/08/2022":0}]}

The below is my current coding approach:
weekly['registered'] = weekly.apply(lambda row: {row['daily_dates']: row['registered']}, axis=1)
response["registered"] += weekly['registered'].tolist()

I am looking for a much efficient and direct way of achieving this.

A: Direct but ugly:
response = {"registered":[], "attended":[]}
for _, d, r, a in weekly.itertuples(name=None):
    response['registered'].append({d: r})
    response['attended'].append({d: a})

A: I think you can build it manually like this:
Option 1:
dd = df.set_index('daily_dates').to_dict()
for k in dd.keys():
  l = []
  for ki, v in dd[k].items():
      l.append({ki: v})
  dd[k] = l
dd

Output:
{'registered': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 1}],
 'attended': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 0}]}

Option 2 using defaultdict:
from collections import defaultdict
defd = defaultdict(list)

dd = df.set_index('daily_dates').to_dict()
[defd[k].append({ek:ev}) for k, v in dd.items() for ek, ev in v.items()]
dict(defd)

Output:
{'registered': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 1}],
 'attended': [{'02/10/2022': 0}, {'02/09/2022': 0}, {'02/08/2022': 0}]}


text:
Q: How can I disconnect the client just after I received a new message from a chat, in Telethon library I'm using telethon and for some reason, I need to use one session to connect and disconnect my client, so I want after receiving an event from a specific chat (one message from a specific bot), the client will disconnect, this is what I am doing...
bot_id = "chat id of telegram bot"

await client.connect()

        @client.on(events.NewMessage(chats=bot_id))
        async def imp_msg(event):
            # print(event)
            await client.send_message(123456, event.message)

        await client.start()

If I use await client.disconnect() It does not make any change and gives me sqlite3.OperationalError: database is locked probably I am doing some mistake.
await client.connect()

    @client.on(events.NewMessage(chats=bot_id))
    async def imp_msg(event):
        # print(event)
        await client.send_message(123456, event.message)
        await client.disconnect()

    await client.start()

A: You can do:
client = TelegramClient('session',api_id,api_hash)

async with client:
     print('Connected')
     @client.on(events.NewMessage(chats=bot_id))
     async def imp_msg(event):
         await client.send_message(123456, event.message)
         await client.disconnect()
     await client.run_until_disconnected()


text:
Q: Unknown column 'PROGRAMMEDescription' in 'field list' I'm trying to write a servlet which makes a query to a database, but when it runs, I get this error:

java.sql.SQLSyntaxErrorException: Unknown column 'PROGRAMMEDescription' in 'field list'

The code:
response.setContentType("text/html; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String requestType= request.getParameter("requestType");
if (requestType == null) {
    createDynPage(response, "Μη έγκυρος τύπος ερωτήματος");
}

if (requestType.equalsIgnoreCase("insert")) {
    String descr = request.getParameter("descr");
    String mins = request.getParameter("mins");
    String sms = request.getParameter("sms");
    String mb = request.getParameter("mb");
    String pagio = request.getParameter("pagio");
    String minstoall = request.getParameter("minstoall");
    String costpermin = request.getParameter("costpermin");
    String costpersms= request.getParameter("costpersms");
    String costpermb = request.getParameter("costpermb");
    int m = Integer.parseInt(mins);
    int s = Integer.parseInt(sms);
    int d = Integer.parseInt(mb);
    float fc=Float.parseFloat(pagio);
    int mta = Integer.parseInt(minstoall);
    float cpm=Float.parseFloat(costpermin);
    float cps=Float.parseFloat(costpersms);
    float cpmb=Float.parseFloat(costpermb);

    try {
        Connection con = datasource.getConnection();

        Statement stmt = con.createStatement();
        StringBuilder x = new StringBuilder();

        String insertStmt = "INSERT INTO CUSTOMERS (PROGRAMMEDescription, PROGRAMMESpeechTime, PROGRAMMESMSNumber, PROGRAMMEData, PROGRAMMEFixedCost, PROGRAMMESpeechTimeToAll, PROGRAMMECostPerMinute, PROGRAMMECostPerSMS, PROGRAMMECostPerMB)" +
                " VALUES (";
        insertStmt += "'" + descr + "',";
        insertStmt +=  m + ",";
        insertStmt +=  s + ",";
        insertStmt +=  d + ",";
        insertStmt +=  fc + ",";
        insertStmt +=  mta + ",";
        insertStmt +=  cpm + ",";
        insertStmt +=  cps + ",";
        insertStmt +=  cpmb + ")";

        stmt.executeUpdate(insertStmt);
        createDynPage(response, "Το πρόγραμμα δημιουργήθηκε επιτυχώς!");
        stmt.close();

        con.close();

    } catch(SQLException sqle) {
        sqle.printStackTrace();
    }

} else {
    createDynPage(response, "The request type parameter must be insert");
}

The table:

As you can see from both the code and the table, the column PROGRAMMEDescription exists normally. I can't understant why Java think it doesn't. Any ideas?

A: I think it may be because the field is not in the database! Perhaps you should get the sql statement executed this time and execute it once in the database to determine whether the field exists in the database!


text:
Q: Symfony get single form field post value in controller method I'm using symfony 2.8, I'm submitting a registration from to registerAction method. I'm getting all my submitted data like this when I use $form-getdata() in registerAction method.
AppBundle\Entity\User Object
(
    [id:AppBundle\Entity\User:private] =>
    [name:AppBundle\Entity\User:private] => testname
    [email:AppBundle\Entity\User:private] => test@test.com
    [roles:AppBundle\Entity\User:private] => Admin User
    [plainPassword:AppBundle\Entity\User:private] => 123456
    [password:AppBundle\Entity\User:private] =>
)

I have used $request->request->get('name') to get single name value but it is showing blank screen and printing nothing.
My html form looks like this on viewing source code in browser.
<form name="user" method="post" novalidate="novalidate">

Name<input type="text" id="user_name" name="user[name]" required="required" class="form-control" />

Email<input type="email" id="user_email" name="user[email]" required="required" class="form-control" />

Roles<select id="user_roles" name="user[roles]" class="form-control" style="margin:5px 0;"><option value="Normal User">Normal User</option><option value="Admin User">Admin User</option></select>

Password<input type="password" id="user_plainPassword_first" name="user[plainPassword][first]" required="required" class="form-control" />

Repeat Password<input type="password" id="user_plainPassword_second" name="user[plainPassword][second]" required="required" class="form-control" />

<button type="submit" id="user_Register" name="user[Register]" class="btn btn-success form-control">Register</button>
<input type="hidden" id="user__token" name="user[_token]" value="epZFHVctxHFlsnxG-H4OdS92DmGVjP1DDF-bKJrV2Ss" />
    </form>

How can I get single posted form value.?

A: If $request->request->get('{form_name}') returns an array with your form data, then you can access the specific input field with $request->request->get('user')['name']. But you should use form classes instead, where you can define all of necessary fields with validation constraints, etc. Hope this helps!


text:
Q: How to install Plotly for Python 3 Jupyter Notebook? I'm a total beginner and I have a problem installing plotly to use it in my Jupyter Notebook. I have installed the Python 3 version. I am also using a Mac if that matters.
I tried a variety of commands in the terminal but none of them worked.
This is my command in Jupyter Notebook:
from plotly import __version__
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

print(__version__) # requires version >= 1.9.0

This is the error I get:

ModuleNotFoundError: No module named 'plotly'

I would really appreciate some help! Thanks in advance.
Desperate beginner

A: I have now solved the problem. I just opened a new Terminal and made sure that I wrote the command
pip install cufflinks

directly after the second line.
The same worked for
pip install plotly

A: Download whl file:
https://files.pythonhosted.org/packages/3e/77/905effe9361395d3e094ffd2b54b4085d339a7b7de9c2c91fa55ec257422/plotly-3.5.0-py2.py3-none-any.whl
use pip install C:\Users\Downloads\plotly-3.5.0-py2.py3-none-any.whl

A: Official documentation page says:
For use in the classic Jupyter Notebook, install the notebook and ipywidgets packages using pip...
$ pip install "notebook>=5.3" "ipywidgets>=7.2"

or conda.
$ conda install "notebook>=5.3" "ipywidgets>=7.2"

These packages contain everything you need to run a Jupyter notebook...
$ jupyter notebook

Display plotly figures inline using the notebook renderer...
import plotly.graph_objects as go
fig = go.Figure(data=go.Bar(y=[2, 3, 1]))
fig.show()


text:
Q: Как добавить объект из библиотеки на сцену? ActionScript 2.0 Как добавить объект из библиотеки на сцену? ActionScript 2.0
A: Убедиться, что для клипа в библиотеке в свойствах стоит галочка "Export for ActionScript" и имя для экземляра. Далее добавить через MovieClip.AttachMovie()
this.attachMovie("linkageLibraryName", "instance", this.getNextHighestDepth());


text:
Q: Isapi Rewrite - preserving HTTPS in redirects behind load balancer I'm running a site which has 2 separate sub-domains - one for HTTP and another for HTTPS.

*

*http://www.example.com

*https://secure.example.com
http://secure.example.com does not exist and will not resolve.
The problem is that the site is running behind a load balancer which handles all SSL. Communication between the load balancer and the web servers in always HTTP.
So, when using Isapi Rewrite 3 (a mod_rewrite clone for IIS) to implement some redirects I'm running into a problem.
As far as Isapi Rewrite is concerned HTTPS is turned off - so redirects on secure.example.com are failing.
Say I have a rule which says:
RewriteRule ^/example/$ /test/ [R=301,L]

If I make a request for https://secure.example.com/example/ I would like to end up on https://secure.example.com/test/ but, because Isapi Rewrite sees HTTPS as OFF, I end up on  http://secure.example.com/test/.
Is there any way I can force redirects to be to HTTPS if the domain is secure.example.com?
Something along the lines of this:
RewriteCond %{SERVER_NAME} secure.example.com
RewriteRule ^/(.*)$ https://secure.example.com/$1

Except that doesn't work - it immediately forces an explicit redirect, whereas I want to continue processing other RewriteRules.
Thanks,
Stu

A: How about smth like this:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^secure\.mydomain\.com$ [NC]
RewriteRule ^/example/$ https://secure.mydomain.com/test/ [R=301,L]


text:
Q: PostgreSQL JSONB find documents by word I have a table of the form:
                          Table "public.items"
     Column      |           Type           |         Modifiers
-----------------+--------------------------+---------------------------
 item_id         | character varying        | not null
 content         | character varying        |
 tags            | jsonb                    |
 body            | jsonb                    |

The body field contains data like these:
[{"text": "As a child home ..."},
{"text": "Great post. Watch this }]

What query is needed to find documents by word in the text section?

A: The standard (and most adequate) approach is the one provided by @Dan in the other answer, namely to treat a jsonb column as such an parse it using the operators -> and ->>.
An alternative to that would be to cast the column to text and go from there, e.g. body::text:
SELECT * FROM public.items WHERE body::TEXT LIKE '%child%';
SELECT * FROM public.items WHERE body::TEXT SIMILAR TO '%child%';

In case you don't want it to be case sensitive, convert both strings before comparing them, for instance using LOWER or UPPER (see documentation):
SELECT * FROM items WHERE LOWER(body::TEXT) LIKE LOWER('%CHILD%');

As suggested by Dan in the comments, ILIKE is another elegant way for dealing case insensitive queries:
SELECT * FROM items WHERE body::TEXT ILIKE '%child%'

Note: both approaches rely on a proper index to work satisfactory, otherwise the query might get very slow. See this other answer with a GIN index

A: You can do the seach using jsonb functions.
Lets say you have this:
item_id | body
--------+---------------------------------------------------------------
1       | [{"text":"aSdf aSdf"},{"text":"12 41f"},{"text":"1 31s sf"}]
2       | [{"text":"31fa3"},{"text":"3f43f"}]
3       | [{"text":"l8412"},{"text":"52%$3d1f"},{"text":"agasd as3"}]
4       | [{"text":"i8i23"}]

You can search for every element in your jsonb using:
SELECT * FROM (SELECT t.id,elem.*
FROM public.items t,jsonb_array_elements(t.body) AS elem)json_vals
WHERE value->>'text' ILIKE '%s%'

This will return the next result because the query uses ILIKE:
item_id | value
--------+----------------------
1       | {"text":"aSdf aSdf"}
1       | {"text":"1 31s sf"}
3       | {"text":"agasd as3"}

If you just need the id, you can change the * in the query for item_id and use DISTINCT. But with this query you can access every JSON in the record without having to cast it as text.
NOTE: if you just query SELECT t.id,elem.* FROM public.items t,jsonb_array_elements(t.body) AS elem you get every element in a row:
itme_id | value
--------+--------------------
1       | {"text":"aSdf aSdf"}
1       | {"text":"12 41f"}
1       | {"text":"1 31s sf"}
2       | {"text":"31fa3"}
2       | {"text":"3f43f"}
3       | {"text":"l8412"}
3       | {"text":"52%$3d1f"}
3       | {"text":"agasd as3"}
4       | {"text":"i8i23"}