text:
Q: How to add a new column with multiple string contain conditions in python pandas other than using np.where? I was trying to add a new column by giving multiple strings contain conditions using str.contains() and np.where() function. By this way, I can have the final result I want.
But, the code is very lengthy. Are there any good ways to reimplement this using pandas function?
df5['new_column'] = np.where(df5['sr_description'].str.contains('gross to net', case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('gross up', case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('net to gross',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('gross-to-net',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('gross-up',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('net-to-gross',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('gross 2 net',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('net 2 gross',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('gross net',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('net gross',case=False).fillna(False),1,
    np.where(df5['sr_description'].str.contains('memo code',case=False).fillna(False),1,0)))))))))))

This output will be,
if those strings contain in 'sr_description' then give a 1, else 0 to new_column
Maybe store the multiple string conditions in a list then read and apply them to a function.
Edit:
Sample Data:
sr_description                  new_column
something with gross up.           1
without those words.               0
or with Net to gross               1
if not then we give a '0'          0

A: Here is what I came up with.
Code:
import re
import pandas as pd
import numpy as np

# list of the strings we want to check for
check_strs = ['gross to net', 'gross up', 'net to gross', 'gross-to-net', 'gross-up', 'net-to-gross', 'gross 2 net',
             'net 2 gross', 'gross net', 'net gross', 'memo code']

# From the re.escape() docs: Escape special characters in pattern.
# This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
check_strs_esc = [re.escape(curr_val) for curr_val in check_strs]

# join all the escaped strings as a single regex
check_strs_re = '|'.join(check_strs_esc)

test_col_1 = ['something with gross up.', 'without those words.', np.NaN, 'or with Net to gross', 'if not then we give a "0"']
df_1 = pd.DataFrame(data=test_col_1, columns=['sr_description'])

df_1['contains_str'] = df_1['sr_description'].str.contains(check_strs_re, case=False, na=False)

print(df_1)

Result:
              sr_description  contains_str
0   something with gross up.          True
1       without those words.         False
2                        NaN         False
3       or with Net to gross          True
4  if not then we give a "0"         False

Note that numpy isn't required for the solution to function, I'm just using it to test a NaN value.
Let me know if anything is unclear or your have any questions! :)


text:
Q: What data does the SCOM agent look at in an MS SQL environment? I'm a new (US based) SCOM admin and have been asked to add a few of our SQL servers located in the UK to our monitoring.  The question coming from the UK admins is "Is there a possibility that a SCOM component (agent) will look at any sovereign data?"
I'm pretty sure that the answer is 'no', but would like to hear from an experienced SCOM admin as to the data that SCOM would look at in an MS SQL environment.

A: The short answer is "no," the SQL management pack for SCOM will not look at any sovereign data.
For the most part, the SQL management pack will only look at WMI information.
More information can be found in the Microsoft supplied documentation that can be found at this location:  https://www.microsoft.com/en-us/download/details.aspx?id=56203
If you are interested in learning more about SCOM, please be sure to check out these other two SCOM communities:
Microsoft Operations Manager Forums:
https://social.technet.microsoft.com/forums/en-us/home?category=systemcenteroperationsmanager
SquaredUp Community Answers:
https://community.squaredup.com/answers/
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как отправить и получить ajax запрос Пытаюсь третий день найти способ решения своей проблемы, но никак не могу выйти из неё.
Мне нужно, чтобы при клике на div (из кода под номером 1) у меня открывалась и сортировалась таблица уже в label (из кода под номером 2) в базе данных с названием таблицы teacher по ключу faculty.
контент ключа faculty меняется в зависимости от нажатой кнопки
вот пример пары кнопок номер 1

      Факультет 1

      Факультет 2

вот пример обработки данных из получаемой базы данных номер 2

    <img src="<?php echo $teacher["img"]; ?>" class="teacher-photo"/>

        <?php echo $teacher["name"]; ?>
        <?php echo $teacher["surname"]; ?>

В ajax я не силён, но всеми силами пытаюсь победить и изучить. Если кто-то мог бы помочь с кодом - был бы вам очень благодарен


text:
Q: Webpack writes the absolute path info in bundle when Babel-loader is used Here is a piece of my webpack config file:
`

// webpack.config.js
  entry: path.resolve(__dirname, 'src/app.js'),
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/js/'),
    library: 'app',
    publicPath: '/js/',
    pathinfo: NODE_ENV === 'development',
  },
  //...
    module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel',
          },
          {
            loader: 'eslint',
          },
        ],
      },
      //...
    ],
  },

 // .babelrc
 {
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "last 1 Chrome versions",
            "last 1 Firefox versions",
            "last 1 Edge versions",
            "last 1 iOS versions"
          ]
        },
        "modules": false
      }
    ]
  ],
  "plugins": [
    ["istanbul", {
      "exclude": [
        "./test/unit/**/*.js"
      ]
    }]
  ]
}

The Problem: I get the full local path to my js file like this:
path: '/Users/username/MyProjects/projectname/src/view/dialog/Messages.js.
Which don't like to have in my production bundle.
I get this only using babel-loader for js files.
I use "webpack": "3.8.1".
Please help!

A: The problem resolved.
The reason was Istanbul Babel plugin.
The solution is to use 'test' variable and use Istanbul in test mode only:
// .babelrc

{
  "presets": [
    [
     // ...
  ],
  "env": {
    "test": {
      "plugins": [
        ["istanbul", {
          "exclude": [
            "./test/unit/**/*.js"
          ]
        }]
      ]
    }
  }
}

A: this might help.
const path = require('path');
path.join(process.cwd()

ex:
"rxjs/AsyncSubject": path.join(process.cwd(), "/node_modules/rxjs/_esm5/AsyncSubject.js")


text:
Q: Generalizing work orders Hello stackoverflowians,
I am working on designing tables for work orders.
The problem:

*

*There is different work order models (from now on called WOM)

*The WOMs share some attributes (Num, Date, Description, ... etc)

*The WOMs have details such as:

*

*Sectors on wich the work is done.

*Some WOMs use storage tank instead of sectors (products are prepared in storage tanks).

*Products and their quantities (plus or no some info on product) applied to wich sector.

*Human ressources wich worked on the WO.

*Materials used on the work order

*... etc

What is needed

*

*Design tables for work orders and the details ofc.

*They want to know how ressources were spent.

*Design queries to retrieve all shape of infos.

Constraints

*

*Simple presentation for the end users.

*Generalizing the work orders models.

What has been done
Designed all work orders and their details as a hierarchy starting from work order num as the mother node.
WorkOrderTable (ID, ParentID, Type, Value)

example of a work order Transform hierarchical data into flat table
ID  ParentID    Type        Value
38  0           Num         327
39  38          Sector      21
40  38          Sector      22
43  40          Product     NS
44  40          Product     MS
50  40          Temp        RAS
48  44          Quantity    60
47  43          Quantity    25
41  39          Product     ARF
42  39          Product     BRF
49  39          Temp        RAS
51  39          Cible       Acarien A.
46  42          Quantity    30
52  42          Cible       Acarien B.
45  41          Quantity    20

The Question
Is what I am doing good/efficient easy to maintien work with or there is other ideas ?
UPDATE I : More details

*

*Products aren't changing about 50 active ones [products change over time, need to keep track of version]

*Sectors are about 40 (fixe land area)

*People normal HR table

*How Big is a typical WOM :

*

*about 15 attributes (3 of them mportante and shared by all WOMs the others are a little less)

*about 5 or more details sharing : Product, Sector, People and other describing infos like the quantity of the product.

*WOMs are fixe for now but I am worried about them changing in future (or the rise of new ones)

*The versionning isn't a requirement right now, but adding it is a plus.

*I am planning on using different tables for participants (sectors, products ...)

*The meta-data / data confilict is what this design dilemma is about.

*

*Considered any WOM is defined by 3 parts:

*The Work Order General Info (Num, Date, ...)

*The Sectors [Other WOMs use Tank storage] in wich the jobs are done.

*The Ressources to complete the job products, people, machines ...

State of the design

*

*Specific tables for participants sectors,people,machines...

*Meta-data table (ID, meta-data, lvl). Example :

*

*Sector, 1 (directly to WO)

*Tank Storage, 1

*Product, 2 (can be part of sector job not directly to WO) sd

*Work Order table (ID, parentID, metadataID, valueID) the value ID is taken from the participants table

Concerning XML I have so to no informations about how to store them and manipulate them.

A: I think if your looking for design advice, you should go to a meta stack group, i.e code review exchange
That being said, your asking for advice on design, but only giving abstract information.  The scale of a system, the amount of CRUD expected, and several other factors need to be considered in design. With out getting the details and targets its really hard to answer your question. There are trade offs with different approaches. It may even be advisable to use a nosql solution.
That being said, I would suggest not building your own ERP system, and instead look to buy one from a vendor, that is industry specific, and apply your customization to it.
Its very expensive to write your own system, keeping it updated, adding security, and a lot of others features make it a worth while business decision to purchase from a software vendor.
If your just looking to gain more experience by writing this, I would suggest browsing github, and the previously mentioned stack exchange.

A: Without knowing any numbers and further knowledge about your needs no good advise is possible. Here are some question coming into my mind

*

*How many users?

*How many products/locations/sectors/people...?

*

*Is this changing data?

*How many WOMs?

*How big is one typical WOM?

*Is it a plain tree hierarchy

*

*If not: Might there be alternative routes, circles, islands?

*Are these WOMs fix or do they change?

*

*If changing: Do you need versioning?

It looks like trying to re-invent a professional ERP system. As Bostwick told you already, you should rather think about to use an existing one...
Just some general hints:

*

*Do not use the WOM-storage for (meta) data (only IDs / foreign key)

*Try to draw a sharp border between working data and meta data

*Use a dedicated table for each of your participants (sectors, products...)

*A WOM might be better placed within XML

*Read about (Finite) State Machines

*Read about state pattern

*Read about Business-Process-Modelling and Workflows


text:
Q: Обёртка для примитива Boolean как объект Возможно ли заставить обёртку для примитива Boolean вести себя как объект?
Например, следующий код:
public static void testBoolean(int a, Boolean isLeft) throws Exception {
    if (a > 3) {
        isLeft = Boolean.TRUE;
    } else {
        isLeft = Boolean.FALSE;
    }
}

public static void main(String[] args) {
    Boolean isLeft = Boolean.TRUE;
    testBoolean(5, isLeft);
    System.out.println(isLeft);
    testBoolean(1, isLeft);
    System.out.println(isLeft);
}

выводит:

true
true

Есть ли какой-либо способ заставить изменяться isLeft в методе testBoolean как объект (чтобы второй раз выводилось false)?

A: Нет, такого способа нету. Объекты ведут себя именно так. Вы спутали со случаем изменения ссылки на объект со случаем изменения (мутации) самого объекта.
В метод testBoolean передаётся ссылка на объект типа Boolean по значению.
Внутри метода меняется не сам объект, а лишь ссылка isLeft на него! Поскольку в функцию передаётся лишь копия ссылки (в этом смысл передачи по значению), изменения её снаружи не видны. Вот если бы вы как-то меняли сам объект, то тогда да, его изменения были бы видны снаружи.

Java не поддерживает передачу ссылок по ссылке, но можно сделать грубый хак, и передать вместо ссылки одноэлементный массив:
public static void testBoolean(int a, Boolean[] isLeft) throws Exception {
    if (a > 3) {
        isLeft[0] = Boolean.TRUE;
    } else {
        isLeft[0] = Boolean.FALSE;
    }
}

https://ideone.com/wa0prq
При этом передаётся копия ссылки на массив, в котором доступен «оригинал» ссылки на Boolean.
Точно так же в качестве «контейнера» оригинала ссылки можно использовать AtomicBoolean (но он при этом производит ненужную синхронизацию), ну или самостоятельно написать универсальный контейнер:
class UniversalContainer<T> {
    T value;
    public UniversalContainer() {}
    public UniversalContainer(T initial) { value = initial; }
    public T get() { return value; }
    public void set(T value) { this.value = value; }
}

public static void testBoolean(int a, UniversalContainer<Boolean> isLeft) {
    if (a > 3) {
        isLeft.set(Boolean.TRUE);
    } else {
        isLeft.set(Boolean.FALSE);
    }
}

public static void main(String[] args) {
    UniversalContainer<Boolean> isLeft = new UniversalContainer<Boolean>(Boolean.TRUE);
    testBoolean(5, isLeft);
    System.out.println(isLeft.get());
    testBoolean(1, isLeft);
    System.out.println(isLeft.get());
}

https://ideone.com/VwSM19


text:
Q: Zend Autoloader doesn't work when using with command prompt (CLI) I am facing an issue with Zend_Loader_Autoloader, it is working fine when I am running application through my web browser. I tested with few of my modules. However I do have some php scripts to run as a cron job. When I am trying to remove the require_once lines and let zend autoloader to work it fails to load the classes. I am totally frustrated about this problem, if I am doing something wrong or do I need to change my approach. and why this doesn't simply work.

A: My guess is that the php.ini files differ between apache sapi and cli versions. Maybe different values for safe_mode, include_path and/or open_basedir.

A: This code is working for me :
define('WWW_PATH', dirname(__FILE__) . '/../..');

set_include_path(implode(PATH_SEPARATOR, array(realpath(WWW_PATH . '/library'), get_include_path())));

require_once 'Zend/Loader/Autoloader.php';

$autoloader = Zend_Loader_Autoloader::getInstance();

$autoloader->registerNamespace('Zend_');


text:
Q: OS X: Increase granularity of audio volume controls I'm using USB headphones with a Mac Mini, and the lowest volume setting is too loud for most applications. Is there any way to increase the granularity (number of steps) in the volume control, or to apply some fractional factor to the volume level?

A: Hold Shift + Option while you change the volume with the keyboard. You get 4 times finer volume control.

A: option-shift volume up and
option shift volume down
will change the volume in smaller increments.

A: What worked best to adjust the volume is going to Audio MIDI Setup and adjusting output volume by going to the device and editing front-left, front-right.

A: Just to be clear, if the poster is saying that the normal built-in volume control on Mac OS X doesn't allow him/her to lower the volume sufficiently, it may be possible to route the sound via a different sound driver (not the default system one).
You should be able to use an audio extension created in an app like Sound Flower.
To do this, in conjunction with the Audio MIDI Setup.app in your Utilities folder to control the 'master volume' in that extension, unless your particular USB speaker has that feature disabled.

A: I had the same problem using a USB Plantronics headset.
I went to system preferences -> Sound -> Output -> Plantronics Headset -> Output Volume
Increase that, then for myself, I chose my default sound output to the internal speakers. Otherwise all the system sounds come through the headset.
Hope that is what you were looking for.

A: On MacOS Monterey and above
Use:
[SHIFT+OPTION] + VOLUME UP/DOWN Keys
This reduces the volume change amount to 25%, i.e. you can break up 1 change into 4 changes. So instead of the 16 steps you can have 64.


text:
Q: How can i disable or affect null to a variable in php I have 3 web pages one for sign-in, one for sign-up, and the last one is the home page (index). I have 2 variables from the sign-in and 5 variable from sign-up, all the variables are sent into the home page so when I sign up in the sign-in variable have no values so it gives an error  "notice undefined index", and when I sign up the same happens but the error shows the sign in's variables.
I have so many searches in google and I've found a function called unset to disable the variables, but nothing happens.
// Sous WAMP
$bdd = new PDO('mysql:host=localhost;dbname=test exbook;charset=utf8', 'root', '');
$reponse = $bdd->query('SELECT * FROM registration');
$nom = $_POST['nom'];
$birthday = $_POST['birthday'];
$genre = $_POST['genre'];
$email = $_POST['email'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

if (isset($nom , $birthday , $genre , $email, $password )) {
    unset($nom);
    unset($birthday);
    unset($genre);
    unset($email);
    unset($password);
} else {
    $req = $bdd->prepare('INSERT INTO registration(`Nom`, `Date de naissance`, `Genre`, `Email`, `Password`) VALUES(?,?,?,?,?)');
    $req->execute(array($nom, $birthday, $genre, $email, $password));
}

while ($donnees = $reponse->fetch()) {
    echo $donnees['Nom'];
}

$bdd = new PDO('mysql:host=localhost;dbname=test exbook;charset=utf8', 'root', '');
$emailsignup = $_POST['emailsignup'];
if (isset($emailsignup)) {
    unset($emailsignup);
} else{
    $bdd1 = $bdd->query('SELECT * FROM registration WHERE $emailsignup');
}

Thank you for reading this, and for trying to help.
Have a nice day :)

A: The undefined index error is coming from $_POST variable. When you are trying to emailsignup the parameters nom, birthday... are not present in $_POST array. You can do something like this:
           // Sous WAMP
            $bdd = new PDO('mysql:host=localhost;dbname=test exbook;charset=utf8', 'root', '');
            $reponse = $bdd ->query('SELECT * FROM registration');
            $hasnom=isset($_POST['nom']);
            $hasbirthday=isset($_POST['birthday']);
            $hasgenre=isset($_POST['genre']);
            $hasemail=isset($_POST['email']);
            $haspass = $isset($_POST['pass']);

            if ($hasnom && $hasbirthday && $hasgenre && hasemail && haspass) {
              $nom=$_POST['nom'];
              $birthday=$_POST['birthday'];
              $genre=$_POST['genre'];
              $email=$_POST['email'];
              $password=password_hash($_POST['password'], PASSWORD_DEFAULT);

                $req = $bdd ->prepare('INSERT INTO registration(`Nom`, `Date de naissance`, `Genre`, `Email`, `Password`) VALUES(?,?,?,?,?)');
                $req->execute(array($nom,$birthday,$genre,$email,$password));
             }
              while ($donnees = $reponse->fetch())
              {
                echo $donnees['Nom'];
              }
          ?>
          <?php
                $bdd = new PDO('mysql:host=localhost;dbname=test exbook;charset=utf8', 'root', '');
                $hasemailsignup=isset($_POST['emailsignup']);
                if ($hasemailsignup) {
                    $emailsignup = $_POST['emailsignup'];
                    $bdd1=$bdd ->query('SELECT * FROM registration WHERE $emailsignup');
                }
             ?>


text:
Q: TypeScript class with a method not used in each instances I have a TypeScript class that is creating the basics of a ZMQ bus communication. I first wanted to make a general class that I can instantiate as many time as required. But now, i need to make more instances that does not totally fit the general class i made. Actually, the only difference is that in these new instances, the request method is never used depending on type. So, is it somehow possible to keep the same general class but to ignore the request method when it is not required ?
let zmq = require("zeromq")

class ZMQBus {
    socket:any
    port:number

    constructor(type:string, port:number) {
        this.socket = zmq.socket(type)
        this.port   = port
    }

    open(): void {
        this.socket.connect("tcp://localhost:" + this.port)

        this.socket.on("message", function(reply) {
            console.log("Received reply : " + reply.toString());
        })
    }

    request(msg:any): void {
        this.socket.send(msg);
    }

    close(): void {
        this.socket.close();
    }
}

A: I know you said you wanted to avoid two classes because you didn't want to imply that the two were different. The request being unimportant in certain cases does not make it harmful. You could still use a single class with a a single implementation of request that you only use when it is required. If you really need to stipulate that request is not present, you will have to create a separate type. You might achieve semantically what you want, without any antipatterns by utilizing a factory pattern and conditional types
type ZmqTypes = "REQUEST" | "NOREQUEST";

interface ZMQBus {
  open: () => void;
  close: () => void;
  request?: (msg: any) => void;
  type: ZmqTypes;
  port: number;
}

interface ZMQBusR extends ZMQBus {
  request: (msg: any) => void;
}

interface ZMQBusNoR extends Omit<ZMQBus, "request"> {}

class GenericZMQBus implements ZMQBus {
    socket:any
    port:number

    constructor(type:string, port:number) {
        this.socket = zmq.socket(type)
        this.port   = port
    }

    open(): void {
        this.socket.connect("tcp://localhost:" + this.port)

        this.socket.on("message", function(reply : any) {
            console.log("Received reply : " + reply.toString());
        })
    }

    close(): void {
        this.socket.close();
    }
}

class ZMQBusWithRequest extends GenericZMQBus implements ZMQBusR {
  request(msg : any) {
    console.log(msg);
  }
}

function createZMQBus<T extends ZmqTypes>(type: T, port: number) : T extends "REQUEST" ? ZMQBusR : ZMQBusNoR {
  if (type === "REQUEST") {
    return new ZMQBusWithRequest(type, port) as unknown as T extends "REQUEST" ? ZMQBusR : ZMQBusNoR;
  }
  return new GenericZMQBus(type, port) as unknown as T extends "REQUEST" ? ZMQBusR : ZMQBusNoR;
}

const zmqObj = createZMQBus("REQUEST", 999);
const zmqObj1 = createZMQBus("NOREQUEST", 999);

zmqObj.request('hello');
zmqObj1.request('error'); // is an error

You still have multiple classes and interfaces with a strict type system, but a single way of creating those objects that implies a consistent purpose, if not a consistent implementation. And since both extend a single generic interface, you can pass either type around as a single ZMQType. You just have to make sure that you check for the correct presence of the request method before you try to use it.
function testZMQImplementation(z: ZMQBus) {
  if (z.request) {
    z.request('testing')
  }
}

testZMQImplementation(zmqObj);
testZMQImplementation(zmqObj1);


text:
Q: Revisiting changes to answer sorting menu: better use of space, moving menu into a dropdown, ascending/descending sort options, clearer descriptions Update (Mar 21, 2022): The dropdown menu for the answer-sorting options is now live.

Update (Feb 9, 2022): I've added an additional question in the Feedback section below.

Last week, I posted proposed changes to the answer-sorting menu. The changes I originally suggested were easy things we could do to make the existing implementation incrementally better, but they weren't the result of us taking a holistic view of how to improve the sorting menu. Based on your feedback, I asked our Design team to take a deeper look, and they went back to the drawing board (literally, ha ha) and came up with new ideas:

*

*Keeping the menu right-justified and making better use of space.

*Condensing the sort options into a dropdown menu.

*Introducing ascending and descending sorts for most (if not all) of the options.

*Having clearer descriptions that eliminate the need for info icons and tooltips.

*Adding a "Sort by" label to describe what this UI element is for.
We will run an A/B test to make sure that this new design doesn't dramatically suppress clicks on the answer-sorting menu. Assuming no negative impact, we will implement these changes in the coming weeks across all of our Stack Exchange sites.
Here is what the current menu looks like:

Here is what the new menu looks like:

Making better use of space
I originally stated that we would run an experiment to test moving the menu from its current position — right-justified next to the number-of-answers header — to a new position underneath the header.
What was I thinking? Turns out you didn't like it, Design didn't like it, our own devs didn't like it... You get the (bad) idea.
So, we are NOT going to experiment with moving the menu. It's staying in its happy place on the right, and the menu now takes up less space overall.
Moving the sort menu into a dropdown menu
We took a number of things into consideration when settling on this new approach:

*

*A dropdown menu is a much more common pattern across the web for sorting menus.

*It scales better, allowing for a larger number of sort options. We are planning on introducing a Trending sort on Stack Overflow in the near future, and this change allows for more flexibility when it comes to adding additional sort options, without risking taking up too much horizontal space on the screen.

*It gives us future flexibility to separate sorts and filters on other areas of the site. For example, we could (eventually) have separate dropdowns for filters and sorting that would allow you to more easily control the sorting on filters – like unanswered or bountied questions – all in one interface, rather than both the button bar (which includes a dropdown) and the separate filter dropdown. (This is a future idea that is not yet on our roadmap, but highlights the consistency that a dropdown menu could help bring.)

*It gives us more room to explain how each sort works, without needing to rely on info icons and tooltips (more on that below).
We are aware that it has a couple of drawbacks, but we feel the benefits outweigh the inconveniences:

*

*It will now take two clicks to change the sort: one click to open the dropdown menu and another click to choose your desired sort. Currently, only about 0.25% of visitors click the existing sort buttons, so this isn't a common action that will greatly inconvenience a substantial number of users. In addition, even if we kept the existing buttons, we would have been heading into two-click territory anyway; one of the top suggestions from last week was to have a single button for Oldest/Newest, but to click twice to toggle between the two.

*You can no longer see the entire menu of sorts on the page at all times, but we don't feel we will lose much by tucking them away in a dropdown. We will run an A/B test prior to graduating the change to make sure we don't dramatically suppress clicks.
Introducing ascending and descending sorts for all of the options
We announced last week that we are creating a Newest sort to complement the existing Oldest sort. We decided for consistency's sake to create ascending/descending versions of all of the existing sort options: Highest score (default), Newest modified, Oldest modified, Newest created, Oldest created, and, potentially, Lowest score.
Per the Feedback section below, we have some concerns about the Lowest score option and would love to hear your thoughts.
Having clearer descriptions
With more space, we are now able to write longer, clearer descriptions for each sort. This eliminates the need for tooltips and info icons. The new descriptions are:

*

*Highest score (default) – renames the previous "Votes" sort

*Lowest score

*Date modified (newest first) – renames the existing "Active" sort

*Date modified (oldest first)

*Date created (newest first)

*Date created (oldest first) – renames the existing "Oldest" sort

Feedback
I've posted this primarily to give the community advance notice on changes that are coming. We have settled on the dropdown menu as our preferred path forward, and aren't considering doing additional design work to come up with alternative solutions.
Lowest score sort: We are debating internally whether or not to include lowest score as a sorting option. Because we remember your sorting preferences, we are concerned that someone could set "lowest score" as their sorting preference, forget they chose it, and then be utterly perplexed as to why they are seeing so many low-scored answers.
Do you see any value in having a lowest-score sort? Why or why not? When and how would you use it?
How to handle deleted answers (for mods and users with 10K rep): See the answer below that suggests that deleted answers be segregated from other answers in the Date Modified and Date Created sorts, appearing at the bottom instead of being mixed in with the other posts. (For the Score sort, deleted answers are already sorted below visible answers.) Is there any reason we should keep the sorts as is, with deleted answers mixed in? Why or why not?

A: On whether or not to mix in deleted answers:
There are an awful lot of 10k users, but I think it's safe to say that the majority of them are not super-active moderators. (If this is not true, then the remainder of my argument is moot.) I'm assuming that most, like me, are just looking for answers to their questions while also trying to give back to the community once in a while.
A deleted answer is almost never useful.

*

*If it was so far off the mark that the author and/or community decided the only option was total removal, then it probably won't be useful to me.

*If it was identical to another answer and the author felt it was not useful to have that answer twice, then it probably won't be useful to me.

*If it was spam, then it definitely won't be useful to me.

About the only time that a deleted answer is actually useful is when a new, dejected user deletes it after the first downvote because someone else didn't understand it. It's not unheard of, but I think it's fair to call it an exception to the norm.
As a 10k user, it's fun to be able to participate in meta discussions where I can see some problematic answer and weigh in on the conversation, but I also have no way of easily turning this "privilege" off. If I'm just trying to figure out why my foo won't bar when baz is set to bat, then cluttering the answers with useless junk, just because I wanted to be helpful to others, feels more like a punishment.
Please leave the deleted answers at the bottom of the stack, regardless of my chosen sort order.

A: status-declined
Can we separate sorting a single post's answers from the remembering my preferred settings for the site?  Usually, my preferred order stays the same for any given site, and on the occasions I change to something different, it's frustrating to find the next post I read isn't sorted the usual way.
I'd envision a "remember this" button near the sort menu, and some indicator in the sort choice highlighting which option is default for me (giving an at-a-glance indication of "this isn't my default sort").

A: Interestingly, the change from "Activity" to "Modified" may have cleared up a misconception I had about the old sorting behavior:

*

*When I read "Modified," I think Post created and Post edited.

*When I read "Activity," I think Post created, Post edited, and Post commented on.
So if the real sort behavior has been the former all along, bravo for the changed text.

A: The wording of "Reset to default" is a bit misleading:

"Reset" sounds like a permanent action, but here it has no lasting effect. I clicked "Reset to default" on multiple questions before realizing it's apparently meant to be temporary and that we need to use the dropdown to permanently "reset" the sort order.
Perhaps "View as default" would better reflect that it's only a temporary view (assuming this is not a bug).

A: Looking at the lowest scored answers lets me find posts that may need to be flagged, try to help authors getting downvoted improve their answers, or quickly see the least popular option in a meta discussion, which might challenge my perspective. (I seek out opinions that are different from mine, because I like confirming that my certainty I'm right is warranted, and like to know how certain I should be before I open my mouth ;))
I would use both "lowest" and "highest" score sort orders, and would be mildly uncomfortable by the lack of symmetry if "lowest" wasn't there.
I really like the switch to a dropdown, and the explicit highest/lowest, newest/oldest type options instead of the ascending/descending toggle.

A: status-planned
TylerH makes a good argument in a comment. When changing the sort order, deleted answers should remain at the bottom. The current behavior of mixing them in when sorting on date ("active" or "oldest") is confusing.

A: Regarding the sorting of deleted posts:
I use "Date modified (newest at top)" sort to answer the question "Why was this post bumped to the home page?" I wouldn't expect deleted posts to be always at the bottom and it would cause the sort not to be able to answer my question when a new answer that bumped the post is deleted.
I would expect I would use "Date created (newest at top)" sort to see what answers have a fresh perspective. For that, deleted answers would just get in the way.

A:
Do you see any value in having a lowest-score sort? Why or why not? When and how would you use it?

That's certainly easier than having to scroll down or even paginate when there are lots of answers. Would it be an option to not store that specific sort option in your preferences? Perhaps with a banner notifying you of this, after you select it? Or would that be too confusing?

A: Regarding the handling of deleted answers...
My initial reaction is that all three of these views have value:

*

*seeing the deleted answers in context of the other answers, sorted appropriately

*seeing only deleted answers

*hiding deleted answers

Pushing all deleted answers to the bottom is an easy way of handling #2 and #3. Leaving them interleaved for only some sort modes is a less than optimal way of handling #1.
When I was a mod, I would have liked a toggle to either include the deleted answers in my current sort, or push them to the bottom out of the way. I'm on the fence about whether hiding them entirely is a good idea. It's easy to forget you hid them and assume the question has no deleted answers. Pushing them to the end is good enough I think.
(And it would be nice if the deleted answers were sorted according to the current sort order even when they are being pushed to the bottom.)

A: status-declined
I am not sure if this is a good idea, but I would like to propose it.
I certainly agree with ColleenV's answer. But, I also understand your concern about "someone could set "lowest score" as their sorting preference, forget they chose it, and then be utterly perplexed as to why they are seeing so many low-scored answers."
I am not sure if this concern would be valid to users who have spent a good amount of time in Stack Exchange and know how things work in Stack Exchange.
But, it might be a problem to low-reputation users.
I propose that the Lowest score sort feature be available as a privilege to users only above a certain reputation (250 seems like a nice number). Of course, the exact reputation required for this privilege is debatable.

A: Would it be possible to remove the sort option altogether when there's only one answer available? The option is meaningless in that context and it clutters the page


text:
Q: Encoding two Unix timestamps into one My application requires a date range in a GET parameters. I was thinking there must be some genius way of encoding two Unix timestamps into one, effectively shortening the URL parameters.
I realize a simple CSV of two timestamps would do the trick, but the goal here is to reduce the URL size as much as possible.
PS: This would also need to work if there is only one date (the start date), in which case the end date will be assumed as today.

A: Well, here are a few ideas:

*

*If the two timestamps are likely to be close to one another, store them as a pair of the first time and the difference. For example, for now and tomorrow, you'd store 1361666257,86400.

*Store the timestamps in hexadecimal (base 16) instead of base 10; e.g, 512960d1

*If the timestamps are always dates, store them in terms of days since the epoch, rather than seconds, by dividing by 86400 and discarding the remainder. Today is day 15760, for instance.
And/or combine all three of these: 3d90,1

A: If your goal is reducing the URL size as much as possible, you can come up with your own "timestamp" format, choosing the granularity and offset at your convenience.
For example, if the dates you need to pass are usually around the current date of the request and if you only need the date and not the time of day, you could use the number of days ago, instead of the number of seconds since year 1970, which is the UNIX timestamp definition.
Here is what a random date range looks like with unix timestamps and with this variant:
Date range: 2012-09-21 to 2013-01-10
Timestamp:  1348178400_1357772400
Days-ago:   156_45

Notice I have used _ to separate the from and to parts, because the minus sign - is needed for dates before 1970 when using UNIX timestamps, or dates in the future in my example encoding.
This is just an example. You should come up with your own encoding (or not) based on your application needs. For example if the date range is usually small, you could encode it as a date + a difference. The difference could be in days, or in months, or in whole years... depending on your needs.


text:
Q: Can't explain results when testing clojure data structures I'm fairly new to clojure and functional programming generally. Being curious about the speed of some basic operations with data structures (clojures defaults and some I may implement) I wrote something to automate testing operations such as adding to the structures.
My method that runs a test for 3 data structures consistently returns very different average run times depending on how its called even when its inputs remain the same.
Code with tests and results at the bottom

(import '(java.util Date))

(defrecord test-suite ;;holds the test results for 3 datastructures
[t-list
 t-vector
 t-set]
)

(defrecord test-series ;;holds list of test results (list of test-suite) and the list of functions used in the respective tests
[t-suites
 t-functions])

;;;Runs the test, returns time it took
(defn time-test [func init-ds delta-list]
  (def startTime (. (new Date) (getTime)))
  (reduce func init-ds delta-list)
  (def endTime (. (new Date) (getTime)))
  (- endTime startTime)
)

;;;Runs the test x number of times returning the average run time
(defn test-struct ([iter func init-ds delta-list] (test-struct iter func init-ds delta-list ()))
  ([iter ;;number of times to run tests
    func ;;function being tested (add remove etc)
    init-ds ;;initial datastructure being tested
    delta-list
    addRes ;;test results
    ]
  (println (first addRes));;print previous run time for debugging
  ;;test if done recursing
  (if (> iter 0)
    (test-struct
     (- iter 1)
     func
     init-ds
     delta-list
     (conj addRes (time-test func init-ds delta-list)))
    (/ (reduce + addRes) (count addRes)))
))

;;;Tests a function on a passed in data structure and a randomly generated list of numbers
(defn run-test
  [iter ;;the number of times each test will be run
   func ;;the function being tested
   init-ds] ;;the initial datstructure being tested
  (def delta-list (shuffle (range 1000000)));;the random values being added/removed/whatever from the ds
  (println init-ds)
  (println iter)
  (test-suite.
   ;;the list test
   (test-struct iter func (nth init-ds 0) delta-list)
   ;;the vector test
   (test-struct iter func (nth init-ds 1) delta-list)
   ;;the set test
   (test-struct iter func (nth init-ds 2) delta-list)
   )
)

;;;Calls run-test a number of times storing the results as a list in a test-series data   structure along with the list of functions tested.
(defn run-test-set
  ([iter func-list ds-list] (run-test-set iter (test-series. nil func-list) func-list     ds-list))
  ([iter ;;the number of times each test is run before being averaged
   series ;;data-structure that aggregates the list of test results, and ultimately is     returned
   func-list ;;the list of functions to be tested
   ds-list] ;;the list of initial datastructures to be tested
  (if (> (count func-list) 0)
    (run-test-set ;;recursively run this aggregateing test-suites as we go
     iter
     (test-series. ;;create a new test series with all the functions and suites run so     far
      (conj (:t-suites series) ;;run a test suite and append it to those run so far
            (run-test iter (first func-list) (first ds-list)))
      (:t-functions series))
     (rest func-list)
     (rest ds-list)
     )
    series)) ;;finished with last run return results
)

Tests
All times in ms
;;;;;;;;;;;;;;;;;;EVALUATING 'run-test' directly
;;;get average speeds for adding 100000 random elements to list vector and set
;;;run the test 20 times and average the results
(run-test 20 conj '(() [] #{}))
;;;;;RESULT
#test.test-suite{:t-list 254/5, :t-vector 2249/20, :t-set 28641/20}

or about 51 112 and 1432 for list vector and set respectively
;;;;;;;;;;;;;;;;;;EVALUATING using 'run-test-set' which calls run-test
(run-test-set
 20              ;;;times the test is run
 '(conj)         ;;;just run conj (adding to the ds for now)
 '((() [] #{}))   ;;;add random values to blank structures
 )
;;;;RESULT
#test.test-series{
  :t-suites (
    #test.test-suite{
      :t-list 1297/10,
      :t-vector 1297/10,
      :t-set 1289/10}) ;;;;;;;;;;;;Result of adding values
  :t-functions (conj)}

or about 130 for list vector and set, this is roughly the same rate as vector above
Does anyone know why its returning such different results depending on how its run?
Is this clojure related or possibly an optimization Java is doing?

A: The right way to test performance of clojure code is criterium. Among other things, criterium reports statistical information about the distribution of times of code execution, and ensures that the jvm hotspot compiler is warmed up before taking the measurements. The jvm hotspot compiler is likely the reason you are seeing these performance discrepencies.
Don't use def inside defn, def is designed for top level global definitions. Use let for bindings that are only used inside one function.
Defining records that are only used once and only exist to hold a few variables is not idiomatic in clojure, the overhead of defining the classes is greater than any benefit they may give you (for increased difficulty understanding the code, if not the performance of your code). Save records for when you need to specialize a protocol or improve performance in a tight loop.
When your priority is human readability of numbers, rather than accuracy, you can use double to coerce to a more readable format for printing.
Here is how one would test the properties you are interested in idiomatically (transcript from a repl session, though this could be run from a -main function as well):
user> (require '[criterium.core :as crit])
nil
user> (def input (shuffle (range 1000000)))
#'user/input
user> (crit/bench (reduce conj [] input))
WARNING: Final GC required 3.501501258094413 % of runtime
WARNING: Final GC required 2.381979156956431 % of runtime
Evaluation count : 1680 in 60 samples of 28 calls.
             Execution time mean : 36.435413 ms
    Execution time std-deviation : 1.607847 ms
   Execution time lower quantile : 35.764207 ms ( 2.5%)
   Execution time upper quantile : 37.527755 ms (97.5%)
                   Overhead used : 2.222121 ns

Found 4 outliers in 60 samples (6.6667 %)
    low-severe   1 (1.6667 %)
    low-mild     3 (5.0000 %)
 Variance from outliers : 30.3257 % Variance is moderately inflated by outliers
nil
user> (crit/bench (reduce conj () input))
WARNING: Final GC required 9.024275674955403 % of runtime
Evaluation count : 3540 in 60 samples of 59 calls.
             Execution time mean : 19.623083 ms
    Execution time std-deviation : 3.842658 ms
   Execution time lower quantile : 17.891881 ms ( 2.5%)
   Execution time upper quantile : 26.569738 ms (97.5%)
                   Overhead used : 2.222121 ns

Found 3 outliers in 60 samples (5.0000 %)
    low-severe   3 (5.0000 %)
 Variance from outliers : 91.0960 % Variance is severely inflated by outliers
nil
user> (crit/bench (reduce conj #{} input))
WARNING: Final GC required 12.0207279064623 % of runtime
Evaluation count : 120 in 60 samples of 2 calls.
             Execution time mean : 965.389668 ms
    Execution time std-deviation : 682.645918 ms
   Execution time lower quantile : 674.958427 ms ( 2.5%)
   Execution time upper quantile : 2.287535 sec (97.5%)
                   Overhead used : 2.222121 ns

Found 9 outliers in 60 samples (15.0000 %)
    low-severe   9 (15.0000 %)
 Variance from outliers : 98.2830 % Variance is severely inflated by outliers
nil
user>


text:
Q: Building agents with GuiAgent class I want to create Multi Agent application with GUI and I supposed to use GuiAgent class, but I didn't find any documentation to start developing it, my application consist to create a chat room between two agents and communicate by using the interface, so plz help me

A: You can find an example in this link:
http://jade.tilab.com/documentation/chat-demo/
If you want more information about JADE, there is a good book which covers differents topics of it:
https://www.mit.bme.hu/system/files/oktatas/targyak/8671/Developing-Multi-Agent-Systems-with-JADE.pdf


text:
Q: Is this matrix diagonalizable I don't believe this matrix is diagonalizable, but I wanted to make sure.
Here's the matrix:
$A=\begin{bmatrix} 4 & 0 & 0 \\2 & 2 & 0 \\ 0 & 2 & 2 \end{bmatrix}$
A nice thing about this matrix is that it is diagonal, so the eigenvectors are $\lambda_1 = 4$, and $\lambda_2 = 2$ with algebraic multiplicity $2$.
The associated eigenvector for $\lambda_1$ is $x_1 = (1,1,1)$.  When trying to solve for the eigenvector of $\lambda_2$, one gets the reduced matrix
$C = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 0 \end{bmatrix}$
Here, there is only the trivial solution, and that can't be an eigenvector due to definition.  Based on that, can I rightly say that this matrix is not diagonalizable?

A: Yes, your argument works. You can also remark that since the minimal polynomial of the matrix is the same as its characteristic one, i.e. $(x-4)(x-2)^2\,$ , then as the min. pol. is not a product of different linear factors the matrix isn't diagonalizable.


text:
Q: Flatsome theme, show sidebar without clicking on mobile product page I have a quick question about the theme's product pages on mobile. How can I show the sidebar below the content. I know how to show the sidebar by using the "filter" button but I need to show it without having to click.
I looked at the event on the filter button but it is a minified function inside flatsome.js?ver=3.12.1
but didn't figure out how to call the funcion.
Thank you in advance!

A: From the WP dashboard, go to Appearance > Customize > WooCommerce > Product Page and uncheck the option that says "Off-canvas Sidebar for Mobile."
screenshot of Customizer option described above
This should place the sidebar below the product page content on mobile.


text:
Q: Change MySQL 4.1 Windows to MySQL 4.1 Linux- Problem with the key Sensitive in query I need help to resolve this problem.
change the server MySQL 4.1 run on Windows to MySQL 4.1 run on Linux(debian).
This all working, but same query not return the correct data because key sensitive<\h1>.
In windows server i type:
  selete * from acao;
or
  Selete * from ACAO;
this two query return data.
But on Mysql 4.1 on linux is difference.
Is key sensitive<\h1>,
if the table is difine on server "acao",
the query
  selete * from acao;
the query returns data, but if the query is:
  Selete * from ACAO;
I have more than 200 files with this query, so I do not have time to change all of this.
bests,
jgois

A: There is a system variable that needs to be set in your my.cnf file.  You will need to add:
lower_case_table_names=1 in the [mysqld] section of your cnf file.
Kevin


text:
Q: Dropbox Core SDK for iOS using access token I need to upload files from my iOS application into my Dropbox account. I'm following this tutorial to do so: https://www.dropbox.com/developers/core/start/ios. But I don't understand how to use the generated access token to access my own account without going through the authentication flow.

A: The generated access token available on the Dropbox App Console is an OAuth 2 access token, just meant as a shortcut to let your app to your own account. The Dropbox iOS Core SDK uses OAuth 1 though, so you can't use the generated access token with it. That being the case, you'll need to implement the app authorization flow so that you, and additionally your end-users, can link your iOS app to their Dropbox accounts, as shown in the tutorial.
If you only ever need to link to your own account, you'll still need to process the app authorization flow for your own account once to get an OAuth 1 access token.


text:
Q: Setting base class property using derived class Constructor I am setting a property of base class from derived class as following:
public abstract class Coverter
{
    public Mydata data { get; set; }
    public abstract void Convert();

}
public class Mydata
{
    public int i;
}
public class Coverter1 : Coverter
{
    public Coverter1(Mydata data1)
    {
        data = data1;
    }

    public override void Convert()
    {
        Console.WriteLine(data.i.ToString());

    }
}

private static void Main(string[] args)
{
    Mydata data = new Mydata();
    data.i = 5;
    Coverter c = new Coverter1(data);
    c.Convert();
    Console.ReadLine();
}

Is there any flaw with this kind of implementation ? What could be the better approach?
I can do the same thing in the following approach.
public abstract class Coverter
    {
        public Mydata data { get; set; }
        public abstract void Convert();

    }

    public class Mydata
    {
        public int i;
    }
    public class Coverter1:Coverter
    {
      override public void Convert()
      {
          Console.WriteLine(data.i.ToString());

      }
    }
    static void Main(string[] args)
    {
        Mydata data1 = new Mydata();
        data1.i = 5;
        Coverter c = new Coverter1();
        c.data = data1;
        c.Convert();
        Console.ReadLine();
    }

Which appraoch is better?

A: Pass the field down in the constructor. (Note: normally you should name fields starting with a lower case character and properties with uppercase). Here is an example where I fixed the naming.
public abstract class Converter
{
    private readonly MyData data;
    protected Converter(MyData data)
    {
       this.data = data;
    }

    public MyData Data { get { return data; } }
}

public class MyData
{
    private readonly int value;
    public MyData(int value)
    {
       this.value = value;
    }

    public int MyValue { get { return value; } }
}

public class Converter1 : Converter
{
   public Converter1()
      : base(new MyData(5))
   {
   }
}

I recommend the practice of using readonly fields and getters only for properties to start with. Doing so will make your types immutable which usually helps get your program correct initially. Start off immutable and then introduce mutability where you need it, and only once you need it. Having the types immutable like this requires passing the values through the constructor.


text:
Q: generator object  at 0x09778430 Сгенерировал список из предложений,но за место самих предложений выдает это:generator object  at 0x09778430.Что делать?

A: Я не знаю, как вы «сгенерировали» ваш «список» — может быть, что вы хотели использовать генератор списка, но вместо квадратных скобок вы применили круглые.
                  Помените их на квадратные.
Пример:
(i * i for i in some_list)         # генератор — вы это не хотите
^                        ^

[i * i for i in some_list]         # список
^                        ^

A: Можно обернуть генератор в list, а можно сгенерировать список из элементов генератора, если элементы ещё предстоит как-то модифицировать:
def modify(x):
    ...
    return modified_x

lst = [modify(x) for x in generator]

A: Примените цикл for для печати элементов вашего «списка» (который нет списком, а генератором).
for element in your_generator:
    print(element)

Цикл for принудит генератор постепенно генерировать все элементы.


text:
Q: Delimited Vertical Bar in SQL Table to another colum table I have table data textstring using separator '|'

I've tried using SSIS to export to excel file and import again using SSIS to remove "|" and add to each column. like this

But I was just wondering if any clue how to delimit to each column without export and import? Using query SQL?
Because my data rows more than 1000 I tried using this query.
 SELECT
     REVERSE(PARSENAME(REPLACE(REVERSE(DataTextRaw), ',', '.'), 1)) AS [Num]
   , REVERSE(PARSENAME(REPLACE(REVERSE(DataTextRaw), ',', '.'), 2)) AS [Index]
   , REVERSE(PARSENAME(REPLACE(REVERSE(DataTextRaw), ',', '.'), 3)) AS [Value]
FROM dbo.RAW;

but because my data rows more than 1000 I think this query not okay.

A: You can use string_split()
select s.*
from t cross apply
     (select max(case when seqnum = 1 then value end) as num,
             max(case when seqnum = 2 then value end) as index,
             max(case when seqnum = 3 then value end) as year,
             max(case when seqnum = 4 then value end) as curr,
             max(case when seqnum = 5 then value end) as val
      from (select s.value,
                   row_number() over (order by charindex('|' + s.value + '|', '|' + t.datatextraw + '|') as seqnum
            from string_split(t.datatextraw, '|') s
           ) s
      ) s;

Rumor has it that you can use order by (select null) instead of the strange charindex() expression because the latest versions of SQL Server return the values in order.  However, until the documentation changes, I won't recommend that approach.


text:
Q: Как программно нажать на кнопку confirm диалогового окна? Как программно нажать на кнопку confirm диалогового окна?
Я пробывал удалить , по не выходит в , не могу понять почему. Потому решил подумать может как-то можно программно нажать на кнопку диалогового окна.
input.eq(iinp).attr('onclick','myFunction()');
input.eq(iinp).prop('onclick',null);
input.eq(iinp).off('click');
$('html').unbind('click');
input.eq(iinp).removeAttr("onclick");

<input type="submit" name="fyy" value="конец" onclick="return confirm('Вы точно этого хотите?')" />

A: Вы не можете ни стилизовать, ни как либо воздействовать на системные окна с помощью javascript из браузера.
Вам необходимо самому реализовать подобное модальное окно или воспользоваться одним из готовых решений. Например, SweetAlert. Он поддерживает окна с подтверждениями.
Вот пример его работы (подробнее по ссылке выше):


text:
Q: odoo 14 how to get the user hardware information for health monitoring I need to get the internal user information hardware and software installed. Is this can be done with python through a browser then the user login or do I need to create a python app to send this information to odoo.
it is for IT help disk, so when the internal user creates a ticket I would have this info to help him/her.

A: The problem is not Odoo. The problem is a Browser cannot access to the hardware information.
Access Hardware Information from Web Browser
But you can write a script to execute on compute to send information in Odoo.
Help:
You can use Platform package to get information from computer.
And use Odoo External API to inject data in Odoo.


text:
Q: Отправка формы по api записать в JSON Angularjs У меня имеется api конкретного JSON файла в который я должен записать:
1. Имя пользователя
2. Его коммент
3. Страницу, с которой был отправлен коммент
Что я имею:
<form>

     <input type="text" class="form-control" placeholder="Имя">

      <textarea class="form-control" rows="4" placeholder="Ваш комментарий">
      </textarea>

      <button type="submit" class="SendFormBtn">Отправить</button>

</form>

Эта страница конролится контроллером (ссори) "DetailCtrl" который получает товар под определенным ID, что в принципе тоже нужно отправить в JSON, поскольку он-то формирует адрес страницы.
DetailCtrl:
velesApp.controller('DetailCtrl',['$scope','$http', '$location', '$routeParams', function($scope, $http, $location, $routeParams) {
  $scope.kitchenId = $routeParams.kitchenId;
  var url = '/api/v1/kitchens/'+$routeParams.kitchenId;
  $http.get(url).success(function(data, status, headers, config) {
  $scope.kitchen = data;
  });
  $http.get('/api/v1/kitchens').success(function(data, status, headers,    config) {$scope.kitchens = data;});
  $http.get('/api/v1/hits').success(function(data, status, headers, config) { $scope.offerdets = data; });
  }]);

Вот ссылка на JSON
(post) /api/v1/commentaries.json
Подскажите, как использовать метот POST, я с ангуляром знаком 1.5 недели.
З.Ы. мог бы попробовать прописать ng-model полям, но боюсь что я их еще неправильно понимаю


text:
Q: Using selectList in Persistent Haskell MongoDB to return json list I am working on a yesod app. I am trying to write a handler which simply queries a collection and returns all of the results.
In my config/models file the relevant entry is
Survey json
    name              String
    questions         [QuestionId]
    deriving (Show)

I am working on the following handler:
module Handler.ListSurveys where
import Import

getListSurveysR :: Handler Value
getListSurveysR = do
    res :: [Entity Survey]  <-  runDB $ selectList [] []
    return   $ object ["surveys" .= res]

This is leading to the following error:
Handler/ListSurveys.hs:6:41:
    Couldn't match type 'YesodPersistBackend App'
                   with 'mongoDB-2.0.7:Database.MongoDB.Query.MongoContext'
    Expected type: YesodDB App [Entity Survey]
      Actual type: ReaderT
                     mongoDB-2.0.7:Database.MongoDB.Query.MongoContext
                     (HandlerT App IO)
                     [Entity Survey]
    In the second argument of '($)', namely 'selectList [] []'
    In a stmt of a 'do' block:
      res :: [Entity Survey] <- runDB $ selectList [] []

I could really use some help as to understand what is going on with the types here (relatively inexperienced with Haskell) and how to fix this.


text:
Q: Solving $\int dx {\sqrt{x^2+a}} e^{-A x^2} erf \left( c(x-b) \right)$ I got as far as:
$$\int dx {\sqrt{x^2+a}} e^{-A x^2} erf \left( c(x-b) \right) $$
  $$=\frac{2}{\sqrt{\pi}} \int dx \int^{c(x-b)}_0 dy {\sqrt{x^2+a}} e^{-A x^2 - y^2}$$
  $$=\frac{-2 c}{\sqrt{\pi}} \int db \int dx {\sqrt{x^2+a}} e^{-A x^2 - c^2 (x-b)^2} $$
  $$=\frac{-2 c}{\sqrt{\pi}} \int db e^{-b^2 \left\{ c^2 + \frac{c^4}{A+c^2} \right\} } \int dx {\sqrt{x^2+a}} e^{ - \left(A+c^2 \right) \left( x-\frac{b c^2}{A+c^2} \right)^2} $$

A: Hint:
$\int\sqrt{x^2+a}e^{-Ax^2}\text{erf}(c(x-b))~dx$
$=\dfrac{2}{\sqrt\pi}\int\sum\limits_{n=0}^\infty\dfrac{(-1)^nc^{2n+1}(x-b)^{2n+1}\sqrt{x^2+a}e^{-Ax^2}}{n!(2n+1)}~dx$
$=\dfrac{2}{\sqrt\pi}\int\sum\limits_{n=0}^\infty\sum\limits_{k=0}^{2n+1}\dfrac{(-1)^{n-k+1}(2n)!b^{2n-k+1}c^{2n+1}x^k\sqrt{x^2+a}e^{-Ax^2}}{n!k!(2n-k+1)!}~dx$


text:
Q: Search date in database PHP When I was a start up student in PHP I made my database to store dates the date and time together, now I have a big problem, I have already in the database over 3000 orders but when I want to make a search with dates am I in big trouble because the dates and time is together in one field, I tried to make the query like where date LIKE '%$date' but I'm getting no results, has anybody any idea what I can do now?
And also how can I change the whole database it should be all dates and time separately and it should not effect my database?
UPDATE:
The data in the database looks like, 10/16/2012 5:00pm
Appreciate any help.

A: Why %$date? You should do the opposite.
WHERE date LIKE "".$date."%"

A: You can do the following:
$date = "2012-03-08";
$sql = "SELECT * FROM table WHERE date => '$date 00:00:00' AND date =< '$date 23:59:59'

Edit: Seeing your edit, this does not work anymore. You will need to convert your date column to a proper MySQL datetime or TIMESTAMP type.
At the current database design you could use something like this:
date
$date = "10/16/2012";
$sql = "SELECT * FROM table WHERE date LIKE '$date%'

time
$time = "5:00pm";
$sql = "SELECT * FROM table WHERE date LIKE '%$time'

A: In response to the sections of your question:
1. Finding the dates you need in the current schema.
Based on your edits, use:
 <?php

 $query = "SELECT * FROM table_name WHERE `date` LIKE '{$date}%'";

 ?>

A query similar to what you posted should help you:
<?php

$query = "SELECT * FROM table_name WHERE `date` LIKE '%{$date}%'";

?>

Please note that your use of % in your question ( '%$date' ) will only match values that end with $date, while the pattern in my example ( '%{$date}%' ) will match values that have $date anywhere in them.  Alternatively, you could use '{$date}%' to match date at the beginning of the value -- not sure which you want.

2. Updating your schema to split date and time into two columns.
The first step you should take here, is to add two columns ( date_only and time_only ) to your table.  Next, update your code to process and store this information in addition to the 'all-in-one' date column your are currently using; you don't want to break your current codebase by switching over in one step.  Once you can verify that date/time data is being written the way you want it to be, the third step is to read (and log) from the new date/time columns along with your production reads to date.  Once you can verify that the reads are working as planned, switch over your dev environment to read from the new columns and test until you are confident that everything works.

A: If it's a DATETIME field, you can use
WHERE DATE(datetime_field) = '01-01-2012';

or (better, as it can use indexes)
WHERE datetime_field >= '01-01-2012 00:00:00' AND datetime_field <= '01-01-2012 23:59:59';

A: this is what worked for me
$date = "2018-05-13";
"SELECT * FROM $username WHERE reg_date LIKE '%$date%'";


text:
Q: MySql - List with Count for an Specific Field How can i count while listing for an specific field?
For my example (on the image), the intended result for COUNT_ROWS should be:
/App/RaspLot - 2;
/App/RaspLot - 2;
/Home/ePortal_Options - 2;
/Home/ePortal_Options - 2;
/Home/ePortal_Logout - 1;

Current Result on Image Below:

I'm Trying:
SELECT T.`MAIN_PATH`, A.`SUB_PATH`, T.`COUNT_ROWS`
FROM `SIDENAV` A
INNER JOIN (
    SELECT `MAIN_PATH`,  COUNT(DISTINCT `MAIN_PATH`) AS `COUNT_ROWS`
    FROM `SIDENAV`
    GROUP BY `MAIN_PATH`
) T ON A.`MAIN_PATH` = T.`MAIN_PATH`
ORDER BY `ORDER_1`, `MAIN_NAME`, `ORDER_2` ASC

A: It really looks like you just want aggregation:
select main_path, count(*) as count_rows
from sidenav
group by main_path
order by count_rows desc, main_path

If you want the count on each row, you can use window functions:
select s.*, count(*) over(partition by main_path) as count_rows
from sidenav s

This requires MySQL 8.0. In earlier versions, you can perform the window count with a subquery:
select s.*,
    (select count(*) from sidenav s1 where s1.main_path = s.main_path) as count_rows
from sidenav s


text:
Q: Extracting individual columns in column_list transformations to spark ml label, features format sc.version => u'2.2.0'
I'm experiencing challenges with extracting individual columns of RDD data to construct spark ML pipeline. I first read in the data. Used struct function to combine the columns before grouping by "A".Subsequently, I applied collect_list. However, I'm stuck at converting it to spark ml label, features format like so:
df = sc.createDataFrame(input_data, ["label", "features"])

Below was the initial table:
import pyspark
from pyspark import SparkContext
from pyspark import Row
from pyspark.sql import SQLContext
from pyspark.sql import functions as F

_c0|             A|     B|    C|     D|     E|       F|     G|     H|     I|       J|
+---+--------------+------+-----+------+------+--------+------+------+------+--------+
|  0|50009100010000|-999.0| 90.0|-999.0|-999.0|264.7466|-999.0|-999.0|-999.0|  -999.0|
|  1|50009100010000|-999.0| 90.5|-999.0|-999.0|258.5411|-999.0|-999.0|-999.0|  -999.0|
|  2|50009100010000|-999.0| 91.0|-999.0|-999.0|252.3356|-999.0|-999.0|-999.0|  -999.0|
|  3|50009100010000|-999.0| 91.5|-999.0|-999.0|246.1301|-999.0|-999.0|-999.0|  -999.0|
|  4|50009100010000|-999.0| 92.0|-999.0|-999.0|239.9246|-999.0|-999.0|-999.0| 39.8812|

Joining the columns before grouping the data by A:
df_next = df.select("A", F.struct(["B","C","D","E","F","G","H","I","J"]).alias("allcol"))
df_next.show(5)

+--------------+--------------------+
|             A|              allcol|
+--------------+--------------------+
|50009100010000|[-999.0,90.0,-999...|
|50009100010000|[-999.0,90.5,-999...|
|50009100010000|[-999.0,91.0,-999...|
|50009100010000|[-999.0,91.5,-999...|
|50009100010000|[-999.0,92.0,-999...|

Grouping by A and collecting the columns in the nested list:
df_next_list = df_next.groupBy("A").agg(F.collect_list("allcol").alias("collected_cols"))

 +--------------+--------------------+
|             A|      collected_cols|
+--------------+--------------------+
|50009100090000|[[-999.0,210.0,-9...|
|50009100070000|[[-999.0,1110.0,-...|
|50009100170000|[[10.14438,303.0,...|
|50283200140000|[[9.8958,36.0,-99...|
|50009100040000|[[-999.0,290.5,-9...|
+--------------+--------------------+

This is how calling df_next_list.rdd.take(n) looks like:
Row(A=50009100090000, collected_cols=[Row(B=-999.0, C=210.0, D=-999.0, E=-999.0, F=16.016660690307617, G=-999.0, H=7.6022491455078125, I=-999.0, J=30.627119064331055), Row(B=-999.0, C=210.5, D=-999.0, E=-999.0, F=18.973539352416992, G=-999.0, H=15.784810066223145, I=-999.0, J=29.249160766601562......)])]

From here onwards, I got stuck with extracting the right element grouped by Column A for each variable (BCDEFGHIJ) in the collected_cols list and converting the df_next_list to Spark ML form of label (J) and features (B,C,D,E,F,G,H,I). With that, I can construct the Spark ML algorithm. This is how I would like the rdd to look like which makes it easy to extract the elements:
Row(A=50009100090000, B=-999.0, C=210.0, D=-999.0, E=-999.0, F=264.7466125488281, G=-999.0, H=-999.0, I=-999.0, J=-999.0),....

Any help will be immensely appreciated. Thanks


text:
Q: why this property doesn't want to be deleated Wrote this code only for experimental purpose. here i used Object.defineProperty to create a property called 'fullName' and using set i defined another property to person called middleName . I have to pass value to middleName through fullName.Both of them has enumerable property TRUE,so that for..in loop can access it.But then i wanted to delete the middleName property from the object.But it is still there.Why it is still there??

(function(){
  person = {
    firstName: 'will',
    lastName: 'Smith'
  };

  Object.defineProperty(person,'fullName',{

    set:function(mid){
      Object.defineProperty(person,'middleName',{
        value     : mid,
        enumerable: true,
        writeable : false
      });
    },
    get:function(){
      document.write(this.middleName);
    },
    enumerable:true
  });

  person.fullName='lol';
  person.fullName;
  document.write(Object.getOwnPropertyNames(person)+'
');

  for(key in person){
    document.write(key+'
');
  }

  document.write('\n');
  delete (person.middleName);
  document.write(person.middleName+'
');

  for(key in person){
    document.write(key+'
');
  }
})()

A: When using Object.defineProperty, the configurable attribute is set to false by default (see ToPropertyDescriptor, step 4) so the middleName property is not deletable.
Note that in:
delete (person.middleName);

the parenthesis are redundant, it should be written:
delete person.middleName;

A simple example is:
// Create object o
var o = {};

// Define property a with value bar
Object.defineProperty(o, 'a', {
  value : 'bar'
});

console.log(o.a); // bar

// Since the configurable property of a was not set, it defaults to false
// so it can't be deleted
delete o.a;

console.log(o.a); // bar

// Create property b with value fum and configurable true
Object.defineProperty(o, 'b', {
  value : 'fum',
  configurable: true
});

console.log(o.b); // fum

// Since b's configurable attribute is true, it can be deleted
delete o.b;

console.log(o.hasOwnProperty('b')); // false
console.log(o.b); // undefined


text:
Q: How to retrieve this data from firebase database
I want to get to a listview the data on "Categorias" folder, but i try everthing and i can't do this.
Fragment code:
myRef.addValueEventListener(new ValueEventListener() {

            public static final String TAG = "TNW";
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.

                Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();

                list3 values = td.values();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getActivity().getApplicationContext(), "Ese usuario ya existe ", Toast.LENGTH_SHORT).show();
            }

        });

A: Its very simple, here is the code to fetch your values.
    DatabaseReference db = FirebaseDatabase.getInstance().getReference("people");

    db.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for(DataSnapshot ds: dataSnapshot.getChildren()){

                //get the categorias node
                DataSnapshot dsCategorias = ds.child("categorias");

                //loop inside the categorias node for all children
                for(DataSnapshot dbValSnapshot: dsCategorias.getChildren()){

                    //Assuming all children have only boolean values

                    //getting the key and the values
                    String key = dbValSnapshot.getKey();
                    boolean value = dbValSnapshot.getValue(Boolean.class);
                }

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Let me know if you are not able to understand any part of my code. Thanks


text:
Q: Email Domain Too Long Hi Just wanna how to make the email shorter in email services please help for this thank you

A: The email address is defined by Salesforce and you cannot modify it.
Maybe you have a bit of an X-Y Problem?

A: You can create a shorter alias in a variety of ways, including Google Groups. See the Add members to your Group section of this groups help document:

Add members to your Group
You can directly add up to 10 people to your Group at once. Only 25 people can be directly added to a Group.

*

*Sign in to Google Groups.

*Click My Groups.

*Choose a group.

*Near the top right, click Manage.

*On the left, click Members and then Direct add members.

*Enter the email addresses of the people to add.

*Enter a welcome message.

*Set how members will get email from the group.

*Click Add.

So copy that long email address and add it to the group as a member. Now every time someone sends an email to yourShortAlias@gmail.com it will forward the message on to your email service.


text:
Q: Upload image to node/express and then s3 I am writing a redux-form which updates user information to a database, the user information includes a profile picture of the user.
I want to upload the profile picture to s3 and update the s3 url link of the picture into the database.
This is the flow:

*

*web reactjs client sends user information including image to node/express,

*nodejs uploads the image to s3 and retrieves the URL

*nodejs updates user infomation and URL into mongodb

I am relatively new when it comes to forms and images and after looking through multiple examples of redux-form, react-s3-uploader, react-dropzone etc. I am yet unable to figure how the image reaches node/express from reactjs.
Most of the examples, just falls short of explaining how the image is sent to the server, maybe it is something very simple.
Can someone help me with some example client react code and server nodejs code(express), so I get some direction on this.
I have seen examples (react-s3-uploader) of uploading the image from the browser directly to S3, but I want to send it to my server, retrieve the image URL and update the URL in a mongo database.


text:
Q: How to decrypt pgp armored string using PGPy when the armored string isn't from PGPy? I'm creating a script that communicates with a server that is using PGP encryption to encrypt it's responses.
I can request the public key of the server, and use that key to encrypt my request via the PGPy library, and the server is able to decrypt it and respond.
The scripts encrypted request has it's public key in it, which the server is expecting as a part of it's API, so it takes that key and encrypts the response and sends it back to my script. My script receives this encrypted response fine, but PGPy appears to lack the facilities to decrypt it.
From what I can tell, PGPy can only decrypt a message that it encrypted because the the PGPKey.decrypt() takes a PGPMessage object, not an armored string, and I cannot find any method that takes an armored string and either decrypts it or turns it into a PGPMessage so that I can decrypt it.
This is as far as I've gotten:
def get_token_from_payload(encrypted_payload):
    print("Payload: ", encrypted_payload)
    privkey, _ = pgpy.PGPKey.from_file('private.key')
    message_blob = pgpy.PGPMessage.new(encrypted_payload)
    token_string = privkey.decrypt(message_blob).message
    print("Token: ", token_string)
    return json.load(token_string)

The message_blob = pgpy.PGPMessage.new(encrypted_payload) that I thought would do the right thing, doesn't, and instead makes it's own encrypted text blob that the line token_string = privkey.decrypt(message_blob).message simply turns back into the armored ascii string I started with. Of course the last line fails because there is no json to do anything with so we'll ignore that for right now as that should work just fine once PGPy is decrypting things.
I must be missing something. This library is essentially useless if it can't do this. How do I either decrypt the armored string or convert the armored string into a PGPMessage that can then be decrypted?
Update:
def get_token_from_payload(encrypted_payload):
    ep_file = open("ep.pgp", "w")
    ep_file.write(encrypted_payload)
    ep_file.close()
    privkey, _ = pgpy.PGPKey.from_file('private.key')
    message = pgpy.PGPMessage.from_file("ep.pgp")
    token_string = privkey.decrypt(message).message
    return json.loads(token_string)

This solution does work, but I don't find it acceptable as it requires an extraneous set of IO steps, creating a file and then reading it right back in. I already have the armored ascii message in memory, I just want to decrypt it directly.

A: You should be able to create a PGPMessage object from the ascii armored string in memory by using pgpy.PGPMessage.from_blob()
def get_token_from_payload(encrypted_payload):
  print("Payload: ", encrypted_payload)
  privkey, _ = pgpy.PGPKey.from_file('private.key')
  message_blob = pgpy.PGPMessage.from_blob(encrypted_payload)
  token = privkey.decrypt(message_blob).message
  print("Token: ", token)
  return json.load(token)

You might also need to convert the token value from a bytearray to a string. Something like this should work:
  token_string = str(token, 'UTF-8')
  print("Token: ", token_string)
  return json.load(token_string)


text:
Q: CustomView don't show in design mode I have a CustomView extend from RelativeLayout.
I Use this CustomView in layout file but Android Studio in design mode not showing the CustomView. what is problem?
koala_appbar.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_gravity="top"
    tools:context=".activity.basic.BaseActivity">

    <ImageView
        android:id="@+id/appbar_imgLogo"
        android:layout_width="@dimen/appBar_iconWidth"
        android:layout_height="@dimen/appBar_iconHeight"
        android:src="@drawable/logo"
        android:layout_marginTop="@dimen/appBar_iconTopMargin"
        android:layout_marginLeft="@dimen/appBar_iconLeftMargin"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/appbar_height"
        android:orientation="horizontal"
        android:layoutDirection="ltr"
        >

        <koala.android.customer.views.widget.CustomTextView
            android:id="@+id/appBar_txtTitle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center|right"
            android:text="@string/app_name_persian"
            android:textColor="@color/colorPrimary"
            android:textSize="@dimen/TextSize_large"
            app:tvCustomFont="@string/baseFont"
            />

        <koala.android.customer.views.widget.CustomImageView
            android:id="@+id/appBar_imgBack"
            android:layout_width="@dimen/appbar_height"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/ic_arrow_right"
            app:ivDrawableTint="@color/colorPrimary"
            android:padding="@dimen/appBar_backPadding"
            />

    </LinearLayout>

</RelativeLayout>

KoalaAppBar.java:
public class KoalaAppBar extends RelativeLayout {

    private static final String DEFAULT_TITLE = "default";

    private static final int DEFAULT_TITLE_COLOR = ResourcesCompat.getColor(AppController.getContext().getResources(), R.color.colorPrimary , null);

    private static final float DEFAULT_TITLE_FONT_SIZE = AppController.getContext().getResources().getDimension(R.dimen.TextSize_small);

    protected CustomTextView txtTitle;

    protected CustomImageView imgBack;

    protected ImageView imgLogo;

    public KoalaAppBar(Context context) {
        super(context);
        init(context , null);
    }

    public KoalaAppBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context , attrs);
    }

    public KoalaAppBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context , attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public KoalaAppBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        if(context != null){
            findViews(context);
        }

        if(attrs != null){
            initAttribute(context,attrs);
        }
    }

    private void initAttribute(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.KoalaAppBar);

        String title = a.getString(R.styleable.KoalaAppBar_appTitle);

        if(title == null || title.isEmpty()){
            title = DEFAULT_TITLE;
        }

        int titleColor = a.getColor(R.styleable.KoalaAppBar_appTitleColor, DEFAULT_TITLE_COLOR);

        float fontSize = a.getDimension(R.styleable.KoalaAppBar_appTitleFontSize, DEFAULT_TITLE_FONT_SIZE);

        boolean logoVisibility = a.getBoolean(R.styleable.KoalaAppBar_appLogoVisibility , true);

        initTitle(title , titleColor , fontSize);

        initLogo(logoVisibility);

        a.recycle();
    }

    private void initLogo(boolean logoVisibility) {
        if(logoVisibility){
            this.imgLogo.setVisibility(VISIBLE);
        }else{
            this.imgLogo.setVisibility(GONE);
        }
    }

    private void initTitle(String title, int titleColor, float fontSize) {
        this.txtTitle.setText(title);
        this.txtTitle.setTextColor(titleColor);
        this.txtTitle.setTextSize(fontSize);
    }

    private void findViews(Context context) {
        View rootView =
                LayoutInflater.from(context).inflate(
                        R.layout.koala_appbar,
                        this,
                        true
                );

        this.txtTitle   = rootView.findViewById(R.id.appBar_txtTitle);

        this.imgBack    = rootView.findViewById(R.id.appBar_imgBack);

        this.imgLogo = rootView.findViewById(R.id.appbar_imgLogo);
    }

}


text:
Q: extracting files from request I'm using ASP.net MVC 5.
The code below works to store files, but I need to store the request or extract the files uploaded from the request so I can pass the file to a method in another class for validation BEFORE I upload to the file server.
I noticed below that Request.Files[upload].SaveAs contains the files, but how do I pass the file to another class? I tried passing the HttpPostedFileBase File to another class, but it doesn't recognize Files.
In my view:
 @using (Html.BeginForm("FileUpload",
                          "Upload",
                          FormMethod.Post,
                          new { enctype = "multipart/form-data" }))

  { Upload Image:
         <input type="file" name="FileUpload" />

         <input type="submit" name="Submit" id="Submit" value="Upload" />

 }

My Controller:
 public ActionResult FileUpload(HttpPostedFileBase file)
    {
        //HttpPostedFileBase request = file;
        foreach (string upload in Request.Files)
        {

          System.Diagnostics.Debug.WriteLine("*********************savepath:" + Request.Files[upload].FileName+"********************");

            string savePath = "C:\desktop";
            string newPathForFile = Path.Combine(savePath, Path.GetFileName(Request.Files[upload].FileName));
            Request.Files[upload].SaveAs(Path.Combine(savePath, newPathForFile));
        }

        return View("Home");
    }

A: You can't really pass the "file," since at this point there really isn't a file.  We're really looking at a bunch of bytes. Your Request.Files should also have an InputStream.  Use that to copy the file to a Byte[] buffer, and go from there.


text:
Q: How to get UIButton Target, Action and Control events? I am using UIImageView's with UIButtons a whole bunch.  So, I created a custom class to permanently marry these two an make things a little simpler.  It all works well until I decided to implement -(id)initWithObject:(AUIImageViewButton *) imageViewButton.
Clearly I need to copy all relevant properties from the imageViewButton object being passed. The UIImageView is not problematic at all.  Something like this deals with it:
imageview = [[UIImageView alloc] initWithFrame:imageViewButton.imageview.frame];        // Copy all relevant data from the source's imageview
[imagebutton.imageview setBackgroundColor:imageViewButton.imageview.backgroundColor];   //
[imagebutton.imageview setImage:imageViewButton.imageview.image];                       //

Most of the button stuff is also readily available:
button = [UIButton buttonWithType:imageViewButton.button.buttonType];                   // Copy all relevant data from the source's button
button.frame = imageViewButton.imageview.frame;                                         //
[button setTitle:imageViewButton.button.titleLabel.text forState:UIControlStateNormal]; //
button.tag = imageViewButton.button.tag;                                                //

I am having a little trouble figuring out how to get all the data for the addTarget:action:forControlEvents method.
Looking at the docs I can see that I might be able to use UIControl's allControlEvents and allTargets methods.  I'll dig into that right now and see how much trouble I can get into.  The one I am not sure about is the action.
Can anyone give me a shove in the right direction?
Thanks,
-Martin

A: UIControl's allTargets and allControlEvents are the way to start. The final piece of the puzzle is actionsForTarget:forControlEvent:, call it once for each target and event.

A: Showing how to iterate over a button's targets and create copies of the selector on another button. Specific example is just the touchupinside event, but that's usually all I use.
for (id target in button.allTargets) {
     NSArray *actions = [button actionsForTarget:target
                                      forControlEvent:UIControlEventTouchUpInside];
     for (NSString *action in actions) {
          [newButton addTarget:target action:NSSelectorFromString(action) forControlEvents:UIControlEventTouchUpInside];
     }
}

A: I used this to remove any possible unwanted target/action before assigning a new one:
if let action = button.actions(forTarget: target, forControlEvent: .touchUpInside)?.first
{
    button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
}

or if you really want to remove all actions:
if let actions = button.actions(forTarget: target, forControlEvent: .touchUpInside)
{
    for action in actions
    {
        button.removeTarget(target, action: NSSelectorFromString(action), for: .touchUpInside)
    }
}


text:
Q: Php does not store dynamically added extra input fields data i had following html code for add more input fields to my form, but when i submit form database does not store extra fields data, i got only first field data.
HTML

Add Another Input Box

        <input type="text" id="p_scnt" size="20" name="course_article[article_title]" value="" placeholder="Input Value" />

SCRIPT

PHP
    if (isset($this->request->post['course_article'])) {
                $this->data['course_articles'] = $this->request->post['course_article'];
            } else {
                $this->data['course_articles'] = '';
            }

**Store to databse**
if (isset($data['course_article'])) {
            foreach ($data['course_article'] as $course_article) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "course_article SET course_id = '" . (int)$course_id . "', article_title = '" . $this->db->escape($course_article['article_title']) . "'");
            }
        }

i don't know what goes error here, any help.?
thanks

A: Both in HTML and js add a [] in name like this name="course_article[article_title]" should be name="course_article[article_title][]"

A: When you add an input field to the form, you add a number to the name attribute, like so:
name="course_article[article_title]2"

This is invalid,
Try posting the fields as an array:
 name="course_article[article_title][]"

As you post, you can use this in your PHP:
 foreach($_POST['article_title'] as $article){
     //Do something with each title
 }


text:
Q: Okta Auth  Component seems to have a problem with reach-router Here is the error that I get once I run the application.
ERROR in ./node_modules/@okta/okta-react/bundles/okta-react.esm.js 284:14-27
export 'useRouteMatch' (imported as 'useRouteMatch') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)
Here is what my code looks like in my Index.tsx file.
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "mdb-react-ui-kit/dist/css/mdb.min.css";

import { Security } from "@okta/okta-react";
import { OktaAuth } from "@okta/okta-auth-js";

const config = {
  clientId: "*********************",
  issuer: "https://****************/oauth2/default",
  redirectUri: "http://localhost:3000/login/callback",
  scopes: ["openid", "profile", "email"],
  pkce: true,
};

const oktaAuth = new OktaAuth(config);

const restoreOriginalUri = () => {
  // Callback function to restore URI during login
};

ReactDOM.render(
  <React.StrictMode>
    <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
      <App />
    </Security>
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more:
reportWebVitals();

A: I will go on a hunch and assume that you use newer react-router version than v5.
As per https://github.com/okta/okta-react/issues/187
@okta/okta-react currently only supports react-router v5. We are currently investigating v6 support


text:
Q: JSONexception in never thrown in the corresponding Hi in the app that I build, it show me this error, in the (JSONException e), What i may be?

exception 'org.json.JSONexception' in never thrown in the corresponding

public void fetchData(final DataCallback callback) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());

                        try {
                            callback.onSuccess(response);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(jsonObjectRequest);
    }

A: It means in your try catch there is no possibilty for that execption to occur. You don't need try catch for that line
 public void fetchData(final DataCallback callback) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                        callback.onSuccess(response);

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

    AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}


text:
Q: Cómo validar que la entrada es numérica Estoy realizando un ejercicio en el que tengo que leer un número, pero el ejercicio me prohíbe usar el tipo int. ¿Cómo hago que mi programa solo acepte un número sin usar int?
Éste es el código que tengo hasta el momento:
Console.WriteLine("Escoge un ataque para tu monstruo: ");
string a = Console.ReadLine();
short decision = Convert.ToInt16(a);
try
{

}
catch (Exception)
{
  Console.WriteLine("Solo ingresa números por favor!");
}

A: Deberías usar Regex si se te permite, con esto puedes hacer que compruebe si el string dado está formado por números únicamente. Ejemplo:
Console.WriteLine("Escoge un ataque para tu monstruo: ");
string a = Console.ReadLine();

Regex regex = new Regex("[^0-9]+");

if (regex.IsMatch(a))
{
    //es un número
}
else
{
Console.WriteLine("Solo ingresa números por favor!");
}

A: También podes usar
tuString.All(char.IsDigit);

Va a retornar true si en la variable tuString hay un número entero (en caso de tener coma/punto será falso)
Para usar este método tenes que tener en cuenta 2 situaciones.

*

*Si tuString es null se producirá un ArgumentNullException

*Si tuString es una cadena vacía, retornará true

Respuesta basada en la de Kunal Goel en StackOverflow en inglés

A: Entiendo que es algún tipo de trabajo escolar y de ahí la restricción de no usar int.
Una posible solución es usar el ascii de la entrada para comprobar que los caracteres son numéricos. Todo aquel caracter que sea menor que 0 o mayor que 9 no es un dígito, y hace que el bucle se repita.
bool valido;
do
{
    valido = true;
    Console.WriteLine("Escoge un ataque para tu monstruo: ");
    string entrada = Console.ReadLine();

    foreach (char c in entrada)
    {
        if (c < '0' || c > '9')
        {
            valido = false;
            break;
        }
    }
    if (!valido)
        Console.WriteLine("Solo ingresa números por favor!");
} while (!valido);

A: Tal vez este código te sirva:
Console.WriteLine("Escoge un ataque para tu monstruo: ");
string a = Console.ReadLine();
int num;
if (int.TryParse(a, out num))
{
    Console.WriteLine("El número ingresado es {0}", num);
}
else
{
    Console.WriteLine("Solo ingresa números por favor!");
}


text:
Q: Get products which are back in stock in Magento How to get products which are back in stock i.e whose quantity is changed from 0 in Magento recently?

A: Open Admin > go to catalog> Manage Product > Select multiple product that have 0 qty > Select UPdate attribute (left to submit button) > Submit > Product Information > Inventory > Change Qty > save.


text:
Q: apache down aftertry to open Magento admin page I try to open magento admin page but my apache is restart twice and down on second restart.
after try to open magentosite/admin my apache error log show me

13:19:23.826733AH00428: Parent: child process exited with status 255
  -- Restarting.

and start then finish at this line.

13:19:27.383539 AH00354: Child: Starting 64 worker threads.

and 3 sec after restart complete apache try to restart again and stop log on this line below

13:19:30.097944 AH00428: Parent: child process exited with status 255
  -- Restarting.

this second restart is not restart apache but apache is down until i go to push start service again.
Thank you for your help.


text:
Q: Chartingtoolkit ColumnSeries Binding Problems I try to Bind this KeyValuePair to a ColumnSeries chart:
private KeyValuePair<string, double> _totalProfit;

public KeyValuePair<string, double> TotalProfit
{
    get { return _totalProfit; }
    set
    {
        _totalProfit = value;
        OnPropertyChanged("TotalProfit");
    }
}

In my code I fill it with a KeyValuePair:
TotalProfit = new KeyValuePair<string, double>("Total", 200.00);

When I debug this code, everything works fine. Total profit gets the string and double I want it to have, but the ColumnSeries does not display the value of this KeyValuePair. What am I doing wrong.
Here´s the XAML:
<TabItem Header="Profit">
    <chartingToolkit:Chart>
        <chartingToolkit:ColumnSeries DependentValuePath="Value" IndependentValuePath="Key" ItemsSource="{Binding TotalProfit}"/>
    </chartingToolkit:Chart>
</TabItem>

What I want to have is something like that:

A: The problem is, that the ColumnSeries needs a ObservableCollection with KeyValuePairs to display them. It´s seems to be impossible to display only one KeyValuePair itself.


text:
Q: How to get Header value of MenuItem from custom Binding? I have defined RoutedCommand in my class and in XAML
Public Shared CustomCommandShowAll As New RoutedCommand

Public Shared CustomCommandFirstPage As New RoutedCommand

Public Shared CustomCommandSecondPage As New RoutedCommand

<Window.CommandBindings>
        <CommandBinding Command="local:DynamicTab.CustomCommandShowAll" Executed="ShowAll_Executed" />
        <CommandBinding Command="local:DynamicTab.CustomCommandFirstPage" Executed="FirstPage_Executed" />
        <CommandBinding Command="local:DynamicTab.CustomCommandSecondPage" Executed="Secondpage_Executed" />
    </Window.CommandBindings>

    <Window.InputBindings>
        <KeyBinding Command="local:DynamicTab.CustomCommandShowAll" Key="F1" Modifiers="Alt"/>
        <KeyBinding Command="local:DynamicTab.CustomCommandFirstPage" Key="F2" Modifiers="Alt"/>
        <KeyBinding Command="local:DynamicTab.CustomCommandSecondPage" Key="F3" Modifiers="Alt"/>
    </Window.InputBindings>

These bindings are hooked up by Menuitems
<Menu DockPanel.Dock="Top" >

                <MenuItem x:Name="filtermenu" Header="_FilterType" BorderBrush="White" >

                    <MenuItem Header="ShowAll" IsChecked="True" InputGestureText="Alt+F1"/>

                    <MenuItem Header="FirstPage" InputGestureText="Alt+F2"/>

                    <MenuItem Header="Secondpage" InputGestureText="Alt+F3"/>
                </MenuItem>
            </Menu>

Now, when i press ALT+F1 , ShowAll_Executed Method will get a call and here i have two Parameters ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs
    Private Sub ShowAll_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs)

End Sub

I don know how to get the ShowAll *MenuItem Header Name* from these two parameters, if i get the value, i can use only one RoutedCommand for all three MenuItems. Thanks in advance.