text:
Q: Deleted NetworkServices - How to recover and will the PC work? Our junior-admin at university deleted the NetworkServices directory in Documents and Settings on all local computers. Will the PC work (AD Authentication) and can I just copy the NetworkServices directory from another PC?
I'm a Linux admin who has to fix this mess, so I need your advice!

A: That's the network service profile folder, which is a user folder for the built-in network service account.  The purpose of that account is to authenticate the computer to the domain for the purpose of accessing certain resources on the network. See the below article for a bit more information on local/network service accounts.
http://www.windowsitpro.com/article/services/understanding-the-local-service-and-network-service-accounts
If I remember correctly, Windows XP will just restore the folder upon reboot.  I would recommend, if you have a desktop that you can afford to "break", simply rebooting a machine and checking it out.

A: That should just be the profile for the NetworkServices account.  The folder should recreate itself when the PC reboots.  The easy way to check would to be take a test machine and reboot it then check the event log for error messages.


text:
Q: Can Security Center trigger a webhook Is there a way to have Security Center trigger a webhook whenever a recommendation or alert is made?
Currently, I can create an alert in Azure Monitor and have it query OMS, then if the alert fires, have it notify an Action Group using a webhook.
As far as I can tell, the only notifications in Security Center are "Email notifications" under the "Security Policy" section which are "[used] in case our security team finds that your resources are compromised."
I'm hoping I can avoid having to create alerts that mirror their queries in order to set up webhook.

A: I am not aware of the ability to use webhooks in Azure Security Center but you can have a look at a preview feature from earlier in the year called Security Playbooks
Link: https://learn.microsoft.com/en-us/azure/security-center/security-center-playbooks
Essentially though a security playbook in security center is the below:
Security playbook is a collection of procedures that can be executed from Security Center once a certain playbook is triggered from selected alert. Security playbook can help to automate and orchestrate your response to a specific security alert detected by Security Center. Security Playbooks in Security Center are based on Azure Logic Apps, which means you can use the templates that are provided under the security category in Logic Apps templates, you can modify them based on your needs, or you can create new playbooks using Azure Logic Apps workflow, and using Security Center as your trigger.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Puppeteer fails in React app after running electron-builder I am using puppeteer in some back-end js within a react app.
The code is fairly simple in regards to the puppeteer components and it works when testing the app in a normal development script within yarn. The likely relevant code is fairly simple:
const puppeteer = require('puppeteer');
  try {
     let browser = await puppeteer.launch({headless: false,
     executablePath: process.env.CHROMIUM_PATH,
     args: ["--no-sandbox",
            "--disable-setuid-sandbox"]
});}
  catch (error) {
    return await error;
  }

However, when I use electron-builder to compile the project into an executable I get the following error message:
Error: Failed to launch the browser process! spawn
<project directory in AppData>\node_modules\puppeteer\.local-chromium\win32\chrome-win\chrome.exe
ENOENT TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

I thought it might be a problem with my dependencies, but I feel like I've tried everything
Anyone have any guidance?
.local-chromium file summary:
.local-chromium
  |win32
    |chrome-win
      |locales
      |MEIPreload
      |swiftshader
      |files within chrome-win

Files within chrome-win include:
-chrome.exe
-chrome_proxy.exe
-chrome_pwalauncher.exe
-chrome.dll
-Other PAK files, and smaller applications

There is nothing located in .local-chromium or win32 besides the subdirectories

A: As sebasaenz suggested, it was a problem with puppeteer accessing Chromium. I looked into the directory not being zipped but all files looked extracted.
I couldn't figure out what the issue was with .local-chromium so I decided to switch angles and just direct puppeteer to my normal chrome.exe to run itself. You can do this with the executablePath argument in puppeteer.launch:
let browser = await puppeteer.launch({executablePath: "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"})

chrome.exe might be in a different location for you, but I'm pretty sure mine is the default
This did allow my app to work when packaged, unfortunately it means that it won't automatically work when moved to a different machine if the chrome path is different. Not the worst trade off for a working program though.

A: Puppeteer fails because it not able to find its executable, Use bellow solution this works for me Prod as well as Dev enviroment.

"build": {
   "asar": true,
   "asarUnpack": "node_modules/puppeteer/.local-chromium/**/*"
 }

 function getChromiumExecPath() {
    return puppeteer.executablePath().replace('app.asar', 'app.asar.unpacked');
 }

 export function createBrowser(options = {}) {
     return puppeteer.launch({
            ...options,
            executablePath: getChromiumExecPath()
      });
 }

A: It seems that the issue has to do with a failed unzipping. There's actually an open issue about this on GitHub.
A possible workaround is to manually unzip the zip file and extract it into the chrome-win folder in this case.
For Mac (the workaround in the GitHub issue) it's something like this:
unzip node_modules/puppeteer/.local-chromium/chrome-mac.zip
cp -r chrome-mac/Chromium.app/ ./node_modules/puppeteer/.local-chromium/mac-756035/chrome-mac/Chromium.app/

So I think that in your case you should look for the zip file in the win32 or chrome-win folders and copy it to the chrome-win folder.

A: My app installs with a resources/app.asar.unpacked directory.  The error it was throwing was
spawn <install_directory>\win-unpacked\resources\app.asar\node_modules\puppeteer\.local-chromium\win64-856583\chrome-win\chrome.exe ENOENT
So, when starting puppeteer, I do this:
async function openBrowser() {
  var executablePath =
    puppeteer
      .executablePath()
      .replace("app.asar", "app.asar.unpacked")

  const browser = await puppeteer.launch({
    executablePath: executablePath
  });

  return browser
}

Works on first pass, haven't distributed to users yet.  Haven't tested on OSX.


text:
Q: Parsing CSV file with \n in double quoted fields I'm parsing a CSV file that has a break line in double quoted fields. I'm reading the file line by line with a groovy script but I get an ArrayIndexOutBoundException when I tried to get access the missing tokens.
I was trying to pre-process the file to remove those characters and I was thinking to do that with some bash script or with groovy itself.
Could you, please suggest any approach that I can use to resolve the problem?
This is how the CSV looks like:
header1,header2,header3,header4
timestamp, "abcdefghi", "abcdefghi","sdsd"
timestamp, "zxcvb
fffffgfg","asdasdasadsd","sdsdsd"

This is the groovy script I'm using
def csv = new File(args[0]).text
def bufferString = ""
def parsedFile = new File("Parsed_" + args[0]);

csv.eachLine { line, lineNumber ->

    def splittedLine = line.split(',');

    retString += new Date(splittedLine[0]) + ",${splittedLine[1]},${splittedLine[2]},${splittedLine[3]}\n";

         if(lineNumber % 1000 == 0){
                parsedFile.append(retString);
                retString = "";
         }

}
parsedFile.append(retString);

UPDATE:
Finally I did this and it works, (I needed format the first column from timestamp to a human readable date):
 gawk -F',' '{print strftime("%Y-%m-%d %H:%M:%S", substr( $1, 0, length($1)-3 ) )","($2)","($3)","($4)}' TobeParsed.csv > Parsed.csv

Thank you @karakfa

A: If you use a proper CSV parser rather than trying to do it with split (which as you can see doesn't work with any form of quoting), then it works fine:
@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv

def csv = '''header1,header2,header3,header4
timestamp, "abcdefghi", "abcdefghi","sdsd"
timestamp, "zxcvb
fffffgfg","asdasdasadsd","sdsdsd"'''

def data = parseCsv(csv)
data.eachWithIndex { line, index ->
    println """Line $index:
              |    1:$line.header1
              |    2:$line.header2
              |    3:$line.header3
              |    4:$line.header4""".stripMargin()
}

Which prints:
Line 0:
    1:timestamp
    2:abcdefghi
    3:abcdefghi
    4:sdsd
Line 1:
    1:timestamp
    2:zxcvb
fffffgfg
    3:asdasdasadsd
    4:sdsdsd

A: awk to the rescue!
this will merge the newline split fields together, you process can take it from there
$ awk -F'"' '!(NF%2){getline remainder;$0=$0 OFS remainder}1' splitted.csv

header1,header2,header3
xxxxxx, "abcdefghi", "abcdefghi"
yyyyyy, "zxcvb fffffgfg","asdasdasadsd"

assumes that odd number of quotes mean split field and replace new line with OFS.  If you want to simple delete new line (the split parts will combine) remove OFS.


text:
Q: Matplotlib `fill_between` to fill in rhomboid I'm currently trying to color in a region that looks like a rhomboid using the matplotlib.pyplot.fill_between() method.
I'm currently using fill_between() twice but I was wondering if there was a way to fill in the shape using the method just once. Allow me to elaborate.
In order to get the following image:

The code I wrote looks like this:
import matplotlib.pyplot as plt

# Fill in area.
plt.fill_between([0, 1, 4], [0, 1, 4], [0, 3, 4], color='C2', label=r'$c\vec{v} + d\vec{w}$')
plt.fill_between([0, 3, 4], [0, 3, 4], [0, 1, 4], color='C2')

# v
plt.quiver(0, 0, 3, 1, color='C0', angles='xy', scale_units='xy', scale=1, label=r'$\vec{v}$')

# w
plt.quiver(0, 0, 1, 3, color='C1', angles='xy', scale_units='xy', scale=1, label=r'$\vec{w}$')

# Miscellaneous.
plt.xlim(-1, 6)
plt.ylim(-1, 6)
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.xlabel(r'$x$', fontsize='large')
plt.ylabel(r'$y$', fontsize='large')
plt.grid()
plt.legend()
plt.show()

Is there a way to fill in the shape by using the fill_between() method just once?
Thank you.

A: Since you are drawing a polygon, consider drawing a Polygon.
import numpy as np
import matplotlib.pyplot as plt

# v
plt.quiver(0, 0, 3, 1, color='C0', angles='xy', scale_units='xy', scale=1, label=r'$\vec{v}$')
# w
plt.quiver(0, 0, 1, 3, color='C1', angles='xy', scale_units='xy', scale=1, label=r'$\vec{w}$')

verts = [0,3,4,1,0]
poly = plt.Polygon(np.c_[verts,verts[::-1]], color="C2", zorder=0,
                   label=r'$c\vec{v} + d\vec{w}$')
plt.gca().add_patch(poly)

# Miscellaneous.
plt.autoscale()
plt.margins(.2)
plt.grid()
plt.legend(loc="upper left")
plt.show()


text:
Q: Add router-link-exact-active to parent component when child component is in view I have character component where I have a listing of characters. Each characters have a router-link which is redirecting to characters detail component. I want to add router-link-exact-active in Nvabra's character when character detail is in view.
{
    path: '/characters',
    name: 'characterList',
    component: () => import('../components/characters/characterList.vue')
  },
  {
    path: '/characters/:id',
    name: 'characterDetail',
    component: () => import('../components/characters/charactersDetail.vue')
  },

Navbar

   <router-link to="/">home</router-link>

   <router-link to="/about-Us">about us</router-link>

   <router-link to="/characters">characters</router-link>

   <router-link to="/our-comics">comics</router-link>


text:
Q: What implementation of cycle is better? I wonder, what implementation is better from reading and performance sides.
1)
for (DateTime
         dayStart = GetDayStart(today),
         dayEnd = GetDayEnd(today);
     dayStart < endOfPeriod;
     dayStart = dayStart.AddDays(1), dayEnd = dayEnd.AddDays(1))
{
    // ...
}

2)
DateTime dayStart = GetDayStart(today),
         dayEnd = GetDayEnd(today);

while (dayStart < endOfPeriod)
{
    // ...
    dayStart = dayStart.AddDays(1);
    dayEnd = dayEnd.AddDays(1);
}

3) Or, may be any another?
Thanks in advance.

A: Personally, I find the second one the most readable. Multiple statements in a for-loop are more error-prone and less clear to an objective reader of your code.

A: For readability I would go with the second choise. The for statement is great for simpler loops, but it gets harder to follow when it gets more complicated.
For performance there should be no difference at all. The compiler will likely produce the exact same code from the two different source codes.

A: If you looking for minor variations of your approach you could also look at using Timespan...
        DateTime dayStart = GetDayStart(today);
        TimeSpan days = GetDayEnd(today) - dayStart;
        while (dayStart < endOfPeriod)
        {
            DateTime dayEnd = dayStart.Add(days);

            // ...
            dayStart = dayStart.AddDays(1);
        }

Only reason I like this more is because I didn't like the fact you had to increment both dates.


text:
Q: default type used by jayway jsonpath? when I have a value such as
x = 0.5771622052130299

and I want to do the following, using spring 3.2 Resutlmatcher :
.andExpect(jsonPath("$.[1].myX").value(myPojo.getMyX()))

where myPojo.getMyX returns a double, the test fails as the json is converted to a BigDecimal, with the error messaeg
java.lang.AssertionError:
For JSON path $.[1].myX type of value expected:
<class java.lang.Double> but was:<class java.math.BigDecimal>

How can I avoid this ?

A: Use Hamcrest to create a custom matcher which casts to BigDecimal. Here is a tutorial:

*

*Writing Custom Matchers
Code from an unrelated question may also help.
References

*

*JSONPath

A: I had the same problem but I could not change the type Hamcrest was using for the JSON value (BigDecimal).
Used this Workaround:
public static final double DEFAULT_PRECISION = 0.000001;

public static Matcher<BigDecimal> closeTo(double value, double precision) {
    return BigDecimalCloseTo.closeTo(new BigDecimal(value), new BigDecimal(precision));
}

public static Matcher<BigDecimal> closeTo(double value) {
    return closeTo(value, DEFAULT_PRECISION);
}

...
.andExpect(jsonPath("$.values.temperature").value(closeTo(-13.26517)));

A: I had the same problem with different values where some were parsed as BigDecimal and some as double.
So I choose not to use jsonPath, instead I convert the response to the actual object using MappingJackson2HttpMessageConverter:
public class ControllerTest {

    @Autowired
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;

    @SuppressWarnings("unchecked")
    protected <T> T toObject(MockHttpServletResponse response, Class<T> clazz) throws IOException{
        MockClientHttpResponse inputMessage = new MockClientHttpResponse(response.getContentAsByteArray(),
                HttpStatus.valueOf(response.getStatus()));
        return (T) mappingJackson2HttpMessageConverter.read(clazz, inputMessage);
    }

    @Test
    public test(){
        MvcResult result = mockMvc.perform(get("/rest/url")...)
            .andExpect(status().isOk())
            .andExpect(content().contentType(APPLICATION_JSON_UTF8))
            .andReturn();

        MyPojoClass pojo = toObject(result.getResponse(), MyPojoClass.class);
        assertArrayEquals(new double[]{0.1, 0.2, 0.3}, pojo.getDoubleArray());
    }

}

A: Since it is expecting a Big Decimal...you can convert the double to Big Decimal
.andExpect(jsonPath("$.[1].myX", is(new BigDecimal(myPojo.getMyX()))))


text:
Q: Construct an order on a field $\mathbb{Q}^2$ Let $\mathbb{Q}$ be the field of rational numbers. Let $\mathbb{Q}^2=\{(a,b):a,b\in\mathbb{Q}\}$ and define addition and multiplication as follows:
$$
(a,b)+(c,d)=(a+c,b+d)\\
(a,b)\cdot(c,d)=(ac+2bd, ad+bc)
$$
Then $(\mathbb{Q}^2, +, \cdot)$ is a field, and $(0,0)$ is its zero element while $(1,0)$ is its unit element. The inverse of $(a,b)$ is $(\frac{a}{a^2-2b^2},-\frac{b}{a^2-2b^2})$. I'm asked to construct an order on it such that it becomes an ordered field, namely invariant under addition and multiplication with a positive element.
What I know is $(1,0)>(0,0)$, so $(n,0)>(0,0)$ for any natural number $n$. I don't quite know how to proceed. Is there any rules to follow to construct an order on a field?
Thank you for any help!

A: There aren't any general rules, but in this case your field is actually (isomorphic to) a sub-field of $\mathbb{R}$. If you calculate what $$(0,1) \cdot (0,1)$$ is it may suggest how to map your field into $\mathbb{R}$. Then you can "pull back" the order on $\mathbb{R}$ onto your field.
BTW, @Toby's observation that such an order is not unique supports the idea that there are not general rules. If there were a set of rules they would likely lead to a unique answer, but we can see that there isn't a unique answer. And while we're talking more generally it's also worth noting that sometimes there is no such order, e.g. there never is for any finite field.

Follow up: If my comments about uniqueness don't make sense to you right now feel free to ignore them; they're just there to give a wider more general view.
Yes, that's the isomorphism I was thinking of. Because $$(1,0) \cdot (a,b) = (a,b)$$ for any $(a,b)$ we can see that $(1,0)$ acts like $1 \in \mathbb{R}$, and because $$(0,1)^2 = (0,1)\cdot(0,1) = (2,0)$$ we can see that $(0,1)$ acts like $\sqrt{2} \in \mathbb{R}$ (or like $-\sqrt{2}$ if you prefer - you can choose either but then must stick with it,)
So it makes sense to define $\phi : \mathbb{Q}^2 \rightarrow \mathbb{R}$ by $\phi( (a,b) ) = a+b\sqrt{2}$. Now you must explicitly show that $$ \phi((a,b)+(c,d)) = \phi((a,b)) + \phi((c,d))$$ and $$ \phi((a,b)\cdot(c,d)) = \phi((a,b)) \cdot \phi((c,d))$$ (As you write out the proof for multiplication you might see why we had to choose $\pm\sqrt{2}$ for $(0,1)$.
After you've done that you can "pull back" the ordering on $\mathbb{R}$, which means you define that "$(a,b) \lt_{\mathbb{Q}^2} (c,d) \iff \phi((a,b)) \lt_\mathbb{R} \phi((c,d))$", where the $\lt_\mathbb{R}$ on the right-hand side is the usual order on $\mathbb{R}$. You should then be able to show that  $\lt_{\mathbb{Q}^2}$ is invariant under addition and multiplication by using the invariance of $\lt_\mathbb{R}$. Note that this is something that you have to write out explictly; it's not enough to observe it. If you're just getting started in abstract algebra you might find this a little hard but really you're just applying $\phi$ and $\phi^{-1}$ and "pushing symbols around".
Notice that this method assumes the existence of both $\mathbb{R}$ and its invariant ordering $\lt_\mathbb{R}$ (and also the existence of $\sqrt{2})$. Since this will make the problem much easier I'd go ahead and assume we know they exist. If we were not allowed to assume them we'd have to find a way to express "$a+b\sqrt{2} \lt c+d\sqrt{2}$" without using the concept of $\sqrt{2}$, which gets a lot more complicated.

A: The quick and easy answer is to notice that this field is isomorphic to $\mathbb Q[\sqrt{2}]$ by sending $(a,b)$ to $a+b\sqrt 2$, so $(a,b)<(c,d)$ if $a+b\sqrt 2<c+d\sqrt 2$.


text:
Q: Using a email list from .txt file to cycle through and test logins? Basically I have a list of emails on a .txt file. My goal is to run through each of them one by one and test to see if accounts are valid. What I'm trying to set up in my code is to set variable to go up one by one with this login = email[0].format(start + i). In theory this would change the selection of the emails in my list. So each time a new email is selected it would run the code with that email. But it seems to just pick [0] every time, is this the correct method for what I'm trying to obtain? If not would you be able to point in a more efficient method of obtaining each email to run in the code?
I also was thinking this may be something i should try login = email[num] but i get a error asking for a integer not a string. Any advice on which direction to go would be greatly appreciated.
CODE
import requests
import time

start = 1
#while True:
for i in range(500):
    password = 'abcdefg'
    num = ('{0}').format(start + i)

    with open('email.txt') as email_text:
        email = email_text.read().splitlines()

    login = email[0].format(start + i)
    #login = email[num]

    APP_VERSION = '100'
    EXPERIENCE = '200'

    session = requests.Session()
    session.headers.update({
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
    })
    session.get('https://www.nike.com/snkrs/')
    try:
        print(login)
        print('Logging in...')
        login_data = {
            'username': login,
            'password': password,
            'keepMeLoggedIn': True,
            'client_id': 'hfkjshfkjshfkjshdf',
            'ux_id': 'com.nike.commerce.snkrs.web',
            'grant_type': 'password'
        }
        login_params = {
            'appVersion': APP_VERSION,
            'experienceVersion': EXPERIENCE,
            'uxid': 'com.nike.commerce.snkrs.web',
            'locale': 'en_US',
            'backendEnvironment': 'identity',
            'browser': 'Google Inc.',
            'os': 'undefined',
            'mobile': 'false',
            'native': 'false'
        }
        login_url = 'https://unite.nike.com/loginWithSetCookie'

        login_res = session.post(login_url, json=login_data, params=login_params)
        time.sleep(1)
    except:
        pass
        time.sleep(1)
        access_token = None
    try:
        access_token = login_res.json()['access_token']
    except ValueError:
        print('Could not login.')
    except KeyError:
        print('Could not login.')
    if not access_token:
        quit()

    print('Logged in.')

    print('Getting address info...')

    get_address_params = {
        'appVersion': APP_VERSION,
        'experienceVersion': EXPERIENCE,
        'uxid': 'com.nike.commerce.snkrs.web',
        'locale': 'en_US',
        'backendEnvironment': 'identity',
        'browser': 'Google Inc.',
        'os': 'undefined',
        'mobile': 'false',
        'native': 'false',
        'viewId': 'commerce',
        'token': access_token
    }
    get_address_url = 'https://unite.nike.com/getUserService'
    get_address_res = session.get(get_address_url, params=get_address_params)
    print('Retreived address info.')

    verified = 'verifiedphone' in get_address_res.json()
    print('Verified: '+str(verified))

A: *

*pip install pandas

*Your email list should be a csv or excel.

*Lets assume your emails as stores in the emails column
import pandas as pd

df = pd.read_csv('file.csv')

def check_valid_emails():
    try:
    """login and check emails valid
     assign responses """
    is_valid = response.post(login here)
    except:
return {'email':email,'valid':''}

valid_emails_report = map(check_valid_emails,df.emails.tolist())
pd.DataFrame(valid_emails_report)


text:
Q: Cron service is not executing my script I created a shell script that will move and copy some files. My script is working. Everyday I run it manually because cron is not doing its job (I probably did it wrong). My shell file has permissions 777, all folders, CRON/ROOT is have permissions 777. I'm running Cent OS 6.7 Final. I want to run this cron everyday at 01:01AM.
My script (pdb.sh)
#!/bin/bash
/etc/init.d/pdb stop
mv /var/www/html/acesso/ui/root/mtaserver.conf /root/PDB/mods/deathmatch/mtaserver.conf
sleep 2
cp /root/PDB/mods/deathmatch/mtaserver.conf /var/www/html/acesso/ui/root/mtaserver.conf
sleep 2
mv /var/www/html/acesso/ui/root/admintag.lua /root/PDB/mods/deathmatch/resources/[RESOURCES]/022/admintag.lua
sleep 2
cp /root/PDB/mods/deathmatch/resources/[RESOURCES]/022/admintag.lua /var/www/html/acesso/ui/root/admintag.lua
sleep 2
chmod -R 777 /var/www/html/acesso/ui/root/
/etc/init.d/pdb start

crontab -l

crontab -e

A:
Try putting /bin/sh in front of the script location. – Matt Schuchard


text:
Q: Crystal Reports "File Break" I'm generating a Crystal Reports report which will ultimately need to be split into thousands of pdf files. What would be ideal would be if Crystal Reports had something like a "file break", like a page break, that you could insert into the file at the appropriate places.
I will need reasonably fine control over the file names, as well....something like "fileName_{CustomerId}_{CustomerIsLocal}.pdf".
I'm presuming a third-party piece of software will probably be needed. Thoughts?
TIA.

A: I wanted to document this for anyone else who shows up looking for the answer:
private readonly CrystalReportViewer reportViewer = new CrystalReportViewer();
...
this.reportViewer.ReportSource = @"C:\PathToReport\Report.rpt";

using (var crystalReport = new ReportDocument())
{
    foreach (DataRow row in dataSet.Tables[0].Rows)
    {
        var customerId = int.Parse(row["customerId"].ToString());
        var isCurrent = bool.Parse(row["isCurrent"].ToString());
        var totalSales = int.Parse(row["totalSales"].ToString());

        // generate the report for each row
        this.CreateReport(customerId, isCurrent, totalSales, crystalReport);
    }
}

private void CreateReport(int customerId, bool isCurrent, int totalSales, ReportDocument crystalReport)
{
    crystalReport.Load(this.reportViewer.ReportSource.ToString());

    crystalReport.SetParameterValue("customerId", customerId);
    crystalReport.SetParameterValue("isCurrent", isCurrent);
    crystalReport.SetParameterValue("TotalSales", totalSales);

    var fileName = string.Format("EndOfYear_{0}_{1}.pdf", customerId, isCurrent ? 1 : 0);

    var outputPath = Path.Combine(this.txtOutputDirectory.Text, fileName);

    crystalReport.ExportToDisk(ExportFormatType.PortableDocFormat, outputPath);
}

References:
CrystalDecisions.CrystalReports.Design
CrystalDecisions.CrystalReports.Engine
This code yields a filename like so:
"EndOfYear_123456_1.pdf"
It is certainly possible to generate the report object for each row, rather than passing it in, but slows things down quite a bit. Reusing the same report object doesn't have any negative impact as far as I could see, and made things go about ten times faster.
The only other thing you need is how to prepare a Crystal report, which is beyond the scope of this tutorial. Good luck!

A: I do not think Crystal supports such functionality. We currently manage this ourselves in our application, asspecially where the name format is required to be customized, and your intensions are to run the report for a Customer Group. You will have to look at doing this job using some code (C# is what we used).
If you have more questions in this regard, Please feel free to ask, so that i can assist.
Adriaan

A: The functionality you're looking for is generally referred to as "bursting". While there are various third-party tools to do this, Business Objects Enterprise also can (though Crystal Reports Server can't). It might be out of your price range, but it's definitely worth looking at for the flexibility it gives you in report distribution...

A: Report Runner Batch is an inexpensive 3rd party solution that can do it:
http://www.reportrunner.com


text:
Q: Oracle: spool data to different files depending on where condition (loop) I am trying to get my way around something like this
declare
  filename varchar2(100);
begin
  for condition in (select fieldN from mytable) loop
    filename := 'data_for_value'||condition.fieldN||'txt';
    spool filename
    select some_data from some_table where fieldN = condition.fieldN;
    spool off
  end loop;
end;

In order to export different sections of data from a table onto different files but I just cannot get it right, I have read this and tried to do something similar in consequence:
set serveroutput on
set pagesize 0
set numwidth 2
set trimspool on

DECLARE
  filename varchar2(100);
BEGIN
  for field2 in (select field2 from blau2) loop
    filename := 'COST_TRAN_BASE '||field2.field2||'.txt';

    spool "run_query.sql" REPLACE

    select distinct 'spool "' || filename || '.txt"' || chr(10) ||
              'select field1, field3 from blau2 where field2 = ' || field2.field2|| ';' || chr(10) ||
              'spool off' cmd
    from blau2;
    spool off
    @"run_query.sql"
  end loop;
END;

But to no avail. I get the feeling that I am not allowed to use the spool command where I am trying to (I recently started working in the Oracle environment and the line between SQL*Plus and PL/SQL is still a bit blurry (you can kill me now for my ignorance :') ))
Am I just struggling against the impossible? D:
Edit:
with the initial help of Balazs Papp and my follow up investigations I came up with this system:
Using this file:
basic_script.txt
-----------------
SET PAGESIZE 0
SET TRIMSPOOL ON

spool RUN_QUERY.sql REPLACE

select distinct 'set heading off' || chr(10) ||
        'spool "BLAU2 ' || field2 || '.txt"' || chr(10) ||
                'select field1||chr(9)|| field3 from blau2 where field2 = ' ||
field2 || ';' || chr(10) ||
                'spool off'
    from blau2;

spool off
-----------

And this other file:
basic_script_condition.sql:
-----------
set feedback off
set trimspool on
set recsep off
set serveroutput on

col some_column new_value script_name
select decode((select count(*) from (select distinct FIELD2 from BLAU2)),1,'exit.sql','RUN_QUERY.sql') some_column from dual;
@&script_name
-----------

Calling them from command line in a simple .bat program:
basic_launcher.bat:
-------------
echo exit | sqlplus lmartin/lmartin @"BASIC_SCRIPT.txt"
echo exit | sqlplus lmartin/lmartin @"BASIC_SCRIPT_CONDITION.sql"
-------------

A script for exporting the different sections of data in the BLAU2 table is generated and executed only if there is data to export (if there is no data to export, basic_script would generate a .sql file with no rows selected as its content, possibly repeated N times, and the execution would fail, hence the basic_script_condition.sql controlling this behavior).

A: SQL> create table t1 (c1) as select mod(rownum, 4) from dual connect by level <= 12;

Just to have some sample data.
$ cat run.sql
set heading off feedback off echo off termout off pagesize 0
spool select.sql
select distinct 'spool c1_' || c1 || '.txt ' || chr(10)|| 'select c1 from t1 where c1 = ' || c1 || ';' || chr(10) || 'spool off' from t1 order by 1;
spool off
@select.sql
!rm select.sql
exit

$ sqlplus -s bp/bp @run.sql

And the result:
$ grep "" *txt
c1_0.txt:         0
c1_0.txt:         0
c1_0.txt:         0
c1_1.txt:         1
c1_1.txt:         1
c1_1.txt:         1
c1_2.txt:         2
c1_2.txt:         2
c1_2.txt:         2
c1_3.txt:         3
c1_3.txt:         3
c1_3.txt:         3

A: spool is a SQL*Plus internal command. In your example you are trying to use spool inside a PL/SQL block. The spool command is unknown to the PL/SQL language.
The best option to achieve what you want (write to different text files inside PL/SQL) is to use the UTL_FILE (Oracle 9i and beyond) Oracle internal package.
http://oracle-base.com/articles/9i/utl_file-random-access-of-files-9i


text:
Q: DataTable Custom Search Box Ok. I am new to DataTables and recently I needed to find a way to add my own search box for Datatables grid and failed brilliantly. I looked for a solution on Datatables.net forum and Stackoverflow but none of the solutions worked for. Although later combining two solutions and thanks to Jsfiddle I managed to find something that works and repeatable.
This just me sharing what I think is useful for a beginner like myself so it's up to you to treat it how you like.

A: HTML
<input type="text" class="column_filter form-control input-lg" id="col0_filter" size="40">

                MotherTag
                Projected Delivery Date
                SPPO
                Batch Qty
                PO
                Select

                    bla bla

JavaScript/ Jquery


text:
Q: How to use mktime64(), time64() and localtime64() function with 32-bit time library? How to use the mktime64() in Linux with 32-bit time library to avoid the year 2038 issue?
We have tried using the macro _Time64 but failed as compiler still throws undefined mktime64() error:
typedef long long _Time64_t;

_Time64_t _Time64(_Time64_t *pt);

struct tm *_Localtime64(_Time64_t *pt);

_Time64_t _mktime64(_Time64_t pt);

main.c:(.text+0x68): undefined reference to `_mktime64'

Could you please help me how to use the mktime64, time64 and localtime64 function using 32-bit library?

A: C standard libraries (CRT) on Linux only has one time_t type so there's no _mktime64 for you
On 32-bit Windows there are 2 different time_t types (__time32_t and __time64_t) and 2 versions of each time functions (like _mktime32 and _mktime64) just because Microsoft gradually added 64-bit time support to their CRT without breaking old code. Standard identifiers like time_t or mktime are actually macros that will be defined as the desired 32 or 64-bit version. time_t was changed to 64-bit by default in VS2015 so all apps compiled since then will not suffer from year 2038 problem. For more information read Another look at the year 2038 problem

Linux CRTs address the year 2038 issue by changing time_t to a 64-bit type immediately without any gradual intermediate steps. That happened in 32-bit glibc 2.32+ and musl 1.2+ running on Linux kernel 5.6 or later. So to avoid the year 2038 issue on 32-bit Linux you must be on a new enough kernel and CRT

*

*All user space must be compiled with a 64-bit time_t, which will be supported in the coming musl-1.2 and glibc-2.32 releases, along with installed kernel headers from linux-5.6 or higher.

*Applications that use the system call interfaces directly need to be ported to use the time64 syscalls added in linux-5.1 in place of the existing system calls. This impacts most users of futex() and seccomp() as well as programming languages that have their own runtime environment not based on libc.

https://lkml.org/lkml/2020/1/29/355?anz=web

If you can't upgrade the CRT and kernel version then you need to use a 3rd party library like evalEmpire/y2038

This is an implementation of POSIX time.h which solves the year 2038 bug on systems where time_t is only 32 bits. It is implemented in bog-standard ANSI C.

If your kernel version is between 5.1 and 5.6 then you can also write your own wrapper functions because 64-bit time support on 32-bit platforms was introduced to the Linux 5.1 kernel with the addition of the new *time64 syscalls
For more information read

*

*Approaching the kernel year-2038 end game

*64-bit time symbol handling in the GNU C Library

*glibc Y2038 Proofness Design

*Change time_t and clock_t to 64 bit

*A look at the Year 2036/2038 problems and time proofness in various systems

A: These functions seem to be Microsoft only


text:
Q: How to set Word2007 to reject US spellings for Canadian dictionary I've got MSWord2007 set to use a Canadian dictionary but it's still accepting American spelling for words (i.e. 'color' instead of 'colour'). I would like it to reject/highlight any spelling that does not conform to Canadian dictionaries, but Word 2007 is very alien to me. Any ideas?

A: Never mind... Google teaches me things! I found that I had both US and Canadian dictionaries enabled.
For reference, go to the Office Tools folder from Windows' start menu and select 'Microsoft Office Language Settings', you can add/remove dictionaries there.
Reference link: http://www.lizjamieson.co.uk/2007/12/03/how-to-set-the-default-language-dictionary-on-microsoft-word-2007/


text:
Q: Does interface builder support multiple image resolutions for different screen sizes? The form factor button is great for testing the different iphone screen sizes, as is the assitant editor preview for older iOS version layouts.
Ofcourse if there is a background image that covers most of the screen then we need to creating tweaked images to fit the available space in each screen configuration.
Coding for it is the obvious way but working intuitively in interface builder becomes broken.
Does IB support this somehow I'm not seeing?

A: Well, one way of doing it is you can just load different XiBs depending on the screen size. Create two XiBs - VC1 and VC2.
You can then do this:
if([[UIScreen mainScreen]bounds].size.height == 1136) {
    MyViewController *vc = [[MYViewController alloc] initWithNibName: @"VC1"];
    // push vc in Navigation Controller
}
else if ([[UIScreen mainScreen]bounds].size.height == 960) {
     MyViewController *vc = [[MYViewController alloc] initWithNibName: @"VC2"];
    // push vc in Navigation Controller
}

Hope that helped. I've used this method before and it worked fine. Also, apologies if there are any typos in the code. Didn't type it in Xcode.


text:
Q: How do I photograph the Master Sword for the Hyrule Compendium? I am trying to photograph the Master Sword so I can complete the weapons section of the Hyrule Compendium. Unfortunately, I obtained the Master Sword before taking a photo of it.
I tried to drop the  Master Sword on the ground to take a photo, but the game doesn't let you drop the legendary blade once you've picked it up.
How can I take a photo of the Master Sword for the Hyrule Compendium after I've picked it up?

A: It is possible to take a good picture of it inside the last room of the Master Trials, while it is still on the pedestal at the top of the staircase.

A: If you equip the Master Sword, use the camera rune, and switch it to selfie mode, you can turn the camera just right to capture the sword. The image probably won't be of a very good quality since your body will be in the way, but it will count for completion. It is also possible to purchase the image for 100 rupees, as well as any other image in the game, by going

 to the Hateno Tech Lab and talking to Symin.

The images purchased this way are usually a lot better than any I've taken.

 Specific images can't be purchased. You pick a category, and it gives you a random image out of that category. You might need to purchase most of the ones in the weapon category before it gets down to the Master Sword. It is impossible to get duplicates, so you'll never waste money brute-forcing it this way. You can also reduce the amount you have to pay (and increase the chance of getting the Master Sword image sooner) by filling out most or all of the Weapon category before attempting the purchase.

A: All you have to do is activate the camera push the x button and you will be able to take a picture of the master sword as link is wearing it.


text:
Q: Subsonic Simple Repository String Lengths I'm playing around with the SimpleRepository provider (with automigrations) in SubSonic 3 and I have an annoying problem:
The only way I can control the string length in my database tables is by adding the SubSonicStringLength or SubSonicLongString attributes to the properties of the objects that need to be persisted.
I don't really want a dependency on SubSonic anywhere except in my repository class, and certainly not in my model objects if I can avoid it.
Are there anyways to get round this or am I stuck using SubSonicStringLength and the other attributes?

A: Basically the only way around this would be to have a DTO object that you map to/from your SimpleRepository classes inside your repository. You could use a mapping tool like AutoMapper to convert to/from your DTOs to your SimpleRepo objects.
This would isolate your application from SubSonic dependencies outside of your repo but would obviously involve a non trivial amount of work.


text:
Q: MySQL server connections capped at 1013 For the last few days I've been trying to figure out why my MySQL read slave servers are capped at 1012+1 (+1 for the superuser) connections when I have the max_connections set to 5000. It seems that no matter what I change, the "Historic max_used_connections" never increases beyond 1013.
The mysql read slaves support a high traffic web site. I have a cluster of 3 read only slaves. Each read slave seems to be capped at 1013 max connections. I can take two out of the cluster so all connections go to one and still only 1013. No error messages show up in the mysql log file.
A mysqladmin status on one of the read slaves shows this:
Uptime: 1661  Threads: 128  Questions: 17634224  Slow queries: 0  Opens: 2441  Flush tables: 1  Open tables: 938  Queries per second avg: 10616.630
Same server, mtop shows this:
load average: 0.05, 0.15, 0.19 mysqld 5.1.66-log up 0 day(s),  0:28 hrs
106 threads: 4 running, 906 cached. Queries/slow: 1.6K/0 Cache Hit: 99.96%
Opened tables: 0  RRN: 278  TLW: 1.0K  SFJ: 0  SMP: 0  QPS: 1
Each server has 12 dual-core Intel CPU's (24 cores) with 140 GB of RAM running RHEL 6.3, Kernel 2.6. (x86_64)
Any idea what would be limiting/capping the connections at 1012+1 ?
EDIT
Also wanted to add two things:
1) I am running the "free/community" edition of MySQL that you get from a Red Hat 6.3 YUM install. Could there be some limitation in that version?
2) I've changed the /etc/security/limits.conf file on the MySQL read slaves, increasing values for users mysql and root (did not help my situation):
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 1161534
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 10240
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 32768
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

A: We had the same issue.  Put this at the top of the mysql start script.
ulimit -u 102400 -n 102400
Has to be at mysql start time.


text:
Q: Sort a list from Arrays.asList() changes also the origin array? I noticed a strange behavior (for me) when sorting a list retrieved with Arrays.asList(). It seems that after Collections.sort( list ), the origin array is also sorted !
How is it possible ?
List<Rate> rates = Arrays.asList( arrayRates );
Collections.sort( rates, new RateEffectiveDateComparator() );
/* after that the rates list AND arrayRates array are sorted in the same way */

A: From the documentation of Arrays.asList():

Returns a fixed-size list backed by the specified array.  (Changes to the returned list "write through" to the array.)

The array you pass will be the array the list is based on. When sorting the list, you are actually sorting the array. Check the sourcecode of Arrays.asList()...


text:
Q: "Losing" the address to my root in a binary tree after successful insertion Objective
I am attempting to implement a binary tree sort in C from the pseudocode located at the wiki page on Tree Sort(https://en.wikipedia.org/wiki/Tree_sort).
Problem/Observation
Symptom: Segfault upon entering the InOrder function.
Within the TreeSort function(responsible for passing all of the collection items to the Insert function), after all of the insertions, but before I call the InOrder function which is responsible for printing the sorted tree node keys, I am losing my access to my root pointer. Because the root address is initialized within the same function that InOrder is called(TreeSort), I don't think I'm losing it due to a scope issue.
What I have done to fix the problem
Working function by function and watching the parameters through GDB compiler's debugger, I was able to see that all of the values in my source array/collection were properly initialized and each child node pointer was being properly allocated as needed. I have attempted to include print statements in my debugging to observe the state of certain parameters but none of them are printing and the program is going to directly to a SEGFAULT after I input the array length.
Note: I am aware that an error of 'segmentation fault' means I attempted to access restricted memory. The address has been lost. As such, the address passed to InOrder is 0x0, according to the GDB debugger.
Where the problem is located(to the best of my knowledge)
I have traced the address issue specifically to the line after initialization of all tree nodes when I call InOrder. I have included the full code at the behest of someone looking to assist me. It is listed below.
Additional comments
I am aware that I will need to destroy/free each of the initialized child Nodes that I have created. Because I am working on a basic implementation, I will add an appropriate function to handle the disposal of those nodes in the time it takes to receive a response, or shortly thereafter.
# include <stdio.h>
# include <stdlib.h>
# include <time.h>

typedef struct binTree binTree;

struct binTree {
    binTree* leftNode;
    binTree* rightNode;
    int key;
};

void Insert(binTree* Node, int item);
void InOrder(binTree* Node);
void TreeSort(int* numberArr, int length);
binTree* createNode();
int* fillArray(int length);

int main() {

    int* numberArray;
    int lengthArray;

    printf("Length of array of items: ");
    scanf("%d", &lengthArray);

    numberArray = fillArray(lengthArray);

    TreeSort(numberArray, lengthArray);

    free(numberArray);

    return 0;
}

int* fillArray(int length) {

    time_t t;
    int* array = malloc(length * sizeof(int));

    srand((unsigned) time(&t));

    for(int i = 0; i < length; ++i) {
        *(array + i) =  (rand() % 50) + 1; // random num 1-50
    }

    for(int i = 0; i < length; ++i) {
        printf("%d ", *(array + i));
    }

    return array;
}

void TreeSort(int* array, int length) {
    binTree* root = calloc(1, sizeof(binTree)); // root

    for(int i = 0; i < length; ++i) {
        Insert(root, *(array + i));
    }

    InOrder(root);
}

void Insert(binTree* Node, int item) {
    if(Node->key == 0) {
        Node->key = item;
    }
    else {
        if(item < Node->key) {
            Node->leftNode = createNode();
            Insert(Node->leftNode, item);
        }
        else {
            Node->rightNode = createNode();
            Insert(Node->rightNode, item);
        }
    }
}

void InOrder(binTree* Node) {
    if(Node->key == 0) {
        printf("Leaf found!\n");
    }
    else {
        InOrder(Node->leftNode);
        printf("Node: %d", Node->key);
        InOrder(Node->rightNode);
    }
}

binTree* createNode() {
    binTree* Node;

    Node = calloc(1, sizeof(binTree));

    return Node;
}

Thank you in advance for your insight and advice.

A: Your InOrder function assumes that leaf nodes can be identified by checking if the key is zero.
However, your Insert function doesn't ensure that. Consequently you end up dereferencing a NULL pointer.
As a simple example consider a case with just a single element with value 42. When you call Insert your tree will become:
                          root -> --------------------
                                  | key = 42         |
                                  | rightNode = NULL |
                                  | leftNode = NULL  |
                                  --------------------

Then call InOrder with this tree. The first call will be fine but the second call (recursive call) will pass a NULL pointer and then you do:
if(Node->key == 0)

which will crash because Node is NULL.
Also notice that your Insert function is wrong. It keeps adding new nodes directly under the root. That's wrong. You need to "go down" in the tree until you have a node where rightNode or leftNode is NULL. Then you can create a new node.
In other words - only do stuff like Node->leftNode = createNode(); when Node->leftNode is NULL.


text:
Q: XAConnection performance in Oracle (10g) In our project, we use the Oracle XA Connection pool.
Only a small subset of the queries(transactions) are distributed.
Rest are quite straightforward single database modification.
I would like to know if there is a performance difference in using
XAConnections Vs the normal ones.
We use websphere v6.1 as the server.
If XAConn, is not very performant, then iam planning to have two datasources and use connections from them as appropriate.
Any pointers would be of great help.

A: I have no benchmarks to substantiate the following, this is just "we all know that" conventional wisdom. As with all performance discussions Your Milage Will Vary, if this is absolutely critical to your application then you need to perform your own benchmarks.
I believe that there is no signifincant performance overhead from using an XA-capable connection pool for non-XA work - WebSphere is careful to use 1PC transactions when only a single resource is used in a transaction. The primary overhead of XA is the extra Prepare/Commit/Forget set of XA messages, these will not occur in a simple 1PC case.
So the primary danger is of inadvertantly initiating a 2PC transaction. This can happen if you do several pieces of work supposedly against the same resoruce but with (for example) different isolation levels. You obtain a connection from the pool and do some work, that connection is now associated with your transaction until COMMIT. You "close" the connection, notionally returing it to the pool, but in fact WebSphere's pooling keeps the connection for your transaction. You ask for the connection again to do some more work, provided that you are asking for exactly the same connection you will be given the same connection again and so work continues in a single transaction - we have only 1PC, no overhead.
I would take the approach of initially haveing a single, XA-capable pool, but have two separate resoruce references, one for 2PC work, one for 1PC work. Have both references point to the same connection pool. Your code now is isolated from any need to have separate connection pools, it's just a matter of rebinding the resource-ref if you ever do need to make the change.


text:
Q: Project runs locally but not on server - Could not load type 'System.Web.UI.WebControls.DataBoundControlMode' from assembly System.Web I am working a little project for myself using ASP.Net MVC 2 Preview 2 and it works great locally but won't run on my dedicated server - I get the following error:
Could not load type 'System.Web.UI.WebControls.DataBoundControlMode' from assembly 'System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Looks like it is my:
<%=Html.EditorFor(model=>model) %>

That is causing this error - anyone else running into this and know how to fix it?

A: go to control panel --> administrative tools --> net framework configuration --> manage assembly cache --> view list.
can you find System.web there ? .. whats the version ? .. is it correct.
Reinstall .NET framework to be sure you have it installed correctly.


text:
Q: kubectl after device login returns error you must be logged in to the server (Unauthorized) What works on one corporate computer doesn't work on another.
Maybe corporate network proxy or CA cert? Domain whitelisting? How do you debug this?
az login
az account set --subscription <subscription>
az aks get-credentials --resource-group <group name> --name <aks name>
kubectl get nodes

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code ... to authenticate.
E1201 ...  11576 round_trippers.go:174] CancelRequest not implemented by *azure.azureRoundTripper
error: You must be logged in to the server (Unauthorized)

A: When I wanted to open an Azure support ticket, it alerted  that there were failures because of using an old kubectl CLI.

A: I had a similar issue and found that the version of "Docker for Mac" I was using was overriding the kubectl installation I had done via `homebrew.
❯ which kubectl
/usr/local/bin/kubectl
❯ ls -l /usr/local/bin/kubectl
lrwxr-xr-x  1 root  staff  55 16 Sep  2019 /usr/local/bin/kubectl -> /Applications/Docker.app/Contents/Resources/bin/kubectl

And when I checked the version of the client, sure enough:
kubectl version --client
Client Version: version.Info{Major:"1", Minor:"14" //snip

This seems to have been resolved quite some time ago, but may save some time for someone in the future
The solutions seem to be:

*

*Upgrade docker for mac (if this is your problem)

*Delete the link to the docker for mac provided kubectl and set to a current version


text:
Q: Failing GET request with knockout.js and CakePHP I'm incorporating paypal into my site , however, once I receive the token and try to redirect to paypal's site, nothing happens. I'm using knockout.js on my front end. When I click a button to make a GET request, the values are sent over to a corresponding CakePHP action which verifies the data and then redirect to paypal's site to finish the transaction.
Now here's the strange part. At first I assumed I messed up the jQuery to make the GET but that doesn't seem to be the case.  When I make the GET request with the header('location...') code included in the corresponding action, the network tab shows the request failed as "canceled". However, when I comment out the header('location..') code the request goes through successfully.
Here's GET request on
//order_processing.js

$.getJSON("/orders/pay_for_order/" + itemNumbers + "/" + quantities + "/" + prices + "/" + productNames + "/" + self.fullName() + "/" + self.addressLine1() + " " + self.addressLine2() + "/" + self.city() + "/" + self.state() + "/" + self.ZIP() + "/" + self.email(),function(data) {

});

Here's the action that the request goes to
//OrdersController

function pay_for_order($id = null){
     //processing code here
     //get token from paypal

    if($finalize_order->verifyPrice($item_numbers, $prices) == TRUE){
        //when I comment out this header redirect the GET request is successful, but of course then does not redirect
        header( 'Location: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$token ) ;
    }
}

I know my calls to paypal are working correctly to get the token, because when I copy/paste the link into the address bar it then redirects (meaning the token was successfully received). This to me seems like it's an issue with jQuery making the request. However, I'm confused as to why the GET request fails when I have the header redirect included, but when it's commented out the GET passes.
Update
I swapped out the header redirect for the following and it doesn't fail, however, it doesn't redirect either. This code showing up in the response as well, so I think this probably means CakePHP does not like header('location') redirects.
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$token.'">';

A: getJson expects json
$.getJSON is a method for requesting json, it's not appropriate for making a request which is expected to return not-json.
Further, if the response only emits redirect headers the (sub) request will get redirected, not the page making the (xhr) request.
redirect with javascript
Given the example code, one way to achieve the desired result is to modfy the request to return valid json:
{
    "success": true,
    "url": "https://www.sandbox..."
}

And then use an appropriate success handler:
$.getJSON(url, function(data) {
    if (data.success) {
        document.location = data.url;
    }
});


text:
Q: Is it possible to reuse MongoDB connection when multiple application servers connect to the mongodb server and restarted using java We have MongoDB on a separate server. There are multiple application servers and each will try to establish the connection to the MongoDB using
MongoClientURI uri = new MongoClientURI(url.toString());
MongoClient client = new MongoClient(uri);
For example, if there are 10 application servers(tomcat) and each establishes connection on startup.
So, now there are 10 connections to the mongodb.
Now, if any one of the application server restarts, it will again establish new connection to MongoDB. So the number of connections to MongoDB will be 11.
When a server restarts, how to close the previous connection and establish the new connection or is it possible to reuse the existing connection?


text:
Q: .css effect is not being applied after ajax response Im trying to apply a jquery .css effect after an ajax success response. I suppose that this doesnt work because Im getting the height from a recently generated element and then applying it to another recently generated element. I'm trying to move the .opts div to bottom, based in the height of the .col-4 div, which is dynamic.
Here is the pen: https://codepen.io/Pancuatico/pen/abpOeZy
When you open the pen, you can apply this code in the console: $(".opts").css("margin-top",$(".col-4").height()); and you will see that it works perfectly but, what is the right way to make this work after that ajax success response?
Edit
I'll put my js code here, so you can see where is my mistake.
$(document).ready(function(){
    loadImgs();
});

function loadImgs(){
    $.post("anurl.php",function(data){

        //Some process with the data here
        //...

        var out = "

";
        out += "
";
            out += "";
            out += "
";
                out += "<button>add</button>";
                out += "<button>rm</button>";
            out += "
";
        out += "
";

        $(".row").html(out);
        var col4Height = $(".col-4").height();
        $(".opts").css("margin-top",col4Height); //this does not work
    });
}

A: It is working
https://codepen.io/flakerimi/pen/ZELbYoK
I added more css params and they show up.

        var col4Height = $(".col-4").height();
        $(".opts").css("padding",'10px');

        $(".opts").css("background",'green');
        $(".opts").css("top",col4Height);

Also use $(".opts").css("top",col4Height);   since its position absolute

I would do it differently tho.
$(document).ready(function(){
    doWork();
});

async function loadImages(){}

async function doWork(){
    await loadImages();

    //do some other stuff after loadImages is finished like
    var col4Height = $(".col-4").height();
    $(".opts").css("padding",'10px');

}

CHECK THIS
$(document).ready(async function() {
  await loadImgs();
 // When we begin, assume no images are loaded.
  var imagesLoaded = 0
  // Count the total number of images on the page when the page has loaded.
  var totalImages = $("img").length

  // After an image is loaded, add to the count, and if that count equals the
  // total number of images, fire the allImagesLoaded() function.
  $("img").on("load", function (event) {
    imagesLoaded++
    if (imagesLoaded == totalImages) {
      allImagesLoaded()
    }
  })

  function allImagesLoaded() {
    console.log("ALL IMAGES LOADED");
     change();
  }
  });

async function change(){

    if($(".col-4").height() != 0) {
   var col4Height = $(".col-4").height();
      console.log(col4Height);
        $(".opts").css("padding",'10px'); //this does not work

        $(".opts").css("background",'green'); //this does not work
        $(".opts").css("margin-top",col4Height); //this does not work
    }
};
async function loadImgs(){
   await $.post("https://jsonplaceholder.typicode.com/posts",function(data){
        console.log(data);
        //...
        //Some process with the data here
        //Im just using that url for testing purposes
        //...
...

    });
  var col4Height = $(".col-4").height();
  console.log(col4Height);

}

A: The reason is, when you are adding the margin-top of that elements, the images are still loading up. So the height of .col-4 is only about the size of the buttons at that moment.
You have to wait till the images are loaded, then update the margin equal to the height of .col-4.
A Better way would be to create the elements dynamically, instead of putting as html in a string. That way you can bind the load event on that image with-
myImage.load(imgLoaded);

and to update the margin after image is loaded-
function imgLoaded() {
$(".opts").css("margin-top", $(".col-4").height(););
}

However, you can achieve your result in your code with html onload attribute.
$(document).ready(function(){
    loadImgs();
});

function loadImgs(){
    $.post("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js",function(data){

        //...
        //Some process with the data here
        //Im just using that url for testing purposes
        //...

        var out = "

";
        out += "
";
            out += "";
            out += "
";
                out += "<button>add</button>";
                out += "<button>rm</button>";
            out += "
";
        out += "
";

        $(".row").html(out);

    });
}

function imgLoaded() {
    $(".opts").css("margin-top", $(".col-4").height(););
}


text:
Q: What is the bigOh or running time of the following algorithm What is the running time of the following algorithm in bigO.
for(int i=1;i<=n;i++){
    for(int j=i;j<=n;j++){
        for(int k=j; k<=n;k++){
            for(int l=k; l<=n;l++){

                ...

            }
        }
    }
}

A: This algorithm seems to be n^4. Of course, from the theoretical perspective (without any compiler considerations).

A: N^4. The fractional part doesn't count.

A: A formula for such a collection of dependent loops, can be inferred like the following:

Where c (constant) is the number of operations inside the innermost loop, n is the number of elements, and r is the number of nested loops.
In the question's case:

Another methodology, efficient but tedious, is to use Sigma notation:

A: O(N^4) is the cost.
each for nested is N^
 so essentially N * N * N * N = N^4
CS610, Algorithm Development, NJIT.
My graduate coursework is actually coming in handy.

A: my answer is O(N^4)...because there are four "for loops"..and it is easy to judge the runing time of this algo...thanks !


text:
Q: What are the consequences of creating a custom own property (not a custom attribute) on an HTML element? In an answer I gave to another SO question I was very proud of having come up with a very short click-handler-toggle. Slightly re-written, it's this:
document.getElementById("myToggle").addEventListener("click", function() {
  (this.oddClk = !this.oddClk) ? oddHandler() : evenHandler();
});

This isn't central to my question, but in case you're wondering what I'm doing here, read this paragraph. I'm adding a custom property, oddClk, to the HTML element I clicked. After the first click, this property is initially undefined but then is immediately negated to true. (Note that the first part of the ternary statement intentionally uses = not == or ===.) The second time through it's negated again to false, etc. Based on its value, one of two handlers is invoked. Not only is the code short, but it also doesn't require any global variables, and can be used on multiple targets simultaneously. If you're interested, here's a working version:

document.getElementById("myToggle").addEventListener("click", function() {
  (this.oddClk = !this.oddClk) ? oddHandler(): evenHandler();
});

function oddHandler() {
  document.getElementById("result").innerHTML = "odd";
}
function evenHandler() {
  document.getElementById("result").innerHTML = "even";
}

Not clicked yet

<button id="myToggle">Click me to toggle</button>

My question, though, is this: What are the consequences of using this.myCustomProperty where this is an HTML element (in this case, the target that was clicked)?
Note that I'm not setting a custom attribute on the element. Rather, I'm setting a new custom property on the HTML element. It actually ends up being the only own property on the element. Are there any significant side-effects of assigning an own property onto an HTML element object like this, side-effects that might have negative consequences elsewhere?
I've found other questions on custom attributes, but that's clearly a different kettle of fish. And references to this in discussions of addEventListener don't seem to bring up new own properties.
One possible down-side is that I might pick a property name that will be defined in future versions of HTML. In that case my own property would clobber the newer inherited property. However, if I name my property carefully or strangely enough, I should be OK on that front. So, are there other problems?
Note that I'm not really asking to see if I should include this in production code. I wrote my toggle routine above basically just as a mental exercise, to see how short I could write it. I'm asking more just to better understand the inner workings of HTML.


text:
Q: how to parse json object inside json object in java in the Guardian API? I want to parse JSON data from API the Guardian news to Java Android for my app. The JSON data is JsonObject inside JsonObject. I have to try several ways, but still not return the data.

JSON data

{
   "response":{
      "status":"ok",
      "userTier":"developer",
      "total":1,
      "content":{
         "id":"us-news/2019/sep/09/us-briefing-taliban-talks-brexit-turmoil-and-nadal-wins-us-open",
         "type":"article",
         "sectionId":"us-news",
         "sectionName":"US news",
         "webPublicationDate":"2019-09-09T10:25:05Z",
         "webTitle":"US briefing: Taliban talks, Brexit turmoil and Nadal wins US Open",
         "webUrl":"https://www.theguardian.com/us-news/2019/sep/09/us-briefing-taliban-talks-brexit-turmoil-and-nadal-wins-us-open",
         "apiUrl":"https://content.guardianapis.com/us-news/2019/sep/09/us-briefing-taliban-talks-brexit-turmoil-and-nadal-wins-us-open",
         "fields":{
            "headline":"US briefing: Taliban talks, Brexit turmoil and Nadal wins US Open",
            "standfirst":"
Monday's top story: Taliban warn of further US deaths after Trump says he cancelled peace talks. Plus, why the breakup of Big Tech is beginning at last
",
            "trailText":"Monday's top story: Taliban warn of further US deaths after Trump says he cancelled peace talks. Plus, why the breakup of Big Tech is beginning at last",
            "byline":"Tim Walker",
            "main":"

 Afghans at the site of a deadly car bomb attack in Kabul last week. Photograph: Rahmatullah Alizadah/Xinhua/Barcroft Media

",
            "body":"
Subscribe now to receive the morning briefing by email.

Good morning, I'm Tim Walker with today's essential stories.

Republicans and Democrats denounce Taliban talks

Lawmakers from both sides of the aisle have criticised Donald Trump after he revealed he had planned a secret peace summit with the Taliban at Camp David on Sunday, only to call it off at the last minute. ",
            "wordcount":"1172",
            "commentCloseDate":"2019-09-12T10:30:00Z",
            "commentable":"false",
            "firstPublicationDate":"2019-09-09T10:25:05Z",
            "isInappropriateForSponsorship":"false",
            "isPremoderated":"false",
            "lastModified":"2019-09-09T10:48:23Z",
            "productionOffice":"UK",
            "publication":"theguardian.com",
            "shortUrl":"https://gu.com/p/ca9ye",
            "shouldHideAdverts":"false",
            "showInRelatedContent":"true",
            "thumbnail":"https://media.guim.co.uk/9c05cc7c0e69a78aa3f71f94a4bdd28e3d044a48/0_124_5610_3364/500.jpg",
            "legallySensitive":"false",
            "lang":"en",
            "bodyText":"Subscribe now to receive the morning briefing by email. Good morning, I'm Tim Walker with today's essential stories.",
            "charCount":"7006",
            "shouldHideReaderRevenue":"false",
            "showAffiliateLinks":"false",
            "bylineHtml":"Tim Walker"
         },
         "isHosted":false,
         "pillarId":"pillar/news",
         "pillarName":"News"
      }
   }
}

I want to loop the content data, and get webTitle, fields, also body inside fields.
Thanks, advance.

A: I found solution for this
// Create a JSONObject from the JSON response string
        JSONObject baseJsonResponse = new JSONObject(result);

        //Create the JSONObject with the key "response"
        JSONObject responseJSONObject = baseJsonResponse.getJSONObject("response");

        // Extract the JSONArray associated with the key called "content",
        // which represents a list of news stories.
        JSONObject newsContentArray = responseJSONObject.getJSONObject("content");

        Iterator<String> keys = newsContentArray.keys();

        while(keys.hasNext()) {
            String key = keys.next();
            if (newsContentArray.get(key) instanceof JSONObject) {
                Object webTitle = newsContentArray.get("webTitle");
                Object webPublicationDate = newsContentArray.get("webPublicationDate");

                JSONObject fields = newsContentArray.getJSONObject("fields");
                String body = fields.getString("body");
                String main = fields.getString("main");

                setTextNews(webTitle.toString(), webPublicationDate.toString(), main, body);
            }
        }


text:
Q: Why am I not able to type anything in the terminal window after running npm start in order to fire up the development server? I am using create-react-app tool to create a React project. But after running npm start command in my terminal window in order to fire up the development server, I am not able to type anything in the terminal. Why so and how can I rectify it?

A: That terminal command is still running (specifically it is running your server) so it can't take anymore commands. If you want to run other commands while it is running, you will have to open another terminal tab/window. The + button in the top right of the terminal window should do it for you

A: Press Ctrl c twice it will show you ^c
Then you can write your command under the ^c


text:
Q: PHP radio button check issue No matter which radio button is checked then submitted, no is always shown.
HTML:
<input type="radio" id="formyes" name="checkyn" value="yes"/>
yes
<input type="radio" id="formno" name="checkyn" value="no"/>
no

PHP var dump of $_POST:
'checkyn' => string 'no' (length=2)

How can I test if yes is selected if when yes is selected no is always logged?

A: Try this
if($_POST['checkyn']=='yes')
{
    echo "Yes checked";
}elseif($_POST['checkyn']=='no')
{
   echo "No checked";
}

A: You have two button with same name it means that you can select one at a time. if you select one then another will be unselect.
I think you are saying that $_POST['checkyn']  is always  give you no. if that the case  you should select one by default in your html:
<input type="radio" id="formyes" name="checkyn" value="yes" checked/>
yes
<input type="radio" id="formno" name="checkyn" value="no"/>
no

you can get is value like this:
  if(isset($_POST['checkyn']) )
    if( $_POST['checkyn'] == 'yes'){

    //yes selected do your stuff
    }
    else{

    //no selected
    }
}

A: Try this:
if($_POST){
print_r($_POST['checkyn']);
}

A: Your HTML should be
<input type="radio" id="formyes" name="checkyn[]" value="yes"/>
yes
<input type="radio" id="formno" name="checkyn[]" value="no"/>
no

ADD [  ] after checkyn in HTML this will denote array in PHP
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $check = $_POST['checkyn'][0];
}
?>

if you echo $check; checked button value will return


text:
Q: Is it possible to execute multiple commands with ssh_exec();? Good morning, forgive my question but I am stuck on a thorny problem. To explain because it's a bit twisted, I'm currently working in php 7.4 and I have to make an application capable of configuring a cisco switch from a web page. To do this I have to connect to it by ssh using the ssh2 library of php, the connection is functional. Now the part I'm stuck on is executing commands.
The idea was to make a command table containing the list of commands to execute to configure the switch then do a for each to iterate through the table and do an ssh_exec() of each command. Everything goes well for the first command, but from the 2nd I have this error: " ssh2_exec (): Unable to request a channel from remote host". The question I was asking myself then is is it even possible to execute several commands in a row with this library?
Sorry for the inconvenience.
Thank you in advance for your answers, and have a nice day!


text:
Q: Advanced improper integral involving periodic function of polynomial In what conditions do these two improper integrals $$\int^\infty_0 x^{k} e^{P(x)} \sin (Q(x)) \mathrm{d}x \text{ and } \int^\infty_0 x^{k} e^{P(x)} \cos (Q(x)) \mathrm{d}x$$ converge, where $k$ is a real number, $P(x)$ is an $m$-degree polynomial with real number coefficients whose leading coefficient is positive, $Q(x)$ is an $n$-degree polynomial ($n\geq 2$) with real number coefficients?

A: The degree of $Q'$ is $n-1$, so there exist constants $C_1$ and $a_1$ such that $|Q'(x)| \le C x^{n-1}$ for $x\ge a_1$. Since $|Q(x)| \to \infty$ as $x\to\infty$, there exists a strictly increasing sequence $(x_j)$ with $x_j \to \infty$ and $\sin Q(x_j) = 1$. Let $\epsilon_j = \frac1{2 C x_j^{n-1}}$, and let $I_j = [x_j - \epsilon_j, x_j]$. For large $j$ we have that $x_j - \epsilon_j \ge a_1$, so $|Q'| \le Cx_j^{n-1}$ on $I_j$, implying that the image $J_j = Q(I_j)$ has length $\le \frac12$, so that $\sin y \ge \frac12$ for $y \in J_j$, i.e., that $\sin Q(x) \ge \frac12$ for $x\in I_j$.
Now if $P$ is non-constant with positive leading coefficient, then there exists constants $C_2>0$ and $a_2$ with $P(x) \ge C_2 x $ for $x \ge a_2$. Since $x^k e^{C_2\sqrt{x}} \to \infty$ as $x\to\infty$, for any value of $k$, there exists $a_3\ge a_2$ such that $x^k e^{P(x)} \ge x^k e^{C_2 x} \ge e^{\sqrt{x}}$ for $x \ge a_3$.
Taken together, this implies for large $j$:
$$\int_{x_j-\epsilon_j}^{x_j} x^k e^{P(x)} \sin Q(x) \, dx \ge \frac12 \epsilon_j e^{\sqrt{x_j - \epsilon_j}} = \frac{e^{\sqrt{x_j - \epsilon_j}}}{4C x_j^{n-1}} \to \infty$$
as $j \to\infty$, so that the integral does not converge. The same argument shows that the other integral does not converge either if $P$ is non-constant with positive leading coefficient.
Now if $P$ is constant, the question is whether the integral
$$ \int_0^\infty x^k \sin Q(x) \, dx $$
converges. For $k<0$ there is a singularity at $x=0$, which is always integrable if $-1<k<0$. For $-2<k\le -1$ it is integrable iff $\sin Q(0)=0$, for $-3<k \le -2$ it is integrable iff $\sin Q(0)=0$ and $Q'(0)=0$ etc. Similar results are true for the other integral, but since $\sin$ and $\cos$ are never simultaneously $0$, at least one of the integrals always diverges if $k\le -1$. For the convergence at $\infty$ one can observe that the sequence of zeros of $\sin Q(x)$ asymptotically looks like $x_j \approx c j^{1/n}$ with some constant $c>0$, and that $x_{j+1} - x_{j} \approx c((j+1)^{1/n} - j^{1/n}) \approx cj^{1/n}\frac{1}{nj}=\frac{c}{n} j^{1/n-1}$, so the integral near $\infty$ behaves like the alternating series
$$ \sum_j (-1)^j (cj^{1/n})^k \frac{c}n j^{1/n-1} = C \sum_j (-1)^j j^{(k+1)/n-1}$$
with a constant $C$. This series converges iff the exponent is negative, i.e., iff $k+1 < n$. There are some details to be filled in, but I believe this can be made rigorous, i.e., both integrals converge iff $P$ is constant and $-1<k<n-1$, they both diverge if $k\ge n-1$, and one of them may converge if $k\le -1$ if $\sin Q(x)$ or $\cos Q(x)$ vanishes to the appropriate order.


text:
Q: what is alternative/opposite to piecemeal statistical approach? I have only basic knowledge about bio-statistics. For not normally distributed data, I used Kruskal-Wallis test to investigate the statistical significance between different variables. I performed an exercise with three different intensities (different weights w1, w2, w3), then with one weight at three different speeds (s1, s2, s3). The readings were observed from 3 different points(p1, p2, p3).
I opted for statistical significance among p1, p2, p3 at (w1 and w2 and w3) and at (s1 and s2 and s3). then i opted statistical significance among w1, w2, w3 for p1 and p2 and p3. then i opted statistical significance among s1, s2, s3 for p1 and p2 and p3. So, there are 36 independent Kruskal-Wallis tests.
After that, Mann-Whitney test was performed for pairs (post hoc analysis).
I got comment on the test that, "the piecemeal statistical approach, consisting of a very large number of comparisons made between dependent variables during different conditions, without corrections for multiple testing, renders it probable that "significant" results may well be due to chance."
Can someone please suggest where I am wrong, and how and where to adjust the p value?

A: So far, what i found about this particular problem, it should be done by repeated measures of ANOVA, with Bonferroni method for posthoc.
The reason is the data is not independent. The p value is needed to be adjusted for multiple tests.


text:
Q: "Open file - security warning" on local exe: "Unblock" does *not* work - why? I use Process Explorer on a Windows Vista (Business 32bit) box. I have extracted the files from the zip file to C:\Program Files\Process Explorer. Every time I open the executable (procexp.exe) I get the security warning that the file is not from this computer etc.
Neither checking the checkbox on the security warning to "not warn again" nor using the [Unblock] button in the executables properties page will remove this warning. It will always popup again, and when I re-open the properties page of procexp.exe the [Unblock] button will be displayed again.
Why can't I remove this security descriptor from this file in C:\Program Files\... and what do I have to do to remove it?
Other questions that did not help so far:

*

*Remove Process Explorer's "Open File - Security Warning"

*Get rid of Vista security warning
Questions/answer that may provide a solution (once I figure it out) ... but still the question remains as to why the [Unblock] button works for some but not for me?

A: OK, I figured it out:
If you have a file that is tagged as "unsafe" and you copy this file into the Program Files folder, than you cannot remove the "unsafe" tagging via [Unblock] because you need elevation to edit the file inside Program Files and the Vista properties dialog does not request elevation and therefore cannot remove the "unsafe" tagging.
The solution is to move the "unsafe" executable to your documents folder, [unblock] it there and then move the file back to the Program Filesfolder.

A: Funny enough, you can use the Sysinternals 'streams' utility to unblock them all in bulk.
Just use streams -d *.* from within a command prompt with administrative privileges (i.e. enter "cmd" in the Windows search box, right click cmd.exe and choose Run as Administrator).


text:
Q: PYCURL ERROR 6 - "Couldn't resolve host 'mirrorlist.centos.org'" I have a problem with CentOS 6.4 on Hyper-V. I can't install using yum or ping any DNS address. There is a announcement: Couldn't resolve host 'mirrorlist.centos.org' etc.  I've been trying to fix it according to this video: http://www.youtube.com/watch?v=2BZHvVpXsg4 but still nothing. What should I do?

A: Try to add this line into the /etc/hosts
64.235.47.134    mirrorlist.centos.org

A: I had the same problem.
After logining my compony account, the networking can connect the Internet. But my vitrual manchine cound not login.
I change the network mode, use the "private network", then can connect the Internet.
Good luck.

A: Check network ... I use vm-player and add custom-virtual-network ( vmnet bridget )
Type:
ifdown eth0
ifup eth0
yum update

for me works ....

A: For the record: if you are in a Python shell, try to start a new one. I know the question is not about this, but it is the only top hit from google for this error. The original reason of the issue is still not clear as curl from command line downloaded the same URL with no problem, and I had no networking issue in any other application at the same time. I did ip link set <ifname> down/up, nmcli con down/up wired with no success. I added some of the domains to /etc/hosts, this once hasn't resolved the problem, but later at an other domain it worked. Here is a minimal example for easy testing:
import pycurl
import io

s = io.BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.VERBOSE, 1)
c.setopt(pycurl.WRITEFUNCTION, s.write)
c.setopt(pycurl.URL, 'http://speedtest.ftp.otenet.gr/files/test100k.db')
c.perform()
s.seek(0)
print('Downloaded %u bytes.' % len(s.getvalue()))


text:
Q: Korrekt way to get the duration between a time strings and current time in Kotlin what is the correct and easiest way to get the duration between a time string and actual time in Kotlin?
I have following time strings (timeStr): "18:00:00"
At the end I like to have a string like this: "x hours and y minutes to ..."
My current solution:
val diff: Long = (LocalTime.parse(timeStr).toSecondOfDay() - LocalTime.now().toSecondOfDay()).toLong()
val duration: LocalTime = LocalTime.ofSecondOfDay(diff)
outStr = duration.hour + "hours and " + duration.minute + " minutes to ..."

I am aware that the solution is error prone, so I am looking for a clean solution. I have only recently started using Kotlin and am not yet familiar with the possibilities.


text:
Q: Removing code for mobile screen menu I have the following code which adds/removes a .show-nav and .hide-nav class to my navigation. This is applied to the  .mobile-nav div with the .toggle-nav button.
functions.php
$(function() {

// Bind a click event to anything with the class "toggle-nav"
$('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
        $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

        setTimeout(function() {
            $('.mobile-nav').removeClass('hide-nav');
        }, 500);

    } else {
        $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
});

});

.mobile-nav is a full screen overlay menu which I only want to use on mobile devices so I remove the .toggle-nav button on screen size ( >768px). .mobile-nav remains invisible until .toggle-nav is clicked.
css
.toggle-nav { display: none; }

@media screen and (max-width: 768px) {

.toggle-nav { display: inline-block; }
}

Problem is if the mobile-nav is 'opened' and the user makes the screen large, the toggle-nav button is hidden but the menu remains open.
Basically, I want the class .hide-nav applied (or .show-nav is removed) if the screen goes larger than 768px.

A: I have created a short example of  things need to be done. Added some jquery codes to make it work the way you want .

Step 1 - Add class hide-nav on window width

 /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }

Step 2 - Add class hide-nav on window resize

  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');

$(function() {

  // Bind a click event to anything with the class "toggle-nav"
  $('.toggle-nav').click(function() {
    if ($('.mobile-nav').hasClass('show-nav')) {
      $('.mobile-nav').removeClass('show-nav').addClass('hide-nav');

      setTimeout(function() {
        $('.mobile-nav').removeClass('hide-nav');
      }, 500);

    } else {
      $('.mobile-nav').removeClass('hide-nav').addClass('show-nav');
    }

    return false;
  });

  /* logic For window width */
  if ($(window).width() > 768) {
    $('.mobile-nav').addClass('hide-nav');
    $('.mobile-nav').removeClass('show-nav');
  } else {
    $('.mobile-nav').removeClass('hide-nav');
  }

  /* logic For Window Resize */
  function resize() {
    if ($(window).width() > 768) {
      $('.mobile-nav').addClass('hide-nav');
      $('.mobile-nav').removeClass('show-nav');
    }

    $('.mobile-nav').addClass('hide-nav');
  }

  $(window).resize(resize)
    .trigger('resize');

});
.mobile-nav {
  width: 100px;
  height: 100px;
  background: red;
}

.show-nav {
  display: block;
}

.hide-nav {
  display: none
}

.toggle-nav {
  display: none;
}

@media screen and (max-width: 768px) {
  .toggle-nav {
    display: inline-block;
  }
}

Toggle Nav


text:
Q: PHP using sessions value will be subtracted upon session start I have a form in my PHP file for students registration that have four inputs name, ID, email and time slot (this have options of 4 time slots and in each slot 8 seats remaining).
I don't want store data in database. My purpose is that when a student put info in fields and select one time slot and proceed by clicking on submit button then next time the same slot shows seat subtracted i.e if it was 8 now it will shows 7 and after 7 submission it will show no seats or 0 seats. I want to apply this method on 4 slot (option) in this input fields.


text:
Q: Appending list to column of a CSV file There are 5 polygons in a shapefile. I am extracting the mean value of the NDVI pixel inside each polygon using "zonal statics as table". At this moment, I have 3 NDVI files, thus, I will get 3 sets of values. The codes are as follow
NDVI = ['1.tif', '2.tif', '3.tif']
poly_shape  = "polygon.shp"
table = r"E:\dump.gdb\NDVI_table.dbf"

for NDVI_file in NDVI:
    arcpy.gp.ZonalStatisticsAsTable_sa(poly_shape, "FID", NDVI_file, table, "DATA", "MEAN")
    single_list = [i[0] for i in arcpy.da.SearchCursor(table, "MEAN")]

As you can see, in each pass of the for loop I am getting one new list. I would like to create a CSV file to store the values. After each pass, I want to assign the values of the list in a new column.
To make it clear, after 1st pass, I will get the list below
single_list = [1,2,3,4,5]

after 2nd pass
single_list = [6,7,8,9,10]

after 3rd pass
single_list = [11,12,13,14,15]

I want the csv file to look like the following table (the first row will act as header and contain the raster file name)
1.tif   2.tif   3.tif
1       6       11
2       7       12
3       8       13
4       9       14
5       10      15

Is there any way to do that? I am using both ArcMap 10.6 and ArcGIS Pro 2.

A: You can use pandas module which is included in 10.6 and Pro:

pandas is an open source, BSD-licensed library providing
  high-performance, easy-to-use data structures and data analysis tools
  for the Python programming language.

import arcpy
import pandas as pd

NDVI = ['1.tif', '2.tif', '3.tif']
poly_shape  = "polygon.shp"
table = r"E:\dump.gdb\NDVI_table.dbf"

df = pd.DataFrame() #Create empty data frame

for NDVI_file in NDVI:
    arcpy.gp.ZonalStatisticsAsTable_sa(poly_shape, "FID", NDVI_file, table, "DATA", "MEAN")
    single_list = [i[0] for i in arcpy.da.SearchCursor(table, "MEAN")]
    df[NDVI_file] = pd.Series(single_list) #Add new column named after file and fill with values from list

df.to_csv(r'C:\folder\csvfile.csv', index=False) #Save as csv


text:
Q: MIPS assembly `addi` instruction, how is a hexadecimal immediate interpreted? there is a difference between those two instructions?
addI $12,$1,0x0000ffff
vs
addI $12,$1,0xffff
I need to know what is the value of
$12 after those instruction :
lui $1,0xffffff00
addi $12,$1,0x0000ffff

should i treat 0x0000ffff as sign extended - 0xfffffffff
or as it is - 0x0000ffff
and then $12 is 0xff00fffff ?
thanks


text:
Q: how to enter username and password in postman for spring security login page from postman? I am using Spring boot security to force authentication. So anytime an endpoint in this web server is called, it forces a username/password to be put in.
I've played around with the Authorization options available in Postman, but I can not find any that will perform the steps necessary to get me past the authentication. I always get the HTML response of the login page.
Any help or direction would be appreciated.

A: Find the type of Authorization which is used in your project and select the same in Authorization tab in Postman and pass the user name and password accordingly.

A: Go to Authorization tab and select basic auth from drop down. At right side user name and password prompt would appear.


text:
Q: Accessing Eval value inside Gridview Using JQuery OR JavaScript  I have gridview with four columns. All the data inside is generated in RowDataBound event using Literals
eg.
      <asp:TemplateField HeaderText="" >
            <ItemTemplate>
                 <asp:HiddenField ID="ID"  Value='<%#Eval("id")%>' runat="server" />

                <asp:Literal ID="ltrImage" runat="server"></asp:Literal>

            </ItemTemplate>
        </asp:TemplateField>

       and

      <asp:TemplateField HeaderText="" HeaderStyle-HorizontalAlign="Center"
            ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Literal ID="lrtBrief" runat="server"></asp:Literal>
            </ItemTemplate>
        </asp:TemplateField>

In one of these Literals I am creating a  tag and I want to find the <%#Eval("id")%> value in click event of the  tag.
I did try something like this but didn't work
$('.contactLink').click(function () {

    var grd = $('#MainContent_cphMain_DisplayResults1_gvDisplay');
    var txt = $(grd).find("cells[1].innerHTML").html();

});

HTML Looks Like this

<input id="MainContent_cphMain_DisplaySearchResults1_gvListing_Listing_0" type="hidden" value="1" name="ctl00$ctl00$MainContent$cphMain$DisplaySearchResults1$gvListing$ctl02$Listing">

Test

      Contact
      View

Any help will be appreciate
Thanks

A: Note that you're missing a closing h3 around your two links.
$(".contactLink").click(function() {
    var value = $(this).closest("table") // Get the 's closest

                       .siblings(":hidden") // <hidden>
                       .val();
});

Fiddle for reference.

A: if I understand your question right:

In one of these Literals I am creating a  tag and I want to find
  the <%#Eval("id")%> value in click event of the  tag.

I would say something like this would do the trick
$('a').live("click", function () {
alert($(this).attr("id"))
});


text:
Q: Sound card vanished from sound settings For no apparent reason the sound card is no longer visible in sound settings. Even dummy device is gone. Unsurprisingly flash produces no sound. The sound card is working as the system sounds are still active although sound test does nothing.
What is the problem and how do I fix it (idally without restating)
I have tried sudo modprobe snd-hda-intel which has been a faithful fixer of sound problems in the past but this was not the case this time.
I followed instructions on restarting pulseaudio (I must confess I was not really clear what I was doing or why so I was probably just wasting time) this has not helped.

A: *

*Try to reset pulseaudio configuration :
rm -fr .pulse
then reboot.

*If not better , what is this 2 commands results:
pactl info|grep sink
and
aplay -l

*Do you see faders running alsamixer in a terminal ? Are main faders (master, pcm, speakers... )  unmuted  (m key to mute/unmute when fader selected with arrow key)?


text:
Q: (JS) How to use the "new" operator and return something other than "this"? I am making a JavaScript game framework. I have a function called Color3. I am trying to use the function using the new operator. However, every time it returns the object instead of the string I wanted to return. Here is the code:

Color3 = function(r, g, b) {
    this.r = 255;
    this.g = 255;
    this.b = 255;

    if (r != null)
        this.r = r;
    if (g != null)
        this.g = g;
    if (b != null)
        this.b = b;

    return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
};

var myColor = new Color3(0, 255, 0);
console.log(myColor);

Expected output:
"rgb(0, 255, 0)"

Actual output:
Color3 {r: 0, g: 255, b: 0}

Is there a way that I can get the expected output? Or do I have to not use the new operator?

A: The return value is only returned if it is an object. If you return a primitive (number, boolean, string, undefined, null), the object constructed is returned.
You can probably return a String object:
return new String("rgb(" + this.r + ", " + this.g + ", " + this.b + ")");

This will probably work, though there are some differences between string primitives and string objects.
The more important questions is "why do you want to do this?" It doesn't seem like you actually want to construct an object at all (you're discarding the one you construct): a plain old function would work just fine.

A: If what you return is not an object, the default object is returned. You should return an object to change the return value. Try return new String("rgb(" + this.r + ", " + this.g + ", " + this.b + ")")

A:
"Is there a way that I can get the expected output? Or do I have to not use the new operator?"

Yes, you can construct objects like that and still get the expected output. You do this by adding a .toString() method to the .prototype of the constructor.

Color3 = function(r, g, b) {
    if (r != null)
        this.r = r;
    if (g != null)
        this.g = g;
    if (b != null)
        this.b = b;
};

Color3.prototype.r = 255;
Color3.prototype.g = 255;
Color3.prototype.b = 255;

Color3.prototype.toString = function() {
  return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
}

var c = new Color3(123, 234, 345);
console.log(`Color is: ${c}`);

I also added the default RGB values to the prototype.

A: The new method for Javascript contructors creates a "new" instance of an Object specified by the constructor. You would need to do something like this:
Color3 = function(r, g, b) {
    this.r = 255;
    this.g = 255;
    this.b = 255;

    if (r != null)
        this.r = r;
    if (g!= null)
        this.g = g;
    if (b != null)
        this.b = b;

    this.getColor = function(){
      return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
    }
};
var someColor = Color3.new(200,200,200);
someColor.getColor();

A: If you want to return the string that Color3 returns, you should call Color3 function with out the 'new' operator:

Color3 = function(r, g, b) {
    this.r = 255;
    this.g = 255;
    this.b = 255;

    if (r != null)
        this.r = r;
    if (g != null)
        this.g = g;
    if (b != null)
        this.b = b;

    return "rgb(" + this.r + ", " + this.g + ", " + this.b + ")";
};

var color =  Color3(8,22,3);

//testing the Color3 function
console.log(typeof(color));
console.log(color);

A: Is that what you are after?

Color3 = function(r, g, b) {
    this.r = 255;
    this.g = 255;
    this.b = 255;
    this.rgb;

    if (r != null)
        this.r = r;
    if (g != null)
        this.g = g;
    if (b != null)
        this.b = b;

    this.rgb = this.r + ", " + this.g + ", " + this.b ;

};

var myColor = new Color3(0, 255, 0);
console.log(myColor.rgb);


text:
Q: How to make height constraint to view in tableviewcell? I have tableview, 1 cell and 1 view in cell.
Constraints for view:
top, right, bottom, left equal to superview
height = 250
And there is an error.
class ViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
    tableView.estimatedRowHeight = 250
    tableView.rowHeight = UITableView.automaticDimension
}

}

extension ViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    let view = UIView()

    view.translatesAutoresizingMaskIntoConstraints = false
    cell.contentView.addSubview(view)
    view.backgroundColor = UIColor.red
    view.heightAnchor.constraint(equalToConstant: 250).isActive = true
    view.topAnchor.constraint(equalTo: view.superview!.topAnchor).isActive = true
    view.bottomAnchor.constraint(equalTo: view.superview!.bottomAnchor).isActive = true
    view.leftAnchor.constraint(equalTo: view.superview!.leftAnchor).isActive = true
    view.rightAnchor.constraint(equalTo: view.superview!.rightAnchor).isActive = true
    return cell
}
}

I expected no error messages, but here there are.

2019-10-21 18:05:41.265530+0300 ffffffffff[73908:5577499]
  [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one
  you don't want.   Try this:       (1) look at each constraint and try to
  figure out which you don't expect;        (2) find the code that added the
  unwanted constraint or constraints and fix it.
"<NSLayoutConstraint:0x600002d9ea30 UIView:0x7feb2a700c00.height == 250   (active)>",
"<NSLayoutConstraint:0x600002d9e2b0 V:|-(0)-[UIView:0x7feb2a700c00]   (active, names:
'|':UITableViewCellContentView:0x7feb2a5050b0 )>",
"<NSLayoutConstraint:0x600002d9e1c0 UIView:0x7feb2a700c00.bottom == UITableViewCellContentView:0x7feb2a5050b0.bottom   (active)>",
"<NSLayoutConstraint:0x600002db8b90 'UIView-Encapsulated-Layout-Height'
UITableViewCellContentView:0x7feb2a5050b0.height == 250.333 (active)>" )

Will attempt to recover by breaking constraint

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints
  to catch this in the debugger. The methods in the
  UIConstraintBasedLayoutDebugging category on UIView listed in
   may also be helpful.


text:
Q: What does "swing through" mean?
The Swedish Academy announced March 29th Bob Dylan will receive his Nobel Prize when he swings through Stockholm for two performances on April 1st and 2nd.

swings through here means goes to ?

A:
swing through something (Macmillan Dictionary)
to visit a place for a short time on your way to another place


text:
Q: how can I let other people download my app so I created a little calculator app and I wanna let my friends download it so they can use it, but how can they download it, how do I share it to other people

A: [Note that in this answer I'm assuming that your calculator has no dependencies outside the Python standard library.]
For ms-windows there are basically two options.

*

*Distribute only your script. Your friends would have to separately download and install Python. Assuming this is a tkinter script, it should have the extension .pyw, otherwise .py. Sometimes the OS doesn't know what to do with .pyw files, and you have to tell it to always open them with pythonw.exe.

*Make a self-contained executable package with e.g. PyInstaller and distribute that.
POSIX platforms like Linux, *BSD and OS X generally either come with Python or have it easily available in their standard packaging system. So distributing the script is sufficient in that case.