text:
Q: Emacs scrollbars with exact positioning How can I get scrollbars with exact positioning?
To illustrate what I mean:

*

*C-h C-f (Read the The GNU Emacs FAQ)

*Now try to position the buffer content such that the paragraph starting with This is the version ... is on top. With the default scrollbar you need several redraws to do this. Or you left-click for cursor positioning then C-lC-l

*Now go back to where you have been before. This is impossible with regular scrollbars.
What I would like to have is to just click in the scrollbar at the height of This is the version ... to position this line on top for step 2. And to go back where I came from, I rightclick (without having moved the mouse, indeed).
In the past, I have always installed Emacs with the Athena widgets-like option to get such scrollbars, see a description of them. But I wonder if there is now a better or more modern way to do this. After all, I'd rather like to use standard distributions.
Maybe, it is not even necessary to change the scrollbars at all but to use rather the left-fringe for it. After all, mouse clicking in the fringe is recognized as <left-fringe>
M-x emacs-version
GNU Emacs 23.3.1 (x86_64-pc-linux-gnu, GTK+ Version 2.24.10) of 2012-09-21 on batsu, modified by Debian

A: Maybe a change of usage habits could help? Some Emacs user recommend disabling the scrollbars completely and navigate Emacs exclusively with the keyboard. (This habit is also beneficial for using Emacs inside a shell.)
Emacs provides a large number of navigation shortcuts. For instance, for jumping up and down large amounts of buffer space, you have:
C-v scroll-up
M-v scroll-down
M-} forward-paragraph
M-{ backward-paragaph
C-x ] forward-page
C-x [ backward-page
However, I would argue that by far the most useful navigation commands are:
C-s isearch-forward
C-r isearch-backward
In Emacs, search is so cheap, it is such an integral part of the work flow that it's often times much faster to get to a different point in the buffer by using a reference word as an anchor for a quick search, rather than leaving the home row to reach for the mouse. Hitting C-s or C-r repeatedly will move the point to consecutive matches. (You can even switch to regular expression search by hitting M-r while searching to make search even more powerful.)
You already mentioned C-l C-l to view the current line at the top of the buffer.
Now, if you want to go back to the previous location, you could use
C-u C-x
which jumps back to the mark. All the above commands for navigation push their start position on a "mark-ring" which means you can not only jump back one position, repeatedly hitting C-u C-x will take you back to many previous positions.

A: For this task I press C-l once, twice, three times.They will switch between middle-top-bottom.


text:
Q: MERN Heroku returns index.html instead of actual JSON data from server this was working perfectly fine with localhost but after I deployed from Heroku it doesn't work.
please help.
Index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
const postRoute = require("./routes/posts");
const multer = require("multer");
const path = require("path");

dotenv.config();

mongoose.connect(
  process.env.MONGO_URL,
  () => {
    console.log("Connected to MongoDB");
  }
);

app.use("/img", express.static(path.join(__dirname, "public/images")))

//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/images");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name);
  }
});

const upload = multer({storage});
app.post("/api/upload", upload.single("file"), (req,res)=>{
  try {
    return res.status(200).json("file uploaded successfully");
  } catch(err){
    console.log(err);
  }
})

if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'frontend/build')));
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'frontend/build', 'index.html'));
});
}

app.use("/api/auth", authRoute);
app.use("/api/users", userRoute);
app.use("/api/posts", postRoute);

//const port = parseInt(process.env.PORT) || 8800;

app.listen(process.env.PORT || 8800, () => {
  console.log("backend server is running");
});

Feed.jsx
import "./feed.css";
import Share from "../share/Share";
import Post from "../post/Post";
import { useEffect, useState, useContext } from "react";
//import {Posts} from "../../dummyData";
import {axiosInstance} from "../../config";
import { AuthContext } from "../../context/AuthContext";
export default function Feed({username}) {
  const [posts, setPosts] = useState([]);
  const { user } = useContext(AuthContext);

  //this helps you to render once when the page open.  and only re-render whatever you put in[] changes, which is the dependency
  useEffect(() => {
    const fetchPosts = async () => {
      const res = username
        ? await axiosInstance.get("/posts/profile/" + username)
        : await axiosInstance.get("/posts/timeline/" + user._id);
      console.log(user._id);
      console.log(username);
      console.log(res.data);
      setPosts(
        res.data.sort((p1,p2)=>{
          return new Date(p2.createdAt) - new Date(p1.createdAt);
        })
      );

    };
    fetchPosts();
  },[username, user._id])

  return (

            {(!username || username === user.username) && <Share/>}
            {posts.map((p) => (
              <Post key={p._id} post={p}/>
            ))}

  );
}

if I do Console.log(res.data) from Feed.js, I see index.html data instead of JSON data I should be getting from "api/posts/timeline/"...
this was working perfectly fine with localhost but after I deployed from Heroku it doesn't work.
please help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a container's info when using rhuss/docker-maven-plugin? How to get a container's info (e.g.: the ip) using the docker-maven-plugin by rhuss (groupId: "org.jolokia")?
Their changelog mentions "Allow the container's host ip to be bound to a maven property and exported" on version 0.13.3. But apparently it's not documented how to do it.

A: I found instead that the plugin can have docker forward a port in the container to a random (available, I assume) port on the host. So you can access applications in the container with <host-ip>:<mapped-port>
As in the sample project:
On the plugin declaration, under <image> and then <run>, declare a <port>your.key:8080</port>. The plugin will set the property your.key with the random port it had assigned to the container.
I found this to work on Maven 3, but not 2. Also my IntelliJ can't figure out that your.key is valid and marks it red.


text:
Q: Bootstrap wells <div class="well" style="width: 100%; height: auto;">
    SOME OTHER CONTENT DIVS BLA BLA
</div>

My wells because height auto doesn't keep under all content and it stays by default size with no content...
And my content overflows it.
When I add overflow:hidden to wells I get what I need wells are all under whole content.
But when I need to overflow over well like for some dropup menu or something I can't do it because overflow:hidden
Is there way to say overflow hidden for all child divs except one with some unique id or something?


text:
Q: https://github.com/ymasory/iText-4.2.0 content extraction issue I am using  iText-4.2.0 https://github.com/ymasory/iText-4.2.0 project for pdf page content extraction. For some pdf files, it works properly. But for some files it's just return page no as content.
Any help on this?
code:
//in constructor
fis = new FileInputStream(file);
reader = new PdfReader(fis);
pdfTextExtractor = new PdfTextExtractor(reader);

//in extractContent method
return pdfTextExtractor.getTextFromPage(pageNo);


text:
Q: firestore ограничение длины массива на запись В документе есть поле
myProp
[
   someid_0,
   simeid_1,
   ...
]

Как можно ограничить размер массива?
Я делаю так:
allow write: if  request.auth.uid == userId  &&
            request.resource.data.myProp.length() < 2;

Но это так, наугад, потому что документация максимально убогая, особенно о правилах...
Как то возможно это проверить? Функции не предлагать - мне не нравится такое решение. Спасибо!

A: Разобрался. (У меня было разрешающее правило ниже, которое отменяло это)
Правильно так:
 request.resource.data.myProp.size() < 2;


text:
Q: Adding Strings to an ArrayList I need to make sure I am building this program right. I have to write a program that uses an ArrayList container and put 5 Strings in it and then print out the 5 Strings from the ArrayList. I am new to ArrayList's so want to make sure I have the requirements fulfilled.
My question is: "Is this the proper way to Create Strings, Create an ArrayList, add the Strings to the List and then Print the List?"
public static void main(String[] args)
{

ArrayList<String> names_and_numbers = new ArrayList<>();
String bob = "bob";
String nancy = "nancy";
String jim = "jim";
String claire = "claire";

names_and_numbers.add( bob );
names_and_numbers.add( nancy );
names_and_numbers.add( jim );
names_and_numbers.add( claire );

for (String e : names_and_numbers)
{
 System.out.println(e);
}

int six = 6;
String numbers = "";

ArrayList<Integer> myList = new ArrayList<>();

myList.add( 1 );
myList.add( 2 );
myList.add( 3 );
myList.add( 4 );
myList.add( 5 );
myList.add(six);

for (int x : myList)
{
 System.out.println(x);
}

//System.out.println(myList);
//System.out.println(names_and_numbers);
}
}

A: You're doing ok, I don't see a question but I think that arraylists store objects, so if you want an integer, get build an object. I guess if you can compli that, this is done automatically.
Integer i = new Integer(1);
myList.add(i);

Or in 1 line
myList.add(new Integer(1));

Edit:
As Paul Bellora says, new Integer(i) is unnecessary and you can replace it with just i. I just wanted to point out that ArrayLists store objects (somehow i forgot to mention that), not primitive data types like int and when you try to do it, the data is converted if possible (to the compiler) to a child of Object just like Integer.


text:
Q: home socket with DC voltage I'm wondering why, in a standard house, instead of using many low power AC-DC rectifier, there isn't a big (like 12V 20~50A) AC-DC rectifier which supplies some wall socket with a DC voltage?
In the long run this should be less expensive, given the fact that AC to DC in one big apparatus is done better than in many low-quality transformers, right?
Also, modern chip DC voltage regulators have efficiency of >90%, so smaller (or even larger) voltages are still efficient and possible.
So we could use a 12V socket to charge a phone, desktop computer, laptop, radio etc... and still have an AC socket to move washing machine engine and other things that work better with an AC supply.
Why isn't this done?
edit: real question is:
is it convenient, given a standard family (2 laptop, 1 desktop, 4 smarthpone, 1 big tv and some minor electonic) to do so?

A: I think you are focusing on a small fact about power conversion efficiency, and ignoring all the more important factors:

*

*extra cost of copper in house wiring to carry significant DC power
(this is partly why Tesla's AC beat Edison's DC system),

*the lack of a single standard DC voltage so there is still conversion
required,

*the requirement for higher-voltage AC anyway for existing and likely
future home devices,

*the reliability, availability and economy of low-power AC-DC
converters,

*the flexibility of AC-DC conversion techniques

*the flexibility and scalability of converting from a single AC
standard to the specific requirement of the device

*the extra complexity of house wiring if two 'standards' have to be
routed, e.g. the need for new plug standards, extra cables routed
through building

*there will still be a period of transition when both systems must be
supported, and IMHO no sane democratic government would mandate the change-over,

*I also believe as power increases the cost of components for DC-DC increases quite
quickly above modest power conversion requirements

Edit:
Copper is expensive, London Metal Exchange - copper lists one tonne of copper (cash) is $7050, and that hasn't been processed into cable.
By comparison, London Metal Exchange - steel billet lists one tonne as $430, i.e. copper is 16x more expensive than steel.
So how thick must the 50A 12V cable be so as not to waste more energy as heat than AC? (Remember most of the benefit sited is efficiency, so it seems reasonable to ensure the losses due to heat in the DC cable are not worse than 230V AC.)
Lets compare AC mains cable rated at say 15A (Europe 230V), to 12V 50A DC cable.
Power loss = I^2 R
15^2 Rac = 50^2 Rdc
Rdc =  Rac x 15^2/50^2 = Rac x 0.09,
i.e. Rdc must be ~11x lower resistance than Rac to achieve a similar power loss
DC cable would need to have over 11x greater cross sectional area than AC cable to reach the same power loss in heat. Put another way, DC house wiring would need 12x more copper so that the losses in the DC cables were no worse than AC mains.
Further, while the 230V 15A AC cable could carry 3.6kW, the 12V 50A DC cable carries 600W for the same losses.
Yes, for 11x more copper (to maintain comparable energy losses to AC) the DC cable carries 1/6th the power. Even at the scale of a house, the proposed low voltage DC cabling is not viable vs 230V AC.
The significant and important economic, practical, political and transition costs seem to dwarf any notional benefit.

A: For a given power required by a device, the lower is the voltage the higher should be the current. That would imply much thicker wires, and a possible overheat where the section is not enough.
Even creating your DC rail, what voltage you would choose? If you choose 12VDC, for instance, you should add one or more DC-DC for lower voltages. At that point, where is the convenience?

A: I've thought that if things were done over, knowing what we know now, houses would better be supplied with 3-phase 60Hz or 50Hz power.
It's easily turned into DC with 6 diodes (no capacitor required for moderate ripple), easily transformed into other voltages with a mains-frequency transformer, and will directly run efficient quiet 3-phase motors that do not require 'run' capacitors. If you want a variable frequency 3-phase motor, you don't need a huge capacitor that is the first thing to die.
Presently, in North America 3-phase power is used in virtually all commercial and industrial installations, and many apartment buildings (though not brought to individual units). It is split out on a street-by-street basis in subdivisions.
The savings in billions of gadgets would probably vastly outweigh the added capital cost.

But, it's too late for that, and standards were set well before any thought of electronics on a mass scale. Most consumers were happy with a few primitive incandescent bulbs, a bulky weak motor in the electric ice box and washing machine etc., none of which was all that concerned with single phase vs. three phase.
If you made an outlet with (say) 300VDC out it would run many of the electronic gadgets we have now (the input filter capacitor life would no longer be an issue). They would not be much simpler, but they might be more compact. However, even today, many devices would go up in smoke with DC input (anything with a mains-frequency transformer or motor, and probably some others on top). So, you'd need a different plug.

A: Because a "Standard House" came into existance a Century (or so) ago, and slowly modified as needed (public safety and standard electrical code), at the speed of buerocracy. People are very resistant to change. Once the IEC was formed, and consolidation of standards happened, anything too different must have wide support to spread. Which is a catch 22. Unless there is demand, there is no supply.
Since everything already works on the current system, with all the negatives invisible to the common user, negatives that are very neutral. Effeciency doesn't matter to someone who just cares on if it works or not.
That said, low voltage DC is a standard used in many homes. Or I should say alongside homes. It is used in landscaping lighting. And new products pushing DC exist. In wall 2+ Amp usb chargers. AC outlets with builtin usb charger ports. I give it a decade before they have become so common that a house without them will be shunned by young first time buyers.


text:
Q: Is there anyway to convince Zelazny to stand down? Heng Sha second visit: I'm on a mission (I believe it's called Talion AD) to convince Zelazny not to go a killing spree. Other than killing him, is there any way to stop him?
If not, what is the best way to complete this mission (ie. getting most experience)?

A: According to the wiki, you can't reason with the guy. He's just too darn stubborn, and reasoning will only make him fight you.
You CAN, however, decide to approve of his actions, side with him, and then later lie to Dr. Wing about what happened, and you'll still get the quest reward.
Source: Wikia: Talion A.D. page

A: As Artless said, you can't reason with him. However, you don't have to kill him. A gas grenade is a particularly effective way of taking him and his men down non-lethally.

A: In addition to Artless's answer, you do not have to lie to Dr. Wing in order to complete this quest and get the Praxis kit, simply tell him the truth and use the 'convince'* option.
**I have the 'social enhancer' augmentation and do not know if it is required for this option to be available*


text:
Q: Represent JSON as a C# Class I'd like to deserialize this JSON as a C# class, but I need to define the class first:
{
"Prods": [
    {
        "ID": {
            "1001": [
                {
                    "Name": "Name1",
                    "Prod": "XXX"
                },
                {
                    "Name": "Name2",
                    "Prod": "XXXX"
                }
            ]
        }
    },
    {
        "ID": {
            "2001": [
                {
                    "Name": "Name3",
                    "Prod": "XXX-000"
                },
                {
                    "Name": "Name4",
                    "Prod": "XXXX-1111"
                }
            ]
        }
    }
]
}

I'd like to deserialize it into something like this, but nor sure if my JSON structure fits it:
public class Prod
{
    int CATID;
    Dictionary<string, string> prods = new Dictionary<string, string>();
}

public class Prods
{
   public List<Prod> Products {get;set;}
}

How should I change the JSON above to fit with my class below it, so I can use JsonConvert to deserialize into it?
Thanks!

A: To me your JSON just looks wrong as you don't always have 'consistent' name/value pairs. First I'd define my JSON like this
{
  "Prods":
    [{
      "ID": "1001",
      "Items":
        [{
          "Name": "Name1",
          "Prod": "XXX"
        },
        {
          "Name": "Name2",
          "Prod": "XXXX"
        }]
    },
    {
      "ID": "2001",
      "Items":
        [{
          "Name": "Name3",
          "Prod": "XXX-000"
        },
        {
          "Name": "Name4",
          "Prod": "XXXX-1111"
        }]
    }]
}

then I'd have the following classes to handle the data
public class Item {
  public string Name { get; set;}
  public string Prod { get; set;}
}

public class Product {
  public string ID { get; set;}
  public List<Item> Items { get; set; }
}

public class Products {
  public List<Product> Prods { get; set; }
}

then I'd use something like json.net to handle the serialization

A: In Visual Studio 2019, you can create a new class file, delete the class stub and use Edit->Paste Special->Paste JSON as Classes.  This very quickly generates the classes you need to represent your JSON. If you don't like the way it comes out, you can adjust your JSON string and try again.
If you have some properties that don't show up in every instance of the JSON object, you can define JsonExtensionData to hold the additional properties
    [JsonExtensionData]
    public Dictionary<string, object> additionalJSON { get; set; } =
        new Dictionary<string, object>();


text:
Q: How to transform an url to other? I need to transform this url's :

*

*localhost:8080/codeschoolangular/codeschoolangular/ApiRest/users/1

*localhost:8080/codeschoolangular/codeschoolangular/ApiRest/users

to

*

*localhost:8080/codeschoolangular/codeschoolangular/ApiRest/api2.php?rquest=users&id=$1

*localhost:8080/codeschoolangular/codeschoolangular/ApiRest/api2.php?rquest=users

in the same .htacces
I try:
RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond %{REQUEST_FILENAME} !-s

RewriteRule  ^([A-Za-z]+)/?$ /codeschoolangular/codeschoolangular/ApiRest/api2.php?rquest=$1 [QSA,NC,L]

RewriteRule "^users/([0-9]+)/$" /codeschoolangular/codeschoolangular/ApiRest/api2.php?rquest=users&id=$1 [QSA,NC,L]

but don't work.
Can any one help to resolve this problem?
Thanks in advance.

A: You're missing the "?" after the "/" in the seconde rule. Try this:
RewriteRule "^users/([0-9]+)/?$" /codeschoolangular/codeschoolangular/ApiRest/api2.php?rquest=users&id=$1 [QSA,NC,L]


text:
Q: How use Crud with CodeIginiter I'm new to codeigniter and am having a hard time understanding how to use crud for my application. Please give me some slack if the code I'm using is totally wrong as I'm very new, and been trying for a week already to figure it out.
I am able to create and insert data into the database, but am having trouble updating. If you guys can take a look at my code, that would be great. Thanks.
Here is my code:
login.php controller
<?php
class login extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form','url','html'));
        $this->load->library(array('session', 'form_validation'));
        $this->load->database();
        $this->load->model('user_model');
    }
    public function index()
    {
        // get form input
        $email = $this->input->post("email");
        $password = $this->input->post("password");
        $image = $this->input->post['image'];

        // form validation
        $this->form_validation->set_rules("email", "Email", "trim|required");
        $this->form_validation->set_rules("password", "Password", "trim|required");

        if ($this->form_validation->run() == FALSE)
        {
            // validation fail
            $this->load->view('login_view');
        }
        else
        {
            // check for user credentials
            $uresult = $this->user_model->get_user($email, $password, $image);
            if (count($uresult) > 0)
            {
                // set session
                $sess_data = array('login' => TRUE, 'uname' => $uresult[0]->firstname, 'uid' => $uresult[0]->id, 'image' => $uresult[0]->id);
                $this->session->set_userdata($sess_data);
                redirect("Profile/index");
            }
            else
            {
                $this->session->set_flashdata('msg', '
Wrong Email-ID or Password!
');
                redirect('login/index');
            }
        }
    }
}

Profile.php Controller

<?php
class Profile extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('url','html', 'form'));
        $this->load->library(array('session', 'form_validation'));
        $this->load->database();
        $this->load->model('user_model');

    }

    function index()
    {
        $details = $this->user_model->get_user_by_id($this->session->userdata('uid'));
        $data['uname'] = $details[0]->firstname . " " . $details[0]->lastname;
        $data['uemail'] = $details[0]->email;
        $this->load->view('profile_view', $data);
    }

    public function upload_profile() {
        $input = $this->input->post();

        $config['upload_path'] = './assets/images/'; //path were I save the uploaded profile pics
        $config['allowed_types'] = 'gif|jpg|png'; // allowed types that is mention
        //size of the picture by default
        $config['max_size'] = '100';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        $config['overwrite'] = true;

        $this->load->library('upload', $config);
        // display error if the picture is not on the config (sample bmp)
        if ( ! $this->upload->do_upload())
        {
            $error = $this->upload->display_errors(); // display the errors

            $data['upload_error'] = $error;
            if($this->session->userdata('account_id') != null) {  // if there is an account
                $this->load->model('profile'); //model
                $this->load->model('account'); //model
                $data['user'] = $this->profile->get_profile($this->session->userdata('account_id')); //get_profile is a function in model
                $data['account'] = $this->account->get_account($this->session->userdata('account_id')); //get_account is a function in model
                $data['view'] = 'users/settings';
                $data['title'] = "User's Settings";
                $data['error'] = $error;
                $this->load->view('masterpage', $data);
            } else {
                redirect(base_url('index.php/Profile/index'));
            }

        }
        else
        {
            //if no error
            $data = $this->upload->data();
            $updateProfile = array(
                'profile_pic' => $data['file_name']
            );
            $this->load->model('profile');
            $this->profile->update_profile($this->session->userdata('account_id'), $updateProfile); // update the profile of the user
            redirect(base_url('index.php/profile/index'));
        }
    }

}

user_model.php model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class user_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    function get_user($email, $password)
    {
        $this->db->where('email', $email);
        $this->db->where('password', $password);
        $query = $this->db->get('user');
        return $query->result();
    }

    // get user
    function get_user_by_id($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get('user');
        return $query->result();
    }

    // insert
    function insert_user($data)
    {
        return $this->db->insert('user', $data);
    }

    public function get_profile($profile_id)
    {
        $this->db->select()->from('profile_tbl')->where('profile_id', $profile_id);
        $query = $this->db->get();

        return $query->first_row('array');
    }

    public function update_profile($profile_id, $data)
    {
        $this->db->where('profile_id', $profile_id);
        $this->db->update('profile_tbl', $data);
        return $this->db->affected_rows();
    }

    public function get_account($account_id)
    {
        $this->db->select()->from('account_tbl');
        $this->db->where('account_id', $account_id);

        $query = $this->db->get();

        return $query->result_array();
    }
}

?>

?>
Profile_view.php view
<!DOCTYPE html>

    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="<?php echo base_url('css/mystyle.css'); ?>" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="<? echo base_url('assets/css/mystyle.css');?>" />
    <link rel="stylesheet" href="<?php echo base_url()?>assets/css/mystyle.css" type="text/css">
    <?php
    $autoload['helper'] = array('css_js');?>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

            </button>

                    <img src="<?php echo base_url()?>assets/img/monstercode.png" alt="Green Monster Mascot" style="width:160px;height:32px;">

<a href="<?php echo site_url('')?>">Home

<a href="<?php echo site_url('Site/sites')?>">Projects

<a href="<?php echo site_url('Site/developers')?>">Developers

<a href="<?php echo site_url('Site/employers')?>">Employers

Contact

                <?php if ($this->session->userdata('login')){ ?>

Hello <?php echo $this->session->userdata('uname'); ?>

<a href="<?php echo base_url(); ?>index.php/home/logout">Log Out

                <?php } else { ?>

<a href="<?php echo base_url(); ?>index.php/login">Login

<a href="<?php echo base_url(); ?>index.php/signup">Signup

                <?php } ?>

User Picture

User Info
 Name: <?php echo $uname; ?>
 Email: <?php echo $uemail; ?>

Profile Summary

Name: <?php echo $uname; ?>

Email: <?php echo $uemail; ?>

...

More User Info

Lorem ipsum...

Job Offers

Job Offers

        // default.png if haven't uploaded profile picture
        <?php $profilePic = "default.png"; ?>
        // if already uploaded profile picture it will display
        <?php if ($user['profile_pic'] != null) { ?>
            <?php $profilePic = $user['profile_pic']; ?>
        <?php }  ?>
        // if there is an error in uploading
        <?php if(isset($upload_error)) { ?>

                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    Uploading profile image could not be completed. <?php print_r($upload_error); ?>

        <?php } ?>

            //display the profile picture
            <img src="<?php echo base_url('assets/images/'.$profilePic); ?>" width="100" />
            // call the controller upload_profile
            <?php echo form_open_multipart(base_url('index.php/Profile/upload_profile'));?>
            <input type="file" name="userfile" id="userfile" size="20" style="display:none;" />
            Choose Image
            <input type="submit" class="btn btn-xs" value="edit profile" />
            </form>

A: Look at this block of code
function index()
    {
        $details = $this->user_model->get_user_by_id($this->session->userdata('uid'));
        $data['uname'] = $details[0]->firstname . " " . $details[0]->lastname;
        $data['uemail'] = $details[0]->email;
        $this->load->view('profile_view', $data);
    }

You are olny sending users email and name to the view.
But in your view you are using this <?php $profilePic = $user['profile_pic']; ?> which does not exists.That is why you are getting undefined variable error.
Model
 // instead of returning $query->result(), return $query->row() which would return only one row
    function get_user_by_id($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get('user');
        return $query->row();
    }

Controller
Instead of passing individual users details like you have done, pass the whole user object. You can show data in view like this Email : <?= $user->email ?>   That way you wont have to use hundreds of variable if your user table contains hundreds of fields(I know it can't have that many fields, its just to point out the issue).
function index()
    {
        $user = $this->user_model->get_user_by_id($this->session->userdata('uid'));
        $data['user'] = $user;
        $this->load->view('profile_view', $data);
    }

If profile_pic is a field in your user table, you can always check by
<?php if($user->profile_pic != null)

A: This is in answer to the appearing Comments you have...
Your code in your view needs to be altered a little as you've put your PHP Comments outside of your PHP Tags and you've gone overboard with the php tags so that could do with some cleanup. You could change that...
From
// default.png if haven't uploaded profile picture
<?php $profilePic = "default.png"; ?>
// if already uploaded profile picture it will display
<?php if ($user['profile_pic'] != null) { ?>
    <?php $profilePic = $user['profile_pic']; ?>
<?php }  ?>

To
<?php
// default.png if haven't uploaded profile picture
$profilePic = "default.png";
// if already uploaded profile picture it will display
if($user['profile_pic'] != null) {
    $profilePic = $user['profile_pic'];
}
?>


text:
Q: rename files in a selected directory using if else c# I am very new to C# and having trouble adapting/writing code for me needs, apologies if I use the wrong terms. I am developing a Windows Form App to rename only word documents within a given directory. I wish to utilize an "if else" approach to rename files dependent on what combobox item is selected.
Example:

*

*Users are given a drop down menu to select a rename value depending on what item is selected (if the user selects "<StudentCode>_Draft" or "<StudentCode>_Final", the word file will be renamed to <StudentCode>_Draft.docx or <StudentCode>_Final.docx respectively).

*The rename function would have to be split into a sting using '_' to delim as the file name is always be:
<Assignment name> allocated on <website>_<StudentCode>_<attempt>_<Year>-<Month>-<Date>-<Hour>-<Minute>-<Second>.docx
... as that is the output value from the website.

Would I need to specify the If Else function in private void RenameFiles_Click(object sender, RoutedEventArgs e)?
If so, here is the code I currently have (found from another project);
private void RenameFiles_Click(object sender, RoutedEventArgs e)
{
    DirectoryInfo d = new DirectoryInfo($"{PathStamp.Text}");
    FileInfo[] Files = d.GetFiles($"{ExtensionCombo.Text}");
    foreach (FileInfo file in Files)
    {
        File.Copy(
            sourceFileName: $"{file.FullName}",
            destFileName:
                $"{PathStamp.Text}{file.LastWriteTime.Date.Year}-{file.LastWriteTime.Date.Month}-" +
                $"{file.LastWriteTime.Date.Day}-{file.LastWriteTime.Hour}{file.LastWriteTime.Minute}{file.LastWriteTime.Second}{file.Extension}"
        );
    }

    Refresh();
}

*

*DirectoryInfo($"{PathStamp.Text}") refers to grabbing the selected folder from a text box that displays the file path

*d.GetFiles($"{ExtensionCombo.Text}"); refers to the current combo box where the items are located for the user to select an option. Currently, the options are 'StudentCode_Draft' and 'StudentCode_Final'

A: So basically you could use regex to pick out the Student code:
\S*_(\S*)_\S*_\d+-\d+-\d+-\d+-\d+-\d+

The above just validates the dashes and underscores to find the student code. Also I have used a switch with an index to work out what was chosen, you could use an if statement if you choose and a string comparison.
Given
private static readonly Regex _regex = new (@"\S*_(\S*)_\S*_\d+-\d+-\d+-\d+-\d+-\d+", RegexOptions.Compiled);

Example
private static bool TryGetFileName(int selectedIndex, string fileName, out string outputName)
{
   outputName = null;
   var match = _regex.Match(fileName);

   // If the file name doesn't look right, return false
   if (!match.Success)
      return false;

   var suffix = selectedIndex switch
   {
      0 => "Draft",
      1 => "Final",
      _ => throw new ArgumentOutOfRangeException(nameof(selectedIndex))
   };

   var path = Path.GetDirectoryName(fileName);
   var extension = Path.GetExtension(fileName);

   outputName = Path.Combine(path, $"{match.Groups[1].Value}_{suffix}{extension}");
   return true;
}

public static void Rename(int selectedIndex, string path, string searchPattern)
{
   foreach (var file in Directory.GetFiles(path, searchPattern))
      if(TryGetFileName(selectedIndex, file,out var outputName))
         File.Move(file, outputName);
}

Usage
Rename(SelectedIndex,@"D:\SomeExamplePath","*.docx");

Simple Tests
Some examples of what will work and what won't:
var listOfPaths = new string[]
{
   @"D:\Test\AssignmentName allocated on SomeWebSite_Bob1_2342343_2021-1-2-23-45-23.docx",
   @"D:\Test\test\test\fhjfghjgj SomeWebSite_Bob2_2342343_2021-1-2-23-45-23.docx",
   @"D:\Test\test\test\fhjfghjgj SomeWebSite_Bob2_2021-1-2-23-45-23.docx"
};

foreach (var item in listOfPaths)
{
   if(TryGetFileName(1, item,out var name))
      Console.WriteLine("Success : "+ name);
   else
      Console.WriteLine("Failed : " + item);
}

Output
Success : D:\Test\Bob1_Final.docx
Success : D:\Test\test\test\Bob2_Final.docx
Failed : D:\Test\test\test\fhjfghjgj SomeWebSite_Bob2_2021-1-2-23-45-23.docx


text:
Q: Displaying a notification in android I am using the following code to show a notification in my android application, but using this, with the notification an activity also shows up (i.e. a black blank screen) I dont want this screen, but just a simple notification and when the user clicks the notification then I want to launch the activity. What should be done to this code?
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notify = new Notification(R.drawable.mcube_logo, "Message Sent", Calendar.getInstance().getTimeInMillis());

        Intent intent = new Intent(RecieveAlarm.this, otherActivity.class);
        PendingIntent pendingIntent =PendingIntent.getActivity(RecieveAlarm.this, 1, null, PendingIntent.FLAG_CANCEL_CURRENT);

        notify.setLatestEventInfo(RecieveAlarm.this, "Title", "Details", pendingIntent);
        notificationManager.notify(0, notify);

A: I suggest you to use:
        Notification not = new Notification(idIcon, text, System.currentTimeMillis());
    PendingIntent pInt = PendingIntent.getActivity(ctx, 0, new Intent(ctx, the_class_to_call), 0);

    not.setLatestEventInfo(ctx, app_name, text, pInt);

and then not.notify....

A: use AlertDialog, then launch your desired activity on positive button click


text:
Q: Excel Summary sheet multiple worksheets with drop downs SUMMARY SHEETS CODEI am trying to create a project tracker with a summary page. Each team member has their own worksheet to track projects and I need a summary of all of their data.
Columns 'Rep', 'Project Type', 'Task' and 'Status' all have drop down menus.
'Task' column allows you to pick multiple tasks and then have a status for each.
I tried using formulas and a VBA code but none are working (my first try at code)
Any help would be greatly appreciated!

A: Whenever there is a situation where "... each xxx has its own sheet ..." combined with the challenge to report across all sheet, the objective is to generate ONE data source from the many sheets.
Doing this with VBA is possible, but not an easy job, especially not for beginners.
Doing this with Power Query (Get & Transform) will be a lot easier. There are lots of free online tutorials and resources for Power Query and how to consolidate data from multiple Excel worksheets into one query.
Start by looking into that. It's bigger than what fits into an answer here, but that's what you'll need to do.


text:
Q: HTTPS Request in Mapreduce I'm trying to make an HTTPS request from the Mapper class of my job. I'm using Java's HttpsURLConnection library, which requires me to set the following properties:
javax.net.ssl.keyStore
javax.net.ssl.keyStorePassword
There's no problem setting these properties in a Java application, but in MapReduce I'm having trouble setting these properties at the mapper level. I can't figure out how to "reach outside" of Hadoop and set these properties for every mapper.

A: It is not a good approach to create request from MapReduce. The intuition is: you use MapReduce to be able to scale your computation. You havent provided more info about what you are doing, so lets think about what happens when you would scale (orders of magnitude) the task.

*

*If your goal is to connect to one place, you are effectively (D)DoSing it. The server on the other end would not probably scale up as well as your MapReduce (cluster).

*If you are crawling many targets, consider using some crawling distributed framework (find some on Google).

A: Solution wasn't related to anything with the application code, but rather cluster configuration. The keystore file needed to be placed in the same location on each data node. Not exactly endorsing this as the safest solution in terms of security, but it worked for a quick POC.


text:
Q: ValueError: No gradients provided for any variable I'm facing a trouble with tensorFlow. Executing the following code
import tensorflow as tf
import input_data

learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# tensorflow graph input
X = tf.placeholder('float', [None, 784]) # mnist data image of shape 28 * 28 = 784
Y = tf.placeholder('float', [None, 10]) # 0-9 digits recognition = > 10 classes

# set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

# Our hypothesis
activation = tf.add(tf.matmul(X, W),b)  # Softmax

# Cost function: cross entropy
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=activation, logits=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)  # Gradient Descen

I get the following error:

ValueError: No gradients provided for any variable, check your graph
  for ops that do not support gradients, between variables
  ['Tensor("Variable/read:0", shape=(784, 10), dtype=float32)',
  'Tensor("Variable_1/read:0", shape=(10,), dtype=float32)'] and loss
  Tensor("Mean:0", shape=(), dtype=float32).

A: This problem is caused by the following line: tf.nn.softmax_cross_entropy_with_logits(labels=activation, logits=Y)
Based on documentation you should have

labels: Each row labels[i] must be a valid probability distribution.
logits: Unscaled log probabilities.

So logits suppose to be your hypothesis and thus equal to activation and valid probability distribution is Y. So just change it with tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=activation)

A: I ended up here because I had passed my input X data to my model, but not my expected outputs. I had:
model.fit(X, epochs=30)      # whoops!

I should have had:
model.fit(X, y, epochs=30)   # fixed!

A: In my case I've forgotten to add the compile layer to the model
model.compile(optimizer='adam',  loss = 'categorical_crossentropy', metrics = ['accuracy'] )


text:
Q: How to rename package name When I create a package long_term_streaming_monitor by paster
What should I do if I want to change long_term_streaming_monitor to long_term_monitor
What files should I change and how ?
Thanks
setup.py
from setuptools import setup, find_packages
import sys, os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()

version = '0.3'

install_requires = [
    # List your project dependencies here.
    # For more details, see:
    # http://packages.python.org/distribute/setuptools.html#declaring-dependencies
]

setup(name='long_term_streaming_monitor/',
    version=version,
    description="",
    long_description=README + '\n\n' + NEWS,
    classifiers=[
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    ],
    keywords='',
    url='',
    license='',
    packages=find_packages('src'),
    package_dir = {'': 'src'},include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    entry_points={
        'console_scripts':
            ['long_term_streaming_monitor/=long_term_streaming_monitor:main']
    }
)

Package tree view
├── [Mar 21 16:03]  HACKING.txt
├── [Mar 21 16:03]  MANIFEST.in
├── [Mar 21 16:03]  NEWS.txt
├── [Mar 21 16:03]  README.rst
├── [Mar 21 16:03]  bootstrap.py
├── [Mar 21 16:03]  buildout.cfg
├── [Mar 27 18:07]  docs
│   ├── [Mar 25 11:56]  Makefile
│   ├── [Mar 25 11:58]  _build
│   ├── [Mar 25 11:56]  _static
│   ├── [Mar 25 11:56]  _templates
│   ├── [Mar 25 11:56]  conf.py
│   ├── [Mar 25 11:55]  html
│   ├── [Mar 25 11:55]  index.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.tests.rst
│   ├── [Mar 25 11:56]  make.bat
│   ├── [Mar 25 11:55]  modules.rst
│   └── [Mar 25 11:58]  y.rst
├── [Mar 27 18:13]  setup.py
└── [Mar 27 18:13]  src
    ├── [Mar 27 18:13]  long_term_streaming_monitor
    └── [Mar  6 18:00]  long_term_streaming_monitor_.egg-info

A: rename long_term_streaming_monitor to long_term_monitor in setup.py
setup(name='long_term_streaming_monitor/', ..)
to
setup(name='long_term_monitor', ..)


text:
Q: Передача массива в функцию Осваиваю с/с++ для работы с CUDA, застрял в массивах.
Собственно как передать массив в функцию?
есть код
 void print(int ** m);

int main()
{
    int b[5][5] ={{ 1,2,3, 4,5},{ 1,2,3, 4,5},{ 1,2,3, 4,5},{ 1,2,3, 4,5},{ 1,2,3, 4,5}};

    print((int **)b);
    return 0;
}
void print(int **m){

    for(int i=0; i<SIZE; i++){
        for(int j =0; j<SIZE; j++){
            printf(" %d", m[i][j]);
        }
        printf("\n");
    }
}

Компилируется но вылетает постоянно при прпытке доступа к m[i][j]. В чем проблема?
A: Во-первых, прекрасный ответ @mikillskegg.
Во-вторых, вот вам концептуально чистое решение: если вы уж пишете на C++, пользуйтесь идиомами C++, они покажутся вам более интуитивными. В частности, вместо нативных массивов используйте std::vector. Ваш код будет выглядеть так:
#include <iostream>
#include <vector>

using namespace std;

void print(const vector< vector<int> >& v)
{
    for (auto it = v.begin(); it != v.end(); ++it)
    {
        for (auto it2 = it->begin(); it2 != it->end(); ++it2)
            cout << *it2;
        cout << endl;
    }
}

int main()
{
    vector< vector<int> > b(5);
    for (auto it = b.begin(); it != b.end(); ++it)
        *it = { 1, 2, 3, 4, 5 };
    print(b);
    return 0;
}

В-третьих, проведём разбор ошибок. Давайте я объясню, что пошло не так. int** -- это указатель на массив указателей, верно? А вот int[5][5] -- это вовсе не массив указателей! Это непрерывный кусок памяти, к которому компилятор знает, как доступаться по индексу, потому что он знает размер каждой строки вашей таблицы. Поэтому-то print(b); у вас не откомпилировалось, типы ведь разные, расположение элементов в памяти не совместимо! Когда вы жёстким кастом преобразуете его в int**, у вас указатель на первый элемент таблицы интерпретируется как указатель на список указателей, разумеется, это не сработает. Запомните: если вам нужен cast, возможно, что-то идёт не так.
В-четвёртых, если вы всё же остаётесь с нативными массивами, вот вам вариация ответа @mikillskegg ближе к стилю C++ (идея с темплейтом позаимствована на SO):
template <int LINESIZE>
void print (int m[][LINESIZE]) {
    for(int i=0; i<LINESIZE; i++){
        for(int j =0; j<LINESIZE; j++){
            printf(" %d", m[i][j]);
        }
        printf("\n");
    }
}

В-пятых, вот вам ещё один вариант, который, возможно, лучше. Чтобы расположение элементов в памяти было совместимо с двойным указателем, вы могли бы строки таблицы вручную:
const int SIZE = 5;

void print(int** m)
{
    for(int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
            printf(" %d", m[i][j]);
        printf("\n");
    }
}

// ...
int** b = new int*[SIZE];
for(int i = 0; i < SIZE; i++)
{
    b[i] = new int[SIZE];
    for (int j = 0; j < size; j++)
        b[i][j] = j;
}
print(b);

A: Вопрос о передаче многомерных массивов в функцию уже много раз здесь обсуждался.
Передавать можно двумя способами: передавая либо переменную типа многомерного массива, либо простой указатель.
Способ 1.
void print  (int m[][5]) {
    for(int i=0; i<SIZE; i++){
        for(int j =0; j<SIZE; j++){
            printf(" %d", m[i][j]);
        }
        printf("\n");
    }
}
.....
print (b);

Способ 2
const int SIZE = 5; //Именно 5 !!!
void print (int* m) {
    for(int i=0; i<SIZE; i++){
        for(int j =0; j<SIZE; j++){
            printf(" %d", m + SIZE*i + j);
        }
        printf("\n");
    }
}

.....
print ((int*) b);

И указатель на указатель тут не при чем.
Если будет что непонятно, спрашивайте.
И еще: для работы в CUDA очень хорошо проработайте темы указателей и адресации членов многомерных массивов.


text:
Q: How to Disable previous dates of picked "startdate " for "enddate" in php codeigniter Here I have two inputs "startdate" and "enddate", I need to disable previous dates of current date for "startdate" and disable the previous of any chosen "startdate" for "enddate", I am using below jquery but im getting an error Uncaught TypeError: $(...).datepicker is not a function , would appreciate if anyone can help me out here.
Here is the view

    Start Date
    <input type="date" class="form-control" id='Sdate' name='Sdate'   min="<?php echo date('Y-m-d'); ?>"  value="<?php echo set_value('Sdate'); ?>">

<?php echo form_error('Sdate'); ?>

    End Date
    <input type="date" class="form-control" id='Edate' name='Edate' value="<?php echo set_value('Edate'); ?>">

<?php echo form_error('Edate'); ?>

Here is the script

A: input type date does not need the jquery function .datepicker and if you want to use that, you need jquery-ui to load. Well you dont actually need the .datepicker function if you will use the input type date. here is my working code.
https://jsfiddle.net/m3doh5x4/3/

$(document).ready(function(){

    var today = new Date();
    var sdate = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+(today.getDate() < 10 ? '0'+today.getDate() : today.getDate());
    $('#Sdate').prop('min', sdate);

    $('#Sdate').on('change', function(){
    $('#Edate').prop('min', $(this).val() );
  });

});

  Start Date
  <input type="date" class="form-control" id='Sdate' name='Sdate'   min=''  value="">

<?php echo form_error('Sdate'); ?>

  End Date
  <input type="date" class="form-control" id='Edate' name='Edate' value="<?php echo set_value('Edate'); ?>">

<?php echo form_error('Edate'); ?>


text:
Q: How To Remove Link From Browsers' "View Page Source" feature? I have made a simple password protected webpage that provides the link to another webpage when we enter the correct password but we can easily have the webadrress of other page by browsers "View Page Source" feature.So how we can overcome this?

A: The problem is that you are keeping your secret data on the client and client can easily reach it. So, the only posible way for you is to keep them on the server. But, as far as I understand you need help with server part. So here is small instruction with links to the documentation.
You will need:

*

*Some backend that will take data from your users and returns some responce. I would suggest you to have a look into Node.Js as a platform with Express as a server. Benefit from this setup is that Node.Js uses JavaScript so you have not to learn additional language, and Express is a very simple server to use. Of course, if you want to learn some other languages - you can take C# with ASP.NET MVC framework, PHP or any other nice language.

*Some page with form for user's credentials that will post data to your backend. Basic form behavior can be found here

*And some code on server that will validate credentials from form and return new page with or without your secret.
That's it. May be it sound a bit scary but there are lots of guides and information your can google.
Hope this helps. Happy coding!

Btw, if you are lloking for the some ready code, I have Node.JS client/server example with TypeScript (JavaScript with type validation) here. All you need is git, hope you already have it, and Node.Js
Then just execute this commands on your console (bash, cmd, etc)

git clone https://github.com/Drag13/typescript-browserify-template

This will download code from remote server to your local machine

npm install

Installs project dependencies - like express server

npm run server

Starts the server

cd..
  npm run client

Starts the client
Maybe you will find this helpfull.


text:
Q: Thunderbird Lightning caldav sync doesn't show any data/events when i try to synchronize my caldav server implementation with Thunderbird 45.4.0 and Lightning 4.7.4 (one particular calendar collection) it doesnt show any data or events in the calendar though the last call of the sequence provided the data.
In the Thunderbird error log i can see one error:
Zeitstempel: 07.11.16, 14:21:12
Fehler: [calCachedCalendar] replay action failed: null,
uri=http://127.0.0.1:8003/sap/sports/webdav/appsvc/webdav/services/
server.xsjs/cal/_D043133/, result=2147500037, op=[xpconnect wrapped
calIOperation]
Quelldatei:
file:///Users/d043133/Library/Thunderbird/Profiles/hfbvuk9f.default/
extensions/%7Be2fda1a4-762b-4020-b5ad-a41df1933103%7D/calendar-
js/calCachedCalendar.js
Zeile: 327

the call sequence is as follows (detailed content via gist-links):

*

*Propfind Request - Response

*Options Request - Response

*Propfind Request - Response

*Report Request - Response - Response Raw
The synchronization with other clients like macOS-calendar and ios-calendar works in principle and shows the data. Does anyone has a clue what is going wrong here?

A: Not sure whether that is the cause but I can see two incorrect things:
a) Your <href/> property has trailing spaces:
<d:href>/sap/sports/webdav/appsvc/webdav/services/server.xsjs/cal/_D043133/EVENT%3A070768ba5dd78ff15458f1985cdaabb1.ics
</d:href>

b) your ORGANIZER property is not a valid URI
ORGANIZER:_D043133

A: i was able to find the cause of the above issue by debugging Thunderbird as propsed by Philipp. The Report Response has http status code 200, but as it is a multistatus response Thunderbird/Lightning expects status code 207 ;-)
Thanks for the hints!


text:
Q: Using SimpleDateFormat("MM/dd/yyyy").format in an SQL Query Is it possible to use SimpleDateFormat like so in the following SQL query?
SELECT empnumber WHERE compname = 'mycomp' ORDER BY new SimpleDateFormat("MM/dd/yyyy").format(genfield), emppnumber asc

A friend once told me it was possible, but all I'm getting is an error:
ORA-00933: SQL command not properly ended
I'm using Oracle SQL Developer for this, and will eventually put it in a Java program when / if it succeeds.
Thanks.

A: You can not use Javas SimpleDateFormat in plain SQL.
You can either use it in the Java programm and concatenate the query string with the SimpleDateFormat.format() result or you can just use the Oracle sql function TO_DATE()
Like this:
SELECT empnumber WHERE compname = 'mycomp' ORDER BY TO_DATE(genfield, 'MM/dd/yyyy'), emppnumber asc;


text:
Q: Paragraphs not separating I am working on a blog, and every time I compose an article consisting of more than one paragraphs, it gets cluttered up altogether and it's all in the same paragraph.
Here's the code I wrote in my main page ejs for displaying the article content:
<% pos.forEach(function(post) { %>

<%= post.title %>

<%= post.post.substring(0, 101) + "..." %>
  <a href="/post/<%= post.title %>">Read More

<% }); %>

Here's the code I wrote for my post ejs page:
<%- include('partials/header'); -%>

<%= title %>

<%= content %>

<%- include('partials/footer'); -%>

A: I assume your content consist of line break. You can use
 to render those lines

<%= content %>

https://www.w3schools.com/tags/tag_pre.asp

Text in a  element is displayed in a fixed-width font, and the
text preserves both spaces and line breaks. The text will be displayed
exactly as written in the HTML source code.


text:
Q: Should i dockerize django app as non-root? Should i dockerize Django app as a root user? If yes how can i set up non-root user for Django? Because in node.js app should have USER:node which is a better practice.
Code example from official docker page which does not include non-root:
FROM python:3
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/

A: It's generically a good practice.
At the start of your Dockerfile, before you COPY anything in, create the user.  It doesn't need to have any specific properties and it doesn't need to match any specific host user ID.  The only particular reason to do this early is to avoid repeating it on rebuilds.
At the end of your Dockerfile, after you run all of the build steps, only then switch USER to the new user.  The code and any installed libraries will be owned by the root user; and that's good, because it means the application can't accidentally overwrite the application code.
FROM python:3

# Create the non-root user.  Doing this before any COPY means it won't
# be repeated on rebuild, for marginal savings in space and rebuild time.
# The user can have any name and any uid; it does not need to match any
# particular host system where the image might run.
RUN adduser --system --no-create-home someuser

# Install the application as in the question (still as root).
ENV PYTHONUNBUFFERED=1
WORKDIR /code
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

# Explain how to run the container.  Only switch to the non-root user now.
EXPOSE 8000
USER someuser
CMD ["./main.py"]

Do not try to write files inside the container; instead, use a separate database container for persistence.  Do not pass a host user ID as a build argument.  Do not configure a password for the user or otherwise attempt to set up interactive logins.  Do not create a home directory; it won't be used.


text:
Q: How to increase of MAC address by a defined value? I have a mac address string (without ':' in it) I need to calculate second next address.
I've tryed to:
$macDec = hexdec($mac);
$macDec += 2;
$newMac = dechex($macDec);

but this trims decimal value to integer range and calculated mac is incorrect, can i do this in any simple way than using BC Math etc. ?

A: $mac = increment_mac('00:00:00:00:00:fe', 2);

function increment_mac($mac_address, $increment = 1, $return_partition = ':')
{
    $mac_address = preg_replace('![^0-9a-f]!', '', $mac_address);

    $parts = str_split($mac_address, 2);
    foreach($parts as $i => $hex)
    {
        $parts[$i] = hexdec($hex);
    }

    $increase = true;
    if($increment < 0)
    {
        $increase = false;
    }

    $parts[5] += $increment;
    for($i = 5; $i >= 1; $i--)
    {
        if($increase)
        {
            while($parts[$i] > 255)
            {
                $parts[$i] -= 256;
                $parts[$i - 1] += 1;
            }
        }
        else
        {
            while($parts[$i] < 0)
            {
                $parts[$i] += 256;
                $parts[$i - 1] -= 1;
            }
        }
    }

    foreach($parts as $i => $dec)
    {
        $parts[$i] = str_pad(dechex($dec), 2, 0, STR_PAD_LEFT);
    }

    return implode($return_partition, $parts);
}

A: OK, i found a solution, because of fact that each vendor has to use its own VendorID, and standard that MTA MAC is Modem MAC + 2 i strip vendorID part from mac, do a simple calculation, and prepend vendorID
function mac2mtaMac($mac) {
    $mac = preg_replace('/[^0-9A-Fa-f]/', '', $mac);
    $macVendorID = substr($mac, 0, 6);
    $macDec = hexdec(substr($mac, 5));
    $macDec += 2;
    $macHex = dechex($macDec);
    $mtaMac = $macVendorID.str_repeat('0', 6 - strlen($macHex)).$macHex;
    return $mtaMac;
}

@Paul Norman: thx for few hints on how to do that quickly

A: Don't reinvent the wheel, use the netaddr library.  I wrote this to generate a list of MAC addresses based on a serial number range.
from netaddr import *

# Create a list of serial numbers that need MAC addresses
#
sns=range(40125, 40192)

# Create a MAC address and seed it with the first available MAC address then convert
# that MAC address to an integer for easy math
#
mac = EUI('00-11-22-33-02-D7').value

# Assign a MAC address to every serial number
#
for i in range(len(sns)):
    # Notice that we are creating a MAC address based on an integer
    #
    print "{0},{1}".format(sns[i], str(EUI(mac+i)).replace('-',' '))


text:
Q: Is it possible to bind each TextField created using ForEach method to its own variable? How to bind each TextField created using ForEach method to its own variable in SwiftUI?
    @State var textField1 = ""
    @State var textField2 = ""
    @State var textField3 = ""
    @State var textField4 = ""
    @State var textField5 = ""

    var body: some View {

        VStack{
            ForEach(0..<5) { index in
                TextField("\(index)", text: $textField1)
            }

I'm trying to use item indexes to achieve my goal but don't know how.
I need each TextField to be bound to its own individual variable.

A: Just make your @State an array:
@State var textFields = Array(repeating: "", count: 5)

and bind it to each text field:
VStack {
    ForEach(0..<5) { index in
        TextField("\(index)", text: $textFields[index]) // <-- like this
        .padding(.horizontal, 30)
        .font(.largeTitle)
    // ...


text:
Q: POST Request with JSON on iPhone I have the following code with the following errors and I am not sure what I am doing wrong:
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjectsAndKeys: @"init", @"method", nil];

NSString *requestString = [NSString stringWithFormat:@"json=%@", [jsonDict JSONFragment], nil];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://exampleurl.com/json.php"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];

NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

NSLog(@"Returned Json: %@", returnString);

I get the following error before running Instance Method '-JSONFragment' not found(return type defaults to 'id') which suggests that I have not added all the correct files from SBJSON, but all the files are there.
When I run the application I get the following error message:
-[__NSCFDictionary JSONFragment]: unrecognized selector sent to instance 0x4e99010
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary JSONFragment]: unrecognized selector sent to instance 0x4e99010'

I have no idea what I am doing wrong, any suggestions?

A: My version of SBJson doesn't have a method called JSONFragment.  This is how I turn a dictionary into a Json formatted request string.
// assume dictionary has the values you want to post
SBJsonWriter *writer = [SBJsonWriter new];
NSString * jsonData = [writer stringWithObject:dictionary];
NSString * getString = [NSString stringWithFormat:@"json=%@", jsonData];
[writer release];


text:
Q: Return key in IOS/android + phonegap/cordova framework I am creating an app in IOS/android with phonegap/cordova framework. I have a set of input types like input boxes, picklists, etc. How can I set the return key to work such that it focuses on the next input box when pressed. I have tried to use javascript in phonegap like:
document.getElementByid('nextElement').focus();
on return/enter; But it does'nt seem to be working ie. focus is lost from the current element but the soft keyboard is vanishing and focus is not coming to the next element. Any idea of where am i missing?

A: After some googling, it turns out this is not possible on Mobile Safari (although desktop WebKit works).
You can set focus on next element, but soft keyboard won't appear at all.
Here's the PoC of this: http://www.hakoniemi.net/labs/focusOnNext/


text:
Q: Fast way to pick randomly from a set, with each entry picked only once? I'm working on a program to solve the n queens problem (the problem of putting n chess queens on an n x n chessboard such that none of them is able to capture any other using the standard chess queen's moves).  I am using a heuristic algorithm, and it starts by placing one queen in each row and picking a column randomly out of the columns that are not already occupied.  I feel that this step is an opportunity for optimization.  Here is the code (in C++):
    vector<int> colsleft;

    //fills the vector sequentially with integer values
    for (int c=0; c < size; c++)
        colsleft.push_back(c);

    for (int i=0; i < size; i++)
    {
        vector<int>::iterator randplace = colsleft.begin() + rand()%colsleft.size();

        /* chboard is an integer array, with each entry representing a row
        and holding the column position of the queen in that row */

        chboard[i] = *randplace;
        colsleft.erase(randplace);
    }

If it is not clear from the code:  I start by building a vector containing an integer for each column.  Then, for each row, I pick a random entry in the vector, assign its value to that row's entry in chboard[].  I then remove that entry from the vector so it is not available for any other queens.
I'm curious about methods that could use arrays and pointers instead of a vector.  Or <list>s?  Is there a better way of filling the vector sequentially, other than the for loop?  I would love to hear some suggestions!

A: The following should fulfill your needs:
#include <algorithm>

...

int randplace[size];

for (int i = 0; i < size; i ++)
    randplace[i] = i;

random_shuffle(randplace, randplace + size);

You can do the same stuff with vectors, too, if you wish.
Source: http://gethelp.devx.com/techtips/cpp_pro/10min/10min1299.asp

A: Couple of random answers to some of your questions :):

*

*As far as I know, there's no way to fill an array with consecutive values without iterating over it first. HOWEVER, if you really just need consecutive values, you do not need to fill the array - just use the cell indices as the values: a[0] is 0 and a[100] is 100 - when you get a random number, treat the number as the value.

*You can implement the same with a list<> and remove cells you already hit, or...

*For better performance, rather than removing cells, why not put an "already used" value in them (like -1) and check for that. Say you get a random number like 73, and a[73] contains -1, you just get a new random number.

*Finally, describing item 3 reminded me of a re-hashing function. Perhaps you can implement your algorithm as a hash-table?

A: Your colsleft.erase(randplace); line is really inefficient, because erasing an element in the middle of the vector requires shifting all the ones after it. A more efficient approach that will satisfy your needs in this case is to simply swap the element with the one at index (size - i - 1) (the element whose index will be outside the range in the next iteration, so we "bring" that element into the middle, and swap the used one out).
And then we don't even need to bother deleting that element -- the end of the array will accumulate the "chosen" elements. And now we've basically implemented an in-place Knuth shuffle.


text:
Q: Pure CSS parallaxing I'm trying to place the blue as a parallax background behind the gray and the brown footer.
Currently I have this:

Here

Footer

But as you can see, the order is still reversed and has the footer showing up on top of the parallaxed blue div.
This is the CSS I have:
.parallax-bottom {
    background-color: brown;
    min-height: 500px;

    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    }

A: The issue is that you have not closed the div tag correctly.

A: Close your div tag correctly and it will work perfectly.
And I have a suggestion for you that next time you code use Viewport Units like vw and vh instead of px because it will help you make your webpage/website responsive.


text:
Q: Addclass to inactive jQuery UI Tabs I'm using jQuery UI's tabs widget and its really great and useful although i have one simple question. How can i add a class to all inactive tabs? I have the following code so far and it adds a class to the active tab, Now i want to remove the class from the inactive tabs. How can i achieve this?
$("#sidebar").tabs({
    event: "click",
    activate : function(event, ui) { var activeTab = ui.newTab; $(activeTab).addClass(ActiveTab); },
});

TAB 1

TAB 2

TAB 3

A: As my comment suggested, you can do the opposite... add the class to all tabs by default (or simply style the anchor as is) and remove it from the selected one.
PS: I edited your HTML code with an example from jQuery UI.
Here's a fiddle
$('document').ready(function() {
    $("#sidebar").tabs({
        event: "click",
        activate: function (event, ui) {
            var _tab = ui.newTab;
            $('#sidebar li').removeClass('active');
            $(_tab).addClass('active');
        },
    });
});


text:
Q: created nested list in MVC3 I want to create menu using
 and
 tags. Im working in MVC3 + Razor. And I stored menu in database like this
MenuId     Name      ParentMenuId OrderBy
1      Item1         Null        1
2      Item2         Null        2
3      Item2.1        2          1
4      Item2.1.1      3          1
5      Item2.1.2      3          2

The HTML output should be

Item1
`

Item2
`

Item2.1

Item2.1.1

Item2.1.2

Can anyone please help me how can I generated menu from this. I tried searching on internet, but not able to find something which I can use.
I see this article (Recursion in an ASP.NET MVC view) where one reply is to create HTMLHelperExtension.
But not able to find out in my case how to use.

A: you can try something like this :
@helper CreateCategory(int? nid)
{
        var childs = context.Categories.Where(c=>c.parentid == nid).OrderBy(C => C.order);
        int childsCount = childs.Count();
        if (childsCount == 0)
              return;

             @foreach (Category child in childs)
             {

                    @child.Title
                    CreateCategory(child.Id);

             }

}

you most call this helper so :
CreateCategory(null);

hope this could help.

A: You should use DisplayTemplate
Here is an example:

@if (Model.Items != null)
{

        foreach (var item in Model.Items)
        {
            @Html.DisplayFor(m => item)
        }

}

    @Model.Name

@if (Model.Items != null) {

    foreach (var item in Model.Items)
    {
        @Html.DisplayFor(m => item)
    }

}

So you will recurcively call DisplayTemplate from DisplayTemplate to render nested Items


text:
Q: nan values in loss in keras model I have following data shapes
X_Train.shape,Y_Train.shape
Out[52]: ((983, 19900), (983,))
X_Test.shape,Y_Test.shape
Out[53]: ((52, 19900), (52,))

I am running a simple binary classifier as Y_train and Y_test could be either 1 or 2
import  keras
import  tensorflow as tf
from keras import  layers
from keras.layers import Input, Dense
from keras.models import Model,Sequential
import numpy as np
from  keras.optimizers import  Adam

myModel = keras.Sequential([
    keras.layers.Dense(1000,activation=tf.nn.relu,input_shape=(19900,)),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(32, activation=tf.nn.relu),
    keras.layers.Dense(1, activation=tf.nn.softmax)
])

myModel.compile(optimizer='adam', loss='sparse_categorical_crossentropy',metrics=['accuracy'])
myModel.fit(X_Train, Y_Train, epochs=100,batch_size=1000)
test_loss,test_acc=myModel.evaluate(X_Test,Y_Test)

Output of the Code
Training Loss and Accuracy
Epoch 1/100
983/983 [==============================] - 1s 1ms/step - loss: nan - acc: 0.4608
Epoch 2/100
983/983 [==============================] - 0s 206us/step - loss: nan - acc: 0.4873
Epoch 3/100
983/983 [==============================] - 0s 200us/step - loss: nan - acc: 0.4883
Epoch 4/100
983/983 [==============================] - 0s 197us/step - loss: nan - acc: 0.4883
Epoch 5/100
983/983 [==============================] - 0s 194us/step - loss: nan - acc: 0.4873
Epoch 6/100
983/983 [==============================] - 0s 202us/step - loss: nan - acc: 0.4863
Epoch 7/100
983/983 [==============================] - 0s 198us/step - loss: nan - acc: 0.4863
Epoch 8/100
983/983 [==============================] - 0s 194us/step - loss: nan - acc: 0.4883
Epoch 9/100
983/983 [==============================] - 0s 196us/step - loss: nan - acc: 0.4873
Epoch 10/100
983/983 [==============================] - 0s 198us/step - loss: nan - acc: 0.4873
Epoch 11/100
983/983 [==============================] - 0s 200us/step - loss: nan - acc: 0.4893
Epoch 12/100
983/983 [==============================] - 0s 198us/step - loss: nan - acc: 0.4873
Epoch 13/100
983/983 [==============================] - 0s 194us/step - loss: nan - acc: 0.4873
Epoch 14/100
983/983 [==============================] - 0s 197us/step - loss: nan - acc: 0.4883
Epoch 97/100
    983/983 [==============================] - 0s 196us/step - loss: nan - acc: 0.4893
Epoch 98/100
    983/983 [==============================] - 0s 199us/step - loss: nan - acc: 0.4883
Epoch 99/100
    983/983 [==============================] - 0s 193us/step - loss: nan - acc: 0.4883
Epoch 100/100
    983/983 [==============================] - 0s 196us/step - loss: nan - acc: 0.4863

Testing Loss and Accuracy
test_loss,test_acc
Out[58]: (nan, 0.4615384661234342)

I also checked if there is any nan value in my data
np.isnan(X_Train).any()
Out[5]: False
np.isnan(Y_Train).any()
Out[6]: False
np.isnan(X_Test).any()
Out[7]: False
np.isnan(Y_Test).any()
Out[8]: False

My Question is why my training accuracy is not improving and why loss is nan also why without one-hot encoding the softmax in the output is working fine?
Note1: I apologize that my data is big so I cannot share it here but if there are some way to share it here then I am ready to do that.
Note2 There are lot of zero values in my training data

A: If you are getting NaN values in loss, it means that input is outside of the function domain. There are multiple reasons why this could occur. Here are few steps to track down the cause,
1) If an input is outside of the function domain, then determine what those inputs are. Track the progression of input values to your cost function.
2) Check if there are any null or nan values in input data set. Can be accomplished by
DataFrame.isnull().any()

3) Change the scaling of input data. Normalizing the data between 0 and 1 the start the training.
4) Change method of weight initialization.
It's difficult to point to the exact solution with Deep Neural Networks. So try the above methods and it should give you a fair idea on what is going wrong.

A: Sometimes with Keras the combination of Relu and Softmax causes numerical troubles as Relu can produce large positive values corresponding to very small probabilities.
Try to use tanh instead of Relu

A: Softmax activation is not the right choice here. You have only one neuron on the output layer.
Let's consider how softmax function is defined.(Image from wikepedia.org)
.
Since there is only one neuron on the last layer,   will be 1 for all values of .
Since you are using sparse_categorical_crossentropy, keras(or tensorflow) can infer the number of the classes from the shape of the logits. In keras(or tensorflow) the shape of logits is assumed to be [BATCH_SIZE, NUM_CLASSES]. The shape your logits is [None, 1], so keras assumes that the number of your classes is 1, but your are feeding more than one classes( 0 or 1) and that is causing the error.
The right activation function here is sigmoid(tanh also could work by altering the dataset target to be either -1 or 1). The loss should be binary_crossentropy.
myModel = keras.Sequential([
    keras.layers.Dense(1000,activation=tf.nn.relu,input_shape=(19900,)),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(32, activation=tf.nn.relu),
    keras.layers.Dense(1, activation="sigmoid")
])

myModel.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])


text:
Q: Express Js infinitely endpoint called I have a backend route at mainScript in expressJS. I spawn a process from it. It takes some time to run the script. But after some time the express server calls the end point again on it's own and keeps doing that infinitely.
app.get('/mainScript',function(req,res){
        console.log("mainScript API End Point Reached")
        const runScript = spawn('python3',['./demo.py'])
        let error_message = ""
        let stdout_message = ""
        runScript.stdout.on('data', function(data){
                console.log(`stdout:${data}`)
                stdout_message += data
        })
        runScript.stderr.on('data',function(data){
                console.log(`stderr:${data}`)
                error_message += data
        })
        runScript.on('close',function(code){
                console.log(`Child process exited with code : ${code}`)
                if(code == 0){
                        console.log("HI ERROR CODE = 0")
                        res.status(200)
                        res.send(JSON.stringify({"stdout_logs":stdout_message,
                                "Message" : 'Main Script Ran successfully'
                }))
                }else{
                        res.status(400)
                        res.send(JSON.stringify({"stderr_logs":error_message,
                                "Message" : "There was error on running the main script"
                }))
                }
        })
})

What can be the reason for this ??


text:
Q: ASP Checkbox trigger an event in Javascript whenever it is clicked <asp:CheckBox runat="server" ID="checkbox1" />

Whenever I check or uncheck my asp checkbox, it needs to trigger an event in javascript but it seems like the .click function is not triggered. Is the .click event wrong?
$(document).ready(function () {
    $("#checkbox1").click(function (e) {
        if (this.checked) {
            //do something
        }
        else {

        }
    });
});

A: You probably need to change
$("#checkbox1").click(function (e) {

into
$("#<%= checkbox1.ClientID %>").click(function (e) {

asp.net renamed the ID's of Controls to ensure there are no duplicates. If you check the HTML source the could look something like this: ContentPlaceHolder1_checkbox1. That is why jQuery cannot find it.

A: I hope it will work for you.
For dynamically created element you have to use event delegation, if you want to select by an attribute you can use an attribute equals selector.
$(document).on("change", "input[name='member']", function () {
              alert("CheckBox Changed.");
              if (this.checked) {alert("CheckBox checked.");}
              else{alert("CheckBox not checked.");}
          });

OR
$(document).on("change", "$('#<%=checkbox1.ClientID%>')", function () {
              alert("CheckBox Changed.");
              if (this.checked) {alert("CheckBox checked.");}
              else{alert("CheckBox not checked.");}
          });

Here is the link , and go through this link
JS Fiddler


text:
Q: Material emissivity coefficient If I have a coated material (e.g. oxidized steel painted with white paint) which emissivity coefficient do I use ? The one of the paint (0.3-0.5) or the one of the base material (0.8) ? Many collegues go and paint a spot with a black marker and then use ε=1. Is this correct ?

A: Heat passes between the steel and the paint by conduction, which is typically much faster than radiation. The limiting factor is the radiation at the object:air interface i.e. you need the emissivity of the surface at the object:air interface.
So the emissivity you need is the emissivity of the paint.
This also explains why your colleagues are correct to use a high emissivity once they've painted the steel black.


text:
Q: Want a dedicated button AjaxFileManager for TinyMCE I want to add a button in tinyMCE Editor which will open up the AjaxFileBrowser and selecting a file and clicking select Button will return the file path in the editor, as it does in the image/media url field of insert image/media windows.
Actually, I need a way out to add a direct way to access the AjaxFileManager.
setup : function(ed) {
    ed.addButton('MyButton', {
        title : 'MyButton',
        image : './images/copy.jpg',
        onclick : function() {
        ajaxfilemanager('','','file',window); // The first arguement is return field as I know but how to use it??
            ed.focus();
            ed.selection.setContent('<tittle>' + ed.selection.getContent() + '</tittle>');
        }
    });
}

Is there any great documentation for this. Please Suggest Me!!


text:
Q: Column is read differently by pyspark and pandas I have a dataframe exactly like below, read by pandas correctly:
The code I am using is very simple:
import pandas as pd
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
hede = spark.read.parquet(r"C:/users/batuhan.engin/desktop/date=2021-04-01")
he = pd.read_parquet(path=r"C:/users/batuhan.engin/desktop/date=2021-04-01", engine='pyarrow')

The error is, pyspark reads the sales_revenue column incorrectly and I couldn't understand why.
he[he.product_id == 2461]:
    sales_type sales_channel  sales_quantity  sales_revenue  tax_amount currency  product_id  store_id
27     Regular     Wholesale             6.0     818.500000         NaN     None        2461       300
110    Regular     Wholesale             2.0     272.829987         NaN     None        2461        42
132    Regular     Wholesale            18.0    2475.540039         NaN     None        2461       314

But when I read it by Pyspark, sales_revenue column is not correct. Actually, I can't even think how pyspark come up with these values in sales_revenue column:
hede.filter("product_id == 2461").show()
+----------+-------------+--------------+-------------+----------+--------+----------+--------+
|sales_type|sales_channel|sales_quantity|sales_revenue|tax_amount|currency|product_id|store_id|
+----------+-------------+--------------+-------------+----------+--------+----------+--------+
|   Regular|    Wholesale|           6.0|   -186969.84|      null|    null|      2461|     300|
|   Regular|    Wholesale|           2.0|       -444.8|      null|    null|      2461|      42|
|   Regular|    Wholesale|          18.0|      6553.92|      null|    null|      2461|     314|
+----------+-------------+--------------+-------------+----------+--------+----------+--------+

Any idea? Might be versions or packages?


text:
Q: Как правильно перевести секунды в формат HH:mm:ss? Получаю продолжительность видео с ВК в секундах. Никак не могу перевести их в формат HH:mm:ss
Вот мой метод
public String secToStr(int duration){
    SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss");
    String time = df.format(new Date(duration));
    return time;
}

Любой duration переводится в 3 часа. Что я делаю не так? Как можно это сделать двумя-тремя строчками?

A: Разобрался. Вот так надо
public String secToStr(int duration){
    return String.format("%02d:%02d:%02d", duration / 3600, duration / 60 % 60, duration % 60);
}

A: Конструктор java.util.Date(long) принимает миллисекунды.
Источник
public static String secToStr(int duration){
    SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss");
    String time = df.format(new Date(duration*1000)); // Миллисекунды
    return time;
}


text:
Q: Is there any way to ensure all CheckpointListeners notified about checkpoint completion on Flink on job cancel with savepoint? I'm using flink 1.9 and the REST API /jobs/:jobid/savepoints to trigger the savepoint and cancel job (stop the job gracefully to run later on from savepoint).
I use a two-phase commit in source function so my source implements both CheckpointedFunction and CheckpointListener interfaces. On snapshotState() method call I snapshot the internal state and on notifyCheckpointComplete() I checkpoint state to 3rd party system.
From what I can see from source code, only the snapshotState() part is synchronous in CheckpointCoordinator -
// send the messages to the tasks that trigger their checkpoint
                for (Execution execution: executions) {
                    if (props.isSynchronous()) {
                        execution.triggerSynchronousSavepoint(checkpointID, timestamp, checkpointOptions, advanceToEndOfTime);
                    } else {
                        execution.triggerCheckpoint(checkpointID, timestamp, checkpointOptions);
                    }
                }

The checkpoint acknowledge and completion notification is asynchronous in AsyncCheckpointRunnable.
That being said, when the savepoint with cancel-job set to true is triggered, after the snapshot is taken, some of the Task Managers keep up to receive completion notification before the job cancelling and execute notifyCheckpointComplete(), and some not.
The question is whether there is a way to cancel job with savepoint so that the notifyCheckpointComplete() is guaranteed to be invoked by all Task Managers before job cancelled or there is no way to achieve this at the moment ?

A: It's been a while since I looked at Flink 1.9 so please take my answer with some caution.
My guess is that your sources cancel too early. So notifyCheckpointComplete is actually sent to all tasks, but some SourceFunctions already quit the run and the respective task is cleaned up.
Afaik, what you described should be possible if you ignore cancellation and interruptions until you have received the last notifyCheckpointComplete.
class YourSource implements SourceFunction<Object>, CheckpointListener, CheckpointedFunction {
    private volatile boolean canceled = false;
    private volatile boolean pendingCheckpoint = false;

    @Override
    public void snapshotState(FunctionSnapshotContext context) throws Exception {
        pendingCheckpoint = true;
        // start two-phase commit
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {

    }

    @Override
    public void notifyCheckpointComplete(long checkpointId) throws Exception {
        // finish two-phase commit
        pendingCheckpoint = false;
    }

    @Override
    public void run(SourceContext<Object> ctx) throws Exception {
        while (!canceled) {
            // do normal source stuff
        }
        // keep the task running after cancellation
        while (pendingCheckpoint) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // ignore interruptions until two-phase commit is done
            }
        }
    }

    @Override
    public void cancel() {
        canceled = true;
    }
}

A: Wouldn't using stop-with-savepoint[1][2] solve the problem?
[1]https://ci.apache.org/projects/flink/flink-docs-stable/monitoring/rest_api.html#jobs-jobid-stop
[2]https://ci.apache.org/projects/flink/flink-docs-stable/ops/cli.html


text:
Q: Не работает HttpSessionListener Данный вопрос уже подымался тут, тут и тут, но четкого ответа я там так и не увидел.
Проблема: слушатель ShoppingCartManager не работает.
public class ShoppingCartManager implements HttpSessionListener {
    private static final Logger logger = Logger.getLogger(ShoppingCartManager.class.getName());

    @Override public void sessionCreated(HttpSessionEvent event) {
        ShoppingCart shoppingCart = new ShoppingCart();
        event.getSession().setAttribute("shoppingCart", shoppingCart);
        logger.log(Level.INFO, "Shopping Cart was added to the session");
    }

    @Override public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        ((ShoppingCart) session.getAttribute("shoppingCart")).clear();
        session.removeAttribute("shoppingCart");
        logger.log(Level.INFO, "Shopping Cart was removed from the session");
    }
}

web.xml
<listener>
    <listener-class>my.package.listeners.ShoppingCartManager</listener-class>
</listener>

Update: Полный web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <display-name>Book Store</display-name>
    <description></description>

    <!--<resource-ref>
        <res-ref-name>jdbc/BookStoreDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>-->

    <resource-env-ref>
        <resource-env-ref-name>jdbc/BookStoreDB</resource-env-ref-name>
        <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
    </resource-env-ref>

    <context-param>
        <param-name>DEVELOPER</param-name>
        <param-value>Name Surname</param-value>
    </context-param>
    <context-param>
        <param-name>DATABASE_NAME</param-name>
        <param-value>jdbc/BookStoreDB</param-value>
    </context-param>
    <context-param>
        <param-name>LOGGER_NAME</param-name>
        <param-value>BookStoreLogger</param-value>
    </context-param>
    <context-param>
        <param-name>populate</param-name>
        <param-value>false</param-value>
    </context-param>

    <listener>
        <listener-class>my.package.listeners.DatabaseProducer</listener-class>
    </listener>
    <listener>
        <listener-class>my.package.listeners.LoggerProducer</listener-class>
    </listener>
    <listener>
        <listener-class>my.package.listeners.DatabasePopulator</listener-class>
    </listener>
    <listener>
        <listener-class>my.package.listeners.ShoppingCartManager</listener-class>
    </listener>

    <filter>
        <filter-name>LoginFilter</filter-name>
        <filter-class>my.package.filters.LoginFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>my.package.servlets.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>RegistrServlet</servlet-name>
        <servlet-class>my.package.servlets.RegistrServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>PreHomeServlet</servlet-name>
        <servlet-class>my.package.servlets.PreHomeServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>PreBookInfoServlet</servlet-name>
        <servlet-class>my.package.servlets.PreBookInfoServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>PreBooksServlet</servlet-name>
        <servlet-class>my.package.servlets.PreBooksServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>PreAccountServlet</servlet-name>
        <servlet-class>my.package.servlets.PreAccountServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>SearchServlet</servlet-name>
        <servlet-class>my.package.servlets.SearchServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>PreHomeServlet</servlet-name>
        <jsp-file>/home.jsp</jsp-file>
    </servlet>
    <servlet>
        <servlet-name>PreAboutServlet</servlet-name>
        <jsp-file>/about.jsp</jsp-file>
    </servlet>
    <servlet>
        <servlet-name>ShoppingCartManager</servlet-name>
        <servlet-class>my.package.servlets.ShoppingCartManager</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>RegistrServlet</servlet-name>
        <url-pattern>/registr</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PreBookInfoServlet</servlet-name>
        <url-pattern>/book</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PreBooksServlet</servlet-name>
        <url-pattern>/books</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PreAccountServlet</servlet-name>
        <url-pattern>/acc</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SearchServlet</servlet-name>
        <url-pattern>/search</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PreHomeServlet</servlet-name>
        <url-pattern>/home</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PreAboutServlet</servlet-name>
        <url-pattern>/about</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ShoppingCartManager</servlet-name>
        <url-pattern>/to-shopping-cart</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>home.html</welcome-file>
    </welcome-file-list>
</web-app>


text:
Q: Python try / except keep trying until no errors I have the following code that occasionally crashes due to a permissions bug.  I am trying to wrap it up in a try / except statement that will keep trying to launch the driver until successful...
def init_driver():
    ffprofile = webdriver.FirefoxProfile("my_profile")
    ffprofile.add_extension(extension="myaddon.xpi")
    return driver

driver = init_driver()

I have seen examples letting me print a message if an error occurs but how do I get it to keep retrying?  Does anybody have an example they can point me at?

A: Here's one way to do it if you don't want to use a loop. Just recall the function on the exception
 import sys

 def init_driver(tries=0):

     try:
         ffprofile = webdriver.FirefoxProfile("my_profile");
         ffprofile.add_extension(extension="myaddon.xpi")
         return driver

     except Exception: #This should be the exception you expect and not a catch all
         if tries < sys.getrecursionlimit(): #By default 1,000 can be bumped up by setrecursionlimit
             return init_driver(tries+1)
         #just for kicks
         #else:
             #sys.setrecursionlimit(sys.getrecursionlimit() + 1)
             #print("Yes we'll win this game the old-fashioned way, the tried and true way:")
             #print("We'll cheat!")
             #refactor / prettify if's to call init_driver if you want to cheat.
         else:
             print("OH NO RECURSION LIMIT HIT!!!!!! (ノಠ益ಠ)ノ彡┻━┻")

 driver = init_driver()

A: Other answers are fine but they will keep retrying until it hits the recursion depth limit. Consider adding a retry limit:
def init_driver(retry_limit=10, nretry=0):
    if nretry >= retry_limit:
       return # retry limit reached, maybe raise an exception?
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except SomeException:
        return init_driver(nretry=nretry+1)
    return ffprofile

driver = init_driver()

A: Here is a recursive solution (with keeping track of the retries):
def init_driver(retries=0):
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
    except:
        print('attempt nr. ' + str(retries))
        return init_driver(retries+1)
    return driver

A: Do like this:
def init_driver():
    driver = None
    ffprofile = webdriver.FirefoxProfile("my_profile");
    ffprofile.add_extension(extension="myaddon.xpi")
    # do something with a valid profile and set driver to something other than None
    return driver

driver = None
while driver is None:
    driver = init_driver()

A: Here's a loop that iterates over attempts:
while True:
    try:
        driver = init_driver()
        break
    except Foo:
        continue

Note that this is not a bare except clause.  Bare excepts are dangerous because they can capture things like NameError that are so rarely meant to be caught.  You should put the specific exception you expect to catch here.

A: Just a small change required.  Where Foo is the specific exception you get with the permissions bug.
def init_driver():
    try:
        ffprofile = webdriver.FirefoxProfile("my_profile");
        ffprofile.add_extension(extension="myaddon.xpi")
        return driver
    except Foo:
        return init_driver()

driver = init_driver()


text:
Q: Select info from row to another row I have this select on a view:
SELECT
    T1.ID AS [ID],
    T1.A AS [A],
    T1.B AS [B],
    T4.C AS [C],
    ISNULL(NULLIF(T3.D, ''), T2.D) AS [D],
    T1.E AS [E],
    T1.F AS [F],
    T1.G AS [G]
FROM T1
INNER JOIN T2 ON T2.X = T1.X
INNER JOIN T3 ON T3.Y = T2.Y
RIGHT JOIN T4 ON T4.Z = T3.Z

And get this:
║  ID  ║  A   ║  B   ║  C   ║  D   ║  E   ║  F   ║  G   ║
╠══════╬══════╬══════╬══════╬══════╬══════╬══════╬══════╬
║ 1    ║ 3    ║ 4    ║ 1000 ║ X    ║ 1    ║ 1    ║ 1    ║
║ 1    ║ 3    ║ 4    ║ 2000 ║ Y    ║ 1    ║ 1    ║ 1    ║
║ NULL ║ NULL ║ NULL ║ 3000 ║ NULL ║ NULL ║ NULL ║ NULL ║

And I want that the last row be like this:
║ 1 ║ 3 ║ 4 ║ 3000 ║ Z ║ 1 ║ 1 ║ 1 ║

That is, the values of all columns equal to the other rows, except column 'C' and column 'D'. The value of column D is obtained from T2.D
How can I do? Thanks.

A: Without any sample data to use I would suggest lag() may be of use in this exact scenario, such as
select
    IsNull(T1.ID, Lag(T1.ID) over(order by T4.C)) as [ID],
    IsNull(T1.A, Lag(T1.A) over(order by T4.C))) as [A],
    IsNull(T1.B, Lag(T1.B) over(order by T4.C))) as [B],
    T4.C as [C],
    IsNull(NullIf(T3.D, ''), T2.D) as [D],
    IsNull(T1.E, Lag(T1.E) over(order by T4.C))) as [E],
    IsNull(T1.F, Lag(T1.F) over(order by T4.C))) as [F],
    IsNull(T1.G, Lag(T1.G) over(order by T4.C))) as [G],
from T1
inner join T2 on T2.X = T1.X
inner join T3 on T3.Y = T2.Y
right join T4 on T4.Z = T3.Z


text:
Q: Using Spring Integration FTP to connect a FTP Server(vsftpd on ubuntu) that without config "require_ssl_reuse=NO" As the title, if I config "require_ssl_reuse=NO" for vsftpd, the following configuration works well.
Is that possible and how to config Spring Integration FTP to connect the vsftpd that without config "require_ssl_reuse=NO"?
Exception:
Caused by: org.springframework.messaging.MessagingException: Failed to write to '/ftp/upload/test.txt.writing' while uploading the file; nested exception is java.io.IOException: Failed to write to '/ftp/upload/test.txt.writing'. Server replied with: 522 SSL connection failed; session reuse required: see require_ssl_reuse option in vsftpd.conf man page

Here is my configuration:
<beans:bean id="ftpSessionFactory" class="org.springframework.integration.ftp.session.DefaultFtpsSessionFactory">
<beans:property name="host" value="202.101.1.106"/>
<beans:property name="port" value="21"/>
<beans:property name="username" value="tom"/>
<beans:property name="password" value="tom"/>
<beans:property name='clientMode' value='2'/>
<beans:property name='protocols' value='TLSv1, SSLv3'/>
</beans:bean>

A: See the answer to this question for work-around.
Subclass the session factory and override the createClientInstance method.
Feel free to open an 'improvement' JIRA Issue and we can look at adding it as a feature to the framework. Even better, consider contributing.