text:
Q: Resume not compiling due to extra alignment tab I'm a new LaTeX user and am currently using a template on ShareLatex to create my resume. I changed some things and now im having compilation errors. The compiler should be XeLaTeX
\documentclass[a4paper,10pt]{article}

%A Few Useful Packages
\usepackage{marvosym}
\usepackage{fontspec}
%for loading fonts
\usepackage{xunicode,xltxtra,url,parskip}   %other packages for formatting
\RequirePackage{color,graphicx}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[big]{layaureo}              %better formatting of the A4 page
% an alternative to Layaureo can be ** \usepackage{fullpage} **
\usepackage{supertabular}               %for Grades
\usepackage{titlesec}                   %custom \section

%Setup hyperref package, and colours for links
\usepackage{hyperref}
\definecolor{linkcolour}{rgb}{0,0.2,0.6}
\hypersetup{colorlinks,breaklinks,urlcolor=linkcolour, linkcolor=linkcolour}

%FONTS
\defaultfontfeatures{Mapping=tex-text}
%\setmainfont[SmallCapsFont = Fontin SmallCaps]{Fontin}
%%% modified for Karol Kozioł for ShareLaTeX use

%CV Sections inspired by:
%http://stefano.italians.nl/archives/26
\titleformat{\section}{\Large\scshape\raggedright}{}{0em}{}[\titlerule]
\titlespacing{\section}{0pt}{3pt}{3pt}
%Tweak a bit the top margin
%\addtolength{\voffset}{-1.3cm}

%Italian hyphenation for the word: ''corporations''
\hyphenation{im-pre-se}

%-------------WATERMARK TEST [**not part of a CV**]---------------
\usepackage[absolute]{textpos}

\setlength{\TPHorizModule}{30mm}
\setlength{\TPVertModule}{\TPHorizModule}
\textblockorigin{2mm}{0.65\paperheight}
\setlength{\parindent}{0pt}

%--------------------BEGIN DOCUMENT----------------------
\begin{document}

%WATERMARK TEST [**not part of a CV**]---------------
%\font\wm=''Baskerville:color=787878'' at 8pt
%\font\wmweb=''Baskerville:color=FF1493'' at 8pt
%{\wm
%   \begin{textblock}{1}(0,0)
%       \rotatebox{-90}{\parbox{500mm}{
%           Typeset by Alessandro Plasmati with \XeTeX\  \today\ for
%           {\wmweb \href{http://www.aleplasmati.comuv.com}{aleplasmati.comuv.com}}
%       }
%   }
%   \end{textblock}
%}

\pagestyle{empty} % non-numbered pages

\font\fb=''[cmr10]'' %for use with \LaTeX command
\section{Work Experience}
\begin{tabular}{r|p{11cm}}
 Current & Lab Consultant at x University\\Sep. 2016 &
\footnotesize{Ensured printers were all working and were filled.
Ensured labs were clean.
Provided technical assistance to students, and faculty when needed.}\\\multicolumn{2}{c}{} \\
 \textsc{Sep. 20xx-Aug. 20xx} & Teaching Assistant at x\\&
\footnotesize{Helped students who were having trouble with the subject matter.
 Ensured that all students were focused on their work. Ensured that students got the correct work.
 Ensured all work was returned to students in a timely manner.}\\\multicolumn{2}{c}{} \\
\end{tabular}

\section{Education}
\begin{tabular}{r|}
\textsc{Jun. 20xx-Apr. 20xx} & x Program\\&
\footnotesize{Studied logic, mathematical proofs, induction, graph theory, probability,
combinatorics and discrete mathematics. Also studied sorting algorithms, divide and conquer algorithms,
greedy algorithms, dynamic programming, network flows and NP completeness.}\\\multicolumn{2}{c}{} \\
\textsc{Sep. 20xx-Jun. 20xx} & High School\\&
\footnotesize{x Cum Laude | GPA: x.0/4 }\\\multicolumn{2}{c}{} \\
\end{tabular}
\end{document}

A: Well,  you missend an second parameter r (or l or c) in your second table.
Just add r to the line (or in your case better p{11cm}):
\begin{tabular}{r|}

to get
\begin{tabular}{r|p{11cm}}

Complete MWE ( a little bit pretty printed)
\documentclass{article}
\begin{document}

\begin{tabular}{r|p{11cm}}
Current   & Lab Consultant at x University\\
Sep. 2016 & \footnotesize{Ensured printers were all working and were filled.
            Ensured labs were clean. Provided technical assistance to
            students, and faculty when needed.}\\
\multicolumn{2}{c}{} \\
\textsc{Sep. 20xx-Aug. 20xx} & Teaching Assistant at x\\
          & \footnotesize{Helped students who were having trouble with
            the subject matter.  Ensured that all students were focused
            on their work. Ensured that students got the correct work.
            Ensured all work was returned to students in a timely manner.}\\
\multicolumn{2}{c}{} \\
\end{tabular}

\section{Education}
%\begin{tabular}{r|}
\begin{tabular}{r|p{11cm}} % <================================================
\textsc{Jun. 20xx-Apr. 20xx} & x Program\\
         & \footnotesize{Studied logic, mathematical proofs, induction,
           graph theory, probability, combinatorics and discrete
           mathematics. Also studied sorting algorithms, divide and
           conquer algorithms, greedy algorithms, dynamic programming,
          network flows and NP completeness.}\\
\multicolumn{2}{c}{} \\
\textsc{Sep. 20xx-Jun. 20xx} & High School\\
         & \footnotesize{x Cum Laude | GPA: x.0/4 }\\
\multicolumn{2}{c}{} \\
\end{tabular}
\end{document}

results in the pdf:


text:
Q: Должен ли программист/разработчик напрямую общаться с заказчиком Меня мучает один вопрос: должен ли программист/разработчик общаться напрямую с клиентами/заказчиками если для этого в структуре организации предусмотрены менеджеры?
Меня иногда просят позвонить клиенту и уточнить как он видит тот или иной функционал, а мне, честно, не очень-то хочется этого делать, особенно когда приходится играть в игру "что хочет заказчик".
Может быть, в силу возраста и небольшого опыта, я чего-то не понимаю в этой жизни, поэтому прошу высказаться по существу.
P.S. Не интроверт.

A: Общение с заказчиком - штука мерзкая. Но если умеешь - то без куска масла не останешься - фриланс всегда выручит. А вот если работаешь в конторе или сам себе содержишь менеджера\посредника для этих целей - то общение с заказчиком напрямую не только не нужно, но еще и конкретно может навредить проекту.
A: Ничего зазорного в этом нет. Менеджер не всегда может понять определенные технические моменты и ему приходится жевать сопли. И начальник, чтобы не терять клиента и авторитетность поручает это разработчику.
Если разработчик этим проектом не занимается, и ему поручают обсудить с заказчиком те или инные вопрос, то соответственно разработчик не должен общаться с заказчиком.
A: Если Вы участвуете в разработке ТЗ или проекта, то однозначно, надо общаться. И с боссом и (это важнее всего) с людьми, которые непосредственно будут использовать Ваш продукт.
Именно в рамках такого общения возникает понимание, что именно (на деле, а не в словах ТЗ) нужно реализовать.
А вот финансовую сторону вопроса решают манагеры (собственно программистов  к внутреностям этих дел обычно не подпускают).
A: Если менеджер не может справиться, т.е. жует сопли, как выше сказали, то это плохой менеджер, а программисту надо доплачивать за такие дела... Если пишется под конкретного заказчика ПО, то лучше работать напрямую с заказчиками. При общении выпытывать у них все малейшие тонкости, которые приходят в голову, делать поведенческую логику ПО, и естественно все это записывать. Когда настанет момент сдачи проекта, записи могут пригодиться :)
У меня часто, при разговоре с заказчиками выходит, что заказчик не понимает своих желаний полностью, что вызывает небольшой ступор в разработке :( .
A: Мы - программисти создаем продукты, и очень часто на заказ, то есть мы должны по максимуму создать то что нам заказано, а не то что мы представили (как поняли проект). Следовательно чем теснее общение с заказчиком, тем больше вероятность того что мы произведем именно то что от нас и требовалось.
А по себе скажу что это довольно облегчает жизнь, так как не приходится гадать хотел заказчик именно этого или нет, просто спрашиваеш и реализовываеш. Идеального ТЗ нет и не может быть.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to scrap phobos website using open url I'm trying to scrap phobos website using bs4 and getting 418 teapot error Here is my code ....I am getting error when i am using build_opener.open

    from urllib.request import urlopen, Request, build_opener
from sockshandler import SocksiPyHandler
import socks
import pandas as pd
import urllib

from bs4 import BeautifulSoup
phobos = "http://phobosxilamwcg75xt22id7aywkzol6q6rfl2flipcqoc4e4ahima5id.onion/search?query=data"
def clear(toclear):
    str = toclear.replace("\n", " ")
    return (' '.join(str.split()))
#headers = {'User-Agent': 'M',}
req = build_opener(SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050, True))
res = req.open(phobos).read()
soup = BeautifulSoup(res, 'lxml')
print(soup)

#main

HTTPError: HTTP Error 418: I'm a teapot
Actually, it is an onion site which you can access only with TOR Browser and not with normal browsers like chrome.
I want to scrap its results but it is giving me 418 teapot error
If you want to know any other information just comment here, I will try to answer it

A: As a tidbit / Internet curiosity, the error you got is

The HTTP 418 I'm a teapot client error response code indicates that the server refuses to brew coffee because it is, permanently, a teapot. A combined coffee/tea pot that is temporarily out of coffee should instead return 503. This error is a reference to Hyper Text Coffee Pot Control Protocol defined in April Fools' jokes in 1998 and 2014.

The bottom line is Some websites use this response for requests they do not wish to handle, such as automated queries.


text:
Q: Why apache2 server does not working and when I check the status it shows the following ! :( sudo systemctl status apache2

apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: inactive (dead) since Thu 2018-02-15 23:21:31 +06; 17min ago
     Docs: man:systemd-sysv-generator(8)

Feb 15 23:21:31 jucse systemd[1]: Starting LSB: Apache2 web server...
Feb 15 23:21:31 jucse systemd[1]: Started LSB: Apache2 web server.

How to activate it ?

A: First, try using:
sudo service apache2 restart

if that doesn't work, try
sudo systemctl restart apache2

although if service didn't work, I doubt systemctl will to any better.
If those error out, try
sudo apachectl restart

and it will give you any errors that occur.
Note: If you just want to do a config test(without trying to start apache), use:
sudo apachectl configtest

Based on your comment, it appears that your apache install is corrupt. In that case, try:
sudo apt install --reinstall apache2

to re-install apache. This should not affect any of your virtual hosts, but it's still a good idea to back up(something like sudo cp -R /etc/apache2 /etc/apache2.old)


text:
Q: Expected Value of the Probability A paper I was reading they gave the following result without explanation:
Let $s\in\left\{0,1\right\}^n$ where the probability of 1 occurring is p. Let k be the number of 1s occurring in s.
Then $\mathbf{E}[p|k]=\frac{k+1}{n+2}$ .
Intuitively, I would assume $f(p)=p^k*(1-p)^{n-k}$ to be the probability density function. But then I get $\mathbf{E}[p|k]=\int_{0}^{1}x^{k+1}*(1-x)^{n-k}$ which yields a different result.
I'm thankful for any tips! On a side note, I've only done first year probability, hence I'm not very capable.

A: Your $f(p)$ is not a probability density function but is proportional to the likelihood. So if you have a uniform prior on $[0,1]$ then $f(p)$ is also proportional to the posterior; the scaling factor is essentially a Beta function so the probability density function would be $\dfrac{p^k(1-p)^{n-k}}{B(k+1,n-k+1)}$.
The mean of this posterior distribution would then be $$\dfrac{\int_0^1 p \cdot p^k(1-p)^{n-k} \, dp}{\int_0^1 \quad p^k(1-p)^{n-k} \, dp} = \dfrac{B(k+2,n-k+1)}{B(k+1,n-k+1)}=\dfrac{k+1}{n+2}$$


text:
Q: How can I infinite-scroll a web page using selenium webdriver in python I'm newbie of selenium,
I'm trying to figure out how to scroll infinitely
i tried almost everything what other stackoverflow said
1.
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
driver = webdriver.Chrome('chromedriver', options=chrome_options)
driver.set_window_size(1320, 550)

exchange_link = "https://icodrops.com/ico-stats/"
driver.get(exchange_link)
wait = WebDriverWait(driver, 10)

SCROLL_PAUSE_TIME = 0.5

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

*

from selenium.webdriver.common.keys import Keys
Number = wait.until(EC.presence_of_element_located((By.XPATH,'html[1]/body[1]/div[1]/div[1]/div[1]/main[1]/div[1]/div[4]/div[2]/div[1]/div[1]/div[1]')))
lastElement = Number.find_elements(By.XPATH,'div')[-1]
lastElement.send_keys(Keys.NULL)

*

Number = wait.until(EC.presence_of_element_located((By.XPATH,'html[1]/body[1]/div[1]/div[1]/div[1]/main[1]/div[1]/div[4]/div[2]/div[1]/div[1]/div[1]')))
lastElement = Number.find_elements(By.XPATH,'div')[-1]
lastElement.location_once_scrolled_into_view

etc
driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")

driver.execute_script("document.getElementById('mydiv').scrollIntoView();")

idk somethingelse i can do
i spend a lot of time to fix it
thanks for all reply. but nothing works
i tried two things
while True:
        if j == 900:
            break

        try :
            ele = wait.until(EC.visibility_of_element_located((By.XPATH, f"(//div[@id='market-ico-stat-container']/div)[{j}]")))
            driver.execute_script("arguments[0].scrollIntoView(true);", ele)
            ico_name = wait.until(EC.presence_of_element_located((By.XPATH,f'/html[1]/body[1]/div[1]/div[1]/div[1]/main[1]/div[1]/div[5]/div[2]/div[1]/div[1]/div[1]/div[{j}]/a[1]/div[1]/div[1]/div[2]/h3/a'))).get_attribute("textContent")
            print(j)
            print(ico_name)
            j+=1

        except :
            break

but result as same. from 51 it can't crawl. so it means that no scroll down

A: You should scroll each web element one by one with the help of execute_script
Code:
driver = webdriver.Chrome(driver_path)

driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://icodrops.com/ico-stats/")

j = 1
while True:
    ele = wait.until(EC.visibility_of_element_located((By.XPATH, f"(//div[@id='market-ico-stat-container']/div)[{j}]")))
    driver.execute_script("arguments[0].scrollIntoView(true);", ele)
    time.sleep(0.5)
    name = ele.find_element(By.XPATH, ".//descendant::h3//a").get_attribute('innerText')
    print(name)
    j = j + 1

    #below code is just in case you want to break from infinite loop
    if j > 50:
        break

Output:
Ambire Wallet
Himo World
Highstreet
Decimated
Planet Sandbox
BENQI
DeHorizon
Mines Of Dalarnia
MonoX
Lobis
AntEx
Titan Hunters
Tempus
The Realm Defenders
Aurora
XDEFI Wallet
Libre DeFi
Genopets
Mytheria
ReSource
Defactor
PlaceWar
CryptoXpress
Cryowar
Numbers Protocol
Dragon Kart
Trusted Node
Cere Network
Elemon
Meta Spatial
YIN Finance
Ardana
CropBytes
Good Games Guild
Ariadne
ThorSwap
Solend
GooseFX
Galactic Arena
DotOracle
Scallop
AcknoLedger
Clearpool
Sandclock
ArtWallet
Aurory
BloXmove
WonderHero
Lazio Fan Token
Hero Arena

Process finished with exit code 0

Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

the above code will never break and will be executing infinite, to overcome this behavior you should introduce a maximum limit like this:
if j == 500:
    break

However, the web application seems to detect the Selenium script.

A: I was able to scroll this with the next code changes:

*

*Add extra options to make the script undetected (it was blocked as a bot before)

*Add keyboard action ARROW_UP, this does magic and content started to load after js scroll.

*Add 5 seconds timeout to load the new content

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
#extra options
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_argument('--disable-blink-features=AutomationControlled')

driver = webdriver.Chrome('chromedriver', options=chrome_options)
driver.set_window_size(1320, 550)

exchange_link = "https://icodrops.com/ico-stats/"
driver.get(exchange_link)

SCROLL_PAUSE_TIME = 5 #5 seconds
time.sleep(SCROLL_PAUSE_TIME)

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

for x in range(0, 10):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.find_element(By.XPATH, "//body").send_keys(Keys.ARROW_UP)
    time.sleep(SCROLL_PAUSE_TIME)
    new_height = driver.execute_script("return document.body.scrollHeight")
    print('current Y: ' + str(new_height))
    if new_height == last_height:
        break
    last_height = new_height
driver.close()

Output:
current Y: 9792
current Y: 32542
current Y: 68942
current Y: 82592
current Y: 82592

I've tested this with Selenium 4, Chrome 97, Windows.
This code might be improved and optimized, but at least I hope it should work.


text:
Q: Unable to deploy to Genymotion device through Android Studio I'm currently using Genymotion with Android Studio via the Genymotion plugin to try to test and debug my Android applications.  I set up the Android Studio Genymotion plugin a while ago, and it worked.  However, just now I tried to deploy my application to Genymotion, but after starting my Genymotion device, it did not appear in the ADB deployment list.  I have no idea what happened or why.  Does anyone have any idea?
By the way, this means I cannot test my application, as I cannot use the regular ADB virtual device set as per this other continuing issue: How to create an Android AVD without HAXM?
Thanks!

A: It is potentially an incompatibility problem between the adb shipped with Genymotion and the one from your Android SDK.
Turn all your Genymotion devices off.
Then open Genymotion application (not the IDE plugin),  go to settings > adb tab > check "use custom adb" and set the path to yout Android SDK.
Then reopen a device and you should see it on your IDE.


text:
Q: setting url in ajax prefilter causes dataType settings in ajax setup to be ignored I am trying to manipulate the ajax url options using a ajax prefilter like shown below, but when the ajax is called with filter, the new url is used but the dataType is ignored, which means no callback parameter is added to the url, and i get a bad request. this only happens when i try to set a new url. the callback is added as it should for instance when i only set new data parameters. also when i try to set the dataType option in the perfilter together with the url, the callback parameter is still not added. am i doing something wrong? thanks a lot for reading this!!
    var ajaxItem = {
        setUp: function (a) {
            $.ajaxSetup({
                url: "url1.php?",
                data: {
                    'meta_prefix': 'm_',
                },
                dataType: 'jsonp',
            });
        }
    };

    var ajaxProd = {
        setUp: function () {
            $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
                options.url = "url2.php?";
    //also when i set dataType here again, the callback parameter is not added to the url
            //options.dataType = 'jsonp';
            });
        }
    };

A: I found a gist that solved a similar problem (I wanted to send JSONP if a plugin was being run on an external domain, so it could retrieve the same data).
Here's the gist:
https://gist.github.com/craveytrain/1028553
My version:
$.ajaxPrefilter('json', function(options) {
  // replace with your condition or remove the `if` clause and just return jsonp
  if ( true ) {
    return 'jsonp';
  }
});


text:
Q: Circular queue java programming I am trying to insert items circularly in a queue.. i have the following code but it doesn'n insert them right. what's the problem?
public boolean insert(int element){
    if ( head == -1 && tail == -1 ){
        head = 0;
        tail = 0;
        elements[tail] = element;
        return true;
    }
    else if((tail+1)%capacity == head) {
        System.out.println("Full");
        return false;
    }
    else {
        tail = (tail+1)%capacity;
        elements[tail] = element;
        return true;
    }
}

A: public boolean insert(int element){
    if (getCapacity() == capacity) {
        System.out.println("Queue is full.");
        return false;
    }else {
        elements[tail] = element;
        tail = (tail+1)%capacity;
        n++;
       return true;
    }
}

and
public int getCapacity(){
    return n;
}


text:
Q: How to make the chrome browser run in background using selenium I am trying to Automate my WhatsApp to send messages in bulk using pyautogui. I was able to send them but for every message, a new tab pops in and my work gets disturbed. How can I make the WhatsApp web tab run in the background or in another window without disturbing my work? Here is my code. Iam getting an error:
TypeError                                 Traceback (most recent call last)
<ipython-input-1-3555dd798e71> in <module>
     10 chrome_options.add_argument("--headless")
     11
---> 12 driver = webdriver.Chrome(executable_path=r"C:/Users/AB/chromedriver", chrome_options=Options)
     13
     14 data = pd.read_excel("C:/Users/AB/Desktop/contacts2.xlsx")

C:\anaconda\lib\site-packages\selenium\webdriver\chrome\webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, keep_alive) 62         else:
     63             if desired_capabilities is None:
---> 64                 desired_capabilities = options.to_capabilities()
     65             else:
     66                 desired_capabilities.update(options.to_capabilities())

**TypeError: to_capabilities() missing 1 required positional argument: 'self'**

Here is the updated code:
import pyautogui as pg
#import webbrowser as web
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Chrome(executable_path=r"C:/Users/AB/chromedriver", chrome_options=Options)

data = pd.read_excel("C:/Users/AB/Desktop/contacts2.xlsx")
data_dict = data.to_dict('list')
leads = data_dict['contact']
messages = data_dict['msg']
combo = zip(leads,messages)
first = True
for lead,message in combo:
    time.sleep(6)
    driver.get("https://web.whatsapp.com/send?phone="+lead+"&text="+message)
    if first:
        time.sleep(8)
        first=False
    width,height = pg.size()
    pg.click(width/2,height/2)
    time.sleep(8)
    pg.press('enter')
    time.sleep(8)
    pg.hotkey('ctrl', 'w')```

A: To run chrome-headless just add --headless in chrome_options.add_argument, i.e.:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--headless")

In that case you will not see chrom window.


text:
Q: Output between two dates mysql I need the out in MYSQL like this.
Records :
start_date |  to_date
2013-01-01 | 2013-12-31
2013-02-01 | 2013-05-04
2013-01-30 | 2013-04-02
2013-04-30 | 2013-07-06
2013-06-30 | 2013-06-09
2013-08-30 | 2013-10-03

my input is from_date 2013-04-01 and to_date 2013-06-10
my out put shuld be like this :
start_date | to_date
2013-01-01 | 2013-12-31
2013-02-01 | 2013-05-04
2013-01-30 | 2013-04-02
2013-04-30 | 2013-07-06
2013-06-30 | 2013-06-09

can any one help on this.

A: Seems you want to find ranges overlapping your given range;
SELECT * FROM date_table
WHERE start_date < '2013-06-10'
  AND to_date   > '2013-04-01'

That is, you compare your from_date with the column to_date and your to_date with the column start_date.
An SQLfiddle to test with.


text:
Q: "breaks" argument in visreg with multiple predictors I am trying to plot the predicted probabilities from a set of binomial glmer objects produced using package lme4. They are of the form:
library(lme4)
model = glmer(
  LogFlag ~ FRI + Mound + woody + (1 | ID) +
    (0 + FRI | ID) + (0 + Mound | ID) +
    (0 + woody | ID)  + Mound:FRI + Mound:woody,
  family = "binomial",
  data = BBmod
)

To make the plots I am using calls to visreg as follows:
visreg(
  model, xvar = "FRI", by = "Mound", scale = "response",
  rug = 0, overlay = T, partial = F, gg = T,
  breaks = c(2, 4, 6, 8, 10, 15, 20, 40, 80),
  band = F, line = list(col = rainbow(9)), legend = F
)

This usually produces very nice plots with FRI on the x-axis, probability on the y-axis, and 9 separate lines for the values of Mound specified in the breaks argument.
My question is what value of woody, the third predictor, is being used? Without any breaks argument, visreg defaults to using the median of predictors not included in the call, but I have given breaks for Mound. How can I specify, or at least confirm, the value of woody that is being used?

A: I was confusing the breaks and cond arguments. The documentation shows that with
cond = list(woody = Z)

I can control the value of woody, where Z is the value of woody. Maybe this will help someone.


text:
Q: lxml ignoring elements with undefined namespace prefix I've got some simple code stepping through a large XML file (containing entities defined in the DTD):
from lxml import etree
tree = etree.parse(
    file('t.xml', 'r'), etree.XMLParser(dtd_validation=False, load_dtd=True))
for e in tree.iter('bla'):
    process(e)  # whatever to be done with it

This works nicely for plain XML input.
Unfortunately the iter generator does not yield anything for tags with colons inside (namespace prefix).  The namespace is not defined anywhere, and actually I don't care about it.  I just want to iterate through the elements.
Is there an easy way to do this?

A: Well, this may not be entirely satisfying, but here is what I found:
>>> root = tree.getroot()
>>> root.attrib
{'{http://www.w3.org/2001/XMLSchema-instance}schemaLocation': 'http://xmlns.oracle.com/weblogic/security/xacml'}
>>> root.nsmap
{None: 'http://xmlns.oracle.com/weblogic/domain', 'wls': 'http://xmlns.oracle.com/weblogic/security/wls', 'sec': 'http://xmlns.oracle.com/weblogic/security', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance'}
>>>

for a tag like:
<domain xmlns="http://xmlns.oracle.com/weblogic/domain"
    xmlns:sec="http://xmlns.oracle.com/weblogic/security"
    xmlns:wls="http://xmlns.oracle.com/weblogic/security/wls"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.oracle.com/weblogic/security/xacml">

But this should allow you to get everything:

*

*"standard" attributes via attrib

*"namespace" ones through nsmap


text:
Q: Bind goals to cascade them like phases in Maven plugin Let's say I have 5 different goals linked to Mojos that I want to be able to bind, named from goal-a to goal-e.
I would like to be able to bind them like maven lifecycle phases, i.e. if I define an execution path and I call a goal, all previous goals on this path are executed beforehand.
I would then have :
goal-a -> { goal-b -> goal-d
          { goal-c -> goal-e

So if I run mvn groupdId:artifactId:myPlugin:goal-d, it executes goal-a, goal-b, goal-d.
If i run the same command with goal-e, it executes goal-a, goal-c, goal-e.
Is there any way to define such bindings ?

A: You can write a custom plugin quite easily that will accomplish what you are looking for using the Mojo Executor.
For instance, you can write a Mojo for goal-d and in it, you can use the Mojo Executor to execute the goal-a and goal-b Mojos.

A: You can add execution of your plugin into <build> block or create separate profile for its run, and there define all goals. Here is an example:
<build>
    <plugins>
        <plugin>
           <groupId>your.plugin.group.id</groupId>
           <artifactId>your-plugin-artifact-id</artifactId>
           <executions>
               <execution>
                  <!-- here you need to specify build phase where your plugin execution will be started -->
                  <phase>install</phase>
                  <!-- here you can add all your goals to execute -->
                  <goals>
                      <goal>goal-a</goal>
                   </goals>
               </execution>
           </executions>
        </plugin>
   </plugins>
</build>

When you execute phase install on project your plugin will execute its goals.


text:
Q: Where PATH=~/.local/bin:$PATH should be set in zsh shell? In my current environment (Fedora35, zsh user shell, oh-my-zsh, pyenv),
~/.local/bin is not present in the path.
The question is where is the "right" place to add ?
Several options are available:

*

*~/.zshrc

*~/.zlogin

*~/.zshenv

*~/.zprofile

or system wide:

*

*/etc/zshenv

The role of /etc/zprofile, is to source standard /etc/profile, /etc/profile.d/*sh, in 'ksh' emulation mode.
# from /etc/zprofile

       #  Make /etc/profile happier, and have possible ~/.zshenv options like
       # NOMATCH ignored.
       #
       emulate -L ksh

       # source profile
       if [ -f /etc/profile ]; then
           source /etc/profile
       fi

(see: https://apple.stackexchange.com/questions/388622/zsh-zprofile-zshrc-zlogin-what-goes-where)
There are other possibilities (pam_env) too.

In Fedora, /etc/profile contains a block of lines that check for interactive shell (with option i in ${-}):

   for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do
       if [ -r "$i" ]; then
           if [ "${-#*i}" != "$-" ]; then
               . "$i"
           else
               . "$i" >/dev/null
           fi
       fi
   done

In the test in the line if [ "${-#*i}" != "$-" ]; then the expression ${-#*i} has no relation with $i loop variable but  means: "remove a starting string, ending with i (#*i) from the list of options ${-}" and resolves to
# with (interactive) zsh

for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do echo "<${-#*i}> <$->"; done
<kmsy> <569NRXZghikmsy>
<kmsy> <569NRXZghikmsy>
<kmsy> <569NRXZghikmsy>

# with (interactive) bash

for i in /etc/profile.d/*.sh /etc/profile.d/sh.local ; do echo "<${-#*i}> <$->"; done
<mBHs> <himBHs>
<mBHs> <himBHs>
<mBHs> <himBHs>
<mBHs> <himBHs>

From: https://tldp.org/LDP/abs/html/internalvariables.html

$-
Flags passed to script (using set).
This was originally a ksh construct adopted into Bash ...
One possible use for it is to have a script
self-test whether it is interactive.

Probably a way to avoid multiple inclusion of /etc/profile.d/*sh in case of interactive shell.
This case is handled by /etc/bashrc for interactive bash.

# Source global bash config,
# when interactive but not posix or sh mode
   if test "$BASH" &&\
      test -z "$POSIXLY_CORRECT" &&\
      test "${0#-}" != sh &&\
      test -r /etc/bashrc
   then
      # Bash login shells run only /etc/profile
      # Bash non-login shells run only /etc/bashrc
      # Check for double sourcing is done in /etc/bashrc.
      . /etc/bashrc
   fi


text:
Q: How omit certain value from nested zod scheme? I have the following zod schema, and in some cases there is a field I would like to omit from the schema entirely.
I can't just make it optional. I suspect there is some way do it with zod directly. Is there a way to omit fields or to preprocess the schema in some way?
For example, how I can use this schema without this nested field.
const schema = z.object({
  name: z.number(),
  age: z.number(),
  data: z.array(
    z.object({
      id: z.string().optional(),
      name: z.string().nonempty().optional(),
    })
  )
});

const test = schema.shape.data //. ??? how can I omit the name field?
type typeTest = z.infer<typeof test>; // just data without name field

How I can omit this nested value?

A: The minimum change to make that would work is:
const test = schema.shape.data.element.omit({ name: true }).array();

but another option would be to reorganize your schema into a few named parts and use merge to combine them like:
import { z } from 'zod';

const dataSchema = z.object({
  id: z.string().optional(),
  someOtherField: z.number(),
});

const namedSchema = z.object({
  name: z.string().nonempty().optional(),
});

const fullDataSchema = dataSchema.merge(namedSchema);

type Data = z.TypeOf<typeof dataSchema>;
type FullData = z.TypeOf<typeof fullDataSchema>;

The other option using omit on your base data schema type to get a schema without that field and then use typeof on the resulting schema. If you want to use the schemas in different scenarios I recommend giving them names.
import { z } from 'zod';

const dataSchema = z.object({
  id: z.string().optional(),
  someOtherField: z.number(),
  name: z.string().nonempty().optional(),
});

const noNameDataSchema = dataSchema.omit({ name: true });

type Data = z.TypeOf<typeof noNameDataSchema>;

There are pros and cons to either approach but the outcome should be the same. (I personally find myself doing the former more often because I find the code easier to follow)

A: Correct answer
const schema = z.object({
  name: z.number(),
  age: z.number(),
  data: z.array(
    z.object({
      id: z.string().optional(),
      name: z.string().nonempty().optional()
    })
  )
});

const test = schema.shape.data.element.omit({ name: true }).array();
type typeTest = z.infer<typeof test>;


text:
Q: DatePicker in bootstrap I am trying to add time field using datetimepicker. I am getting widget, but if I select AM and leave that field comeback to same field  then it goes to PM. Could anyone suggest on it.
$('.datetimepicker').datetimepicker({
   format: 'LT',
   keepOpen: false,
   locale:'en'
});


text:
Q: Can we set different alignments for widgets in QLayout? I have many widgets in a horizontal layout. I have set alignment to vertical center and hence all the widgets are proportionately placed and the content margins are set to (0, 0, 0, 0).
I want to add one more widget which is aligned to the top and not the center.
Is there a way to add widgets with different alignment in the same layout?
One solution: To add this last widget to a vertical layout and align it to top and add that vertical layout to the horizontal layout. But this adds one more layout which i am thinking can be avoided.


text:
Q: bookmarking multiple reactive tabs not working in shiny Really appreciate if anyone can help me here since I am stuck after researching on this everywhere.
The below application is updating the url based on row selected in the DT table and the selected tab. But what happens is, when the user copy paste the url in another tab, it is not opening the specific tab, instead it is opening the default page (url : http://127.0.0.1:XXXX/?tabs=tabs3).
I mean reactive tabs are not working.
Please follow these steps for the reference

*

*Click on any row(say 3) on DT table(Summary tab)

*An new tab3 opens (that is fine) which prints 3

*Copy the url now (tab3 url)

*Paste this url to another tab (Now it returns to Summary tab only and not tab3).

Am I doing something wrong here?
library(shiny)
library(DT)

ui <- function(request) {
  shinyUI(navbarPage(
    "Title", id = "inTabset", selected = "Summary",
    tabsetPanel(id = "tabs",
                # tabPanel(
                #   "Readme",tags$head(tags$link(rel = "stylesheet", type="text/css", href="style.css"))
                # ),
                tabPanel(
                  "Summary",
                  dataTableOutput("tab")))
  )
  )
}

server <- function(input, output, session) {
  # Make sure you only bookmark the tabsetPanel
  setBookmarkExclude(isolate(names(input)[names(input) != "tabs"]))

  # Every time the tab changes, store the app state as URL bookmark
  observeEvent(input$tabs, {
    session$doBookmark()
  })

  # Set callback that stores the app state in the URL
  onBookmarked(function(url) {
    updateQueryString(paste0("?tabs=", input$tabs), mode = "replace")
  })
  # Set callback to restore the app state from the URL
  onRestore(function(state) {
    updateTabsetPanel(inputId = "tabs", selected = getQueryString()[["tabs"]])
  })

  output$tab <- renderDataTable({
    datatable(iris,selection = 'single')
  })

  observeEvent(input$tab_rows_selected, {
    insertTab(inputId = "tabs",
              tabPanel(paste0("tabs",input$tab_rows_selected), "This a dynamically-added tab",htmlOutput("sd")),
              target = "Summary",select = TRUE

    )
  })

  output$sd <- renderUI({
    as.character(input$tab_rows_selected)
  })

}

enableBookmarking("url")
shinyApp(ui, server)


text:
Q: What language do config files use? I've been using GNU/Linux for over a year now. And there's this question to which I need an answer from you, Linux gurus:
What language(s) do config files like .bashrc, .vimrc, .i3status.conf, .conkyrc, .xinitrc, etc. use?

A: There's no global standard. They can be (and are) all different syntaxes.
For example,

*

*the bashrc is simply a bash script,

*the vimrc a vimscript script,

*i3 uses its own syntax that's pretty
close to a scripting language (but they
claim it isn't a
programming language, but I think they're lying there, the conditional screen placement thing looks extremely much like you can build a turing machine out of it),

*xinitrc is just an  arbitrary script (which will be run by the shell specified  in the #! line at the beginning of the file, so it could just as   well by say, Python, bash, zsh, tcl, perl, …

*Conky uses JSON or YAML, I think,

Essentially, there is no standard, and you always need to read the documentation.


text:
Q: I can't import a CSS File in a JSP I try to add a CSS file to an JSP which is running on tomcat 8. The CSS just changes the appearance of tables. The CSS file is in the same folder as the JSP. I tried using:
<link href="table.css" rel="stylesheet" type="text/css">

but it didn't show any changes. So I tried:
<style type="text/css">
<%@ include file="./table.css" %>
</style>

But this gives me a weird error, when I try to reach the page in my browser on the first try I get 404 - Resource not found but when I try again it works. What can cause this and is there an easier way to import my CSS file in the JSP? I use a servlet to reach the JSP if that matters.
Edit:// I just checked the WAR File i exported and the WEB-INF Folder only contains my classes the Folders of the HTML and JSP Sites are on the root directory of the WAR file.

A: I'd put all your .css files in a folder named /css right under the root of your WAR.  The path would be css/table.css.
Same for JavaScript: create a folder named /js right under the root of your WAR. The path to JavaScript is js/foo.js


text:
Q: Is there a usecase to create separate indices on the foreign keys of junction/associative table? Imagine an associative/junction table junction_table_ with (pseudocode) columns like:
id_of_table_x REFERENCES TABLE X
id_of_table_y REFERENCES TABLE Y

PRIMARY KEY (id_of_table_x, id_of_table_y)

So id_of_table_x and id_of_table_y are foreign keys referencing some primary keys of other tables and are used as composite primary key.
Now I could add:
CREATE INDEX some_index ON junction_table_ (id_of_table_x);

and
CREATE INDEX some_index ON junction_table_ (id_of_table_y);

Would this have any (positive) effect?
What would be a valid use case for separate indices on the single columns?
e.g. queries that WHERE-filter on one of the two foreign keys within a join or delete operations which need to check whether the target is still referenced - do they profit from separate, additonal indices.

A: You don't need a separate index for the first column of your primary key (id_of_table_x in your example) because Postgres will happily use that  index in every situation where it would use the single-column index on the first column.
If you very often delete rows from the referenced table, then adding another index on the second column helps validating the foreign key during deleting.
The index on the second column might help for joins that only use that (but not the first column).


text:
Q: Jquery Interval Loop change numbers after every one min? I try to make a function for change a div number when one min is passed. I need to do this again and again. I mean to say if i give numbers 241. I need to change this after one min 320 or like this any one. I try to much but still not success full. If any one knows how to do this please help me.

A: Use setInterval for that.

var div = document.getElementById('nums');
var currNum = 260;
div.innerHTML = 260;

setInterval(function () {
  currNum += 20;
  div.innerHTML = currNum;
}, 2000); // time in miliseconds.

A: Working Code:
<!DOCTYPE html>

A: Maybe you could try something like this:
setInterval(function(){ $("#id").html(320); }, 60000);

A: Use window.setInterval function

$(() => {
  var counter = 0;
  window.setInterval(() => {
    counter++;
    $("#test").html('Has been running since '+counter+' seconds!');

  }, 1000); // After 1s for demo
})


text: Q: Do taylor series smooth functions of power series with finite convergence radius at every point converge to itself on every point of real line Let $g$ be a smooth function with all n-th derivatives satisfying $\vert g^{n}(x)\vert\leq \frac{C n!}{\rho^n}$ where $\rho$ is a fixed number for all $x\in R$. $f(x)=\sum_n \frac{g^{(n)}(0)}{n!}(x)^n$. Is this series converges to $f(x)$ uniformly on $R$? I am looking for a counter example as I do not think it holds.


text:
Q: Why are my for loops not working correctly with my arrays? I need to make a program that populates an array with randoms numbers between 25 and 80 then uses another for loop to print the results on a new line each time. I'm not sure why I get some output and then errors in this code.
    int[] myIntArray = new int [20];
    Random r = new Random();

    for (int i = 0; i <= 20; i++){
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i <= 20; i++){
        System.out.println(myIntArray[i]);
    }

A: please your array has a size of 20 but you are putting 21 element into it so try this instead
int[] myIntArray = new int [21];
    Random r = new Random();

    for (int i = 0; i <= 20; i++){
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i <= 20; i++){
        System.out.println(myIntArray[i]);
    }

A: You should show the error message in your question :)  The index of an array in Java starts at 0, so the highest index in an array of size 20 is 19.  You're going out of bounds.  Use < not <= when iterating over an array manually.
    int[] myIntArray = new int[20];
    Random r = new Random();

    for (int i = 0; i < myIntArray.length; i++) {
        int rand = r.nextInt(80 - 25) + 25;
        myIntArray[i] = rand;
    }

    for (int i = 0; i < myIntArray.length; i++) {
        System.out.println(myIntArray[i]);
    }


text:
Q: Is there an Asp.Net Core 1.1 replacement for UrlHelper? There are many older examples with this kind of syntax (from the question):

Here's a typical example of what you should never do:
<script type="text/javascript">
    $.ajax({
        url: '/home/index'
    });
</script>

and here's how this should be done:
<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("index", "home")'
    });
</script>

Running an ASP.NET MVC app from a virtual directory in IIS7
I then found UrlHelper configuration is more difficult than in previous versions of MVC,
Unable to utilize UrlHelper
Are the Url Action methods "gone" or not what should be used now?  Does Core want URL rewriting?  How do I create a dynamic url string in Core 1.1 for JavaScript the "Core" way?  I could build it manually and pass it to my View, but that is not what I wanted to do.
(no jQuery please, and yes I know the question above has jQuery)
Edit:  In my JavaScript I have,
var xhr;
xhr = new XMLHttpRequest();
var url = //this is what I want Asp.Net to generate.  Currently I manually build it within the JavaScript.  It should be,

var url = 'Home/Index' //this can change possibly depending on where the application is deployed.

I have tried this:
 @UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext)
var url = '@url.Action("index", "home")';

It does at the first Razor code with:
"The name 'UrlHelper' does not exist in the current context"
I can probably figure this part out (I have tried it with the full namespace as well).  My main question is if this is still the right way to do things in Core.  It seemed it might not be so which is when I stopped and asked here.  I thought I was missing something.


text:
Q: Syslog is taking up all my space! I was having a issue with something taking up my memory and not letting me boot, I have found the culprit - it's my syslog file in /var. It's now 170 GB!
I deleted syslog.1 which was 64GB but it has only made things much worse because syslog is now 10x bigger.
From what I have read online so far it's because a repeating error in the file. The error I'm getting is:
docker.dockerd[1128]: time="2019-11-17T03:06:48.667249945+11:00"
level=error msg="failed to get event" error="rpc error: code =
Unavailable desc = all SubConns are in TransientFailure, latest
connection error: connection error: desc = \"transport: Error while
dialing dial unix /run/containerd/containerd.sock: connect: permission
denied\"" module=libcontainerd namespace=moby

I have no idea what this means but it's taking up all space again and now I can't boot again, I will try and delete what little other files I have so that I can hopefully boot again but I need some help ASAP on getting this syslog file fixed. Sorry if I seem impatient I'm just really starting to worry.

A: booting
If you cannot boot into the GUI mode, you can choose the recovery mode from your Grub menu.
Choose root mode - then go your log directory and delete the syslog file.
You should be able to boot into the GUI mode again.
get rid of the root problem
I neither know what the error message means, but it is clearly issued by the docker demon.
I'd suggest to deinstall docker for now.
Then you have time to google for the reason or try to get help elsewhere.


text:
Q: Creating Unique RSA Key pairs (More than one pairs) I am doing RSA key pair generation in my code. I am also able to do encryption and decryption using this code. What I need is unique key pairs for each user.
In my application there will be multiple users. I want to assign these Key pairs to different users so that they can use it for encryption and decryption via my application.
Currently I am using below Code  to produce my RSA Public and Private Key pair.
RSAKeyPairGenerator adam = new RSAKeyPairGenerator();

try {

        String path = "C:\\Users\\Dream\\Documents\\NetBeansProjects\\ABEPHR\\web\\KeyFiles";

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

        keyGen.initialize(1024);
        KeyPair generatedKeyPair = keyGen.genKeyPair();

        PublicKey pub = generatedKeyPair.getPublic();
        System.out.println("Public Key: " + getHexString(pub.getEncoded()));

        PrivateKey priv = generatedKeyPair.getPrivate();
        System.out.println("Private Key: " + getHexString(priv.getEncoded()));

    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

This code can give me only one pair of RSA keys. How can I get more than one pair ?
++ Note :
 So many people suggesting me to add Loop here. To be clear, I cant add loop to my code as this code will be run on server for each user (within JSP).
Lets me explain by one example:
Suppose I have 3 users Users A, B and C. Now after validating credentials, whenever user A comes to this page (page containing above code) , This page should generate a Unique Key pair for User A. Later user A can store this Key for future use.
Now When User B login with his Credentials, than he also land in same page with above code. But Above code doesn't give me different Public Key and Private Key pair. So here I am getting same RSA key pair as it was there in case of User A.
Same case is happening with User C also.
Hope this clear my question now. As suggested by below, I also try to execute above code in loop . In each iteration, Code is giving me same Key pairs. I also try to encrypt msg with public key generated in first iteration and try to decrypt it with private key generated in second iteration. The msg is successfully got decrypted.
I want to know, am I missing something in attempt to get unique RSA key pairs ?

A: Here's a simple test that works fine on my system. Try it and post your results in your question.
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

final class UniqueKey
{

  public static void main(String... argv)
    throws Exception
  {
    SecureRandom gen = new SecureRandom();
    System.out.println(gen.getProvider());
    System.out.println(gen.getAlgorithm());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048);
    System.out.println(keyGen.getProvider().getName());
    for (String user : new String[]{"A", "B"}) {
      KeyPair pair = keyGen.genKeyPair();
      String pub = getHexString(pair.getPublic().getEncoded());
      System.out.printf("Public Key of %s: %s%n", user, pub);
    }
  }

  private static String getHexString(byte[] arr)
  {
    return new BigInteger(arr).toString(16).toUpperCase();
  }

}

My results from a trial:

SUN version 1.8
NativePRNG
SunRsaSign
Public Key of A: 30820122300D06092A864886F70D01010105000382010F003082010A02820101009EEE0526A9EBA8E2CCA4CE7FFAB78257F8275EB36DCBFADB9488939455BD4303804DEBFB2D544983CE8D12511042A20370CAE3E440EAA8873448DB68A4ACDD2C63D309B9550A2B3A2D2AF94E9F879F1DE120FFA061534EA6F5D72A32F064739562E9A6032DC0598A6750AF4CF1CDC0A214A4F9E514171DC847CBA2CDA3F95046EA74F67039806994789D8F0B2BE8539F597F97321C5387F5B51FFB5D5CE1271F216C790AC1D6885A8DE043BEAFD123CFD77B560F8B1FCFA4EF542C3205233A4FFFF151950E1278FC6C7CEA0C66992A58A0823CF5209AFEDEAAA201CB40977019F2988AFFDA4DA6B0E7933A9E5A3087C1CEF3D0BAD95FC776B974D6EC25B2E6EB0203010001
Public Key of B: 30820122300D06092A864886F70D01010105000382010F003082010A028201010096BE6F281FD41D0F282F3162ECC0225D973630D2582004D8C1A80BB97C7F959372892C653D7FD29AC1D25EA563139F49073E32182CA8CDF429FBEF67423A701B6C6A9B0A3C9F95CBF6D09F7E54D0F6C3E239BC40AFF877687FCF0B0E88B69A4693E3BC28BED6FEBED0C6CEAE744D712EC24E3809830687D982689F729A3B9AB711945BEBCB55BA780849071F6D0ED26563E5D26BCF6C72327DB2F41459E8879631722DEA0652B8AD4D7FA32F2A981D6B24D6EF7F8C72F784C5894A5B39092489380EF9A12734E30BE2B1A6FE0652CF43B33574650F66C27F49031DDC2FC3D6E8A54C1C6811710FEDFAC41DF69D3D7DE82E7C7409C85DF6836DFB87B6289406670203010001


text:
Q: Android installation - sdk manager.exe does not work I installed the android SDK from developer.android.com for Windows (installer_r08-windows.exe).  I installed to the default location, C:\Program Files\Android\android-sdk-windows.  When I try to run SDK Manager.exe, a console window briefly pops up, but disappears.. nothing else happens.  If I try to run this from the command line, nothing happens, either (and no output).
I have JDK 1.6.0_20 installed, and JAVA_HOME environment variable points to this folder (C:\Program Files\Java\jdk1.6.0_20)
Help?

A: This solution worked for me (copied from this question here)

Step #1: Open up a command prompt.
Step #2: Use the cd command to move to wherever you installed your
  Android SDK.
Step #3: Run tools\android.
If that does not work, you should have information dumped to the
  command prompt that will help you diagnose your setup problem.

A: I Had the same problem.
I had installed Java SDK 1.4 (which is not compatible) so I installed 1.6 and add dir to PATH variable and everything works.

A: Have you already installed Java SE Development Toolkit 1.6? If so, perhaps you already had an older JDK installed and when you try to run "SDK Manager.exe" it first fetchs the older one. There are two possible solutions:
Rollback your JDK instalations, and when you have no JDK present in your netbook, then install the 1.6 version.
OR
Go to "Control Panel"-> System -> Advanced -> "Environment Variables"
In system variables look for "Path" variable and click Edit. Check if the value field doesn't have the path to your Java JDK's bin folder. If that already exists substitute to the correct one. (ie "C:\Program Files\Java\jdk1.6.0_25\bin"). Otherwise, you need to insert this path at the front of the list. Insert the path followed by a ';'. Click ok all the way and reboot your machine.
After this, give another chance to "SDK Manager.exe"! :)

A: This kind of thing can be happen due to the difference in 32-bit/64-bit versions. If you have downloaded the Android SDK for 32-bit version and if you have the 64-bit system, then this kind of issue can happen. Please verify that you have the correct version downloaded and installed.


text:
Q: ASP.NET MVC 5 Adding roles to an existing application w. Forms authentication (C#) situation is as follows:
I have an existing MVC 5 application and created some very, very basic log-in functionality for it. I just have a table for users and passwords in my database, and use forms authentication to check if a user exists (and some actions can only be done if you are logged in).
Now I would like to extend the authentication system to use roles. From what I gather, I need to make a table in the database with roles, and of course give users a field that contains their role.
But I don't know how I could then use that information in my MVC application for authentication (using that nice [Authorize(Roles="admin")] syntax). All the examples i found for using the identity system use the template site, which I did not use to create this app (I started from an empty project).

A: From my understand i think you can Use the User.IsInRole() method or AuthorizeAttribute to verify the user in a particular role instead of Membership method or identity method.


text:
Q: Finding roots of polynomials, negative square root The formula for finding the roots of a polynomial is as follows
$$x = \frac {-b \pm \sqrt{ b^2 - 4ac }}{2a} $$

what happens if you want to find the roots of a polynomial like this simplified one

$$ 3x^2 + x + 24 = 0 $$

then the square root value becomes

$$ \sqrt{ 1^2 - 4\cdot3\cdot24 } $$

$$ = \sqrt{ -287 } $$
which is the square root of a negative number, which isn't allowed. What do you do in this case? I know there are other methods, i.e. factorisation and completing the square, but does this mean that this formula can only be used in specialised cases or have i gone wrong somewhere along the path?

A: 100% correct, and good observation.
To solve this, we define $\sqrt{-1}=i$ where $i$ is the imaginary unit
Then $\sqrt{-287}=\sqrt{287}i$, and we can solve as per the general quadratic formula. Numbers of the form $a+bi$ are known as complex numbers and are extremely useful.
In general the term $b^2-4ac$ is known as the discriminant of the quadratic equation. It should be clear that if $b^2-4ac>0$ there exists two real solutions, if $b^2-4ac=0$ there is one solution (the repeated root) and if
$$b^2-4ac \lt 0$$ there are two complex solutions.
The quadratic formula is the most general way to solve the quadratic equation - so you are doing the right thing.

A: Yeah so have you read about complex numbers. The root will be
$$x = \frac{-1 \pm{i} \sqrt{287}}{2 \times 3}$$

where $i=\sqrt{-1}$. Read more about complex numbers and when a polynomial can have complex roots, that happens when the *Discriminant* factor $b^{2}-4ac <0$.

A: The other answers are nice, so I won't reiterate them.  It's worth pointing out, though, that when you say "I know there are other methods, i.e. factorisation and completing the square, but does this mean that this formula can only be used in specialised cases", you seem to be implying that these other methods might yield different results.
This isn't the case.  If the quadratic formula fails to give you real-valued answers, then the other two methods (and every applicable method) will also fail, because the quadratic polynomial itself simply doesn't have any real-valued roots.
You can visualize this easily: as you may know, the graph of a quadratic polynomial is a parabola, and the real roots of a polynomial correspond to its graphs' zeros, i.e. points where the graph crosses the $x$-axis.  So if you imagine a parabola with its vertex above the $x$-axis and opening upwards, you can see that it will never cross the $x$-axis -- it has no real zeros at all!

This is exactly the situation with $y = 3x^2 + x + 24$ and every other quadratic polynomial for which $b^2 - 4ac$ (the discriminant) is negative.
Why isn't taking the square root of a negative number allowed?
Lastly (since it seems as though this may be one of your first introductions to complex numbers) let me clarify something that confuses my students greatly: don't let the words "real" and "imaginary" mislead you into thinking that real numbers are somehow genuine or actual and imaginary numbers are somehow fake.
Just as a "negative" number isn't sad, cynical, or irritated, and just as an "irrational" number hasn't lost its mind, "real" and "imaginary" are technical terms, and not meant to carry with them their English connotations.  Although they earned those names due to prior misunderstandings about numbers, today we know that imaginary numbers are just as actual and valid as real numbers, and in fact complex (not "complicated") numbers have huge real-world applications and consequences.
Along these same lines: you say that taking the square root of a negative number "isn't allowed".  More accurate would be to say that the square root of a negative number isn't a real number ("real", again, in the technical sense) because the square of a real number is always non-negative.  If you require the result of taking the square root to be a real number, then you're right, taking the square root of a negative isn't allowed.  But otherwise it's perfectly fine.
By analogy: you're allowed to divide the whole number 6 by the whole number 3, and the result is the whole number 2.  But if you divide the whole number 1 by the whole number 2, then the result, $\frac{1}{2}$, isn't a whole number.  If you require your operations on a certain class of numbers to produce a result from that same class of numbers, then lots of operations (like division, and subtraction too, for that matter) will have situations in which they aren't "allowed" to occur.
This requirement is sometimes very desirable, and there are certainly contexts in which you will want to impose it.  But you should understand that imposing this requirement is a choice that you make because it fits the context of the problems you're working on.  It's not divine law.  If you find yourself in a situation in which you would like to take the square root of a negative number and produce the corresponding imaginary number, you are definitely "allowed" to do so.


text:
Q: .NET assembly binding I have an api, MyApi, which is consumed by an application, MyApplication.
MyApi has several dlls targeted to the .NET 4.0 Client Profile. For example:

*

*MyApi.Core

*MyApi.Domain

*MyApi.Providers

(and some more)
For deployment simplicity, these are ILMerged into

*

*MyApi.ClientProfile

All of the MyApis dlls are strong named.
All the projects in MyApplication reference MyApi.ClientProfile.
I'm now adding some web functionality into MyApi, so I've added a dll MyApi.Web, which is targeted to the .NET 4.0 Extended Profile. MyApi.Web references MyApi.Core and MyApi.Domain (as well as System.Web dlls).
There is now also a MyApplication.Web project. It references some other projects in MyApplication (which have references to the MyApi.ClientProfile dll). The MyApplication.Web project needs to reference MyApi.Web dll.
How can I do this?
If I add references to MyApi.Core and MyApi.Domain from MyApplication.Web, then there will be types that exists in multiple assemblies for MyApplication.Web.
If I don't add references to MyApi.Core and MyApi.Domain from MyApplication.Web, MyApi.Web will fail to load because it can't find MyApi.Core or MyApi.Domain (because only MyApi.ClientProfile is present).
I can't handle the assembly resolve event and redirect requests for MyApi.Core/MyApi.Domain to MyApi.ClientProfile because the MyApi assemblies are all strong named and that will make it fail.
I can't merge MyApi.Web into the MyApi.ClientProfile because MyApi.ClientProfile should be supported for the .NET 4.0 Client Profile (and MyApi.Web has references to System.Web, etc.).
If I change MyApi.Web to reference MyApi.ClientProfile, that should work for this one case, but isn't ideal, because it won't work for another application references MyApi.Core and MyApi.Domain directly.
I don't want to force MyApplication.Web to specify bypassTrustedAppStrongNames in its config (thought enabling this setting somehow from MyApi.Web directly might be an acceptable option....).
So, I'm stuck thinking of a suitable/elegant solution to this problem.
Any suggestions?
Thanks.

A: I came to a realization:
If your assemblies have the same Public Key Token, you can do redirection and the name doesn't matter.
So, because MyApi.Client profile is signed with the same key as MyApi.Core, if I handle AssemblyResolve in MyApi.Web, I actually CAN tell it to use MyApi.ClientProfile instead of MyApi.Core.
I would have thought it would throw a strong name verification error. It does not....because the public keys are the same.


text:
Q: Compare edge (must be the same and equal) I need to compare one specific vertex to all other and print if they have exactly the same outE("Pertinent", "Secondaire")
here is the request i made :
SELECT $b
let $a = (
  SELECT *
  FROM Regle
  WHERE titre="1823 - accessoires poids lourds tachygraphe"
),
$b = (
  SELECT *
  FROM Regle
  WHERE out("Pertinent", "Secondaire") = $a.out("Pertinent", "Secondaire")
)

Thanks in advance

A: You could use
SELECT expand($b)
let $a = (
  SELECT *
  FROM Regle
  WHERE titre="1823 - accessoires poids lourds tachygraphe"
),
$b = (
  SELECT *
  FROM Regle
  WHERE out("Pertinent").@rid in $a.out("Pertinent").@rid and out("Secondaire").@rid in $a.out("Secondaire").@rid
)

Hope it helps.


text:
Q: Changing longitude latitude to latitude longitude for coordinate display in ArcMap? How do you change status bar display in arcmap 10.0 from longitude and latitude to latitude and longitude?

A: There is a useful blog posting on Converting and Displaying Coordinates in ArcGIS 10 but a notable item missing from that discussion is whether you can reverse the order that Degrees Minutes and Seconds (DMS) values can be displayed at the lower right of ArcMap from longitude-latitude to latitude-longitude.
I think this is because it cannot be done, and I think the reason is to be consistent about coordinates being expressed as XY rather that YX.


text:
Q: Limited to write only a-z in angular I want to let user to write just english character not number or any languages .
here is my fiddle : Demo but it's not working .
app.directive('validcharEn', function () {
    return {
        require: '?ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function (val) {
                if (angular.isUndefined(val)) {
                    var val = '';
                }
                var clean = val.replace(/[^a-z]/g, '');
                var decimalCheck = clean.split('.');
                if (!angular.isUndefined(decimalCheck[1])) {
                    decimalCheck[1] = decimalCheck[1].slice(0, 2);
                    clean = decimalCheck[0] + '.' + decimalCheck[1];
                }

                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

            element.bind('keypress', function (event) {
                if (event.keyCode === 10) {
                    event.preventDefault();
                }
            });
        }
    };
});

Am i missing something ?

A: You can use the ng-pattern-restrict directive:
<input type="text" ng-pattern-restrict="^[a-z]*$" />

Here'a an example: http://jsfiddle.net/upcvoa4L/

A: How about this : Fiddle , clean and simplest way to do it .
app.directive('validEn', function() {
  return {
    require: '?ngModel',
    link: function(scope, element, attrs, ngModelCtrl) {
      if(!ngModelCtrl) {
        return;
      }

      ngModelCtrl.$parsers.push(function(val) {
        var clean = val.replace( /[^a-z]+/g, '');
        if (val !== clean) {
          ngModelCtrl.$setViewValue(clean);
          ngModelCtrl.$render();
        }
        return clean;
      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
  };
});

HTML
<input type="text" ng-model="employee.age" valid-en />

Update
or maybe for email input :
Fiddle
var clean = val.replace( /[^0-9+.+a-z+@]+/g, '');

Hope this help


text:
Q: Port forwarding with 2 routers I have a simple 2 router setup. I'm using the second router as a switch and for wireless. The first router is forwarding a few ports (80, 443, 1433) on to a computer with a reserved I.P. address 192.168.1.15.

Verizon FiOS router, LAN port 1 -> Netgear WNR3500, LAN port 1 -> Devices
                    192.168.1.1 ->                 192.168.1.2 -> 192.168.1.x

Is it possible to have the the first router forward those ports to the second router, and then have the second router forward them on to the desired computer?  If so, is this a more secure or better way to handle it?
Basically, I just want know what the best configuration is if I am using 2 routers. Or, does it even matter?

A: Yes. Just set up the port forwarding for the range of ports and send them to the WNR3500 - or if you want to forward everything you could set up a DMZ on your FiOS router to point to the WNR3500.
Not being familar with either of the devices, I can't give you any more specific details on how to actually execute that setup.

is this a more secure or better way to
  handle it

Not really. You're going to have headaches as soon as something goes wrong because you've got additional points of failure or places for the config to be messed up. I notice that they're all on the same subnet, so there's no real reason you would want to do this, unless the WNR3500 offers some features not avaliable on the edge router.


text:
Q: Gnome 3 and discrete only nvidia Long ago I've installed Gnome 3 over Ubuntu 12.10
Currently I'm working on a scientific project, that requires lot of graphical work. I'd like notebook to run nvidia GPU only. So I disabled nvidia optimus in BIOS and switched to use discrete videocard.
But now gnome 3 is not loading. It stucks at blue scree. What can I do ?
I also was unable to install nvidia drivers. I'm working on thinkpad W520 with Quadro K2000m. If there's a manual on how to install nvidia drivers - it would be cool.

A: the following post worked for me
http://falkvinge.net/2013/02/15/how-to-install-nvidia-drivers-in-ubuntu-12-10-quantal/
kr raphael


text:
Q: Resetting ip address gives "media disconnected" error message I am using my windows 8 laptop and I am successfully connected to my router and can access my internet with no problem. I want to get a new ip address. I opened up the command prompt and then typed in
ipconfig /renew

and it gave me an error message saying
Windows IP Configuration
No operation can be performed on Local Area Connection* 15 while it has its media disconnected.
No operation can be performed on Local Area Connection* 14 while it has its media disconnected.
No operation can be performed on Ethernet while it has its media disconnected.

Wireless LAN adapter Local Area Connection* 15:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Local Area Connection* 14:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : gateway.2wire.net
   Link-local IPv6 Address . . . . . : fe80::8595:65a1:23db:b3e4%13
   IPv4 Address. . . . . . . . . . . : 192.168.2.37
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.2.1

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Tunnel adapter isatap.gateway.2wire.net:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : gateway.2wire.net

Tunnel adapter Local Area Connection* 13:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Any idea why it is giving this error?

A: There's no error there.

No operation can be performed on Ethernet while it has its media disconnected.

Those lines at the top are just telling you it can't renew the IP address for adapters that are unplugged and/or disconnected.

A: There's no error. You have 4 physical network adapters in the computer, 3 of which are disconnected. You can't acquire or renew an ip address for a NIC that isn't connected.


text:
Q: WP Coding standards - escaping the inescapable? How do you escape these two examples?
wc_price() wraps the already escaped $product_price in p and span tags with currency symbol.
$product_price = $product->get_price();

<?php echo wc_price( esc_html( $product_price ) ); ?>

The next one outputs the complete image with all attributes: src, srcset, alt, etc.
$product_img = $product->get_image();

<?php echo $product_img; ?>

A: For the first example, a lot of people will use wp_kses_post to handle basic HTML output from wrapper functions.  It's a shortcut for some basic attributes and tags using wp_kses.  You could use this function where you specify allowed tags and attributes that can pass through for the second example.

A: My opinion is that you wouldn't. wc_price() and $product->get_image() are both escaped further upstream. In the WordPress Coding Standards sniffs for PHPCS, these would be referred to as "auto escaped functions".
Double escaping by putting wp_kses_post() on everything that's already escaped, just to satisfy code sniff, is a waste of resources and not actually doing anything to solve the problem that the sniffing is supposed to solve in the first place.
The reason PHPCS is flagging these lines even though they're escaped is because the WP Coding standards don't know about 3rd-party functions. If your project is using them, or has its own auto-escaped functions, you should configure your project's rules to cover them. For example, adding this to your projects phpcs.xml file will stop PHPCS complaining about wc_price() not being escaped wherever it's used:
<rule ref="WordPress.Security.EscapeOutput">
    <properties>
        <property name="customAutoEscapedFunctions" type="array" value="wc_price,"/>
    </properties>
</rule>

customAutoEscapedFunctions doesn't support class methods, so to satisfy $product->get_image(); you would use an inline comment:
$product_img = $product->get_image();

echo $product_img; // phpcs:ignore WordPress.Security.EscapeOutput


text:
Q: avoiding code redundancies for a calculation in Java I have a calculation where i can sum or subtract something but this depends on a simple condition. My problem is, that I don't know how I can change the code, so i don't need to write the calculation twice just with the difference of the + or -. Hopefully somebody can helf me. Thanks in advance.
public void changePrice(Stock stock, int amount, boolean isBuying) {
    double roundRandomNumber = Math.round((0.5 + Math.random()) * 100) / 100.00;
    double newPrice;

    //calculates plus or minus depending on the buyoption
    if (isBuying) {
        newPrice = Math.round((stock.getPrice() + roundRandomNumber * 0.1 * amount) * 100) / 100.00;
    } else {
        newPrice = Math.round((stock.getPrice() - roundRandomNumber * 0.1 * amount) * 100) / 100.00;
    }
    if (newPrice > 0 && newPrice < 3000) {
        stock.setPrice(newPrice);
    }
}

A: You can use a +1 or -1 coefficient based on isBuying value.
newPrice = Math.round((stock.getPrice() + (isBuying ? 1.0 : -1.0) * roundRandomNumber * 0.1 * amount) * 100) / 100.00;

A: You could try by extracting just the factor in the condition:
public void changePrice(Stock stock, int amount, boolean isBuying) {
    double roundRandomNumber = Math.round((0.5 + Math.random()) * 100) / 100.00;
    double newPrice;

    //calculates plus or minus depending on the buyoption
    double factor;
    if (isBuying) {
        factor = 1.0
    } else {
        factor = -1.0
    }

    newPrice = Math.round((stock.getPrice() + (factor * roundRandomNumber) * 0.1 * amount) * 100) / 100.00;
    if (newPrice > 0 && newPrice < 3000) {
        stock.setPrice(newPrice);
    }
}

A: I come up with substitution of roundRandomNumber yielding an expression with ( / 100) * 0.1 which can simplified to * 0.001.
Also round(0.5 + x) can be ceil(x).
Or use 1 + new Random().nextInt(100).
double roundRandomNumber = Math.ceil((Math.random()) * 100) * 0.001 * amount;
double newPrice = stock.getPrice();
if (isBuying) {
    newPrice += roundRandomNumber;
} else {
    newPrice -= roundRandomNumber;
}
newPrice = Math.round((newPrice * 100) / 100.00;

if (newPrice > 0 && newPrice < 3000) {
    stock.setPrice(newPrice);
}

For the rest it is the reserved register principle: I do stepwise things to newPrice.
The boundary condition excludes 0, which is questionable.
Of course BigDecimal should be mentioned. The complexity basically stems from wanting fixed point arithmetic with floating point. Unless you need speed, BigDecimal code can be more readable, though verbose.


text:
Q: python - object() takes no parameters error I have following python classes.
class FileMaster(db.Entity):
        id = PrimaryKey(int, auto = True)
        description = Required(str)
        filesource = Required(str)
        createdby = Optional(int)
        createddate = Optional(datetime.datetime)
        updatedby = Optional(int)
        updateddate = Optional(datetime.datetime)
        filelists = Set('FileList')

class FileList(db.Entity):
        id = PrimaryKey(int, auto = True)
        filemaster = Required(FileMaster)
        filelocation = Required(str)
        createdby = Optional(int)
        createddate = Optional(datetime.datetime)
        updatedby = Optional(int)
        updateddate = Optional(datetime.datetime)
        transcripts = Set('Transcript')

The following line runs fine,
filemst = FileMaster(description=desc, filesource = filesourcepath)

But the following line gives error "object() takes no parameters"
filelist = FileList(filemaster=filemst, filelocation='test')

Any one can help me on this?

A: I am not sure what was the issue, but I solved it by removing the tables in the database and used different names for the classess.


text:
Q: submit a list become null in the post + MVC I have a ViewModel:
public class RegistrationViewModel
{
    public string Country { get; set; }
    public ConfigurationParamValue CountryParam { get; set; }
    public string Civility { get; set; }
    public ConfigurationParamValue CivilityParam { get; set; }
    [FirstNameValidator(Category = "Registration", IsLocal = false )]
    public string FirstName { get; set; }
    public ConfigurationParamValue FirstNameParam { get; set; }
    [LastNameValidator(Category = "Registration", IsLocal = false)]
    public string LastName { get; set; }
    public List<int> Days { get; set; }
    public int SelectedDay{ get; set; }
    public List<Month> Months { get; set; }
    public Month SelectedMonth { get; set; }
    public List<int> Years { get; set; }
    public int SelectedYear { get; set; }
    public DateTime BirthDate { get; set; }
}

I create a view with this viewmodel :
@model Registration.Front.Web.Models.RegistrationViewModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Index

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>RegistrationViewModel</legend>

            @Html.LabelFor(model => model.Country)

            @Html.EditorFor(model => model.Country)
            @Html.ValidationMessageFor(model => model.Country)

            @Html.LabelFor(model => model.Civility)

            @Html.EditorFor(model => model.Civility)
            @Html.ValidationMessageFor(model => model.Civility)

            @Html.LabelFor(model => model.FirstName)

            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)

            @Html.LabelFor(model => model.LastName)

            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)

            @Html.LabelFor(model => model.BirthDate)

            @Html.DropDownListFor(model => model.SelectedDay, new SelectList(Model.Days))
            @Html.ValidationMessageFor(model => model.BirthDate)

            @Html.LabelFor(model => model.Occupation)

            @Html.EditorFor(model => model.Occupation)
            @Html.ValidationMessageFor(model => model.Occupation)

            @Html.LabelFor(model => model.ZipCode)

            @Html.EditorFor(model => model.ZipCode)
            @Html.ValidationMessageFor(model => model.ZipCode)

            @Html.LabelFor(model => model.Email)

            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)

            @Html.LabelFor(model => model.Password)

            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)

            @Html.LabelFor(model => model.CGV)

            @Html.EditorFor(model => model.CGV)
            @Html.ValidationMessageFor(model => model.CGV)

            @Html.LabelFor(model => model.Optin)

            @Html.EditorFor(model => model.Optin)
            @Html.ValidationMessageFor(model => model.Optin)

            @Html.LabelFor(model => model.CNIL)

            @Html.EditorFor(model => model.CNIL)
            @Html.ValidationMessageFor(model => model.CNIL)

            <input type="submit" value="Create" />

    </fieldset>
}

    @Html.ActionLink("Back to List", "Index")

this is My contoller:
public ActionResult Index()
        {
        List<int> listDays = new List<int>(){1, 2, 3};
        return View(new RegistrationViewModel() { Days=listDays });
        }

[HttpPost]
public ActionResult Index( RegistrationViewModel rvm)
       {
       if (ModelState.IsValid)
          { return RedirectToAction("Welcome"); }

       return View(rvm);
       }

public ActionResult Welcome()
      {
      return View();
      }

My problem is in the post, the property Days of the viewmodel is null!!!!! How can i correct this?

A: in your View you are not rendering Days inside form
Render hidden fields inside form with name="Days" like
foreach(var day in @Model.Days)
{
<input type="hidden" name="Days" />
}
copy the above code and paste it after

     @Html.EditorFor(model => model.CNIL)
     @Html.ValidationMessageFor(model => model.CNIL)

Now,when you submit, the Days values will also submitted to the Post method and you will get values in Days List.


text:
Q: JMS messages to file in a reliable way I'm looking for a way to reliably retrieve messages from a JMS queue and store them into a flat file. By "reliably" I mean that in case of any failure (excluding failures of physical disks), possibly after system and processes are re-launched, I want:

*

*to not lose any message and

*to not have duplicate messages in my file.

What would be a good way for achieving this goal?
Context: WebLogic on Linux, receiving about 3000 messages/second for several hours.
Thanks -- Florian.

A: The problem you'll face is the file system; JMS supports JTA, but the file system does not. Consider the following:
public void onMessage(Message message){
  try{
    TextMessage msg = (TextMessage)message;
    fileOutput.write( msg.getText());
    fileOutput.flush();

  }catch(Exception e){
    e.printStackTrace();
    throw e;
  }
}

Assuming AUTO_ACKNOWLEDGE, each message received and serialized to the file will be auto acknowledged after onMessage() returns successfully. But the JMS server may crash before the acknowledgment is received, but after the message was written to the file; so you'll get a duplicate.
Instead of writing to a file, have you considered saving to a database, preferably one that has a XA driver? If so, you can use a distributed transaction between JMS and RDBMS, resulting in no message loss or duplicates.
Hope it helps


text:
Q: How can I extract a certain header from http response [Set-Cookie] I've searched around google for this, but I haven't been able to fix this problem yet, so I'm sending a post http request to a certain website, and in return I get this headers
map[Cache-Control:[no-cache] Content-Type:[application/json; charset=utf-8] Date:[Mon, 19 Oct 2020 15:38:41 GMT] Expires:[-1] P3p:[CP="CAO DSP COR CURa ADMa DEVa OUR IND PHY ONL UNI COM NAV INT DEM PRE"] Pragma:[no-cache] Site-Machine-Id:[CHI1-WEB5027] Set-Cookie:[.ROBL=A6251611CFF4513169C4CED10EFDC2DE9444E207CA376B27B906306AC18BFB0ACA6F17381240973900B19186F3E46C6BC9C52B99BC040579110E87145209A47040B241FE2C702C18AEF12A1AC746812B22596BFDB33C24DF1D5CEC72705DAD266343EC259528D8B7617BBE17408A957DF7A1C2CC7AC9DD9CC05FF8F4831BCC1669FB5221A74E6DB5C8EE0ED7F8F4AFA3767CCC39D919A62C6800EFFFF812DED5325F68D36B410D86A0CAB1FB0B8A90ADD529BE75A2DAFD3EB59D86BBC831C3144E577357B8EB0C514D0433F0B8E69DA151E6BA2C63968B46184167CAE05FE6B4749DC0449C71BB80A1306C6699E9EBD79E4C6A348CC33418D3E0DC3E6F5; expires=Wed, 12-Oct-2050 15:38:42 GMT; path=/; HttpOnly .RBID=eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyY2Q5N2IyOS01MjgxLTRjMWQtYjgxMS03OTQzNWZkNzU0ZjkiLCJzdWIiOjcxNjQ3MzgxOH0.yg9EiXLF4VY2O7Eu5mTdbax60tMrodiPbADWwRwZMeo; expires=Thu, 17-Oct-2030 15:38:42 GMT; path=/; secure; HttpOnly Data=UserID=-733325636; expires=Fri, 06-Mar-2048 16:38:42 GMT; path=/ REventTrackerV2=CreateDate=10/19/2020 10:38:42 AM&rbxid=&browserid=65376450118; expires=Fri, 06-Mar-2048 16:38:42 GMT; path=/] Vary:[Accept-Encoding] X-Frame-Options:[SAMEORIGIN]]

I want to extract .ROBL from, [Set-Cookie] just doing res.Header.Get(".ROBL") doesn't seem to be doing the job.
I tried to do split := strings.Split(string(header), ";") but that panics on fail so it's not relaible
Is there any relaible ways to extract .ROBL from [Set-Cookie] in the header?

A: Cookies are sent with the Set-Cookie HTTP header, so you can't simply get them as Header.Get("cookie-name"). You would have to parse the Set-Cookie header values. But the standard lib does this for you:
Cookies sent by a server may be parsed using Response.Cookies(). It returns you a slice of cookies (http.Cookie), just iterate over them until you find the one you're looking for.
cookies := resp.Cookies()
for _, c := range cookies {
    if c.Name == ".ROBL" {
        fmt.Println(c)
        fmt.Println(c.Value)
    }
}

Also note that if you want cookie management, you should consider using a CookieJar. For details, see What is the difference between cookie and cookiejar?


text:
Q: How to transfer a list of files to offline user with basic windows xp? I have a lot of files (100s of gb) and I want to give some of them to my friend. But he must select, which files he needs and I can't give him all files at once (I have no such big usb flash or usb hdd). I can make a list of all files and transfer them on small usb flash to him, and then he can say, which folders he want and which not.
How should I make the list of files, which can be easily viewed in standard windows xp install or with some small WindowsExplorer-like program? I can do an ls -lR-like listing and store it in txt, but it will be hard to my friend to view this list. There is a diskdir plugin of Total Commander, which can archive folder into text file with only names and paths of files stored. Then this plugin allow total commander to move inside this archive like inside the zip or arj.
But I think, total commander is to difficult to use to my friend, so I'm asking about Windows Explorer-like solution (e.g. winzip allows Explorer to move inside zip archives, and I want something like).
So. I can install any program, also I can store viewer program with file list on usb flash.

A: Just use the dir /s > C:\temp\filename.txt command. This will output the directory structure to the file C:\temp\filename.txt. Start in the location you want to go down from.
Then just send him the TXT file.

A: Assuming you can get powershell v2 installed on your local machine (or already have it installed) the following script can do what you're after (it might work in powershell v1, not certain):
$dupedir = "D:\Backup"
$newdir = "C:\Temp"
$dupelist = Get-ChildItem -Force -Recurse -ErrorAction SilentlyContinue $dupedir

foreach ($item in $dupelist)
{
    If ($item -is [Io.DirectoryInfo])
    {
        $itemtype = "directory"
    }
    If ($item -is [Io.FileInfo])
    {
        $itemtype = "file"
    }

    New-Item -Force -type $itemtype -Path $item.FullName.Replace("$dupedir","$newdir")
}

Change the path for $dupedir to the root of the path you want to let your friend know about. Once this script finishes running, you should have an exact mirror of the filestructure (but not actual files) you want to let your friend look over in C:\Temp (or somewhere else if you change the directory for the $newdir variable as well. Don't have the $newdir variable be inside the directory of the $dupedir variable or you will get infinite recursion which could eventually consume all disk space (even if the "files" are 0 byte files).
Nice thing about powershell is that you can "write" scripts at the commandline (similar to bash). Copy the code into a text editor, make the path changes, then copy and past the whole thing into your powershell window and it'll do it's magic.
I know you mentioned you have bash, and if you wanted this on a unix/linux machine I might have been able to do it in bash. Unfortunately I was never very good with bash scripting when it required monkeying around with the windows filesystem.

A: Why not use a zip file?  You can view all the files in one window, yet have them extract to different folders.

A: I thought about this question some time now and I came across two solutions. The best one is the following.
Use cdcat which is a program that can index filesystem trees like DVDs or hard drives (without storing big files to the index) and store multiple of them in one catalog. This is probably the program of choice for such a task because it will also include meta information of music (ID3 tags) and videos (resolution, duration and so on) to the catalog. Another nice feature is that cdcat can calculate how big an indexed directory or a file (node) is.
It will save all the meta information (and small files like nfo if you configure it to do this) in a compressed XML file.
To copy files from you (person A) to someone (person B), after allowing him (B) to select what he actually wants, could work like this:

*

*Person A indexes all of his interesting files (you should check the settings of cdcat before doing so to be sure what is going to be included like nfo, ID3 tags, …) and saves them as one catalog.

*Person A copies the catalog over to person B.

*Now person B has to select the files somehow. I came up with the idea of using the category field which can be added to each node (directory or file). This field could be used as a priority for example. Any node which has no category recursively attached to it or with a special category will not be copied later. The category is also saved to the XML file and it is not very hard to write a parser for this to export for example a .bat script or Bash script to copy all of the wanted files.

*Person B gives the OS specific copy script to person A (or of course person B gives the modified catalog back and lets person A generate the copy script).

*Person A executes the copy script and gives person B the data medium. (There will be one little inconvenience because cdcat does not save the path to the mount point from where the data was indexed to the catalog.)

*Person B copies the files to his storage and hands the data medium back to person A.

This solutions is not yet perfect but it is the best I came up with. I have not used this yet but I will do so in the future. During this I will need to write some extension or script which generates copy scripts for Linux and for Windows. My plan is to include this directly to the cdcat program.
A second and more sophisticated solution which is worth mentoring is to use git-annex which can probably also be used for this, but I did not think about this as careful as about the solution with cdcat because this second approach would somehow require that both persons (A and B) have git-annex and know how to use it …
I will keep you up to date.


text:
Q: Virtual Machines: High-DPI screen scale resets to 100% when I resize VM's window I've installed Ubuntu (tried 17.10 and 18.04 pre-release), since I have a 4k monitor I went to Settings - Devices - Displays and set Scale to 200%.
Everything looks fine until I resize a VM's window (including opening it fullscreen): Ubuntu resets the scale to 100% and everything becomes small.
How can I avoid this and "lock" the scale at 200%?
I tried this with VirtualBox and VMWare Player with the same results.
I know there is a "scale factor" in VirtualBox's settings but it is not the same and it makes pictures blurry.

A: Fire up your terminal and type:
gsettings set org.gnome.desktop.interface scaling-factor 2

In virtualbox i tested it, and i can resize vm window without losing scaling.
This applies to wayland, so 17.10 is best to test this.

A: I'm using VMWare and Ubuntu 18.04 LTS; and later 20.04 LTS. I never got gsettings to work right. Maybe that's because I have Wayland turned off, as it is broken on my all my VMWare VMs.
Instead, I use this command: xrandr --output Virtual1 --scale 1.75x1.75, which seems to work well enough. It doesn't resize until after I log in. The command is persistent, so I haven't added it to any startup scripts or anything.
I don't have any problems with a blurry display, and I definitely have to use a factor greater than zero -- otherwise, the text and user interface elements are very large. It's counter-intuitive, but that's what's working for me!  Maybe two different things are fighting to scale correctly?


text:
Q: How can I check if I said one of the words contained in a list using speech_recognizer I'm trying to create a little program which should print something if in what I say (not only one word but a phrase) (using speech_recognizer) there is  a word which is  contained in a list of words (word_list). Also the output should change if I say one word or another so I need to check exactly which word is it.
import speech_recognition as sr

word_list = ['Giotto', 'Raffaello', 'Michelangelo']

recognizer_instance = sr.Recognizer()

with sr.Microphone() as source:
    recognizer_instance.adjust_for_ambient_noise(source)
    print("I'm listening...")
    audio = recognizer_instance.listen(source)
    print('Printing what I heard...')

try:
    text = recognizer_instance.recognize_google(audio, language='it-IT')
    print(text)
except Exception as e:
    print(e)

this is my code at the moment and I can't figure out how to check if one of the words contained in the text variable is in my word_list

A: If you simply wish to check if what you said is in the list you can use:
if text in word_list:
    #Some logic

this will return True if the variable's text content is inside word_list.
EDIT:
You can define a dictionary instead of a list and store the bio of each artist like that:
artists_bio = {'artist1': 'artist1 bio', 'artist2': 'artist2 bio'...}

Then in order to print this bio if the recognizer heard the matching word you can use:
if text in artist_bio.keys():
    print(artist_bio[text])

EDIT2 :
if your text is an entire sentence you could first split it and then use same logic as before.
list_text = text.split(' ')
for text in list_text:
    if text in artist_bio.keys():
        print(artist_bio[text])


text:
Q: Public static methods vs public methods What's the difference between a public static method and a public method? Why would you use a public static method?

A: static methods are methods that a not specific to any instance of a class (object) they are methods that are not allowed to contain this references and you can access them through the class directly (not the object instances)

A: Static methods can be used as overloaded constructors. ActionScript doesn't have function overloading, so sometimes I'm writing something like:
public class Foo {
    public static function fromBar(bar:Bar):Foo {
        var foo:Foo = new Foo();
        ... //initializing foo object from bar
        return foo;
     }

    public static function fromBaz(baz:Baz):Foo {
        var foo:Foo = new Foo();
        ... //initializing foo object from baz
        return foo;
    }
}

A: To make your concept clear, Suppose if you want to know how many times your class has been instantiated, you will be using static variable counter in your class constuctor, each time your object is created.
Then you have to use static method to access this data else you can declare your variable public or default and access it with class name but that violates the OOP principals. here is the little example
public class CAR
{
private static var Counter:int=0;
private function CAR(){ Counter++; }
public static function ReturnTotalCarInstances():int
{
   return Counter;
}
}
Static variables have their benefit thats why it is provided in most programming languages. Counting instances is the small use of static variable. They are used in much bigger scope. The main point is it is used to share data globally among all objects of Class.

A: The methods of the Math class are static. So, in doing
Math.round(average)

the Math class itself is unchanged by what you've done - it only returns a value or acts upon the value you pass.
So - static methods are useful for utilities. Things like
StringUtils.removeWhitespaceFrom(textContent:String):String

or
BrowserUtils.openInNewWindow(url:String):void

It's very unusual that you'd use a static method for anything else. Don't use statics like 'getInstance()' to create Singletons - look into a framework for dependency injection instead.