text:
Q: How To Hide Taskbar and Have Programs Use Free Space I want to hide the taskbar and have any programs open use the new space from where the taskbar was. I tried to use this class.
using System;
using System.Runtime.InteropServices;
public class Taskbar
{
    [DllImport("user32.dll")]
    private static extern int FindWindow(string className, string windowText);

    [DllImport("user32.dll")]
    private static extern int ShowWindow(int hwnd, int command);

    [DllImport("user32.dll")]
    public static extern int FindWindowEx(int parentHandle, int childAfter, string className, int windowTitle);

    [DllImport("user32.dll")]
    private static extern int GetDesktopWindow();

    private const int SW_HIDE = 0;
    private const int SW_SHOW = 1;

    protected static int Handle
    {
        get
        {
            return FindWindow("Shell_TrayWnd", "");
        }
    }

    protected static int HandleOfStartButton
    {
        get
        {
            int handleOfDesktop = GetDesktopWindow();
            int handleOfStartButton = FindWindowEx(handleOfDesktop, 0, "button", 0);
            return handleOfStartButton;
        }
    }

    private Taskbar()
    {
        // hide ctor
    }

    public static void Show()
    {
        ShowWindow(Handle, SW_SHOW);
        ShowWindow(HandleOfStartButton, SW_SHOW);
    }

    public static void Hide()
    {
        ShowWindow(Handle, SW_HIDE);
        ShowWindow(HandleOfStartButton, SW_HIDE);
    }
}

I then called Taskbar.Hide(), however programs didn't use the new space.


text:
Q: Как на C выделить целую часть числа и как округлить число до ближайшего целого? Как на C можно выделить целую часть числа. И как можно округлить число до ближайшего целого?
A: Хотите целую часть? - Сделайте явное приведение типов:
double a = 1.11
b = (int) a

Хотите узнать дробную часть? Разделите число на него же, но после приведения типов и проанализируйте остаток от деления через if-else блок: сможете своим способом округление сделать.
Или не забывайте про библиотеку math. C++ style:
double d = 2.71;
double x, y;
y = std::modf(d, &x); // целая часть запишется в x, дробная - в y

redpajama_set_name: RedPajamaStackExchange


text:
Q: как с клиента принять файл на node js express? с клиента передается файл excel на сервер node js(express). как на сервере его принять и обработать?

A: Используйте multer - is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const upload = multer({
  dest: path.join(__dirname, 'uploads')
});

app.get('/', (req, res) => {
  res.render('home', { test: 'test' });
});

app.post(
  '/send',
  upload.fields([{name: 'fileEmailTo'}, {name: 'fileMessageTo'}]),
  (req, res) => {
    console.log(req.body);
    res.status(204).json({});
  }
);

app.listen(5000, () => {
  console.log('Server has been started at port 5000...');
});


text:
Q: How to debug if image is not uploading to the server I want to upload image to the server and save the file name in MySql. I am uploading from image from Android Application , i am sending all the required params from android app but still something is wrong in copy image in server. It is echoing "Upload Failed".
<?php

$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];

include('../Config.php');

$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
else
{
        $_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";

        $uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);

        if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
        {
        $filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
        if($type == "Address"){
            $sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
        }else if($type == "ID"){
            $sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
        }else if($type == "GramPanchayat"){
            $sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
        }

            if ($conn->query($sql) === TRUE)
            {

            }
            else
            {
            echo "Error: " . $sql . "
" . $conn->error;
            }
        $conn->close();
    }
    else
    {
    echo "Upload failed";
    }

}
?>

A: Let's start here.  I would change the copy() function to the move_uploaded_file() function.
Secondly, You need to check to make sure the path for the download destination exist.  If it does not then we need to create it.
We also need to make sure the folder/file has permissions to be able to write.  If it does not then change the folder/files permission.
Then when done, change your folder/files permissions back to what they were originally.
Like so:
$uploaddir = 'DocumentClient/';
$cid=$_POST['cid'];
$type = $_POST['type'];
$filetype = $_POST['filetype'];

include('../Config.php');

$conn = mysqli_connect("localhost","$username","$password","$db");
// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
else
{
        $_FILES["uploadedfile"]["name"]=$cid.$type.".jpg";

        $uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);

        //Check to see if the folder exist.
        if(!file_exists($uploaddir)) {

        mkdir($uploaddir, 0777, true); //If it does not exist then create it and set permissions to be able to write.

        }

        //The folder does exist at this point. Check to see if it's writable.
        if(!is_writable($uploaddir)){

          chmod($uploaddir, 0777); //The folder is not writeable. Set the folder to be able to write.

        }

        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile))
        {
        $filename="DocumentClient/".$_FILES["uploadedfile"]["name"];
        if($type == "Address"){
            $sql = "Update `Clients` SET `DocAddress`='$filename' Where CID='$cid'";
        }else if($type == "ID"){
            $sql = "Update `Clients` SET `DocIdProof`='$filename' Where CID='$cid'";
        }else if($type == "GramPanchayat"){
            $sql = "Update `Clients` SET `DocGrampanchyat`='$filename' Where CID='$cid'";
        }

            if ($conn->query($sql) === TRUE)
            {

            }
            else
            {
            echo "Error: " . $sql . "
" . $conn->error;
            }
        $conn->close();

        //Reset the permissions back to what you need them to be.
        //You probably want 0755
        chmod($uploaddir, 0755);
        chmod($uploadfile, 0644); //Sets your new file to read only.

        //Add this code below to test.
        if(file_exists($uploadfile)) {

        echo 'Your file exist.';

        }else{

          echo 'You file does not exist.';

          }

    }
    else
    {
    echo "Upload failed";
    }

}

Some resources for you to read.
move_uploaded_file()
is_writeable()
chmod()
You will also want to read up on file permissions an how to properly set them. Not doing this correctly can leave you open to unwanted security issues.
Hope this helps.


text:
Q: logcat filled with message "Unexpected value from nativeGetEnabledTags: 0" - how to get rid of this?
Possible Duplicate:
Unexpected value from nativeGetEnabledTags: 0

I have just installed the latest version of SDK (r21) and ADT 21.0.0. I shifted my project from the eclipse, I was using previously to the newer version. After shifting the project i clicked on the Run button to test the application, and suddenly i found that the whole logcat was filled with the message
Unexpected value from nativeGetEnabledTags: 0
I just 10 minutes the number of this kind of messages reached more than 10,000 and i am fed up with this. Please tell me how can i remove this message from appearing in the logcat. And i want to stop this message from appearing as well
Skipped 33 frames!  The application may be doing too much work on its main thread.
Please help.

A: Check this answer: Unexpected value from nativeGetEnabledTags: 0
Add this filter to the LogCat: ^(?!.*(nativeGetEnabledTags)).*$
It is a bug introduced in the latest revision of the tools... Google is working on a fix on the next version.

A: I agree with NeTeInStEiN's answer regarding the nativeGetEnabledTags issue, I have the same problem and the following in the logcat filter works to hide them (as mentioned in comments):
^(?!.*(nativeGetEnabledTags)).*$

With regards to the other issue, I have tracked it down to being an emulator that doesn't have enough ram set to cope with running Jelly-bean (or which ever droid version). When I run my app on the emulator I get slow responses (and that error), when I run it on an actual device I don't see the messages.


text:
Q: Structure from motion vs Structure and motion I would like to know the main difference between "structure from motion" and "structure and motion". I think it is the same thing because the result is same and the methods are also same as it is to reconstruct in 3D the environment. But in some papers I have seen sfm in others I have seen sam.
Thank you.


text:
Q: Can I Run Python Function in Php I have a function in file background.py
#! /usr/bin/python
import sqlite3
db = sqlite3.connect("vt.db")
cr=db.cursor()
def content():
icerik =""
sql_sorgusu= db.execute("SELECT * FROM icerik").fetchall()
if len(sql_sorgusu = 0):
    print("")
else:
    icerik +="""

Bilişim Hukuku

""" + str(i[1])+ """
Devamını oku

    """
return icerik

and i want the run this function in my php file. I know the command shell_exec and exec but they are not running the function or idk how to do that can somebody help me.

A:
I don't know how to embed Python code in PHP this python code

#! /usr/bin/python
import sqlite3

db = sqlite3.connect("vt.db")
cr = db.cursor()

icerik = ""
sql_sorgusu = db.execute("SELECT * FROM icerik").fetchall()

for i in sql_sorgusu:
    if len(i) >= 1:
        icerik += f"""

            Bilişim Hukuku

 {str(i[1])}

            Devamını oku

        """
    else:
        print("not SQL match !")

print(icerik) # complete html code

A:
I hope that is what you want

#! /usr/bin/python
import sqlite3

db = sqlite3.connect("vt.db")
cr = db.cursor()

def get_db_data():
    return db.execute("SELECT * FROM icerik").fetchall()

def get_result_html():
    icerik = ""
    for i in get_db_data():
        if len(i) >= 1:
            icerik += f"""

                Bilişim Hukuku

 {str(i[1])}

                Devamını oku

            """
        else:
            print("not SQL match !")

    return str(icerik)


text:
Q: How to create toggle navbar in react with redux thunk I am using react with redux thunk. I created one action, two reducers(One parent and one child) And a store. Now i am using reactstrap for navbar and in that, this.state method is used for toggling the navbar, But i want to do toggle with dispatching an action and setting & getting the state from store. Below is my code:
/* App.js */
import React from "react";
import { connect } from 'react-redux';
import {
  Collapse,
  Navbar,
  NavbarToggler,
  NavbarBrand,
  Nav,
  NavItem,
  NavLink } from 'reactstrap';
import { simpleAction } from './actions/simpleAction';

const mapStateToProps = state => ({
  ...state
})
const mapDispatchToProps = dispatch => ({
  simpleAction: () => dispatch(simpleAction())
})

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }
  simpleAction = (event) => {
   this.props.simpleAction();
  }
  render() {
    return (

        <Navbar color="light" light expand="md">
          <NavbarBrand href="/">reactstrap</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>

              <NavItem>
                <NavLink href="/components/">Components</NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="https://github.com/reactstrap/reactstrap">GitHub</NavLink>
              </NavItem>

          </Collapse>
        </Navbar>

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

/* simpleAction.js */
export const simpleAction = () => dispatch => {
 dispatch({
  type: 'SIMPLE_ACTION',
  payload: 'result_of_simple_action'
 })
}

/* simpleReducer.js */
export default (state = {}, action) => {
 switch (action.type) {
  case 'SIMPLE_ACTION':
   return {
    result: action.payload
   }
  default:
   return state
 }
}

A: Create another action in the same file or any file you wanted
export const toggleNav = () => dispatch => {
 dispatch({
  type: 'TOGGLE_NAV',
 })
}

and a reducer like
export default (state = false, action) => {
 switch (action.type) {
  case 'TOGGLE_NAV':
   return !state;

  default:
   return state;
 }
}

add it to your combine reducer with key navStatus
and update mapDispatchToProps like following
const mapDispatchToProps = dispatch => ({
  simpleAction: () => dispatch(simpleAction()),
  toggleNav: () => dispatch(toggleNav()),
})

add that action on NavbarToggler onClick event (onClick={this.props.toggleNav}) and set that props to the isOpen prop (isOpen={this.props.navStatus}) of Collapse component.
Map Dispatch To Props
mapDispatchToProps is a function, its name can be anything, but for readability, we name it  as mapDispatchToProps, it has a parameter dispatch, if you want to access an action within a component as props you have to follow this syntax, or you can simply use the following syntax
export default connect(mapStateToProps, { simpleAction, toggleNav })(App);
//or
export default connect(mapStateToProps, {
  simpleAction: simpleAction,
  toggleNav: toggleNav,
})(App);

react-redux will check whether mapDispatchToProps is action or object if the value is object react-redux will do the dispatch operations itslef.

A: You can create a new action for the toggle like:
export const toggleAction = () => dispatch => {
 dispatch({
  type: 'TOGGLE_ACTION'
 })
}

and in reducer:
export default (state = { isOpen: false }, action) => {
 switch (action.type) {
  case 'TOGGLE_ACTION':
   state.isOpen = !state.isOpen;
   return state;

  default:
   return state;
 }
}

After you can combine the reducers and action onto the connect method of redux.
You can simply use the updated props value onto the isOpen attribute.
EDIT
the app component will be like:
...
import { toggleAction } from './actions/toogleAction';

const mapStateToProps = state => ({
  ...state
})
const mapDispatchToProps = dispatch => ({
  simpleAction: () => dispatch(simpleAction()),
  toggleAction: () => dispatch(toggleAction())
})

class App extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
  }
  toggle() {
    this.props.toggleAction();
  }
  simpleAction = (event) => {
   this.props.simpleAction();
  }
  render() {
    return (

        <Navbar color="light" light expand="md">
          <NavbarBrand href="/">reactstrap</NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.props.isOpen} navbar>
            ...
          </Collapse>
        </Navbar>

    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);


text:
Q: Override >> operator like int this is part of a homework assignment. I don't want an answer just help. I have to make a class called MyInt that can store any sized positive integer. I can only use cstring cctype iomanip and iostream libraries. I really don't understand even where to begin on this.
6)  Create an overload of the extraction operator >> for reading integers from an input stream. This operator should ignore any leading white space before the number, then read consecutive digits until a non-digit is encountered (this is the same way that >> for a normal int works, so we want to make ours work the same way).  This operator should only extract and store the digits in the object.  The "first non-digit" encountered after the number may be part of the next input, so should not be extracted. You may assume that the first non-whitespace character in the input will be a digit. i.e. you do not have to error check for entry of an inappropriate type (like a letter) when you have asked for a number.
Example:  Suppose the following code is executed, and the input typed is "  12345   7894H".
MyInt x, y;
  char ch;
  cin >> x >> y >> ch;
The value of x should now be 12345, the value of y should be 7894 and the value of ch should be 'H'.
The last state of my code is as follows:
 istream& operator>>(istream& s, MyInt& N){
N.Resize(5);
N.currentSize=1;
char c;
int i = 0;
s >> c;
N.DigitArray[i++] = C2I(c);
N.currentSize++;
c = s.peek();
while(C2I(c) != -1){
    s >> c;
    if(N.currentSize >= N.maxSize)
        N.Resize(N.maxSize + 5);
    N.DigitArray[i] = C2I(c);
    i++;
    N.currentSize++;
}
}

It almost works! Now it grabs the right number but it doesn't end when I hit enter, I have to enter a letter for it to end.

A: You can create an operator>> overload for your class this way (as a free function, not inside the class):
std::istream& operator>>(std::istream& lhs, MyInt& rhs) {
    // read from lhs into rhs

    // then return lhs to allow chaining
    return lhs;
}

You can use the members peek and read of istream to read in characters, and isspace to test if a character is a space, and isdigit to check if a character is a number (isspace and isdigit are in the <cctype> header).

A: First of all, your operator>> should be concerned only with extracting the sequence of chars from the stream and knowing when to stop based on your rules for that.  Then, it should defer to a constructor of myInt to actually ingest that string.  After all, that class will probably want to expose constructors like:
myInt bigone ("123456123451234123121");

for more general-purpose use, right?  And, functions should have a single responsibility.
So your general form will be:
istream& operator>> (istream& is, myInt x)
{
    string s = extract_digits_from_stream(is);
    x = myInt(s);
    return is;  // chaining
}

Now how do you extract just digits from a stream and stop at a non-digit?  Well, the peek function comes to mind, as does unget.  I'd look at source code for the extraction operator for regular integers and see what it does.


text:
Q: Connect to Azure AD from Apache web server on windows I am trying to use Azure AD to authenticate a website in Apache web server deployed on a windows server. A possible solution we were looking for is mod_auth_openidc, however, it is not available for windows.
Are there any other options that can be used to authenticate a website in apache on a windows server?

A: The design pattern should work in any technology since HTTP interfaces are used:

*

*Reverse proxy is the public URL

*Website uses an Internal URL

*Reverse proxy deals with OAuth and talks to Azure AD

Note that it is generally recommended in terms of secure hosting to put a reverse proxy in front of any of these components, so that an attacker has to breach 2 layers to get to data:

*

*APIs

*Web back ends that access data sources

*Authorization Servers

Here is an option that might work for you - and once you have a good reverse proxy setup it gives you some interesting architectural options:

*

*Use an Azure NGINX managed service which will use Linux based servers, but you don't need to know anything much about Linux to use them

*Use the NGINX openidc module - also provided by Zmartzone - and host that alongside Azure AD
If it helps, at Curity we have some related resources - here is one that shows how to run NGINX on a Windows PC using Docker and how to take control over behaviour via plugins.


text:
Q: Windows 7 won't detect ethernet cable A month or two ago, I bought an ethernet cable to replace my existing wireless connection on my computer, as I frequently live stream and wireless connection is too unstable to do that. I should also mention that my ethernet cable is not a crossover cable.
Upon plugging the cable into my router (Virgin Media Super-Hub) and my computer (Onboard Realtek PCIe GBE Family Controller) it didn't work, ipconfig showed the following:
Ethernet adapter Local Area Connection:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix  . :

Sometimes, after a few hours, a connection will suddenly be made, however only Skype will successfully connect. Steam, Chrome, TeamSpeak and any games will still fail.
Last week it suddenly started working properly, and continued to work up until a few days ago. When my computer went to sleep overnight, the next morning the connection was lost again.
I have tried updating my drivers, only to find I am using the latest version. I've also noticed that restarting my computer after the fake Skype connection has been made will cut the connection again.
The orange/yellow light by the ethernet port on the router lights up normally when any internet connection is there, including the one only Skype can use. However when no connection is made it slowly flashes with a regular pattern (2 flashes and a pause).
The ethernet cable works fine with my laptop, and I've tried reinstalling the network drivers and changing the port used on the router.
A lot of other people with this issue have found the problem to be anything from a faulty cable to needing to plug the cable directly into the modem as opposed to the router (not an option in my case) to an issue with the network adapter on my computer.
However I don't think it's a hardware issue. I know the router works fine, as does the cable, I've tried them with my other computer and laptop. And I don't think it's the computer's network adapter as it was working with no issues for over a week.
The only possible explanation I can think of is some software issue I don't know about.
It may be worth noting that back when I was still using wireless, sometimes my internet connection would act weird, and browsers would be unable to connect, but Skype, Steam, TeamSpeak and any games I already had open would be fine. I found that restarting my computer fixed this at the time.
It may also be worth noting that since the week of functional ethernet connection, my computer has been unable to detect my USB wireless connector either, however that may be due to damage to the USB device itself.

A: You need to narrow down the problem. Firstly try booting your pc from a "live cd". My personal preference is an Ubuntu image loaded onto a usb stick but you can also burn and boot from a DVD.
If your router-cable-pc then connects to the internet with no issues, you can rule out hardware and attempt to diagnose problems within windows. My suggestion would be some or all of the following:

*

*Disable or remove software that might interfere with your
connection. eg firewalls, anti-virus or other internet security
software, connection managers.

*Scan for malware or viruses.

*Delete the network card from the device manager and then reinstall
the card and drivers, perhaps trying once with the Windows default
drivers and then again with the manufacturers drivers.

*System restore might also help you get your pc to a working state.

If the live cd also shows problems, then it suggests a problem with the hardware but the symptoms could also be due to a problem with drivers or support of the card. Check via google to see if your card is fully supported.
Ubuntu can be downloaded from  http://www.ubuntu.com/download/desktop


text:
Q: Angular Typescript Error- error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type I am getting this error while running my Angular app:
error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
34                         {{product.price * quantity.value}}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/cart-items/cart-items.component.ts:6:16
6   templateUrl: './cart-items.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component CartItemsComponent.
Here is my HTML code:

{{product.name}}

                                Status: {{product.status}}

                        <input #quantity (keyup)="0" type="email" class="form-control" id="exampleInputEmail1" value="1">

                        {{product.price}}
                        {{product.price * quantity.value}}	 //ERROR HERE

                        <button type="button" class="btn btn-danger">
                             Remove
                        </button>

If I am changing * to +, then below statement is working
{{product.price + quantity.value}}

But I need to use multiplication here.
Any suggestion?


text:
Q: Maya Python - Set object pivot to selection center I'm trying to move the selected object pivot to the center of the objects selected vertices.
When I run the code I don't recieve any errors and almost everything works as intended, However the pivot of (obj)my selected object doesn't seem to set itself to the locator xform(piv).
import maya.cmds as cmds

sel = cmds.ls(sl=True)
print sel
obj = cmds.ls(*sel, o=True)
print obj

selVerts = cmds.ls(sl=True)
tempClstr = cmds.cluster()
pos = cmds.xform(tempClstr[1], q=True, ws=True, rp=True)
loc = cmds.spaceLocator()
cmds.move(pos[0], pos[1], pos[2])
cmds.delete(tempClstr)

piv = cmds.xform (loc[1], piv=True, q=True, ws=True)
print piv
cmds.xform( obj, ws=True, piv=(piv[0], piv[1], piv[2]) )

Need some help on this one fast.
Any extra eyes that can spot what I'm missing would be greatly appreciated.

A: I think the main issue was that when you were using obj = cmds.ls(*sel, o=True), it was only capturing the object's shape node instead of its transform. You can use cmds.listRelatives to get the shape's transform. You also don't need to create the locator as the cluster already gives you the position.
This seems to work for me, though you may want to consider some additional error checking for the selection portion as it assumes a lot.
import maya.cmds as cmds

sel = cmds.ls(sl=True)
shapes = cmds.ls(sel, o=True)
obj = cmds.listRelatives(shapes[0], f=True, parent=True)[0]

selVerts = cmds.ls(sl=True)
tempClstr = cmds.cluster()
piv = cmds.xform(tempClstr[1], q=True, ws=True, rp=True)
cmds.delete(tempClstr)

cmds.xform(obj, ws=True, piv=(piv[0], piv[1], piv[2]) )


text:
Q: how to Display Google Drive Pdf Url in pdfView And Download and print the file t hii we have a problem we got a link(Url) of pdf from google Drive
url like This:-"https://drive.google.com/file/d/1xYjCqV4LBljBMvn6OsFyK8U6-RK3aGaB/view"
how we can convert this into pdf format.

A: There are at least 3 ways to include your file in a PDF

*

*

*

*Just embed a link to the online location, not ideal from a security aspect.

*

*Embed the media file to be extracted and viewed by another user, but requires them bypassing their security.

*

*Include the graphics as simple images. (Audio would need to be attached if needed)

You asked how to print thus option 3 is the one needed to output a selection of frames as seen here (note the moving pencils on the left)

There are many tools to do that but the simplest I found was https://document.online-convert.com/convert-to-pdf which produced 2 images per page using 300 Tweens = 150 pages and the first 10 pages are dark fade in intro so can be discarded using a PDF arranger.


text:
Q: open tcp/ip conenctions count is around 2.1 million! There are around 1500-2000 users online on this win2008 r2 server on around 50 sites. performance monitor reports around 2.1 million active ip4 conenctions. server is ip6 enabled and has public ip6. although ip6 never used it reports 500-600 active connections on ip6.
are these figures normal?

A: Those numbers are cumulative, meaning those are the number of active connections that have been established since the server has been running.
You want to look at Connections Established, not Connections Active.


text:
Q: How to get friends from XMPPRoster? I try like this:
XMPPRosterMemoryStorage *xmppRosterMemStorage = [[XMPPRosterMemoryStorage alloc] init];
XMPPRoster *xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterMemStorage
                                         dispatchQueue:dispatch_get_main_queue()];
[xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = true;
xmppRoster.autoFetchRoster = true;
[xmppRoster activate:xmppStream];
[xmppRoster fetchRoster];

But xmppRoster is empty. Why?

A: Roster items are stored in [xmppRosterMemStorage mainThreadManagedObjectContext], you can use it with NSFetchedResultsController as datasource for your UITableView, see iPhoneXMPP example in the XMPPFramework sources

A: If you do not want to use NSFetchedResultsController, you can get the JIDs of your roster from calling jidsForXMPPStream on the roster storage object.
Here's how I have used it -
- (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender{
    [appDelegate.mContactHandler clearContacts];
    NSArray* jids = [mXmppRosterStorage jidsForXMPPStream:self.xmppStream];
    for (int i=0; i<jids.count; i++)
    {
        RosterContact* contact = [[RosterContact alloc]init];
        contact.jid = [jids objectAtIndex:i];
        [appDelegate.mContactHandler addContact:contact];
    }
    [self postResultNotification:kReload withResult:nil];
}

I have used XMPPRoster's delegate method to know when the roster have finished loading. I then extract the jid from the storage and create my own RosterContact object which is just a custom class I have created to store contact data. I then post a notification to reload the tableview where I am showing the contact list.
Here's my roster declaration -
mXmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];

mXmppRoster = [[XMPPRoster alloc] initWithRosterStorage:mXmppRosterStorage];

mXmppRoster.autoFetchRoster = YES;
mXmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;

I hope this will be useful.

A: Here is my solution for swift.
https://stackoverflow.com/a/50151198/2781720
func getList() {
  let query = try! XMLElement(xmlString: "<query xmlns='http://jabber.org/protocol/disco#items' node='all users'/>")
  let iq = XMPPIQ(type: "get", to: XMPPJID(string: "Your Host Name"), elementID: xmppStream.generateUUID(), child: query)
  iq?.addAttribute(withName: "id", stringValue: "get")
  xmppStream.send(iq)
}

extension YourClassName: XMPPRosterDelegate {

   func xmppRosterDidEndPopulating(_ sender: XMPPRoster!) {
     if let jids = xmppRoster.xmppRosterStorage.jids(for: xmppStream) as? [XMPPJID] {
       print("JIDS: \(String(describing: jids))")
       for item in jids {
         print(item.user)
       }
     }
   }
 }

Hope this helps!


text:
Q: java.lang.InstantiationError when creating instance of static inner class with Objenesis I am trying to create a utility method that should be able to deep-clone any object.
(Object.clone() only works on Object implementing Cloneable and I heard it's flawed anyways.)
I am using Objenesis to create new instances of objects without the use of constructors.
However, when trying to clone a JFrame I get the following Exception:
(using this class because I think it should be a good and complex test)
java.lang.InstantiationError: [Ljava.util.concurrent.ConcurrentHashMap$Node;
    at sun.reflect.GeneratedSerializationConstructorAccessor12.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:48)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)

I am open to any solution, not necessarily limited to Objenesis.
My Code:
private static ObjenesisStd OBJENESIS = new ObjenesisStd();

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep){
    if(object == null){
        return null;
    }else{
        try {
            T clone = (T) OBJENESIS.newInstance(object.getClass());
            List<Field> fields = ReflectionUtil.getAllFieldsInHierarchy(object.getClass());
            for(Field field : fields){
                boolean isAccessible = field.isAccessible();
                boolean isFinal = ReflectionUtil.isFinal(field);
                field.setAccessible(true);
                ReflectionUtil.setFinal(field, false);
                Class<?> type = field.getType();
                if(!deep || type.isPrimitive() || type == String.class){
                    field.set(clone, field.get(object));
                }else{
                    field.set(clone, clone(field.get(object), true));
                }
                field.setAccessible(isAccessible);
                ReflectionUtil.setFinal(field, isFinal);
            }
            return clone;
        } catch (Throwable e) {
            e.printStackTrace();
            //throw new RuntimeException("Failed to clone object of type " + object.getClass(), e);
            return null;
        }
    }
}

public static void main(String[] args) {
    GetterSetterAccess access = new GetterSetterAccess(JFrame.class);
    JFrame frame = new JFrame("Test Frame");
    for(String attr : access.getAttributes()){
        System.out.println(attr + " " + access.getValue(frame, attr));
    }

    System.out.println("----------------------------------------------");
    frame = clone(frame, true);

    for(String attr : access.getAttributes()){
        System.out.println(attr + " " + access.getValue(frame, attr));
    }
}

EDIT: Got it to work with the accepted answer and a few more fixes:

*

*Avoided cloning Wrappers of Primitive Types (Integer.class etc.)

*Avoided cloning Classes (Objects of the class Class.class)

*Stored the cloned objects in a Map and reused them, so if Object A has a reference to Object B and Object B one to Object A it doesn't get stuck in an infinite loop. I also used a Map that checks for exact equality (==) instead of using equals().

*Created a custom exception class which would just be passed on instead of throwing a new exception on every level (causing a huge caused-by-depth).

A: I finally figured it out. Your code doesn't handle arrays. So it fails with instantiating  "[Ljava.util.concurrent.ConcurrentHashMap$Node;" which is an array of Nodes.
However, I will advocate that indeed, you should not do that. You will end up with fairly complicated code. Depending on what you want to do, you could use Jackson or XStream to do a marshall / unmarshall to perform the copy.
If you really want to continue that path, you will need something like this after the null check of your clone method.
    if(object.getClass().isArray()) {
        int length = Array.getLength(object);
        Object array = Array.newInstance(object.getClass().getComponentType(), length);
        for (int i = 0; i < length; i++) {
            Array.set(array, i, clone(Array.get(object, i), true));
        }
        return (T) array;
    }


text:
Q: What are the properties of countably infinite sets compared to sets of higher cardinality? When looking at mathematical definitions, there are quite a few cases where we limit certain properties to countably infinite sets (e.g. $\sigma$-Algebras).
In some cases we set this limit as we'd lose our intuition of what would happen if we chose an even bigger infinity, in other cases there are hard facts at work.
Yet, the only property of countably infinite sets that comes to my mind is ... well, that they are countable, and the higher cardinalities are not.
I'm sure though that there are many more characteristic properties of countably infinite sets that get lost when moving up to higher cardinalities - so what are they?

A: There are a lot of combinatorial properties you lose. For example:

*

*$\mathbb{N}$ satisfies infinite Ramsey's theorem for pairs: if $c:[\mathbb{N}]^2\rightarrow \{0,1\}$ is a $2$-coloring of pairs of natural numbers, then there is a $c$-homogeneous set $H$ (that is, $c(\{x,y\})=c(\{x',y'\})$ for all $x\not=y, x'\not=y'$ in $H$) of the same size as $\mathbb{N}$. This fails  in general for uncountable sets: if $X$ is uncountable, there may be a $2$-coloring of pairs of elements of $X$ with no size-$X$ homogeneous set. In fact, this fails for most uncountable cardinalities in a precise sense (see below), and provably fails of $\aleph_1$ (and indeed any uncountable $\kappa\le 2^{\aleph_0}$) in particular: fix an injection $i:\aleph_1\rightarrow\mathbb{R}$, and consider the coloring $$c:[\aleph_1]^2\rightarrow\{0,1\}: c(\{x,y\}=1\iff (x<_{\aleph_1}y\iff i(x)<_\mathbb{R}i(y)))$$ (with the two different orderings "decorated" for clarity). - it's not hard to show, using the separability (= countable dense subset) of $\mathbb{R}$, that $c$ cannot have an uncountable homogeneous set.

*$\mathbb{N}$ satisfies Konig's lemma: any infinite-height, finitely-branching tree has an infinite path. The "$\kappa$-version" of this property, for an arbitrary infinite cardinal $\kappa$, should be: "Any $<\kappa$-branching tree of height $\kappa$ has a $\kappa$-length branch," but this too breaks down in general for uncountable sets, and in particular is again provably false for $\aleph_1$.
Combinatorial properties of $\mathbb{N}$ in general are very special, and often correspond to large cardinal properties when lifted to the uncountable setting. For example, it is consistent with ZFC that only $\aleph_0$ has the Ramsey property above.


text:
Q: Access jQuery variable outside of IIFE (function( global, factory ) {
    var jQuery = function( selector, context ) {

    return jQuery;
}));

jQuery('body').click();

I try to study how jquery work and I have a question about IIFE
jQuery wrap insdie of IIFE, how come we still can use var jQuery this variable outside of IIFE?

A: Because at end of source there is a line that assigns it to global window space:
window.jQuery = window.$ = jQuery;


text:
Q: Access Tab Control based on Radio Button Selection I am working in Access. I have a form that users select a "method" in the form of a radio button from a list. Depending on what they select, entry fields will populate. Recently we have moved to a tab control to store all of these fields.
My question is:
How do I make a certain tab show automatically when clicking on the corresponding radio button?
The fields on the corresponding tab populate but the form doesn't automatically switch to show that tab.
Thanks!
Here is the first case. In this case, the visible fields do populate when the corresponding radio button is selected. HOWEVER, the tab where these fields are stored does not automatically display. Just the first tab/page shows. I have to click on the correct tab/page to see the fields. I want the Tab/page to automatically display.
Private Sub frmMethodOptions_AfterUpdate()
Select Case Me.frmMethodOptions.Value
    Case 1
        'International Fields

        lblInternational.Visible = False
        lblBeneBankHeader.Visible = False
        Intl_BeneBankType.Visible = False
        Intl_BeneBankID.Visible = False
        Intl_BeneBankName.Visible = False
        Intl_BeneBankCode.Visible = False
        lblRecBankHeader.Visible = False
        Intl_RecBankType.Visible = False
        Intl_RecBankID.Visible = False
        Intl_RecBankName.Visible = False
        lblBeneInfoHeader.Visible = False
        Intl_BeneInfoAcctNumber.Visible = False
        Intl_BeneInfoAcctName.Visible = False
        Intl_BeneInfoChargeParty.Visible = False

        'Wire Fields

        lblWireInformation.Visible = True
        BeneABA.Visible = True
        BeneBankName.Visible = True
        BeneAcctNumber.Visible = True
        BeneAcctName.Visible = True
        RepetitiveCode.Visible = True

        'Common Fields

        OBI.Visible = True
        DebitAccount.Visible = True

        'Setting the method

        txtMethod.Value = 5
        txtMethodName = "Domestic Wire"

A: Instead of leaving all tab/pages open, I simply made all other tabs invisible. For instance, if I had two tabs and clicked the international radio button, I would want only the international tab/page to show. By setting ONLY the tab you want to visible, you get all of the necessary fields to show and they are ready for user input.
tabMain_Intl.Visible = True
tabMain_Dom.Visible = False


text:
Q: d3js in vue as external script [ d3 is not defined ] I tried to add script d3js in vue
but there's a problem said that d3 is not defined eror is like this

ReferenceError: d3 is not defined
at VueComponent.drawRect (AddMatchingComp.vue?./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0:264)
at VueComponent.mounted (AddMatchingComp.vue?./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0:283)
at invokeWithErrorHandling (vue.esm.js:1862)
at callHook (vue.esm.js:4216)
at Object.insert (vue.esm.js:3145)
at invokeInsertHook (vue.esm.js:6341)
at Vue.patch [as patch] (vue.esm.js:6560)
at Vue._update (vue.esm.js:3945)
at Vue.updateComponent (vue.esm.js:4063)
at Watcher.get (vue.esm.js:4476)

is there anything wrong with my code , why d3 is not defined even i have add the script in mounted
here is my code :

<template>

</template>

A: You should import it as follows :


text:
Q: Accept Input from user through datagridviewcomboboxcolumn I Have a DataGridView with datagridviewcomboboxcolumn, I'd Like the user to choose an item from datagridviewcomboboxcolumn and have the choice to write it himself ,the input field should also be the Combobox if this item does not exist in this Dropdown, the written choice will be only inserted in the database not added as another choice in the dropdown.

A: To make a column in datagridview of combobox type you can use following code:

*

*Add column in datagridview
using System.Data.SqlServerCe;

string sqlConnection = "Data Source";
SqlCeConnection conn = new SqlCeConnection(sqlConnection);
//Get bind from database.
string qryGetCategory = "Query to get data for combo box";
SqlCeCommand cmdCat = new SqlCeCommand(qryGetCategory, conn);
SqlCeDataAdapter daCat = new SqlCeDataAdapter(qryGetCategory, conn);
DataTable dtCat = new DataTable();
daCat.Fill(dtCat);

//Combobox column.
DataGridViewComboBoxColumn ComboBoxCol = new DataGridViewComboBoxColumn();
ComboBoxCol.DataSource = dtCat;
ComboBoxCol.Name = "Column name";
ComboBoxCol.ValueMember = "Value of member";
ComboBoxCol.DisplayMember = "Member to be show";
ComboBoxCol.DropDownStyle = ComboBoxStyle.DropDown;
datagridview.Columns.Add(ComboBoxCol);


text:
Q: How to use return value of a function as condition of while that returns tuple in python I was looking for something like this but I couldn't find so here it goes.
Some background
I use opencv to retrieve frames from a video file. Usually people do it in an endless loop like:
while (True):
    s, img = cv.read()

or
for i in xrange(10000): #just a big number
    s, img = cv.read()

now i want to retrieve all frames and quit the loop when there are no more frames. However my skills in python aren't strong enough to do what I want to do.
What I want to know
read function (or method, i don't know how they are called in python) returns a tuple: first represents success of the operation, and second represents the frame returned. I want to break the while loop when first element of the tuple is false. Having a C background, I thought maybe this would work:
while ((success, img = capture.read())[0]):
    #do sth with img

i thought this will break the loop when success is false. But it did not. Then i thought maybe this will work:
while ((success, img = capture.read()).success):
    #do sth with img

it also did not work. I don't want to do something like
while(True):
    s, i = capture.read()
    if (s == False):
        break

How can test the condition in while, not in an if which breaks if succesful?

A: the best way to think pythonic is to forget other languages
s = True
while s:
    s, i = capture.read()
    if s:
        do_some_stuff(i)

A: Python has an alternative iter signature which takes function as the first argument and sentinel determining the stop condition as the second.
Using it, you can come up with something like this:
for s,img in iter(cv.read, (False, None)):
    print img

Still, I doubt if it is better than just plain break in the if block.
Also, it only accepts sentinel as the overall returned value, and can't base stop condition on some part of it (e.g. on the first value of the tuple). This can be workaround, but will make the code even more obfuscated:
>>> for s,img in itertools.takewhile(lambda x: x[0], iter(cv.read, None)):
    print img

It uses itertools.takewhile to determine when the first value of the returned tuple equals to False.

Full version for testing:
>>> class Capture(object):
    def __init__(self):
        self.L = iter([1,2,3,4,5])
    def read(self):
        try:
            img = self.L.next()
        except StopIteration:
            return (False,None)
        return True, img

>>> cv = Capture()
>>> for s,img in iter(cv.read, (False, None)):
    print img

1
2
3
4
5

>>> cv = Capture()
>>> for s,img in itertools.takewhile(lambda x: x[0], iter(cv.read, None)):
    print img

1
2
3
4
5

A: You could write a generator function.
def readframes(cv):
    while True:
        success, frame = cv.read()
        if success:
            yield frame
        else:
            return

This way you can loop through the frames with a for loop.
for frame in readframes(cv):
    do_something_with_frame(frame)

A: This should work
while capture.read()[0]:
    #do something

Of course you won't be able to access the frame that way!!
There is another way
s,v = capture.read()
while s:
    #Do sth
    s,v = capture.read()

Which of course is a long-ish way of saying
while True:
    s,v = capture.read()
    if not s:
        break

Which (for some reason) you don't want to do

A: you cannot do what you are asking in python (unless there are hacks i don't know about).
what the line:
s, i = capture.read()

is doing is assigning 2 separate variables by unpacking a tuple, there is just no way to tell python that you want the first assigned variable.
It is also illegal in python to assign within an if, for or while conditional statement.
the only thing you could do would be:
if(capture.read()[0]):

Which would mean you lose the image data.
In short, unpacking tuples is actually quite sexy, there's no reason to not take advantage of the functionality it provides!

A: Here is a solution on who to break loop using function which return tuple.
>>> def read(a):
...     if a == 0:
...         return (False, a+1)
...     return (True, a-1)
...
>>> read(5)
(True, 4)
>>> read(0)
(False, 1)
>>> a = True
>>> i = 5
>>> while(a):
...     a, i = read(i)
...     if a:
...         print 'working'
...
...
...
working
working
working
working
working
>>>

Now your code will look like this:
s = True
while(s):
    s, i = capture.read()


text:
Q: If a variable is allocated on the stack in an inline function using alloca, is its reference valid after the inline function returns? I know that the compiler may, not shall unroll inline functions into the calling function to avoid the overhead associated with calling out-of-line functions. I also know, however, that inline functions are linked differently than out-of-line functions, so I can't expect them to act the same way, exactly.
While I am actually using C++, I'm developing a program using an api in which it is convenient to make use of C macros that look something like:
#define func_alloca(ptr) do { *ptr = alloca(size); memset(*ptr, 0, size); }

In the interest of not repeating code several times in different functions, it would be useful for me to be able to functionalize a series of these alloca calls. My question is, (in gcc specifically, since alloca is implementation-defined,) can I initialize variables on the stack using alloca, inside an inline function, and count on them to work outside? Here's an example of what I want to do:
inline void uses_alloca(type*& ptr){
    // do stuff
    func_alloca(ptr);
}

void calls_inline(){
    type *local_ptr;
    uses_alloca(local_ptr);
    // is local_ptr valid?
}

If it does work, will it always work? As in, not only when the compiler chooses to unroll the inline function into the calling function?
Edit:
My guess is that this probably will work in fact, since the alloca call is already valid outside the do{} local scope contained in the macro, and since, if I understand correctly, a function doesn't actually have a different level of scope in C++ than a do{} block. My question remains: is this the way alloca is supposed to work in gcc? Is this defined behavior?

A: If you're using GCC, the intended behavior is that functions with alloca in them aren't inlined automatically. From tree-inline:
  /* Refuse to inline alloca call unless user explicitly forced so as
 this may change program's memory overhead drastically when the
 function using alloca is called in loop.  In GCC present in
 SPEC2000 inlining into schedule_block cause it to require 2GB of
 RAM instead of 256MB.  Don't do so for alloca calls emitted for
 VLA objects as those can't cause unbounded growth (they're always
 wrapped inside stack_save/stack_restore regions.  */

This of course doesn't take into account:

*

*Bugs

*The compiler inlining functions anyways because it's not perfect

*Optimization switches, attributes

*Bad luck

The GCC manual page on inline warns that inlined functions are ill-suited for alloca and Why is the use of alloca() not considered good practice? has a few horror stories as well.
Essentially if you're worried that inlining may affect the semantics of your code, don't rely on it.

A: Declaring a function inline does not extend the scope of the contained variables to the scope, into which it is expanded. So, whatever alloca allocates is not at all guaranteed to be valid in the context that has called the function uses_alloca. If you use the macro func_alloca, you are fine because the macro text is literally expanded in place. However, the use of alloca itself is typically considered a bad practice.


text:
Q: Is calling web service in android as in java I have a .net web service, I tried to connect it in java, so I converted wsdl file to java classes and start calling them and it was sussceccful, now I want to know if this methos can be use in android. should I use ksoap2 or I can to this in the same way of java?

A: We've been using ksoap2 in our Android app for over a year now, with good results. It's quite simple to use, well tested and can be used in commercial projects. Their website: ksoap2-android

A: You can do it by using SOAP library in java and Ksoap2 is for android.


text:
Q: Solution to a Strongly Convex Non-smooth Minimization Problem involving an L1 Norm Let $X \in \mathbb{R}^{n \times d}, w \in \mathbb{R}^d, y \in \{\pm 1\}^{n}, \alpha \in [0,1], \lambda \in \mathbb{R}$. I have an expression that looks as follows
$\frac{1}{2}\|Xw -y \|_{2}^2 + \alpha \|w\|_{2}\|Xw-y\|_{1} + \frac{\lambda}{2}\|w\|_{2}^{2}$
where $\lambda>0$ is sufficiently large so that the entire objective is strongly convex. Note that the second term contains an $L_{1}$-norm term, and that the second term on its own may be non-convex, having local minima both at the origin and in the solution space of $Xw - y$. Furthermore notice that this objective is lower bounded by the first and last terms,
$\frac{1}{2}\|Xw -y \|_{2}^2 + \frac{\lambda}{2}\|w\|_{2}^{2}$
and so the geometry of the first objective is lower bounded by a bowl defined by the second objective. The minimum of the second objective is, straight-forwardly, $w^{*} = (X^{\top}X + \lambda I)^{-1}X^{\top}y$.
However this is not, in general, the minimum of the first objective. Are there tools that will help me find the minimum solution of the first objective in closed form?


text:
Q: Setting up clients based on the different clients I want to restrict the acess based on the ip address of the client.
I have different url each client they should access.
Should I say
<VirtualHost client1:443>
</VirtualHost>
<VirtualHost client12:443>
</VirtualHost>
<VirtualHost client3:443>
</VirtualHost>

thanks for you help in advance

A: No, the IP:Port mapping specified in the VirtualHost block is the IP address on your server that this vhost will be served from, not the client's IP address.
To restrict access based on client IP, use mod_access rules, either in your VirtualHost stanza or via .htaccess files.
For instance:
Order deny,allow
Deny from all
Allow from 192.168.111.222

More details here.


text:
Q: In RSpec, what's the difference between before(:suite) and before(:all)? The before and after hook documentation on Relish only shows that before(:suite) is called prior to before(:all).
When should I use one over the other?

A: When a before(:all) is defined in the RSpec.configure block it is called before each top level example group, while a before(:suite) code block is only called once.
Here's an example:
RSpec.configure do |config|
  config.before(:all) { puts 'Before :all' }
  config.after(:all) { puts 'After :all' }
  config.before(:suite) { puts 'Before :suite' }
  config.after(:suite) { puts 'After :suite' }
end

describe 'spec1' do
  example 'spec1' do
    puts 'spec1'
  end
end

describe 'spec2' do
  example 'spec2' do
    puts 'spec2'
  end
end

Output:
Before :suite
Before :all
spec1
After :all
Before :all
spec2
After :all
After :suite

A:
You can also use before(:suite) to run a block of code before any
  example groups are run. This should be declared in RSpec.configure

http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks


text:
Q: ddslick plugin: get value in wordpress I have a choice menu in WordPress plug-in with ddslick . I want to pass the id of the selected option and send the form to a database , but the value is not saved although it appears within the html . When put into manual is well maintained.

    <select id="demo-htmlselect">

        <?php

             $thumbnails = get_posts('numberposts=5');
  foreach ($thumbnails as $thumbnail) {

    $url = wp_get_attachment_url( get_post_thumbnail_id($thumbnail->ID) );

        ?>

         <option value="<?php echo $thumbnail->ID;?>" data-imagesrc="<?php echo $url; ?>"
            data-description="<?php echo $thumbnail->post_title;?>"><?php echo $thumbnail->post_title;?></option>

    <?php } ?>

    </select>

<?php

?>

        <form method="post" action="options.php">
            <?php wp_nonce_field('update-options') ?>

                <input type="text" name="main_art_id" size="45" value="<?php echo get_option('main_art_id'); ?>" />

<input type="submit" name="Submit" value="Store Options" />

            <input type="hidden" name="action" value="update" />
            <input type="hidden" name="page_options" value="ain_art_id" />
        </form>

<?php

}


text:
Q: Is there way a "reset" a scanner in Java? Reset may not be the right word here, but I am currently building a program that lets the user look up a name, and by scanning a txt file containing a list of names followed by numbers, the program then displays the numbers following said name. The way I am doing this is via .nextLine, but if the user inputs a name that's later in the list (say Samantha in the example) and then tries to look up a name at the top of the list (like Sally), the second name isn't found.
For reference, here is an example of that txt file:
Sally 0 0 0 0 0 0 0 0 0 0 886
Sam 58 69 99 131 168 236 278 380 467 408 466
Samantha 0 0 0 0 0 0 272 107 26 5 7
Samir 0 0 0 0 0 0 0 0 920 0 798

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class BabyNames {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Scanner input = new Scanner (new File("BabyNames.txt"));
        Scanner keyboard = new Scanner (System.in);

        System.out.println("This program allows you to search through the data from the "
                + "Social Security Administration to see how popular a particular name has "
                + "been since 1900.");
        System.out.print("Name? ");
        String name = keyboard.nextLine();
        do {
                while(input.hasNextLine()) {
                    String text = input.nextLine();
                    String[] words = text.split(" ");
                    if (text.contains(name)) {
                        System.out.println("Statistics on name \"" + name + "\"");
                        for (int i = 1; i < words.length; i++) {
                            System.out.println((1900 + (i-1)*10) + ": " + words[i]);
                        }
                        System.out.println("Enter another name or type quit to exit.");
                        name = keyboard.nextLine();
                        break;
                    }
                    else if (name.contains("quit") || name.contains("quit")){
                        System.exit(0);
                    }
                    else {
                        continue;
                    }
                    System.out.print("Error, name not found.");
                }
        } while (!name.contains("quit") || name.contains("quit"));

    }
}

I looked up the .reset method but that hasn't seemed to work. Honestly, I'm stumped here.

A: Again, don't try to "reset" the Scanner or re-read the file. Your best bet is to read the file once and place all the data into a collection of some type, here a Map<String, SomeCustomClass> would work best. I'd first create a class to hold a row of information, perhaps called BabyName, one that holds a String field for name and an Integer List for the numbers listed after the name, something like:
import java.util.*;

public class BabyName {
    String name;
    List<Integer> numberList = new ArrayList<>();

    public BabyName(String name, List<Integer> numberList) {
        this.name = name;
        this.numberList = numberList;
    }

    public String getName() {
        return name;
    }

    public List<Integer> getNumberList() {
        return numberList;
    }

    @Override
    public String toString() {
        return "BabyName [name=" + name + ", numberList=" + numberList + "]";
    }

    // consider adding hashCode and equals methods that are based on the name field alone
    // ...

}

And then I'd recommend in your code a method that takes a line of text that has been extracted from the file, and converts it into a BabyName object:
private static BabyName createBabyName(String line) {
    String[] tokens = line.split("\\s+");
    String name = "";
    List<Integer> numberList = new ArrayList<>();

    // ... code to extract the data and that fills the numberList here
    // ... left blank for you to fill in

    BabyName babyName = new BabyName(name, numberList);
    return babyName;
}

And then create a Map<String, BabyName> babyNameMap = new HashMap<>(); to hold BabyName objects using the name field as the map key, and when you read the file (just once mind you), you fill the map:
Scanner fileScanner = null;
try {
    fileScanner = new Scanner(new File(FILE_PATH_NAME));
} catch (FileNotFoundException e) {
    e.printStackTrace();
    System.exit(-1);
}

// read file and fill the map
while (fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    BabyName babyName = createBabyName(line);
    babyNameMap.put(babyName.getName(), babyName);
}

Then you can use this map to get the data from the user multiple times without having to re-read the file or reuse a Scanner.
e.g.,
String nameEnteredByUser = keyboard.nextLine();
BabyName selectedBabyName = babyNameMap.get(nameEnteredByUser);

// check for null here first
String name = nameEnteredByUser;
List<Integer> numberList = selectedBabyName.getNumberList();

A: Java Scanner, in general, doesn't know/control the pointer position in the file. It wraps over InputStream which in turn provides the input to the Scanner w.r.t every nextLine() call.
Scanner systemInput = new Scanner(System.in);
//new Scanner(new FileInputStream("file.t"));

InputStream has Mark/Reset feature which will help us to control the pointer position.
(Note: mark/ reset enables us to mark a checkpoint and you can jump back to the checkpoint later.)
Unfortunately, FileInputStream doesn't support it. But, BufferedInputStream came to the rescue.
Let's cook a solution for your problem,

*

*Create a FileInputStream with your input file.

*Wraps it with BufferedInputStream which provides mark() and reset() functions.

 BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("BabyNames.txt"));

*Provide it as input to the Scanner constructor.

Scanner input = new Scanner (inputStream);

*Mark a checkpoint at the beginning of the file.

inputStream.mark(0);//saving a checkpoint

*After the end of the inner while loop, reset the pointer to the marked position.

inputStream.reset();

Now, your code works fine.


text:
Q: How to fetch string and return as choice of datatypes In my function, I am fetching a string.
However, I want to use the same function to return either an int, a bool OR a string.  Say I have gotten a string through some other function:
    public object read(string whatstring, string returnhow="string") {

    object result = "a string gotten from another function";

    switch(returnhow){
        case "int":
            result = int.TryParse(result, out result); break;
            case "bool":
                if (result=="0" || result=="false" || result=="") { returnthis = false; } else { returnthis = true; }; break;
        default:
            result = result.ToString(); break;
    }
    return result;
}

And I want to call it like this:
string thisvar = read("300", "int");
//or
bool thisvar = read("true", "string");

I don't think this is right.  Can I fix it, or am I going the wrong direction?
I do get an error, I suppose because of the way I am calling the function - but you get the idea of what I want.  I want it to be returned as the type that I declare the return value.  Maybe I am going the wrong direction?
Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

A: Use this.
public T ChangeType<T>(object value)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));
    return converter != null && converter.CanConvertFrom(value.GetType())
        ? (T) converter.ConvertFrom(value) : default(T);
}

This works with strings as the source, but also supports any other source type. As long as there is a type converter for it, and it can be converted, it will be. Otherwise, you'll get the default value (i.e. null for strings, 0 for ints, DateTime.MinValue for dates, etc.).
Same code, as an extension method of Object:
namespace System
{
    public static class ObjectExtensions
    {
        public static T ChangeType<T<(this object value)
        {
            var converter = TypeDescriptor.GetConverter(typeof(T));
            return converter != null && converter.CanConvertFrom(value.GetType())
                ? (T) converter.ConvertFrom(value) : default(T);
        }
    }
}

The added bonus of using the built-in type conversion from the BCL is that you can support any custom types you want, just by implementing a type converter for them. MSDN has an example of implementing this for the Point class here.
Also, refer to Scott Hanselman's introductory article to this concept here.

A: You could use a function similar to this:
    public object Convert(string toConvert, Type typeToConvert)
    {
        if(typeToConvert is string)
        {
            return toConvert;
        }
        else if(typeToConvert is bool)
        {
            bool convertedOutput;
            if (bool.TryParse(toConvert, out convertedOutput))
            {
                return convertedOutput;
            }
        }
        else if (typeToConvert is Int64 || typeToConvert is Int32 || typeToConvert is Int16)
        {
            Int64 convertedOutput;
            if (Int64.TryParse(toConvert, out convertedOutput))
            {
                return convertedOutput;
            }
        }
        // additional converts here...

        return string.Empty;
    }

A: Generics might be the way to go for your requirement. There is a code snippet...
    public T read<T>(string whatstring, string returnhow = "string")
    {
        T result = default(T) ;
        // Do Something
        return result;
    }

Good Luck!

A: Here's an example implementation:
public static T GetByType<T> (string input) {
    if(typeof(T) == typeof(string)) { return (T) Convert.ChangeType(input, typeof(T)); }

    if(typeof(T) == typeof(Int32)) {
        int output;

        if(int.TryParse(input, out output)) { return (T) Convert.ChangeType(output, typeof(T)); }
    }

    if(typeof(T) == typeof(bool)) {
        return (T) Convert.ChangeType(input == "1", typeof(T));
    }

    throw new ArgumentException("Invalid input");
}

Working example:
void Main()
{
    Console.WriteLine ("Calling with string:");
    object type = GetByType<string>("0");
    Console.WriteLine (type.GetType());

    Console.WriteLine ("Calling with boolean:");
    type = GetByType<bool>("0");
    Console.WriteLine (type.GetType());

    Console.WriteLine ("Calling with integer:");
    type = GetByType<int>("0");
    Console.WriteLine (type.GetType());

    Console.WriteLine ("Calling with DateTime:");
    type = GetByType<DateTime>("0");
    Console.WriteLine (type.GetType());
}

Output:


text:
Q: How to programatically transfer money from a bank account via SEPA I am looking to transfer money via SEPA from one bank account to another - from an application.
The app needs to transfer funds in the name of the person whose bank account the funds are being transferred from - i.e. some third party gateway won't do.

*

*Is there an industry standard/available API for doing this (I couldn't find one off Google)?

*If not 1., are there specific bank accounts that allow API control?

Note: I read this SO article How can I electronically transfer money to another account using Bank Transfer (BACS) and my requirements are the same - i.e. registering a payee manually beforehand is acceptable.

A: Apparently Achta provides an API that connects to SEPA. See https://www.achta.com/Home/AchtaAPI


text:
Q: Post запрос Api Django У меня есть метод post. При вызове метода получаю ошибку
File "C:\Users\79633\PycharmProjects\DiplomProject\python-final-diplom\orders\api\views.py", line 296, in post
items_dict = load_json(items)
TypeError: Expected string or C-contiguous bytes-like object
[01/Feb/2023 12:32:11] "POST /cart HTTP/1.1" 500 89403
Вот мой файл views.py

class CartView(APIView):

permission_classes = [IsAuthenticated]

def get(self, request, *args, **kwargs):
    """Функция для получения содержимого корзины"""
    cart = Order.objects.filter(
        user_id=request.user.id, status='cart'
    ).prefetch_related('ordered_items').annotate(
        total_sum=Sum('ordered_items__total_amount'),
        total_quantity=Sum('ordered__items_quantity')
    )
    serializer = OrderSerializer(cart, many=True)
    return Response(serializer.data)

def post(self, request, *args, **kwargs):
    '''
    добавление товаров в корзину
    '''
    items = request.data.get('items')
    if items:
        try:
            items_dict = load_json(items)
        except ValueError:
            Response({'Status': False, 'Errors': 'Неверный формат запроса'})
        else:
            cart, _ = Order.objects.get_or_create(user_id=request.user.id, status='cart')
            objects_created = 0
            for order_item in items_dict:
                order_item.update({'order': cart.id})
                product = Product.objects.filter(external_id=order_item['external_id']).values('category', 'shop', 'name', 'price')
                order_item.update({'category': product[0]['category'], 'shop': product[0]['shop'], 'product_name': product[0]['name'], 'price': product[0]['price']})
                serializer = OrderItemAddSerializer(data=order_item)
                if serializer.is_valid():
                    try:
                        serializer.save()
                    except IntegrityError as error:
                        return Response({'status': False, 'errors': str(error)},
                                        status=status.HTTP_400_BAD_REQUEST)
                    else:
                        objects_created += 1
                else:
                    return Response({'status': False, 'error': serializer.errors},
                                    status=status.HTTP_400_BAD_REQUEST)
            return Response({'status': True, 'num_objects': objects_created})

    return Response({'status': False, 'error': 'Не указаны необходимые поля'},
                    status=status.HTTP_400_BAD_REQUEST)

def put(self, request, *args, **kwargs):
    """Функция для изменения количества товара в корзине"""
    items = request.data.get('items')
    if items:
        try:
            items_dictionary = loads(items)
        except ValueError:
            Response({'Status': False, 'Errors': 'Неверный формат запроса'})
        else:
            cart, _ = Order.objects.get_or_create(user_id=request.user.id, status='cart')
            objects_updated = 0
            for item in items_dictionary:
                if isinstance(item['id'], int) and isinstance(item['quantity'], int):
                    objects_updated += OrderItem.objects.filter(order_id=cart.id, id=item['id']).update(
                        quantity = item['quantity'])
            return Response({'status': True, 'edit_objects': objects_updated})
    return Response({'status': False, 'error': 'Не указаны все поля'},
    status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, *args, **kwargs):
    """Функция для удаления товара из корзины"""
    items = request.data.get('items')
    if items:
        items_list = items.split(',')
        cart, _ = Order.objects.get_or_create(user_id=request.user.id, status='cart')
        query = Q()
        objects_deleted = False
        for item_id in items_list:
            if item_id.isdigit():
                query = query | Q(order_id=cart.id, id=item_id)
                objects_deleted = True

        if objects_deleted:
            count = OrderItem.objects.filter(query).delete()[0]
            return Response({'status': True, 'del_objects': count}, status=status.HTTP_204_NO_CONTENT)
    return Response({'status': False, 'error': 'Не указаны все поля'}, status=status.HTTP_400_BAD_REQUEST)

Делаю запрос
###
POST http://localhost:8000/cart
Content-Type: application/json
Authorization: Token b2395b613c581c322a833c9ff8661cbf8d248a70

{
    "items": [{"external_id": 4, "quantity": 2}]
}

Помогите исправить ошибку в коде


text:
Q: Unable to use replace in order to rename cells Currently I have some JavaScript within a .hta application which opens a .xlsx workbook, saves each sheet as a CSV file and then removes blank columns/rows.
I am trying to introduce a new step which renames any cells which contain a single question mark "?" in the spreadsheet to a blank "".
The idea is this renaming step happens prior to deleting blank rows/columns.
When I execute the below code the question marks are still present in the csv files? Why is the renaming not working as intended?
          // Open the workbook.
          var wb = xlApp.Workbooks.Open(aFile.Path);
          log('Successfully opened the file.');

          // Save each worksheet as a CSV file.
          var sheetNum = 0;
          for(var sheetIndex = 1, sheetCount = wb.Sheets.Count; sheetIndex <= sheetCount; sheetIndex++) {

        var ws = wb.Sheets.Item(sheetIndex);
        var wsName = ws.Name;
        var usedRng = ws.UsedRange;

        //Replace "?" with ""

    var num_col = ws.UsedRange.columnCount
var num_row = ws.UsedRange.rowCount

for (i = 0; i < num_row; i++) {
for (j = 0; j < num_col; i++) {
    ws.UsedRange.getCell(i,j).values = ws.UsedRange.getCell(i,j).values.replace("?","");
}
}

        //Remove all blank rows

        for(var i = usedRng.Rows.Count; i > 0; i--){
            if( xlApp.CountA(usedRng.Rows(i)) == 0 ) usedRng.Rows(i).Delete();
        }

        //Remove all blank columns

    for(var i = usedRng.Columns.Count; i > 0; i--){
        if( xlApp.CountA(usedRng.Columns(i)) == 0 ) usedRng.Columns(i).Delete();
    }


text:
Q: Запросы ORACLE SQL Задача:
декартово произведение
Вывести:

*

*фамилии и отделы всех сотрудников из таблицы EMPLOYEES, независимо от того, относятся ли они к какому-то отделу или нет; - номера и наименования всех отделов из таблицы DEPARTMENTS, независимо от того, есть ли в них сотрудники или нет.
Колонки отчета назвать "Last Name", "Dept Employye", "Dept Num", "Dept Name"
Моя попытка:
     SELECT Last_Name "Last Name", department_id "Dept Employye", TO_CHAR (NULL) department_name
     FROM employees
     UNION
     SELECT (NULL), department_id "Dept Num", department_name "Dept Name"
     FROM departments

Подскажите пожалуйста,
как использовать в данном запросе CROSS JOIN?


text:
Q: Win 10 One of two screens only maximizes windows and shows 50% I got a really nasty and annoying nut to burst here. Maybe grab a coffee and snack since the story may get a bit long.
TL;DR: User has two screens and only one screen shows 50% of content in random windows that are maximized or some windows turn blank.
Here we go. Everything started with our migration. We are about 16-20 users in now and only this one has the issue. We put in place a temporary laptop until her's arrived that already worked perfectly fine with someone else and was in the wrong OU before. (OU = Organizational Unit)
The setup is this. Laptop to USB-C Docking with connected then 2 Screens of 1920x1080, Ethernet, Wireless USB Mouse and Keyboard. This setup works fine for most users and only some of them have to plug in the USB directly to the laptop because the docking is not yet allowed on those devices.
However for this user the docking was allowed and everything works. Now comes a bit of history. First we wanted to connect 2 4K screens of which only one could run with 4k 60hz while the other one only went as far as 1920x1080 60hz (I think. Maybe only 30hz). We checked if it was maybe an accidental resolution swap but nope. Only one screen can run on 4k.
Then we swapped the screens with 2 1920x1080 screens and then it started. She noticed this maybe a week in and we are since trying to figure it out. So next thing we tried was to swap the laptop as soon as her laptop arrived. There again is the issue.
Next we swapped the docking station, which of course also didn't solve the issue.
Meanwhile we also tried to fix the issue by changing the resolution from 1920 to 1620, applied and then from 1620 to 1920 to see if it was maybe a 4K mixup. We thought so because when we moved the windows with Windows-Key + Arrow Down the window came back and we were able to work with it. So we thought the windows got maximized to 4K instead of 1920.
Then we swapped the screen that had the issue with a brand new out of the box screen. You can guess it. No change. After a few minutes or hours it happened again.
So by now she has basically a whole new setup and we also physically switched the screens so the left screen was on the right and the right was on the left but this only shifted the issue from the right screen to the left screen.
Next we tried another solution from Reddit that I found randomly. I selected "Maintain Screen Scaling" instead of "Scale Full Screen" since it is the same setting my colleague and the screen that worked had. It worked for another few hours and then it came back.
By now the only think that came into my mind was that maybe in the appdata could be a screen setting that got stuck but there I couldn't find anything about a folder or settings that were saved in there.
The only thing we haven't yet tried is to remove all the graphic drivers to see if that may fix the issue but the problem is the laptop needs to work again and we aren't too keen to fubar it.
Any ideas, sugguestions or tips will be more than welcome.
Edit:
While looking some more I remembered that we actually connected the two 4K screens onto the old AND new laptop of that user. So I figured that it may be something related to the settings saved in the registry and found a somewhat useful arcticle.
Screen Cache reset via Registry
I also found this article which may also be of use if it helps us to prevent a reset of the machine.
Screen settings reset with CTRL + Alt +F8
I tried both tips in that order on the old laptop but since I am not working constantly on that machine I cannot see which of the two fixed the issue in case that it is fixed now.


text:
Q: Model view difficulties I've treeview in which I'd like to have displayed files selected by user via file_dialog.getOpenFileNames(); file_dialog is QFileDialog.
I did create model class:
class File_Display_Model : public QAbstractItemModel
{
    Q_OBJECT

private:
    QStringList* selected_files_;

public:
    explicit File_Display_Model(QObject *parent = nullptr,QStringList* selected_files = nullptr);

    int File_Display_Model::columnCount( const QModelIndex & parent ) const
    {
        selected_files_->count();
    }

    QVariant File_Display_Model::data(const QModelIndex & index, int role) const
    {
        if (!index.isValid())
        {
                return QVariant();
        }
        else
        {
            if (role == Qt::DisplayRole) {
                    if (index.row() == index.column())
                    {
                        return 0;
                    }
                    else
                    {
                        return selected_files_->at(role);
                    }
                }
                return QVariant();
        }
    }

    QModelIndex File_Display_Model::index(int row, int column, const QModelIndex & parent ) const
    {
         /*DUMMY - HERE I JUST DON'T KNOW WHAT TO RETURN*/
         return QModelIndex();
    }

    QModelIndex File_Display_Model::parent(const QModelIndex & index) const
    {
        return QModelIndex();
    }

    int File_Display_Model::rowCount( const QModelIndex & parent ) const
    {
        selected_files_->count();
    }
};

And I also provided this class as a model to tree view. There is a problem with a index method in this class - I don't know what to return.
Could someone please help me and guide me how to make it work so files selected by an user are displayed in a treeview?

A: First of all there is no reason for using a QStringList*. Qt uses implicit sharing so it is efficient to pass it as an argument (dont forget that QStringList is nothing more than a QList<QString>).
Second you should review the excellent Qt Model/View Programming documentation.
Row and Column Count
You are trying to create a tree model so you should read carefully the tree model example. Notice that the rowCount and columnCount functions have as argument a model index.

The rowCount() function simply returns the number of child items for
  the item that corresponds to a given model index, or the number of
  top-level items if an invalid index is specified

and for the column count

Since each item manages its own column data, the columnCount()
  function has to call the item's own columnCount() function to
  determine how many columns are present for a given model index. As
  with the rowCount() function, if an invalid model index is specified,
  the number of columns returned is determined from the root item

So you have to think how your stringlist will be represented as a tree model. How columns will you have and what will be stored there for every level? How will be the rows hierarchy? Why are you using as column count the number of strings?
Model Index
When you reimplement the index() function you just have to check if the provided row and column are valid and if yes you should call the createIndex function. Again it all depends on what data your model contains and how you have structured them. Since you want to implement a tree model you have to take under consideration the parent item as well.

When reimplementing this function in a subclass, call createIndex() to
  generate model indexes that other components can use to refer to items
  in your model.


text:
Q: XCode 5 always behind other windows Since upgrading to XCode 5 and Mountain Lion, Xcode is always behind all other windows.
For instance, I open up Safari or Finder to look at something and I have to close or minimize them in order to get back to XCode.  With XCode 4 I would leave several windows open and just click between them.
I know this is probably some stupid OSX setting that got changed in upgrading to Mountain Lion, but for the life of me I know not what!
Thanks in advance!

A: It wasn't working Friday, works fine today (Monday).
Go figure!


text:
Q: Angular 5 Firebase Auth Guard login status different to whats retuned from Auth Service I'm pretty new to Angular and in the process of designing a small web app.
I created a simple email/password login using angularfire2. The authentication part works fine. However, it appears the authguard for some reason always thinks the user is logged out even though the console.log out from the auth service I created returns a user.
Here is my implementation:
Service:
export class AuthService {

  private user: Observable<firebase.User> = null;
  private userDetails: firebase.User = null;

  constructor(public firebaseAuth: AngularFireAuth, private router: Router) {
    this.user = firebaseAuth.authState;
    this.user.subscribe(
      (user) => {
        if (user) {
          this.userDetails = user;
          console.log(this.userDetails.uid);
          console.log('service: logged');
        } else {
          this.userDetails = null;
          console.log('service: logged out');
        }
      }
    );
  }

isAuthenticated() {
     if (this.userDetails == null ) {
      return false;
     } else {
      return true;
     }
   }
}

i use isAuthenticated() function (in the AuthGuard) to establish whether the user is signed in or not.
Auth Guard:
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

  if (this.authService.isAuthenticated()) {
      console.log('guard: user is logged in ')
      return true;
  } else {
      this.router.navigate(['login']);
      console.log('guard: user is not logged in ')
      return false;
  }
}
}

My question is, why does the function used in AuthGuard think the user is not logged in but the AuthService reckons the user is logged in? Also, i've noted when the page refreshes, user logs out. Is there any way to address both together?
Edit:
Routes Array
const appRoutes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full',
  },
  { path: '', component: FullLayoutComponent, data: { title: 'home' }, children: HOME_ROUTES, canActivate: [AuthGuard] }, // 'home page' is here
  { path: '', component: ContentLayoutComponent, data: { title: 'content' }, children: CONTENT_ROUTES}, // login page is a child here

];

login page is defined as a child in CONTENT_ROUTES where the default route is HOME_ROUTES.


text:
Q: remove main title from histogram in pandas I want to remove "SalesPrice" from the plot.
and remove the borders (keep the x,y axes and remove the top border)
and I want to convert the numbers to be written with (e).
I will be grateful for any help.
salesHist = ames.hist(column='SalePrice', grid = False, edgecolor =
"black", color = 'khaki')

for ax in salesHist.flatten():
   ax.set_xlabel('home sale price')
   ax.set_ylabel('Density')


text:
Q: call Form2 from Form1 in wpf vb.net if in vb.net, I can call like this form2.show (), but how in wpf vb.net?
thank you

A: Did you try the Object Oriented method:
Dim f2 as New Form2
f2.Show()

it worked for me.

A: Here in Wpf we cannot open/show the other form directly.
so in Wpf we have to create an object that refer to the form2.
because in Wpf even our form is considered as class.
Dim objForm2 As New Form2

objForm2.Show()


text:
Q: Compare data between 2 different schemas We refactored our old database. Some tables were dropped, some tables were split into 2 new tables etc. So now we have an absolutely new DB schema which has many differences from the old one. Someone has written an application which migrates data from the old database to the new one.
I'm looking for methods/techniques to compare correctness of data migration. Is there any standard or often-used ways to accomplish such compare?
After some research, I found one technique how to do it - create a VIEW of each table of the old database i.e. I will try to represent in VIEW data in format of old table (old schema), and then compare data in old table with data in VIEW.
I'm interested in other ways.

A: Although the representation of the data differs between the old and new schema the data itself should be the same.  This means a series of reconciliation queries will provide certainty that the migration was without error.
Say you have an Orders table.  The total number of Orders per year, month or day will be the same in the old and new databases.  Similarly the total value of those Orders for each time period will match.  You can expand this idea for orders-by-product, orders-by-customer etc.
If any data was changed in the migration the corresponding reconciliation queries will not return the same value from old and new DBs.  You will know immediately that the problem was with an order from customer "X" on day "Y" for product "Z" and can focus your debugging on that area.
The same approach can be used for any other table.  Take customers as and example.  You can count customers by country, business area, first letter of name or any other differentiator you choose.


text:
Q: Send/receive data to external running application thru php As I explain in the title, I have a running app in the background and would like to send commands to it as requested and get the results to the php pages in my local server.
If I run the app multiple times, my project loses its point so I can't use exec() or shell_exec() command.
Do you think it is possible to do? How/Why?
Thanks for the answers and sorry for bad English.


text:
Q: How to use one angularjs app in a different web application? I have made an angularjs app and I want to use it in another web application (eg. C# .Net,JAVA). I have another web app (which does not use angularjs) and when I click a button it should be redirected to my angularjs app to use the functionalities. How can I achieve this? Thanks!

A: IMO, for C# Web App, you can use RedirectPermanent("<AngularJsApplicationFeaturePageUrl>"); spend time in AngularJs application and when it completes, AngularJs Web Application is responsible for redirecting us to appropriate page in C# Web App.
For Example,

*

*You might have experienced it in e-commerce apps. For buying\ checking-out items, you will be redirected to Bank's fund transfer page. When you are done, Bank website will redirect you to original e-commerce app.

*You are seeing in Identity Module Providers like Azure Active Directory, Google Single Sign On,.. redirects you to its login page to challenge your identity and posts you back to original website.
You can find a ton of examples for above use cases.


text:
Q: When running gradle task through teamcity ,getting following issue Could not determine artifacts for javax.ws.rs:javax.ws.rs-api:2.1.1

Could not get resource 'https://jcenter.bintray.com/javax/ws/rs/javax.ws.rs-api/2.1.1/javax.ws.rs-api-2.1.1.$%7Bpackaging.type%7D'.
Could not HEAD 'https://jcenter.bintray.com/javax/ws/rs/javax.ws.rs-api/2.1.1/javax.ws.rs-api-2.1.1.$%7Bpackaging.type%7D'. Received status code 400 from server: Bad Request


text:
Q: Spotfire calculate the difference of values in a single column based on date for each group I have a requirement of calculating the difference in Spotfire for values in a single column based on the occurrence.
the data looks like

ID
Value
Date

1
7
07/01/2021

1
8
09/01/2021

1
10
10/01/2021

1
15
11/01/2021

1
6
12/01/2021

1
3
15/01/2021

2
10
07/01/2021

2
11
08/01/2021

2
12
09/01/2021

the expected output is

ID
Value
Date
Flag

1
7
07/01/2021
True

1
8
09/01/2021

1
10
10/01/2021

1
15
11/01/2021

1
6
12/01/2021

1
3
15/01/2021

2
10
07/01/2021
False

2
11
08/01/2021

2
12
09/01/2021

the logic is
we need to find the flag by comparing the value of first received and latest received for each id.
for id 1 first received value is 7
for id 1 latest received value is 3
is 7>3 True .
for easy understanding i had sorted the id column.
Thanks in Advance.

A: Hi I think you can do this in two step:
First step :
Concatenate(String([Value])) OVER ([ID])

Will say you name this column : test
Which will give you (7,8,10,15,6,3)
Second step :
Integer(left([test],1)) > Integer(right([test],1))

ID
Value
Date
test
flag

1
7
07/01/2021
7, 8, 10, 15, 6, 3
True

1
8
09/01/2021
7, 8, 10, 15, 6, 3
True

1
10
10/01/2021
7, 8, 10, 15, 6, 3
True

1
15
11/01/2021
7, 8, 10, 15, 6, 3
True

1
6
12/01/2021
7, 8, 10, 15, 6, 3
True

1
3
15/01/2021
7, 8, 10, 15, 6, 3
True

2
10
07/01/2021
10, 11, 12
False

2
11
08/01/2021
10, 11, 12
False

2
12
09/01/2021
10, 11, 12
False


text:
Q: How to use PowerManager.goToSleep() in my app that runs on Lineage OS? CyanogenMod/Lineage OS has a feature to turn of the screen by double tapping the status bar. It just turns off the screen, not locking the device. As far as I know, this is not possible with normal apps. The apps on the Store turn off the device by locking the device. I browsed the source code of Lineage OS, and if I understood it correctly, it seemed to use PowerManager.goToSleep().
I want to create an app to turn the screen off, for my personal use on a device that runs Lineage OS. Since it is Lineage OS, not a stock ROM, I can do more things such as getting the root access or flashing something.
But according to this question, that method is not accessible to third-party apps. I created a simple project and called that method, but when I tried to build the project, "error: cannot find symbol method goToSleep(int)" happened.
Can I create an app that calls that method using Android Studio and the official SDK? If not, how can I build the app that calls that method?
Added the code as requested:
public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        pm.goToSleep(100);
    }
}

Manifest:
<manifest package="com.example.turnofftest"
      xmlns:android="http://schemas.android.com/apk/res/android">
    ....
    <uses-permission android:name="android.permissions.DEVICE_POWER" />
</manifest>

After reading the question "ApriOri" told, I knew I have to sign the app using the platform's certificate, which I can probably do, as Lineage OS is open-source. But first, I need to build it.

A: You should make sure that your app has permissions to do that.
Since it's a Linage OS ROM you can easily include your app as a system app that will have access to the PowerManager API.
The question you mentioned include some comments about the required permissions.
There is a specific question regarding the required permissions of PowerManager.goToSleep() here.

A: Use this :
PowerManager pManager=(PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
try {
    pManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(pManager, SystemClock.uptimeMillis());
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

Manifest :
become system uid :
android:sharedUserId="android.uid.system"
add permission :
<uses-permission android:name="android.permission.DEVICE_POWER"/>


text:
Q: SQL index out of range exception when I try to execute the SQL query shown below I get a IndexOutOfRangeException. I can't figure out why it is, on other SO pages it says that it could be because you try to get data from an non-existing field but I am certain that it exists and when i changed both of the requested fields from "ADRES" and "TAAL" to "LEV" like the one above them only the 2 bottom ones would refuse to work, while the top request for "LEV" still worked. "ADRES" is a 8 long varchar and "TAAL" is a 1 long varchar field
try
{
  //BESTEL,[PLAN],LEV,ADRES,TAAL
  SqlCommand getlist = new SqlCommand("select * from BESW where BEST=@best", Connectie.connMEVO);
  getlist.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
  DRorder = getlist.ExecuteReader();
  while (DRorder.Read())
  {
    dateTimePicker1.Value = Convert.ToDateTime(DRorder["BESTEL"]);
    dateTimePicker2.Value = Convert.ToDateTime(DRorder["PLAN"]);
    comboBox1.Text = DRorder["LEV"].ToString();
    comboBox2.Text = DRorder["ADRES"].ToString();
    textBox8.Text = DRorder["TAAL"].ToString();
  }
}
catch (Exception er) { MessageBox.Show("" + er); }

EDIT: seems that if I split up the query like shown below it works, I really don't get why that is.
try
{
  //BESTEL,[PLAN],LEV,ADRES,TAAL
  SqlCommand getlist = new SqlCommand("select BESTEL,[PLAN],ADRES from BESW where BEST=@best", Connectie.connMEVO);
  getlist.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
  DRorder = getlist.ExecuteReader();
  while (DRorder.Read())
  {
    dateTimePicker1.Value = Convert.ToDateTime(DRorder["BESTEL"]);
    dateTimePicker2.Value = Convert.ToDateTime(DRorder["PLAN"]);
    comboBox2.Text = DRorder["ADRES"].ToString();
  }
  SqlCommand getlist2 = new SqlCommand("select LEV from BESW where BEST=@best", Connectie.connMEVO);
  getlist2.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
  DRorder = getlist2.ExecuteReader();
  while (DRorder.Read())
  {
    comboBox1.Text = DRorder["LEV"].ToString();
  }
  SqlCommand getlist3 = new SqlCommand("select TAAL from BESW where BEST=@best", Connectie.connMEVO);
  getlist3.Parameters.Add("@best", SqlDbType.VarChar).Value = data.corrigeerbestnr;
  DRorder = getlist3.ExecuteReader();
  while (DRorder.Read())
  {
    textBox8.Text = DRorder["TAAL"].ToString();
  }
}
catch (Exception er) { MessageBox.Show("" + er); }

A: There could be two possible errors
1. The any of the column could be missing or misspelled.
2. You are trying to set the property to a combo box, which might not have the queried data as its item.
Hope it helps.
Edit: Say, combo box has two items "Yes" and "No", you could be trying to set "Neither of them" as its current item.

A: It apears that when I split the fields into seperate queries they just work, the queries are not altered it just doesn't have all the rows in 1 query. I still don't really know why it did that but using seperate queries at least works around that issue.


text:
Q: Uninstalling Activestate messed up my python directory and all my settings So I was really eager to try generating a django model diagram with django-extensions by doing the following:
manage.py graph_models -a -g -o my_project_visualized.png

Then I realized I need pygraphviz to make it work. I'm running Windows 7 64bit, so I installed Activestate and Graphviz as suggested by the documentation as a requirement. Graphviz 2.28 was installed quite successfully and then Activestate was installed with some tweaks msiexec /package activestate_install.exe /qr because it always stuck at "finish checking disk spaces required".
Later, it turns out activestate wasn't really helping in installing pygraphviz. So after a lot of trial and errors, I managed to install pygraphviz by following this guide http://blog.ropardo.ro/2011/11/28/installing-pygraphviz-on-windows/. Just as I tried to run the graph_models command again, python once again tells me that pygraphviz module is not installed... so I pip freeze to see if it's really not installed. Now comes the good part, pip freeze returns a traceback of ImportError: DLL load failed: %1 is not a valid Win32 application. But that only happens in virtualenvs, when get out of virturalenvs and pip freeze, it works as expected.
By googling around, I realized I might have installed some 64bit version package while having 32bit python 2.7.3 on my machine, and that's indeed what I did. Just that I don't remember which ones I installed were 64bit. It's late at night, and I'm tired and frustrated, so I started uninstalling things that I thought might be causing the problem. I uninstalled mingw32 and Activestate, and the next thing I know, I can't even get into python from command line. pip is not recognized either; every python package is not recognized. Checking back at the Python27 directory, half of the folders are gone in C:\Python27\Lib. There used to be a lot of files and folders which it's impossible for me to recall what they are, and now there's only 4 directories:
bsddb, importlib, site-packages, and test

and the site-packages folder is a lot "cleaner", too! I'm sure there used to be a lot of package files and scripts (some .pth files and .py files). Now there's only two files easy-install.pth and PIL.pth and some folders for some packages I installed. However, the most critical issue is I can't even use python in cmd now.
I thought maybe uninstalling activestate messed up some of the environmental variables I set, then I went into the system settings and added in things like C:\Python27\Scripts;C:\Python27\Lib\site-packages to PATH. I went back into cmd, and typed "python" and "pip", the response I get for python is The system cannot find the path specified., and for pip it's still 'pip' is not recognized as an internal or external command, operable program or batch file.
This is kind of the only time that I regret for not setting up a system restore point..
Could anyone please tell me what's going on here, what am I doing wrong, and how am I supposed to get everything working again? Thanks a lot!

A: Boy, you indeed messed up your installation. "ActiveState" is a python distribution for Windows, so you installed a new python distribution over your old one. When you uninstalled, it obligingly removed your python installation, including the default library.
You'll have to reinstall your Python installation, I'm afraid. Start from scratch or backup.
You have my sympathies, if that's any consolation.