text:
Q: Need to create a thread for spinner? My code is here
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    progress = new ProgressDialog(this);
    progress.setTitle("Loading");
    progress.setMessage("Wait while loading...");
    progress.show();
    Log.i("Spinner", "Starts");
    String trip_id = trips.get(position);
    FeedParser parser = FeedParserFactory.getParser(ParserType.ANDROID_SAX);
    stopTimes = parser.parseStopTime().get(trip_id);
    Collections.sort(stopTimes,StopTime.StopTimeComparator);
    stops = parser.parseStop();
    List<String> stopList = new ArrayList<String>(stopTimes.size());
    for (StopTime st: stopTimes) {
        stopList.add(stops.get(st.getStop_id()).getStop_name() + st.getDeparture_time().toString());
    }
    Log.i("Spinner", "Dismissed");
//      progress.dismiss();
    Intent viewStops = new Intent(this, StopActivity.class);
    viewStops.putStringArrayListExtra("stops_to_parse", (ArrayList<String>) stopList);
    this.startActivity(viewStops);
}

When the list is clicked, I want to show a spinner indicating a loading while the program loads some other stuff, then dismiss it and turn to another activity.
But what it does is when you click on the list, it just load stuff, without displaying the spinner, then after all stuff is loaded, the spinner suddenly flashes out and then turn to another view.
Apparently, the program is busying loading other stuff that not able to display the spinner until it finishes.
How to show a spinner while the program is computing other stuff correctly?

A: What is happening is that you are doing time-consuming work(loading data) in the main thread(the UI thread). While you are loading the data, the interface is frozen and unable to draw or interact.
To solve this, you must move your time-consuming task to another thread. To do this you can use AsyncTask, or plain Java threads if you prefer.
In your main thread:

*

*Show the spinner

*Start the new thread

In your new thread:

*

*Do the work

*Hide the spinner

You can find many AsyncTask tutorials online.

A: You should probably use AsyncTask


text:
Q: why the redfinition in c //-----a.h-------
#ifndef ELEMTYPE
#define ELEMTYPE
typedef int ElemType;
#endif

//------test.c-----
#include <stdio.h>
#define ELEMTYPE
typedef double ElemType;
#include "a.h";

int main(){
    printf("%lu\n", sizeof(ElemType));
}

// my question is that i've already defined ELEMTYPE in test.c, as far as i concerned, the typedef in a.h should not be inlcuded in test.c. why i encountered the problem of redefinition of ElemType?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using C++ implementation of OpenSSL to decrypt data I am trying to decrypt AES-256-CBC encrypted data.
I can decrypt the entire file, but I get additional characters at the end. I also get an error from the OpenSSL libraries that says this...
EVP_DecryptFinal_ex:wrong final block length:evp_enc.c:532
Here is my decryption function which is right out of the wiki:
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext)
{
    int plaintext_len = 0;

    EVP_CIPHER_CTX *ctx;
    int len = 0;
    plaintext_len = 0;
    int error = 0;
    ctx = EVP_CIPHER_CTX_new();

    if(ctx == NULL)
    {
        handleErrors(0,1);
    }

    error = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
    handleErrors(error,2);

    error = EVP_DecryptUpdate(ctx,plaintext, &len, ciphertext, ciphertext_len);
    handleErrors(error, 3);

    plaintext_len = len;

    error = EVP_DecryptFinal_ex(ctx,plaintext + len, &len);
    handleErrors(error, 4);

    plaintext_len += len;
    EVP_CIPHER_CTX_free(ctx);

    return plaintext_len;
}

Note that I am passing in raw bytes using the uint8_t type, but converted it for this function. The plain text that is working contains the file, plus some additional characters at the end.
Here is the encrypted data in hex:
aa371af640b8481203c6bdc21bfccf109d047f0ad38daf0f03d1d7650a25616c019cdf9b80cda8980aa99809c2d9346fd1b501ef3b2f3548479840f897c85592ae90f6d5e9c87e428b00d36631963ca311b4486285495d50296a3d370aa0b82322ad0891adf43b262611cc2238769180f2ec8f7fba7dcb48f6efe9fc0f8725d18a7d29c52fc7d40193b7bed18f549f4e23c5def8f49fbf775e41e9c26d6a6ff3685d2f1a5050e660a9903305500dd946b81f49381b8db215b290b8e526eb463bb4cb9af1fdc3df14e6dfcc14eb6824400b6de24ee9e87170554caa825a2306b9d2f75432532e89871e0a4e64b43b22b69ede8127887408877f50e00368aad3c29a370ecbe3533b2e3b6a3de05ad836fc84eb2fd76c7563f24f215697bfc354c4a6e809c7e25f5d2de6df4ddae6dbb05bcd07217125268aab811183359e714df3e696eca1df2783c8855a048e0fa252c80930cf37be2c1e5eac6ac83e819a639dae9972363d7d89dcf2a2b1761888edd6c263b84cf5c6118e7544656f724156d396f8d8b3b6a49123ef633ced82bc9b65fff6f1d39d5e9e2fa32a3c58fc79459a94d237a5361d2a2db1f7b862cb0f081e6328076339392e59734a006718136d6784a12dfe93384e3e48941870bae48c563cb2474fd926963051c273bf26ce4a9d29e00d628719564cbf8769efb9726157c79b29f10644ea5656df99e20f84e0867b559b682453567c970df8ade768b6cd3498001a30160c83dd3efa3fc58c13ecac7e53041dd617905f1a9f02cc249b8c3523c92eace60a0ad9eba29ec973678859643d0d3765d7b9e2e5b58d639c7d2f6109da979981003c2e41e55d270f276b9edcfe0294d0aa34ade2cfb7140b4fbfb5d202b3079af5f7f2ec5c84a34a8d94cf3698a17fa1ee25767e00a8337f0ed6c2af9fc2dfd6dedfec45a23d376e8d1d

Here is the AES encryption key in hex
174126874a7c7f9a44da4f559cfd628586894e86f7e2eb0561a0809b7a294fd4

Here is the IV
603da7b9f9c365219a8121e528e7dddc

The result is
echo Y | format H: /q /x /fs:NTFS

@echo off

echo.
echo.Stopping the Backup Exec services...
echo.

net stop "BackupExecAgentBrowser"
net stop "BackupExecJobEngine"
net stop "BackupExecManagementService"
net stop "BackupExecRPCService"
net stop "BackupExecDeviceMediaService"
net stop "BackupExecAgentAccelerator"
net stop "bedbg"

echo.
echo.Starting the Backup Exec services...
echo.

net start "bedbg"
net start "BackupExecAgentAccelerator"
net start "BackupExecDeviceMediaService"
net start "BackupExecRPCService"
net start "BackupExecManagementService"
net start "BackupExecJobEngine"
net start "BackupExecAgentBrowser"
pause
exitC��Q�H

Notice the odd few characters at the end.
Also note, I've tried the same thing in Python and am getting the same results. I believe it has to do with the padding. But I don't know if I am supposed to pad the encrypted data, and if so, with what data, or what...


text:
Q: CPU Still Powercycles after swapping PSU > Reset BIOS > SSD won't boot but LIVE USB does Running an Asus Z87-A and a Samsung 840 SSD (I disconnected the GPU and extraneous HDD).
A few weeks ago I got a warning that the Mobo had detected surges (Computer is plugged into a APC UPS). I come in today and the CPU powercycles with the CPU LED on. After powering everything down, and resetting the BIOS, I'm able to boot into BIOS, but when I try to boot into OS (Ubuntu 14.04) I just return to the BIOS.
I'm able to boot onto a live USB, and the SMART tools didn't detect anything wrong on the SSD.
UPDATE
I swapped PSUs and still get powercycling, sometimes the power-cycling stops by itself and computer will POST and then tell me the mobo detected a surge. Is my motherboard fried in some way?

A: Change the BIOS from UEFI to Legacy mode (or reverse).   If that fails, try changing the SATA emulation (AHCI vs Legacy).

A: You should check your wall wiring. As I understand it, smaller consumer UPS systems are switching: there is a measurable time between your power company's power sag and the UPS power becoming available. So unless your UPS is an "online type" (expensive), this is a potential source.
PC power spec has something like a 20ms hold-up time before "all the juice drains out." I'd expect an APC UPS to have a quicker switch-over time, but it is plausible something isn't playing nice. Note that switching can cause transient surges.
It may be that your computer system is detecting the problem during the switch-over. I have had whole-house brownouts where only one out of three computers in the same room responded in any noticeable way.
Additionally, surge protective devices have a life expectancy. Either lots of small events or fewer large events. So it is plausible that you are having lots of small events and your device is still passing power but not actually offering surge protection. Surge protectors should be an order of magnitude faster than switch-over.


text:
Q: Powershell to present 'Net View' data happy Easter!
I am trying to write a script in Powershell that takes a list of hosts from a txt (or csv) and then for each does a "net view /all" on it, returning the presented shares in a csv.
I got something working but I need a column to show the host its looking at for each row otherwise I cant map them back.
Attempt 1 returns the data and the host but looks VERY messy and is proving difficult to dissect in Excel:
$InputFile = 'M:\Sources\Temp\net_view_list.txt'
$addresses = get-content $InputFile

foreach($address in $addresses) {

$sharedFolders = (NET.EXE VIEW $address /all)

    foreach ($item in $sharedfolders)
    {
        $str_list = $address + "|" + $item
        $obj_list = $str_list | select-object @{Name='Name';Expression={$_}}
        $obj_list | export-csv -append M:\sources\temp\netview.csv -notype
    }
}

Attempt 2 works better but cant get the hostname listed, plus the comments seem to appear in the "Used as" section (only using for one host to test the theory (didnt work!)):
$command = net view hostname #/all

$netview = $command -split '\n'

$comp = $netview[0].trim().split()[-1]

$result = $netview -match '\w' | foreach {

    convertfrom-string $_.trim() -delim '\s{2,}' -propertynames 'Share','Type', 'Used as', 'Comment'
    }

$result[0] = $null

$result | format-table 'Share', 'Type', 'Used as', 'Comment' -hidetableheaders

Also neither of these accounts for issues where the host either isn't accessible or has 0 shares.
I have literally spent all day on these - grateful for any guidance!

A: I will provide the way to get what you want in the your 1st example. The main reason it is not appearing like you are expecting it to is because you are not dealing with a PowerShell object. You are getting the raw output from an external command. What you need to do is take the data and create a PS Custom object then you can use it as you will. Below is the code that you should add after you have the $SharedFolder populated heavily commented to explain what each part is for.
# Create Array to hold PSCustom Object and variable to tell when the DO loop is done
$share_list = @()
$completed = $false

# Loop through each line in the output
for($x=0;$x -lt $sharedFolders.count;$x++){
    $next_line = $x + 1
    # If the line is a bunch of - then we know the next line contains the 1st share name.
    if($sharedFolders[$x] -like "*-------*"){
        # Here we will loop until we find the end of the list of shares
        do {
            # Take the line and split it in to an array. Note when you
            # use -split vs variable.split allows you to use regular
            # expressions. the '\s+' will consider x number of spaces as one
            # the single quotes are important when using regex. Double
            # quotes use variable expansion. Single quotes don't

            $content = $sharedFolders[$next_line] -split '\s+'
            $share_name = $content[0].Trim()

            # Create a PS Custom Object. This is a bit over kill for one item
            # but shows you how to create a custom Object. Note the Object last
            # just one loop thus you create a new one each go round then add it to
            # an Array before the loop starts over.
            $custom_object = new-object PSObject
            $custom_object | add-member -MemberType NoteProperty -name 'Share Name' -Value $share_name

            # Add the Custom Object to the Array
            $share_list += $custom_object

            # This exits the Do loop by setting $completed to true
            if($sharedFolders[$next_line] -like "*command completed*"){
                $completed = $true
            }

            # Set to the next line
            $next_line++
        } until ($completed)
    }
}
$share_list


text:
Q: How to pair two Data frames based on their index I have two DataFrames (df1, df2), both with a DateTime index type:
print(type(df1.index))  =>  pandas.core.indexes.datetimes.DatetimeIndex
print(type(df2.index))  =>  pandas.core.indexes.datetimes.DatetimeIndex

Both have just one column with some values:
print(df1):
Sample Date  Value df1
1992-01-02   430.0
1992-01-03   436.0
1992-01-04   439.0
1992-01-05   432.0
1992-01-06   427.0
           ...
2003-12-26   300.0
2003-12-27   306.0
2003-12-28   319.0
2003-12-29   321.0
2003-12-30   310.0

[4381 rows x 1 columns]

print(df2):
Sample Date   Value df2
1992-02-12    15.0
1992-04-11    24.0
1992-09-12    14.0
1992-11-18    26.0
1992-11-25    14.0
           ...
2003-10-09    43.0
2003-10-22    12.0
2003-12-02     4.0
2003-12-03    18.0
2003-12-08    44.0

[424 rows x 1 columns]

I want to get a new DF with those two columns (Value df1 and Value df2) just with the rows where the data is available in both data frames. For simplicity df1 is a DF without missing dates, whereas df2 has missing dates.
The results should look something like this:
Sample Date   Value df1    Value df2
1992-02-12    350.5        15.0
1992-04-11    420.2        24.0
1992-09-12    400.0        14.0
1992-11-18    380.5        26.0
1992-11-25    395.9        14.0
               ...         ...
2003-10-09    500.5        43.0
2003-10-22    480.9        12.0
2003-12-02    500.8        4.0
2003-12-03    350.0        18.0
2003-12-08    370.8        44.0

I tried to create a new df like this:
df = df1[df1.index.isin([df2.index])]

but the result is an empty DF. If I print df1.index.isin([df2.index]) I do get something like this: array([False, False, False, ..., False, False, False]).
Any ideas how can I solve this issue?
Thanks in advance.


text:
Q: Summing two elements of two UITextFields I'm having an issue with summing the element of one UITextField with the element of another UITextField and having the answer displayed in a third UITextField (called answer). The summation would happen by pressing a button. Here's the code I have for the IBAction:
-(IBAction) {
 answer.text = [[NSString stringWithFormat:@"%i",([text1.text intValue] + [text2.text intValue])]];

}
All I get is an error message saying "Expected Identifier"

A: Your message needs a name, and you have too many brackets. Try this:
-(IBAction)myAction {
  answer.text = [NSString stringWithFormat:@"%i",([text1.text intValue] + [text2.text intValue])];
}


text:
Q: XSSF Apache POI I used the below for setting default column style in XSSF sheet? but this is not working  can anyone suggest the bug fix.
format = workbook.createDataFormat();
style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("@"));
sheet.setDefaultColumnStyle(1, style);

A: As of POI 4.1.0 it is working with SXSSF, but with a caveat.
The default column style only defines which style will be applied when users enter data into empty cells in the sheet created by POI.
If you create cells and enter data through POI, the default format does not apply, you have to use
setCellStyle(CellStyle).
E.g. for text styles:
private CellStyle createTextFormat(SXSSFWorkbook workbook) {
    DataFormat fmt = workbook.createDataFormat();
    CellStyle textStyle = workbook.createCellStyle();
    textStyle.setDataFormat(fmt.getFormat("@"));
    return textStyle;
}

// then do both:
int columnIndex = 0;
sheet.setDefaultColumnStyle(columnIndex, textFormat)

SXSSFCell cell = row.createCell(0);
cell.setCellStyle(textFormat);
cell.setCellValue("0100");

A: Probably this bug is causing you headaches. Trying your code with Apache POI 3.7 I get the added effect that the second column gets hidden (width = 0) and the format is not applied.
Cheers,
Wim
PS Note that I talk about the second column, which is what your code is really referring to; if you wanted to apply the style to the first column you should have used 0 (zero-based).

A: Try this it will work:
       style.setDataFormat(HSSFDataFormat.getBuiltinFormat("@"));


text:
Q: Py_Initialize fails - unable to load the file system codec I am attempting to put together a simple c++ test project that uses an embedded python 3.2 interpreter. The project builds fine but Py_Initialize raises a fatal error:
Fatal Python error: Py_Initialize: unable to load the file system codec
LookupError: no codec search functions registered: can't find encoding

Minimal code:
#include <Python.h>

int main (int, char**)
{
  Py_Initialize ();
  Py_Finalize ();
  return 0;
}

The OS is 32bit Vista.
The python version used is a python 3.2 debug build, built from sources using VC++ 10.
The python_d.exe file from the same build runs without any problems.
Could someone explain the problem and how to fix it? My own google-fu fails me.
EDIT 1
After going through the python source code I've found that, as the error says, no codec search functions have been registered. Both codec_register and PyCodec_Register are as they should be. It's just that nowhere in the code are any of these functions called.
I don't really know what this means as I still have no idea when and from where these functions should have been called. The code that raises the error is entirely missing from the source of my other python build (3.1.3).
EDIT 2
Answered my own question below.

A: Ran into the same thing trying to install brew's python3 under Mac OS! The issue here is that in Mac OS, homebrew puts the "real" python a whole layer deeper than you think. You would think from the homebrew output that
$ echo $PYTHONHOME
/usr/local/Cellar/python3/3.6.2/
$ echo $PYTHONPATH
/usr/local/Cellar/python3/3.6.2/bin

would be correct, but invoking $PYTHONPATH/python3 immediately crashes with the abort 6 "can't find encodings." This is because although that $PYTHONHOME looks like a complete installation, having a bin, lib etc, it is NOT the actual Python, which is in a Mac OS "Framework". Do this:
PYTHONHOME=/usr/local/Cellar/python3/3.x.y/Frameworks/Python.framework/Versions/3.x
PYTHONPATH=$PYTHONHOME/bin

(substituting version numbers as appropriate) and it will work fine.

A: Check the PYTHONPATH and PYTHONHOME environment variables and make sure they don't point to Python 2.x.
http://bugs.python.org/issue11288

A: From python3k, the startup need the encodings module, which can be found in PYTHONHOME\Lib directory.
In fact, the API Py_Initialize () do the init and import the encodings module.
Make sure PYTHONHOME\Lib is in sys.path and check the encodings module is there.

A: I had this issue with python 3.5, anaconda 3, windows 7 32 bit. I solved it by moving my pythonX.lib and pythonX.dll files into my working directory and calling
Py_SetPythonHome(L"C:\\Path\\To\\My\\Python\\Installation");

before initialize so that it could find the headers that it needed, where my path was to "...\Anaconda3\". The extra step of calling Py_SetPythonHome was required for me or else I'd end up getting other strange errors where python import files.

A: Parts of this have been mentioned before, but in a nutshell this is what worked for my environment where I have multiple Python installs and my global OS environment set-up to point to a different install than the one I attempt to work with when encountering the problem.
Make sure your (local or global) environment is fully set-up to point to the install you aim to work with, e.g. you have two (or more) installs of, let's say a python27 and python33 (sorry these are windows paths but the following should be valid for equivalent UNIX-style paths just as well, please let me know about anything I'm missing here (probably the DLLs path might differ)):
C:\python27_x86
C:\python33_x64
Now, if you intend to work with your python33 install but your global environment is pointing to python27, make sure you update your environment as such (while PATH and PYTHONHOME may be optional (e.g. if you temporarily work in a local shell)):
PATH="C:\python33_x64;%PATH%"
PYTHONPATH="C:\python33_x64\DLLs;C:\python33_x64\Lib;C:\python33_x64\Lib\site-packages"
PYTHONHOME=C:\python33_x64
Note, that you might need/want to append any other library paths to your PYTHONPATH if required by your development environment, but having your DLLs, Lib and site-packages properly set-up is of prime importance.
Hope this helps.

A: I just ran into the exact same problem (same Python version, OS, code, etc).
You just have to copy Python's Lib/ directory in your program's working directory ( on VC it's the directory where the .vcproj is )

A: There appears to be something going wrong with the release build either failing to include the appropriate codecs or else misidentifying the codec to use for system APIs. Since the python_d executable is working, what does that return for os.getfsencoding()? (Use the C API to call that between your Initialize/Finalize calls)

A: I had the same issue and found this question. However from the answers here I was not able to solve my problem. I started debugging the cpython code and thought that I  might be discovered a bug. Therefore I opened a issue on the python issue tracker.
My mistake was that I did not understand that Py_SetPath clears all inferred paths.
So one needs to set all paths when calling this function.

*

*Link to the issue conversation
For completion I also copied the most important part of the conversation below.

My original issue text
I compiled the source of CPython 3.7.3 myself on Windows with Visual Studio 2017 together with some packages like e.g numpy. When I start the Python Interpreter I am able to import and use numpy. However when I am running the same script via the C-API I get an ModuleNotFoundError.
So the first thing I did, was to check if numpy is in my site-packages directory and indeed there is a folder named numpy-1.16.2-py3.7-win-amd64.egg. (Makes sense because the python interpreter can find numpy)
The next thing I did was to get some information about the sys.path variable created when running the script via the C-API.
#### sys.path content ####
C:\Work\build\product\python37.zip
C:\Work\build\product\DLLs
C:\Work\build\product\lib
C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\PROFESSIONAL\COMMON7\IDE\EXTENSIONS\TESTPLATFORM
C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages

Examining the content of sys.path I noticed two things.

*

*C:\Work\build\product\python37.zip has the correct path 'C:\Work\build\product\'. There was just no zip file. All my files and directory were unpacked. So I zipped the files to an archive named python37.zip and this resolved the import error.

*C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages is wrong it should be C:\Work\build\product\Lib\site-packages but I dont know how this wrong path is created.
The next thing I tried was to use Py_SetPath(L"C:/Work/build/product/Lib/site-packages") before calling Py_Initialize(). This led to

Fatal Python Error 'unable to load the file system encoding'
  ModuleNotFoundError: No module named 'encodings'

I created a minimal c++ project with exact these two calls and started to debug Cpython.
int main()
{
  Py_SetPath(L"C:/Work/build/product/Lib/site-packages");
  Py_Initialize();
}

I tracked the call of Py_Initialize() down to the call of
static int
zipimport_zipimporter___init___impl(ZipImporter *self, PyObject *path)

inside of zipimport.c
The comment above this function states the following:

Create a new zipimporter instance. 'archivepath' must be a path-like
  object to a zipfile, or to a specific path inside a zipfile. For
  example, it can be '/tmp/myimport.zip', or
  '/tmp/myimport.zip/mydirectory', if mydirectory is a valid directory
  inside the archive. 'ZipImportError' is raised if 'archivepath'
  doesn't point to a valid Zip archive. The 'archive' attribute of the
  zipimporter object contains the name of the zipfile targeted.

So for me it seems that the C-API expects the path set with Py_SetPath to be a path to a zipfile. Is this expected behaviour or is it a bug?
If it is not a bug is there a way to changes this so that it can also detect directories?
PS: The ModuleNotFoundError did not occur for me when using Python 3.5.2+, which was the version I used in my project before. I also checked if I had set any PYTHONHOME or PYTHONPATH environment variables but I did not see one of them on my system.

Answer
This is probably a documentation failure more than anything else. We're in the middle of redesigning initialization though, so it's good timing to contribute this feedback.
The short answer is that you need to make sure Python can find the Lib/encodings directory, typically by putting the standard library in sys.path. Py_SetPath clears all inferred paths, so you need to specify all the places Python should look. (The rules for where Python looks automatically are complicated and vary by platform, which is something I'm keen to fix.)
Paths that don't exist are okay, and that's the zip file. You can choose to put the stdlib into a zip, and it will be found automatically if you name it the default path, but you can also leave it unzipped and reference the directory.
A full walk through on embedding is more than I'm prepared to type on my phone. Hopefully that's enough to get you going for now.

A: The core reason is quite simple: Python does not find its modules directory, so it can of course not load encodings, too
Python doc on embedding says "Py_Initialize() calculates the module search path based upon its best guess" ... "In particular, it looks for a directory named lib/pythonX.Y"
Yet, if the modules are installed in (just) lib - relative to the python binary - above guess is wrong.
Although docs says that PYTHONHOME and PYTHONPATH are regarded, we observed that this was not the case; their actual presence or content was completely irrelevant.
The only thing that had an effect was a call to Py_SetPath() with e.g. [path-to]\lib as argument before Py_Initialize().
Sure this is only an option for an embedding scenario where one has direct access and control over the code; with a ready-made solution, special steps may be necessary to solve the issue.

A: In my cases, for windows, if you have multiple python versions installed, if PYTHONPATH is pointing to one version the other ones didn't work. I found that if you just remove PYTHONPATH, they all work fine

A: I had the problem and was tinkering with different solutions mentioned here. Since I was running my project from Visual Studio, apparently, I needed to set the environment path inside Visual Studio and not the system path.
Adding a simple PYTHONHOME=PATH\TO\PYTHON\DIR in the project solution\properties\environment solved the problem.

A: For me this happened when I updated Python 64 bit from 3.6.4 to 3.6.5. It threw some error like "unable to extract python.dll. Do you have permissions."
Pycharm also failed to load interpreter, even though I reloaded it in settings. Running python command gave same error, with and without administrator mode.
Reason
There was error in installation of Python, include folder in python installation directory C:\Users\USERNAME\AppData\Local\Programs\Python\Python36 was missing
Reinstalling Python also dint solve the issue.(Not removal and install)
Solution
Uninstall Python and Install of Python again.
Because running installer was just extracting same files excluding include folder

A: For those working in Visual Studio simply add the include, Lib and libs directories to the Include Directories and Library Directories under
Projects Properties -> Configuration Properties > VC++ Directories :
For example I have Anaconda3 on my system and working with Visual Studio 2015 This is how the settings looks like (note the Include and Library directories) :

Edit:
As also pointed out by bossi setting PYTHONPATH in your user Environment Variables section seems necessary.
a sample input can be like this (in my case):
C:\Users\Master\Anaconda3\Lib;C:\Users\Master\Anaconda3\libs;C:\Users\Master\Anaconda3\Lib\site-packages;C:\Users\Master\Anaconda3\DLLs

is necessary it seems.
Also, you need to restart Visual Studio after you set up the PYTHONPATH in your user Environment Variables for the changes to take effect.
Also note  that :

Make sure the PYTHONHOME environment variable is set to the Python
  interpreter you want to use. The C++ projects in Visual Studio rely on
  this variable to locate files such as python.h, which are used when
  creating a Python extension.

A: So, for some reason the python dll fails to locate the encodings module. The python.exe executable apparently finds it because it has the expected relative path. Modifying the search path works.
The reason for all of this? Don't know but at least it works. I highly suspect a typo on my part somewhere, that's usually the reason for odd bugs it seems.


text:
Q: Unknown words in a trained word embedding (Gensim) for using in Keras I'm training a word embedding using GENSIM (word2vec) and use the trained model in a neural network in KERAS. A problem arises when I have an unknown (out-of-vocabulary) word so the neural network doesn't work anymore because it can't find weights for that specific word. I think one way to fix this problem is adding a new word (<unk>) to the pre-trained word embedding with zero weights (or maybe random weights? which one is better?) Is this approach fine? Also, for this word embedding, the weights are not trainable in this neural network.

A: Most typical is to ignore unknown words. (Replacing them with either a plug-word, or the origin-vector, is more distorting.)
You could also consider training a FastText mode instead, which will always synthesize some guess-vector for an out-of-vocabulary word, from the character-n-gram vectors created during training. (These synthetic vectors are often better than nothing, especially when a word has overlapping word roots with related words – but getting more training data with examples of all relevant word usages is better, and simply ignoring rare unknown words isn't that bad.)


text:
Q: Numerical dimension of nef divisors Let $D$ be a nef divisor (moreover suppose it is effective if you prefer) on a normal projective variety of dimension $n$. Let $k\in[1,n-1]$.
If $D^k\cdot V=0$ for generic subvarieties $V\subseteq X$ of dimension $k$, can I conclude that $D^k\cdot V=0$ for all subvarieties $V$ of dimension $k$?
In other words can I conclude that the numerical dimension of $D$ is less than $k$?


text:
Q: Facebook Messenger Platform Send API unexpected internal error I'm working on my framework for Facebook Messenger Platform Send API and I've got this error when trying to create an Airline Itinerary Template (https://developers.facebook.com/docs/messenger-platform/send-api-reference/airline-itinerary-template):
{
 "error": {
   "message": "(#-1) Send API unexpected internal error",
   "type": "OAuthException",
   "code": -1,
   "fbtrace_id": "DBWbw/pHJGv"
 }
}

Here's the request that triggered it:
{
   "message":{
      "attachment":{
         "type":"template",
         "payload":{
            "flight_info":[
               {
                  "connection_id":"123",
                  "segment_id":"123",
                  "aircraft_type":"Boeing",
                  "travel_class":"business",
                  "flight_number":"123",
                  "departure_airport":{
                     "airport_code":"CT",
                     "city":"Catania",
                     "terminal":"F",
                     "gate":"54"
                  },
                  "arrival_airport":{
                     "airport_code":"BG",
                     "city":"Bergamo",
                     "terminal":"C",
                     "gate":"12"
                  },
                  "flight_schedule":{
                     "boarding_time":"2016-8-25T15:8",
                     "departure_time":"2016-8-25T15:8",
                     "arrival_time":"2016-8-25T15:8"
                  }
               }
            ],
            "passenger_info":[
               {
                  "passenger_id":"1",
                  "ticket_number":"215",
                  "name":"Sarah Hum"
               },
               {
                  "passenger_id":"2",
                  "name":"Jeremy Goldberg"
               }
            ],
            "passenger_segment_info":[
               {
                  "segment_id":"241",
                  "passenger_id":"251",
                  "seat":"14A",
                  "seat_type":"Economy",
                  "product_info":[
                     {
                        "title":"Cabin",
                        "value":"Coach"
                     }
                  ]
               }
            ],
            "price_info":[
               {
                  "title":"Cabin",
                  "amount":100.0,
                  "currency":"USD"
               },
               {
                  "title":"Ticket",
                  "amount":200.0
               }
            ],
            "base_price":200.71,
            "tax":200.0,
            "total_price":4032.54,
            "currency":"USD",
            "pnr_number":"D0FQTK",
            "intro_message":"Here\u0027s your itinerary",
            "locale":"en_US",
            "template_type":"airline_itinerary"
         }
      }
   },
   "recipient":{
      "id":"************"
   }
}

At this URL: https://graph.facebook.com/v2.7/me/messages?access_token=*******
I've got this problem only with this specific template. The other works just fine. Does anybody know what may be the cause of it?
Thank you.

A: I have the same problem, did you try with 2.6 API version ?
https://graph.facebook.com/v2.6/me/messages?access_token=*******

I have just try with a CURL request and it works fine with the facebook docs example
curl -X POST -H "Content-Type: application/json" -d '{
"recipient": {
    "id": "XXXX"
},
"message": {
    "attachment": {
        "type": "template",
        "payload": {
            "template_type": "airline_itinerary",
            "intro_message": "Heres your flight itinerary.",
            "locale": "en_US",
            "pnr_number": "ABCDEF",
            "passenger_info": [
            {
                "name": "Farbound Smith Jr",
                "ticket_number": "0741234567890",
                "passenger_id": "p001"
            },
            {
                "name": "Nick Jones",
                "ticket_number": "0741234567891",
                "passenger_id": "p002"
            }
        ],
            "flight_info": [
            {
                "connection_id": "c001",
                "segment_id": "s001",
                "flight_number": "KL9123",
                "aircraft_type": "Boeing 737",
                "departure_airport": {
                    "airport_code": "SFO",
                    "city": "San Francisco",
                    "terminal": "T4",
                    "gate": "G8"
                },
                "arrival_airport": {
                    "airport_code": "SLC",
                    "city": "Salt Lake City",
                    "terminal": "T4",
                    "gate": "G8"
                },
                "flight_schedule": {
                    "departure_time": "2016-01-02T19:45",
                    "arrival_time": "2016-01-02T21:20"
                },
                "travel_class": "business"
            },
            {
                "connection_id": "c002",
                "segment_id": "s002",
                "flight_number": "KL321",
                "aircraft_type": "Boeing 747-200",
                "travel_class": "business",
                "departure_airport": {
                    "airport_code": "SLC",
                    "city": "Salt Lake City",
                    "terminal": "T1",
                    "gate": "G33"
                },
                "arrival_airport": {
                    "airport_code": "AMS",
                    "city": "Amsterdam",
                    "terminal": "T1",
                    "gate": "G33"
                },
                "flight_schedule": {
                    "departure_time": "2016-01-02T22:45",
                    "arrival_time": "2016-01-03T17:20"
                }
            }
        ],
            "passenger_segment_info": [
            {
                "segment_id": "s001",
                "passenger_id": "p001",
                "seat": "12A",
                "seat_type": "Business"
            },
            {
                "segment_id": "s001",
                "passenger_id": "p002",
                "seat": "12B",
                "seat_type": "Business"
            },
            {
                "segment_id": "s002",
                "passenger_id": "p001",
                "seat": "73A",
                "seat_type": "World Business",
                "product_info": [
                    {
                        "title": "Lounge",
                        "value": "Complimentary lounge access"
                    },
                    {
                        "title": "Baggage",
                        "value": "1 extra bag 50lbs"
                    }
                ]
            },
            {
                "segment_id": "s002",
                "passenger_id": "p002",
                "seat": "73B",
                "seat_type": "World Business",
                "product_info": [
                    {
                        "title": "Lounge",
                        "value": "Complimentary lounge access"
                    },
                    {
                        "title": "Baggage",
                        "value": "1 extra bag 50lbs"
                    }
                ]
            }
        ],
            "price_info": [
            {
                "title": "Fuel surcharge",
                "amount": "1597",
                "currency": "USD"
            }
        ],
            "base_price": "12206",
            "tax": "200",
            "total_price": "14003",
            "currency": "USD"
    }
}
}
}' 'https://graph.facebook.com/v2.6/me/messages?access_token=xxxxx'

A: I see the below issues in your message json.

*

*The segment_id in flight_info section isn't matching the one in the passenger_segment_info section

*Same issue with the passenger_id field.

*The boarding, arrival and departure date format is wrong. You need to prefix 0 if the month, day, hour or minute is single digit.

I tested with the above fixes and it worked fine. Here is the updated example.
{
     "attachment":{
     "type":"template",
     "payload":{
        "flight_info":[
           {
              "connection_id":"123",
              "segment_id":"241",
              "aircraft_type":"Boeing",
              "travel_class":"business",
              "flight_number":"123",
              "departure_airport":{
                 "airport_code":"CT",
                 "city":"Catania",
                 "terminal":"F",
                 "gate":"54"
              },
              "arrival_airport":{
                 "airport_code":"BG",
                 "city":"Bergamo",
                 "terminal":"C",
                 "gate":"12"
              },
              "flight_schedule":{
                 "boarding_time":"2016-08-25T15:08",
                 "departure_time":"2016-08-25T15:08",
                 "arrival_time":"2016-08-25T15:08"
              }
           }
        ],
        "passenger_info":[
           {
              "passenger_id":"1",
              "ticket_number":"215",
              "name":"Sarah Hum"
           },
           {
              "passenger_id":"2",
              "name":"Jeremy Goldberg"
           }
        ],
        "passenger_segment_info":[
           {
              "segment_id":"241",
              "passenger_id":"1",
              "seat":"14A",
              "seat_type":"Economy",
              "product_info":[
                 {
                    "title":"Cabin",
                    "value":"Coach"
                 }
              ]
           }
        ],
        "price_info":[
           {
              "title":"Cabin",
              "amount":100.0,
              "currency":"USD"
           },
           {
              "title":"Ticket",
              "amount":200.0
           }
        ],
        "base_price":200.71,
        "tax":200.0,
        "total_price":4032.54,
        "currency":"USD",
        "pnr_number":"D0FQTK",
        "intro_message":"Here\u0027s your itinerary",
        "locale":"en_US",
        "template_type":"airline_itinerary"
     }
  }
},

I hope Facebook will someday update the documentation with the details about these constraints. Please share your bug ticket link here so that we can subscribe to it.


text:
Q: Computing the Inverse Fourier Transform of $\tanh(x)/x$ Hello fellow Stackexchange users.
I am trying to compute the inverse Fourier transform of
$\frac{\tanh(l_s^{-1}\epsilon\omega)}{\omega}$,
where $l_s^{-1}$ and $\epsilon$ are both real, positive, and known constants.
In an answer to this question a user suggests (in taking the Fourier transform) to apply a complex version of Frullani's theorem.
My attempt at doing so goes as follows
$\begin{align}
f(x)&=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{e^{l_s^{-1}\epsilon \omega}-e^{-l_s^{-1}\epsilon \omega}}{\omega(e^{l_s^{-1}\epsilon\omega}+e^{-l_s^{-1}\epsilon\omega})}e^{-i\omega x}d\omega\\
&=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{e^{l_s^{-1}\epsilon \omega}-e^{-l_s^{-1}\epsilon \omega}}{\omega(e^{l_s^{-1}\epsilon\omega}+e^{-l_s^{-1}\epsilon\omega})}(\cos(\omega x)-i\sin(\omega x))d\omega\\
&=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{e^{l_s^{-1}\epsilon \omega}-e^{-l_s^{-1}\epsilon \omega}}{\omega(e^{l_s^{-1}\epsilon\omega}+e^{-l_s^{-1}\epsilon\omega})}\cos(\omega x)d\omega\\
\end{align}$
Now, to apply Frullani's theorem, I would like to let
$f(\omega)=\frac{e^{l_s^{-1}\epsilon\omega}\cos(\omega)}{e^{l_s^{-1}\epsilon\omega}+e^{-l_s^{-1}\epsilon\omega}}.$
However, $\lim_{\omega\to\infty}f(\omega)$ does not exist.
I am sure I have gone terribly wrong somewhere, and cannot think of a way to find the solution.  Any help would be very much appreciated.  Also, if the answer involves Weierstrass products, could you please also submit a readable introduction to them?
Edit:  After a moment's thought, I am thinking that this integral doesn't even exist, since it decays like $1/\omega$.   So does this integral even exist?

A: Choosing $a=l_s^{-1}\epsilon$, you may use the convolution theorem: $$\begin{align}\mathcal{F}^{-1}\left(\frac{\tanh(a\omega)}{\omega}\right)&=\mathcal{F}^{-1}\left(\tanh(a\omega)\right)*\mathcal{F}^{-1}\left(\frac{1}{\omega}\right)\\&=\left(-\frac{i}{a}\sqrt{\frac{\pi}{2}}\text{csch}(\frac{\pi x}{2a})\right)*\frac{i}{2}\text{sgn}(x)\\&=\frac{1}{2a}\sqrt{\frac{\pi}{2}}\left(2\log\left(\tanh(\frac{\pi x}{4a})\right)-i\pi\right)\end{align}$$


text:
Q: Can't Save hasMany/belongsTo Relationship if Both Are New in Ember-Data I have two models.
App.Request = DS.Model.extend({
    materials: DS.hasMany('App.Material')
});

App.Material = DS.Model.extend({
    request: DS.belongsTo('Mat.Request')
});

In the form for creating a request, I create a new request:
App.Request.createRecord();

And bind it to the fields of the form. To create a new material, you click a button and a modal appears. When the modal appears, it creates a new material in the materials array of the request: (The material modal has its own controller, so I have to get the request by going to the RequestsNewController.)
this.get('controllers.requestsNew.materials').createRecord();

Yay! It works. I can add many materials to the request and the UI is updating to show that the associations are being created correctly. Awesome! Until... I hit the save button, calling this code from the RequestsNewController:
this.get('transaction').commit();

Now, the materials I've added to my request are torn away (the part of the template that shows the materials in the request now shows no materials.)
This is a very simplified version of my code, but the point is that everything looks good until I commit the data to the server. I have a theory as to what's happening, but I have no idea how to fix it! I'm using Rails with Active Model Serializers on my backend, by the way.
When I call commit, the Rest Adapter first POSTs to /requests. The record is added, and I get the following back from the server:
{
    "request": {
        "id": 30,
        "material_ids": []
    }
}

Yay! My request has been saved, and I now have an ID from the server.
Next, the REST Adapter POSTs to /materials and it sends the following JSON:
{
    "material": {
        "request_id": 0,
    }
}

And the server responds, giving the material an ID.
But what's this? The REST Adapter is sending request_id: 0, not request_id: 30 like it should?
Here's my theory: After the request is saved, the server responds with an empty array of material_ids. This makes sense! We haven't sent the materials to the server yet because we need the request ID first! However, when Ember Data sees an empty array of material_ids, it removes the materials from the request. Then, when the materials save, they no longer have a request, hence request_id: 0.
When I create a request with no materials, commit, add materials, commit, it works!
What am I doing wrong?
Thanks!

A: I think this is a known issue currently, and your theory is true. ATM, I have two workarounds in mind. The first one is to embed the materials in the request, by configuring the adapter like this:
DS.RESTAdapter.map('App.Request', {
  materials: {embedded: 'always'}
});

The second one would be to add an observer on the didCreate event on the request, adding the materials once created, and then commit again.
Here are the related current issues about this: https://github.com/emberjs/data/pull/440 https://github.com/emberjs/data/pull/724 https://github.com/emberjs/data/issues/437 https://github.com/emberjs/data/pull/643

A: You may be interested in that PR https://github.com/emberjs/data/pull/876


text:
Q: Python segfault calculating exponential of negative (ppc64le) When calculating the exponential of a negative number in python 3.6 with Ubuntu 18.04 (ppcle64), I receive a segfault.
python -c "import math; math.exp(-1)"
qemu: uncaught target signal 11 (Segmentation fault) - core dumped
Segmentation fault

I am running this in Docker on macOS. Here are the steps to reproduce the error.
docker run --rm -it --platform linux/ppc64le ubuntu:18.04
apt-get update -qq && apt-get install -y -qq python3
python3 -c "import math; print(math.exp(0))"  # 1.0
python3 -c "import math; print(math.exp(-0))"  # 1.0
python3 -c "import math; print(math.exp(1))"  # 2.718281828459045
python3 -c "import math; print(math.exp(-1))"

This error does not happen when using the debian:10 or alpine images.
Here is the output of docker version on my machine:
Client: Docker Engine - Community
 Version:           19.03.8
 API version:       1.40
 Go version:        go1.12.17
 Git commit:        afacb8b
 Built:             Wed Mar 11 01:21:11 2020
 OS/Arch:           darwin/amd64
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          19.03.8
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.12.17
  Git commit:       afacb8b
  Built:            Wed Mar 11 01:29:16 2020
  OS/Arch:          linux/amd64
  Experimental:     true
 containerd:
  Version:          v1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

In case this is a bug, I submitted a report to Ubuntu at https://bugs.launchpad.net/cloud-images/+bug/1871451 and to Docker's fork of qemu at https://github.com/moby/qemu/issues/10.


text:
Q: The specified channel could not be found EventViewer I am opening windows event viewer security logs which under Windows Logs but its displaying an error as below.(Other logs are working)

Event viewer cannot open the event log or custom view, Verify that
  Event Log service is running or query is too long. The specified
  channel could not be found. Check channel configuration ( 15007)

I tried to create custom view but when Security logs selected it shows the same error message
Btw. i was working with c# EventLogReader class for read Security logs and problem is occured after system restarted.
p.s
Event log service is running, query is not long and Security.evtx is exist at folder and local group policy configs are restored default


text:
Q: How to merge two checked out portions of a repository? I have checked out two different parts of a large repository a while ago, but now I need to commit a change that involves files in both parts. To avoid having to check everything out again, I'm trying to merge the two parts into a single working copy.
I tried checking out an empty root directory above the two subdirectories, then running svn update on both subdirectories. It sort of worked, but when I do svn status, it lists all subdirectories with question marks, and commit does nothing at all, even if I explicitly specify a changelist.

A: It depends on how many changes you made. If you changed only files and not directory structure, then you can proceed by checking out from the repository root with no recursion, and then update only the needed paths to be fully recursive.
Supposing the you modified files under Component1/Trunk and Component2/Trunk directories in the repository, then the commands you need are -
svn checkout --depth empty repoUrl localRepo
svn update --depth immediates localRepo/Component1
svn update --depth immediates localRepo/Component2
svn update --depth infinity localRepo/Component1/Trunk
svn update --depth inifnity localRepo/Component2/Trunk

Once you have the repository in place, you can copy your modifications into the single checkout (only copying regular files, no subversion hidden directories). For this operation you may want to use a directory comparison tool such as meld or WinDiff - so that you copy only what you want to be committed.
Now you can commit to the repository via a single commit.
If either you modification affected directory tree structure or the repository evolved beyond simple file modification, you could have better look in performing a new checkout and applying your changes.
To avoid this problems in the future, you may want to look at "external" concepts in subversion to prepare a custom workspace that picks different parts of the repository.


text:
Q: mask 10 values in the middle numpy array I will like mask 10 values in the middle of array and mix with 10 max and 10 min values.
Create array
  z = np.random.random((10,10))

Sorted
  sorted = np.sort(z,axis=None)

logical premise 10 max and 10 min
  p=np.logical_and(z >= sorted[10], z <= sorted[-10])

Execute premise
   c = ma.masked_where(p, z, copy=True)

go to the center
 pos_1=len(sorted)/2-5
 pos_2=len(sorted)/2+5

logical premise 10 values in the middle:
 p=np.logical_or(z < float(sorted[pos_1]) , z > float(sorted[pos_2]))

Execute premise
 c = ma.masked_where(p, z, copy=True)

THE LAST IS WORKING ALSO I DONT KNOW HOW CAN JOIN THE TWO RESULTS. I REFER THE MASK OF THE TWO RESULTS
If you could help me.

A: OK I fint the solution, I think is heavy and any person could find one better
z = np.random.random((10,10))
p=np.logical_and(z >= sorted[10], z <= sorted[-10])
a = ma.masked_where(p, z, copy=True)
p=np.logical_or(z < float(sorted[pos_1]) , z > float(sorted[pos_2]))
b = ma.masked_where(p, z, copy=True)

The problem that I fix, combine the two mask, but you need invert first, because I realease with a OR operation.
 c =np.ma.mask_or(~a.mask, ~b.mask)

and result
 print np.ma.masked_array(z,~c)


text:
Q: iOS11: airplane mode and Bluetooth I just updated to iOS11 and I realized that, when you enable and then disable the airplane mode, the Bluetooth is automatically turned on (even if previously is was switched off).
Is there a way to prevent this annoying functionality?

A: I had the same issue but I finally found out how to fix it. Bluetooth actually stays on the whole time even if in the control center the bluetooth button isn't even blue.
Go open "settings", and you'll see that bluetooth is switched on (and maybe you thought it was off like in my case). If you turn it off in the settings, the bluetooth icon from the control center will get crossed, and from there it doesn't get switched on automatically every time you disable airplane mode.
Good Luck :)

A: On iOS 11 - to disable bluetooth, you'll want to install a configuration profile to accomplish that. Note that the control center now keeps the Bluetooth and WiFi radios on when you disable them - only AirPlane mode truly turns them off and you can turn them on piecemeal when in AirPlane mode. That change may have required the one you wish to modify.
Apple's hardware and services need bluetooth for more than a dozen features all bundled under continuity / handoff / siri knowing which device is closes for "hey siri" so the vast majority of people need bluetooth on all the time for these to work.
You can make profiles with Server.app (which costs money) and with Apple Configurator 2 which is free. You may need to supervise your devices to control bluetooth at that granularity so read into that a bit and be sure to test your profile to be sure it does what you want.


text:
Q: How can I boot Linux in HP Pavillion x360? I recently installed Manjaro on my Windows 10 HP Pavillion x360. Everything went fine until I had to reboot. I hoped to find GRUB but...surprise! it booted into Windows.
After that I rebooted into Manjaro through Windows, and checking with efibootmgr I realized that the boot order was wrong, so I changed it and rebooted, and.. it still booted into Windows. Repeated the same operation, but then I erased the Windows EFI entry and... still booted into Windows! I couldn't find any elegant way to boot into my new Linux system.
In the end I managed to boot, but I had to use a very "shady" solution: I changed the location of my grub.efi to /boot/efi/EFI/Microsoft/Boot/ and changed its name to the windows .efi, then I renamed the Microsoft folder to Microsoftt (so the BIOS wouldnt recognize it as the Windows bootloader and recognized my GRUB instead) and changed the Windows entry in GRUB.
It works, but its way far from optimal, also, every time I update I loose the Windows entry because GRUB fails to recognize it, so I have to add it manually.


text:
Q: Search recent media and comment via Instagram API and Graph API I want to build an app where the app user can from within the app

*

*search Instagram's most recent media by a search term (Hashtag-Search)

*post comments to Instagram posts

For searching Instagram the Graph API can't be used, because it doesn't has such capability. Therefore I need to use the old Instagram API, correct? But Instagram states "The Instagram Graph API is Now Available to All Developers. For Non-Business Instagram Accounts please continue to use the existing Instagram Platform API". The users of my platform have business accounts which I need for posting comments via the Graph API.
Do I have to use the Instagram API for searches by the app users (1.) and the Graph API for posting comments(2.)?
Is there another way to search for Instagram media which is not against Instagram policies?

A: Yes, You need to use both APIs; in other words, have to have access token for both apps just for the same Instagram account, doing oauth handshake to each API's authentication.
Also to note - for your first requirement: Search media by hashtags in Instagram API, you need your app to have public_content scope; which Instagram no longer approves to new apps. So, unless you have an oauth app already with this scope for Instagram API; most likely it wouldn't be possible to use developer apis for search.
For limited tag search you can use public web api:
https://www.instagram.com/explore/tags/{tagName}/?__a=1

for example: https://www.instagram.com/explore/tags/apple/?__a=1
This is just for recent media - I guess, this API does not guarantee all media.

A: This is no longer correct.
The graph API has the endpoint ig_hashtag_search, which will find the ID of the hashtag. You can then use it to search for media on endpoints recent_media and top_media.


text:
Q: MySql stored procedure not work due to error which inside cursor Followed procedure not work due to error at open cr_count line. When i run code without this line it works finely. Also i tried to write query without cursor such as select into even so, procedure not worked. i did not write mysql error print as oracle sqlerrm, i think mysql has not that function.
delimiter $$

create procedure proc_payment(
  in p_transaction_guid varchar(200),
  in p_card_type_id int,
  in p_card_number varchar(100),
  in p_billing_address varchar(500),
  in p_flight_id int,
  in p_flight_date date,
  in p_cabin_class_id int,
  in p_identity_number varchar(200)
)
begin
  declare v_count          int;
  declare v_payment_id     int;
  declare v_passenger_id   int;
  declare v_booking_ref_id int;

  declare cr_count cursor for
    select count(1)
    from tbl_passenger
    where identity_number = p_identity_number;

  declare cr_passenger cursor for
    select passenger_id
    from tbl_passenger
    where identity_number = p_identity_number;

  open cr_count;
  fetch cr_count into v_count;
  close cr_count;

  if v_count = 0 then
    insert into tbl_passenger (
      firstname,
      lastname,
      gender,
      birthdate,
      identity_number
    )
    select
      firstname,
      lastname,
      gender_id,
      birthdate,
      identity_number
    from
      v_booking_transaction
    where
      transaction_guid = p_transaction_guid
      and identity_number = p_identity_number;

    select last_insert_id() into v_passenger_id;
  else
    open cr_passenger;
    fetch cr_passenger into v_passenger_id;
    close cr_passenger;
  end if;

  insert into tbl_payment (
    card_type_id,
    card_number,
    payment_date,
    billing_address
  ) values (
    p_card_type_id,
    p_card_number,
    current_date(),
    p_billing_address
  );

  select last_insert_id() into v_payment_id;

  insert into tbl_flight_booking (
    flight_id,
    flight_date,
    cabin_class_id,
    payment_id
  ) values (
    p_flight_id,
    p_flight_date,
    p_cabin_class_id,
    v_payment_id
  );

  select last_insert_id() v_booking_ref_id;

  insert into tbl_flight_passenger (
    flight_id,
    booking_reference_id,
    passenger_id
  ) values (
    p_flight_id,
    v_booking_ref_id,
    v_passenger_id
  );
end$$

A: Perhaps the cursors can be avoided in this case. The following should work:
delimiter $$

create procedure proc_payment(
  in p_transaction_guid varchar(200),
  in p_card_type_id int,
  in p_card_number varchar(100),
  in p_billing_address varchar(500),
  in p_flight_id int,
  in p_flight_date date,
  in p_cabin_class_id int,
  in p_identity_number varchar(200)
)
begin
  declare v_passenger_id,
          v_payment_id,
          v_booking_ref_id int;

  select
    passenger_id into v_passenger_id
  from
    tbl_passenger
  where
    identity_number = p_identity_number;

  if v_passenger_id is null then
    insert into tbl_passenger (
      firstname,
      lastname,
      gender,
      birthdate,
      identity_number
    )
    select
      firstname,
      lastname,
      gender_id,
      birthdate,
      identity_number
    from
      v_booking_transaction
    where
      transaction_guid = p_transaction_guid
      and identity_number = p_identity_number;
    set v_passenger_id := last_insert_id();
  end if;

  insert into tbl_payment (
    card_type_id,
    card_number,
    payment_date,
    billing_address
  ) values (
    p_card_type_id,
    p_card_number,
    current_date(),
    p_billing_address
  );
  set v_payment_id := last_insert_id();

  insert into tbl_flight_booking (
    flight_id,
    flight_date,
    cabin_class_id,
    payment_id
  ) values (
    p_flight_id,
    p_flight_date,
    p_cabin_class_id,
    v_payment_id
  );
  set v_booking_ref_id := last_insert_id();

  insert into tbl_flight_passenger (
    flight_id,
    booking_reference_id,
    passenger_id
  ) values (
    p_flight_id,
    v_booking_ref_id,
    v_passenger_id
  );
end$$

delimiter ;


text:
Q: An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Error I get:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid object name sp_VehicleInfo.

Code:
protected void btnRegister_Click(object sender, EventArgs e)
{
        VehicleInfo vehicle = new VehicleInfo();
        vehicle.VehicleNo = txtVehicleNo.Text;
        vehicle.Make = txtMake.Text;
        vehicle.Model = txtEmail.Text;
        vehicle.Variety = txtVersion.Text;
        //vehicle.isAc = radAC.Text;
        vehicle.EngineNo = TextBox1.Text;
        vehicle.LExpDate = txtLicenseExpDate.Text;
        vehicle.InsuranceNo = TextBox2.Text;
        vehicle.IExpDate = txtInsuranceExpDate.Text;
        vehicle.Insert();
}

and this is the stored procedure
[dbo].[sp_VehicleInfo]
    @VehicleNo NVARCHAR(50) = NULL,
    @Make NVARCHAR(50) = NULL,
    @Model NVARCHAR(50) = NULL,
    @Variety NVARCHAR(50) = NULL,
    @isAc BIT = NULL,
    @EngineNo NVARCHAR(50) = NULL,
    @LExpDate NVARCHAR(50) = NULL,
    @InsuranceNo NVARCHAR(50) = NULL,
    @IExpDate NVARCHAR(50) = NULL,
    @VehicleId bigint = NULL,
    @mode NVARCHAR(50)
AS
BEGIN
    IF(@mode = 'insert')
    BEGIN
        INSERT INTO sp_VehicleInfo (VehicleNo, Make, Model, Variety, isAc, EngineNo, LExpDate, InsuranceNo, IExpDate)
        OUTPUT inserted.VehicleNo
        VALUES (@VehicleNo, @Make, @Model, @Variety, @isAc, @EngineNo, @LExpDate, @InsuranceNo, @IExpDate)
    END

    IF(@mode = 'update')
    BEGIN
        UPDATE sp_VehicleInfo
        SET VehicleNo = Isnull(@VehicleNo, VehicleNo),
            Make = Isnull(@Make, Make),
            Model = Isnull(@Model, Model),
            Variety = Isnull(@Variety, Variety),
            isAc = Isnull(@isAc, isAc),
            EngineNo = Isnull(@EngineNo, EngineNo),
            LExpDate = Isnull(@LExpDate, LExpDate),
            InsuranceNo = Isnull(@InsuranceNo, InsuranceNo),
            IExpDate = Isnull(@IExpDate, IExpDate)
        WHERE
            VehicleId = @VehicleId
    END

    IF(@mode = 'get' )
    BEGIN
        SELECT *
        FROM sp_VehicleInfo
        WHERE VehicleId = @VehicleId
    END

    IF(@mode = 'delete')
    BEGIN
        DELETE FROM sp_VehicleInfo
        WHERE VehicleId = @VehicleId
    END
END

A: This is a common error message. You are trying to access sp_VehicleInfo somewhere in your code and it seems like it is not a valid object in your database. From the naming convention you followed, I suppose it is a stored procedure. Check your database if this object is available or not.
Please note the following:

*

*It may not be a good way to start a database object's name with "sp_" as system stored procedures follows that naming convention.

*Please include all the code relevant to your question like the code that accesses the database in the post


text:
Q: Authorize attribute is ignoring [AllowAnonymous] I have set-up a customer Authorization Attribute in my asp.net web api
global file:
  FilterConfig.RegisterHttpFilters(GlobalConfiguration.Configuration.Filters);

FilterConfig.cs
public static void RegisterHttpFilters(System.Web.Http.Filters.HttpFilterCollection filters)
    {
        filters.Add(new TokenAuthentication(""));
    }

Authentication Class:
  public class TokenAuthentication : Attribute, IAuthenticationFilter
{
    private readonly string realm;

    public bool AllowMultiple { get { return false; } }

    public TokenAuthentication(string realm)
    {
        this.realm = "realm=" + realm;
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        var request = context.Request;

        // Receive token from the client. Here is the example when token is in header:
        string token = null;

        if (request.Headers.Contains("Token"))
        {
            token = request.Headers.GetValues("Token").FirstOrDefault();
        }

        if (token != null && token != "")
        {
            // Get your secret key from the configuration
            var secretKey = ConfigurationManager.AppSettings["JWTSecurityKey"];

            try
            {
                //Get the Payload from the token
                string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);

                int separatorIndex = jsonPayload.IndexOf(';');
                string userId = "";
                DateTime timeIssued = DateTime.MinValue;
                if (separatorIndex >= 0)
                {
                    //userId = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(jsonPayload.Substring(0, separatorIndex)));
                    userId = jsonPayload.Substring(1, separatorIndex - 1);
                    string tmpTime = jsonPayload.Substring(separatorIndex + 1, (jsonPayload.Length - separatorIndex) - 2);
                    timeIssued = DateTime.Parse(tmpTime);
                }

                short TokenTTL = 10;                //minuets
                //Int16.TryParse(ConfigurationManager.AppSettings["TokenTTL"],TokenTTL);

                // if ((DateTime.Now.Subtract(timeIssued).TotalMinutes >= TokenTTL))
                if ((DateTime.Now.Subtract(timeIssued).TotalMinutes < 0))
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
                else
                {
                    //Save user in context
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name, userId)
                    };
                    var id = new ClaimsIdentity(claims, "Basic");
                    var principal = new ClaimsPrincipal(new[] { id });

                    // Set the user name to the user id in the httpcontext which is passed to the controller
                    context.Principal = principal;
                }

            }
            catch (JWT.SignatureVerificationException)
            {
                context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
            }
        }
        else
        {
            return Task.FromResult(0);
        }
        return Task.FromResult(0);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="context"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        context.Result = new ResultWithChallenge(context.Result, realm);
        return Task.FromResult(0);
    }
}

/// <summary>
///
/// </summary>
public class ResultWithChallenge : IHttpActionResult
{
    private readonly IHttpActionResult next;
    private readonly string realm;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="next"></param>
    /// <param name="realm"></param>
    public ResultWithChallenge(IHttpActionResult next, string realm)
    {
        this.next = next;
        this.realm = realm;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var res = await next.ExecuteAsync(cancellationToken);
        if (res.StatusCode == HttpStatusCode.Unauthorized)
        {
            res.Headers.WwwAuthenticate.Add(
               new AuthenticationHeaderValue("Basic", this.realm));
        }
        return res;
    }
}

Now my issue is this class is being called even when the [AllowAnonymous] attribute is applied to my Controllers Action.
This is giving me trouble specifically with the login action as the user does not have a token yet.
How can I rectify this?

A: AllowAnonymous will work only with authorization filter. What you have here is an authentication filter. Use OverrideAuthentication from System.Web.Http instead.
UPDATE
Where in my original answer did I say you must implement authentication? All I have said is, if you do not want the AuthenticateAsync method of the TokenAuthentication to be called, apply OverrideAuthentication, instead of AllowAnonymous. AllowAnonymous will work only with authroization filters and not authentication filters. So, in your Login action, you will need to have OverrideAuthentication applied like this.
public class SomeController : ApiController
{
    [OverrideAuthentication]
    public HttpResponeMessage Login(Dto dto)
    { }
}


text:
Q: XSL:FO Page-Seqence on left page Hello guys I want to configure my page-master that every "page-sequence" starts on a left page.
         <fo:conditional-page-master-reference master-reference="PageMaster.Inhalt-rechtsLeerseite" odd-or-even="odd" blank-or-not-blank="blank" page-position="last"/>
            <fo:conditional-page-master-reference master-reference="PageMaster.Inhalt-links" odd-or-even="even"/>
            <fo:conditional-page-master-reference master-reference="PageMaster.Inhalt-rechts" odd-or-even="odd"/>

But I get no blank page on the end of the sequence . I also tried  nothing happpens.
I hope someone can help me. I use antenna house.

A: Use <fo:page-sequence initial-page-number="auto-odd">.  See
https://www.w3.org/TR/xsl11/#initial-page-number
The initial values for initial-page-number and force-page-count are both auto, for the combined effect that page numbers just increment across page sequences.  Assuming that your first page number is "1" and an odd-page, then force-page-count="even" on every fo:page-sequence will mean that the next fo:page-sequence also starts on an odd-numbered page.  (Note that AH Formatter offers extended values for force-page-count for more control over the page count of the page sequence and/or the entire document: https://www.antennahouse.com/product/ahf63/ahf-ext.html#axf.force-page-count).
Instead of or as well as using force-page-count on the preceding fo:page-sequence, you can use initial-page-number="auto-odd" on the current page sequence to force the page sequence to start on an odd page.
Once you've got that working, you might want to remove odd-or-even="odd" and page-position="last" from your first fo:conditional-page-master-reference since you likely now won't be producing any odd-numbered pages as the last pages of your page sequences.

A: You have to add force-page-count property to page-sequence if you want even number of pages to be generated even if there is not enough content. You have to define page master for blank page as well.
See https://www.w3.org/TR/xsl/#force-page-count


text:
Q: Not able to trigger JiraTestResultReporter plugin on Post Build Action in Jenkins I want to log defects automatic on jira whenever any test case gets fail.for that i have used JiraTesttResultReport plugin.i have successfully able to create my report.xml file.but i got below errors:
 Build step 'Publish JUnit test result report' changed build result to UNSTABLE
[JiraTestResultReporter] [INFO] Examining test results...
ERROR: Publisher JiraTestResultReporter.JiraReporter aborted due to exception
java.lang.NoSuchMethodError: hudson.model.AbstractBuild.getTestResultAction()Lhudson/tasks/test/AbstractTestResultAction;
    at JiraTestResultReporter.JiraReporter.perform(JiraReporter.java:105)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:761)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:721)
    at hudson.model.Build$BuildExecution.post2(Build.java:183)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:670)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:374)

A: On what version of Jenkins are you working?
JiraTestResultReporter does not work on Jenkins 1.577+
It's a known bug
A workaround is to build and install a snapshot of the plugin.


text:
Q: Mathematical Induction on sports I have just started with mathematical induction please help me to understand in easy way : There are $n$ players in a match. How do I prove that total number of knockout  matches will be $n-1$ to decide the winner.Or help me to understand following attachment.

A: I have no idea how mathmatical induction comes into play here.
To answer your question though, if you consider $n$ player it will take $n-1$ matches for a tournament in elimnation style (only the winner keeps playing) because one person looses the tournament per match played.
If just one person wins you need the other $n-1$ to loose one match and therefore it takes $n-1$ matches to be played in total.
Maybe you could do it the following way:
$A(n)$: For a elimination tournament with $n$ players you need $n-1$ matches ; $n \in \mathbb{N}$ and $n \geq 2$
Induction Base: we show $A(2)$ which is trivial because 2 players need to play 1 match and therefore $A(2)$ holds.
Induction step: we consider $A(n)$ holds for one $n \in \mathbb{N}$.
Now we look at the case $A(n+1)$ - The torunament follows the same rounds as in $A(n)$ - the new player will need to loose one match before he drops out, if he never does one of the other $n$ players will loose it - for both cases we need to have one more match. Therefore the ammount of matches is $(n-1)+1=n$
But this seems way too inconsistent for me - i am curious if there is a better way too show it through mathmatical induction although the idea above makes a alternate proof pretty short.


text:
Q: Emptying cache in wavesurfer Destroying the wavesurfer instance doesn't remove the cache used up. The documentation doesn't cover this. How can I remove the cache?

A: If anyone wants to know I found out the answer.
You first have to destroy it = this.wavesurfer.destroy();
And then you have to clear it to remove the cache = this.wavesurfer = null;
It has to be done in this order.
As with all removal of cache, garbage collection can vary in terms of time, but expect the cache to be cleared within about 30 seconds or so.


text:
Q: An upper limit on the number of rules nftables can realistically process I am designing a large SaaS VPN service and am planning to use nftables.
Is there a realistic limit to the number of rules it can process?
Rules will be compiled from a database. There will be thousands of nodes that will have arbitrary rules connecting them. Each node will have the option to share arbitrary ports with arbitrary other nodes. e.g. Node A can access RDP on node B. Nftables will control the security.
The process is working great in prototype. I'm really happy with how well it works. I am just concerned with scalability. I have the options of scaling up or out. But is there a point where it's going to get horribly inefficient? And at what point is that likely to be? Can it handle 10,000 rules without breaking a sweat? Or is it going to bog down?
It is currently using nftables v0.9.3 (Topsy) on Ubuntu 20.04 with Kernel 5.11.10 and Wireguard 1.0.20200513
I also realize the answer is resource and load dependant. I'm just concerned about the config architecture at the moment. Resources can always be added.
Are there any best practices for this?

A: I'm not an expert by any means, as we have less than a hundred rules on our servers but such a setup with, like you said, tens of thousands of rules sounds like a recipe for disaster or weird performance issues. It's totally possible that nftables on your HW will be able to cope with this number of rules, but if I were you, I'd rethink everything to make everything more manageable. Maybe use lightweight virtualization, e.g. docker or something similar.
I haven't been able to find a surefire answer to your question but for instance Red Hat has seen quite a significant performance hit with just 1000 rules:

*

*https://developers.redhat.com/blog/2017/04/11/benchmarking-nftables

*https://developers.redhat.com/blog/2020/04/27/optimizing-iptables-nft-large-ruleset-performance-in-user-space

*http://his.diva-portal.org/smash/get/diva2:1212650/FULLTEXT01.pdf
Red Hat recommends using sets which could help manage extreme cases like yours.


text:
Q: Debugging SSL connection using openssl terminal command I have a server app running on my computer listening on a certain port.  When I try to use OpenSSL (on Mac, i upgraded via brew already from the default Mac version for OpenSSL).
openssl s_client -connect 0.0.0.0:80051 -showcerts -prexit -servername localhost -debug

Response
CONNECTED(00000003)
write to 0x7fe62b41b370 [0x7fe62b80d000] (118 bytes => 118 (0x76))
0000 - 16 03 01 00 71 01 00 00-6d 03 01 58 d2 84 72 d5   ....q...m..X..r.
0010 - 1b d3 47 9c 8e 6b b3 fb-10 a5 21 af 0e 5d 79 7b   ..G..k....!..]y{
0020 - 54 77 4b 70 11 b0 77 5e-1e 9c e7 00 00 2e 00 39   TwKp..w^.......9
0030 - 00 38 00 35 00 16 00 13-00 0a 00 33 00 32 00 2f   .8.5.......3.2./
0040 - 00 9a 00 99 00 96 00 05-00 04 00 15 00 12 00 09   ................
0050 - 00 14 00 11 00 08 00 06-00 03 00 ff 01 00 00 16   ................
0060 - 00 00 00 0e 00 0c 00 00-09 6c 6f 63 61 6c 68 6f   .........localho
0070 - 73 74 00 23                                       st.#
0076 - <SPACES/NULS>
read from 0x7fe62b41b370 [0x7fe62b812600] (7 bytes => 0 (0x0))
85473:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59.60.1/src/ssl/s23_lib.c:185:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 118 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

On server
E0322 10:04:34.017891000 123145312870400 ssl_transport_security.c:947] Handshake failed with fatal error SSL_ERROR_SSL: error:1408A10B:SSL routines:ssl3_get_client_hello:wrong version number.
E0322 10:04:34.017964000 123145312870400 chttp2_server.c:123] Handshaking failed: {"created":"@1490191474.017913000","description":"Handshake failed","file":"../src/core/lib/security/transport/security_handshaker.c","file_line":274,"tsi_code":10,"tsi_error":"TSI_PROTOCOL_FAILURE"}

I have tried passing -ssl3 and -tls1 in the OpenSSL command with no success.  Any thoughts on how to process the info or use the openssl to debug further what might be causing ssl client connection issues to the server. Thanks

A:
i upgraded via brew already from the default Mac version for OpenSSL...
  0000 - 16 03 01 .... 03 01

The debug logs shows a ClientHello with TLS version 1.0 (0x0301). This suggests that an old version of OpenSSL was used and not the upgraded one, since this version 1.0.1 (released 2012) it supports TLS 1.2 and will use it by default.


text:
Q: Any good Haxe IDE for linux / ubuntu? I have find and tried different Haxe IDE in ubuntu and all have their own issues and dependencies even some have lost their support. Which is causing the IDE difficult to get ready for coding or development.
Currently using HIDE which is fair enough :s and get install in one command.
Is there any good working IDE for linux system ?
[update]

*

*Haxe studio has no autocomplete feature

*Sublime 2 bundle also do not support autocomplete or has one but don't show right properties

*Gedit2 plugin has bugs which says python not found

*Flashdevelope using wine opens a window which show list of flashdevelope extentions and do not go further then this screen.

A: I think you might want to look at this page:
https://haxe.org/documentation/introduction/editors-and-ides.html
The options for Linux are:

*

*Visual Studio Code (With Haxe extension)

*IntelliJ IDEA (With Haxe plugin)

*Sublime Text (With Haxe Bundle)

*VIM (With Vaxe Plugin)

*HaxeDevelop using Wine


text:
Q: GhostScript Font issue when i am converting pdf to image in C# I am using GhostScript (64 bit) gswin64.exe Please suggest how to resolve this.if my pdf font is vani format and after converted in image it has Arial format. But i need it actual font format that was in pdf.
Here my code -
public static void PdfToJpg(string inputPDFFile, string outputImagesPath)
            {
               string ghostScriptPath = @"C:\Program Files\gs\gs9.19\bin\gswin64.exe";
                String ars = "-dNOPAUSE -sDEVICE=pngalpha -r300 -dBATCH -dSAFER -sOutputFile=" + outputImagesPath +Guid.NewGuid() +".png -sPAPERSIZE=a4 " + inputPDFFile;

                Process proc = new Process();

                proc.StartInfo.FileName = ghostScriptPath;
                proc.StartInfo.Arguments = ars;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        enter code here
                proc.Start();
                proc.WaitForExit();
            }

    calling-from

public ActionResult Index()
                {
                    PdfToJpg("C:/Users/admin/Desktop/testdoc.pdf", "E:/output/");
                    return View();
                }

If any one have resolved this issue so please let me know.


text:
Q: How to make .bat that runs two commands from command prompt in admin mode with notepad++ I upgraded to Win10 recently and I keep getting the invalid IP config issue where you have to open cmd or PowerShell in admin mode and type in the following:
netsh i i r

netsh winsock r

doing so can take me a minute and I just want to be able to run a .bat or something to do it instantly.
How would i go about creating a .bat file that could run these to commands with admin privileges ?


text:
Q: Developing Concave Mirror Image Formation Simulation Using three.js How to draw concave mirror and incident ray and reflected ray.
I did following but leads to very annoying result.
I used ellipseCurve to draw mirror.
var curve = new THREE.EllipseCurve(
0,  0,            // ax, aY
10, 10,           // xRadius, yRadius
0,  2 * Math.PI,  // aStartAngle, aEndAngle
false,            // aClockwise
0                 // aRotation
);
var path = new THREE.Path( curve.getPoints( 50 ) );
var geometry = path.createPointsGeometry( 50 );
var material = new THREE.LineBasicMaterial( { color : 0xff0000 } );
// Create the final object to add to the scene
var ellipse = new THREE.Line( geometry, material );
scene.add(ellipse);

Used Following to draw object and incident ray and reflected ray by changing source point and destination point
var sourcePos= new THREE.Vector3(ObjectPositionX,ObjectPositionY,0);
var targetPos = new THREE.Vector3(FocusPointX,FocusPointY,0);
var direction = new THREE.Vector3().sub(targetPos, sourcePos);
var rayParallel = new THREE.ArrowHelper(direction.clone().normalize(), sourcePos, direction.length(), 0x00ff00);
scene.add(rayParallel);

Screen shot of my Result is
Image Formed by concave mirror
Suggesting any other method to solve this is also appreciated.


text:
Q: Stop embeded video from autoplaying Hi I've literally tried everything and cant get anything to work. I'm trying to get a video to not autoplay.
I have added what code i have to this fiddle.
Can anyone help please!
Thanks Alex

A: How are you loading the video? Do you use FLVPlayback?
There is a checkbox in the FLVPlayback component parameters called autoplay.
I can't really see how your Flash File is constructed on the fiddle site.
If you didn't create the Flash you shoudl try to obtain the FLV video.
If that is not an option you could load the swf into a new swf, then try to find the FLVPlayback, or whatever is playing and stop it. But you will need a crossdomain on their server or a local copy of the swf.
Sample code of loading an swf, finding the autoplaying FLVPLayback and stopping it:
import flash.display.Loader;
import flash.events.Event;
import fl.video.*;

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_Complete);
loader.load(new URLRequest("PATH-TO-VIDEO.swf"));

function loader_Complete(e:Event)
{
    addChild(loader.content);

    //here i get the videoplayer and stop it
    var targetPlayer:FLVPlayback = MovieClip(loader.content).getChildAt(0) as FLVPlayback;
    targetPlayer.stop();
}


text:
Q: Imaginary Numbers Can someone help me by explaining what imaginary numbers actually are, please?
I know that it is defined as $i = \sqrt{-1}$  and I can find umpteen sources telling me how to calculate with them but I cannot get my head around what they actually represent.  I've seen a number of argand graphs but I just cannot relate what the lines are describing.
Can anyone help?
Thanks

A: I think you're going in the wrong direction.  In mathematics we don't understand things by what they are, but by what they do.  Philosophers can argue for days about what is the number 1, but ultimately what gives the number 1 its mathematical identity is what it does and how it relates to the other numbers:  It has the property that $1\cdot x = x$ for any other number $x$, for example, and it is the only number with this property.  You would be amazed at the variety of bizarre objects that mathematicians identify as being the number 1. Most of them look nothing like the 1 you know and love.  But they all have the required properties: each one belongs to some system of numbers in which $1\cdot x = x$ holds, among other things. As people sometimes say, if it walks like a duck and quacks like a duck, it must be a duck.
What do imaginary numbers do?  They were first introduced to solve certain kinds of equations.  Italian mathematicians of the 16th century had a method for solving certain equations of the form $$x^3 =  ax + b$$ but they found that under certain circumstances, these methods produced seemingly nonsensical results involving the square root of $-1$; seemingly nonsensical because $-1$, being negative, was thought to have no square root.
For example, the same method that correctly solved many equations, when used to solve $x^3 = 15x + 4$,  would produce the peculiar result $$\sqrt[3]{2+\sqrt{-121}}+ \sqrt[3]{2-\sqrt{-121}}.$$
This is a problem, because the equation $x^3=15x+4$ has an obvious solution, namely $x=4$.  Why doesn't the method work? Why didn't it emit the number 4?
A mathematician named Bombelli observed that if you pretend that the solution makes sense, then it does work. Because if you calculate $(2+\sqrt{-1})^3,$ following all the usual rules, you find $$(2+\sqrt{-1})^3 = 2+\sqrt{-121},$$ and similarly $$(2-\sqrt{-1})^3 = 2-\sqrt{-121}$$ so the nonsense result above simplifies to $$(2+\sqrt{-1}) + (2 - \sqrt{-1})$$  and the nonsensical $\sqrt{-1}$ parts cancel out, leaving you with the correct answer, $4$.
It seemed like nonsense, but it solved the problem and got the right answer, so there must be something to it.  Eventually people got over their prejudice against the seemingly nonsensical numbers (the name "imaginary" still speaks to that ancient prejudice) and we now accept that these numbers work just as well as real numbers.
We have mathematical models of imaginary numbers; these are mathematical objects that, when operated on in certain ways, behave the way we want the imaginary numbers to behave. For example we can model a complex number $a+bi$ as a pair $\langle a,b\rangle$, as a certain matrix, or as a certain family of polynomials.  But the reason we accept these as models of imaginary numbers is because they do the things we want imaginary numbers to do.
What do we want imaginary numbers to do?

*

*We want them to contain a subset that behaves just like the real numbers.

*We want to be able to add and multiply them, and the addition and multiplication, when restricted to the subset that behaves like the real numbers, should give the answers we expect for real numbers. Whatever we identify as $2$ and $4$ in our system, we should still have $2+2=4$.

*Most of the usual rules of addition and multiplication should still apply.  For example, $1\cdot x = x$ should hold when $x$ is imaginary just as it does when $x$ is real.

*There should be some number, which we call $i$, which should have the property that $i^2 = -1$.  (Actually one can show that there are always two such numbers; you can't have one without the other.)

That's what they do; if you can make them do what you want, then it shouldn't matter what they are. This is why the umpteen sources tell you how to calculate with them but not what they are: once you know how to calculate with them, that is the whole story. There is nothing more!


text:
Q: Question about the proof in "Understanding Analysis" by Stephen Abbot My question is rather simple and involves a step that is taken when proving that there is a number squared that equals two. He uses the least upper bound theorem. The first few steps make sense, but how he gets between these two highlighted steps confuses me. I do not know how he derives that second inequality that I have highlighted.

Thank you in advance for your help.

A: He's trying to prove that if $\alpha^2\lt 2$ then he can find a number that is larger than $\alpha$ but still less than $2$.
He is trying to find a positive number $n$ such that $\alpha$ so that the $\left(\alpha+\frac{1}{n}\right)^2\lt 2$
He then expands that to get $$\left(\alpha+\frac{1}{n}\right)^2=\alpha^2+\frac{2\alpha}{n}+\frac{1}{n^2}$$ and notices that if $\frac{1}{n}\lt 1$ then $\frac{1}{n^2}\lt \frac{1}{n}$ which gives us that $$\left(\alpha+\frac{1}{n}\right)^2=\alpha^2+\frac{2\alpha}{n}+\frac{1}{n^2}\lt\alpha^2+\frac{2\alpha}{n}+\frac{1}{n}=\alpha^2+\frac{2\alpha + 1}{n}$$
We want $$\alpha^2+\frac{2\alpha+1}{n}\lt 2$$ so we solve for $n$ to get $$\frac{2\alpha+1}{n}\lt 2-\alpha^2\implies\frac{2\alpha+1}{2-\alpha^2}\lt n\implies\frac{1}{n}\lt\frac{2-\alpha^2}{2\alpha+1}$$
He uses $n_0$ instead of $n$ when he solves for the specific value of $n$ to emphasize that $n$ is a variable and $n_0$ is the specific value that keeps $$\left(\alpha+\frac{1}{n_0}\right)^2\lt 2$$

A:
I do not know how he derives that second inequality that I have highlighted.

You question contains a false premise. He does not derive the second inequality. The second inequality is not a statement about an already-known $n_0$, and it is not arrived at from the previous inequality (at least not directly, see below), it is a constraint describing what $n_0$. He says to pick $n_0$, and then gives the inequality as a description of what sort of $n_0$ to choose. If I say "Find a turkey that's smaller than my oven", then turkey<oven isn't an inequality that I've "derived", it's a description telling you what kind of turkey I want. Now, he obviously has a motivation for why he wants to choose an $n_0$ that satisfies that inequality, and that motivation comes from the previous inequality, but that's a bit different from the second inequality being "derived" from the first.


text:
Q: CR730-A-24 identification Can anyone find a data sheet for what I think is a relay? It has the code cr730-a-24, 7.5A 250V on the case and I've found this picture:

Are the three circles, 3 coils in parallel? How does this circuit relate to the pin-out? In what sequence do the normally open, relay contacts close?

A: It appears to be a relay used in PIR lamps.

source - P29
The diagram appears to be an application where a set of three lights can be switched on by any of three switches or relays. I would guess that PR1 and PR2 are two PIR detector units at separate locations and that wylacznik is a manual switch.  I don't think you can deduce anything about the CR730-A-24 relay from that diagram.


text:
Q: Loop with two counters Following is some C code. How do I do the same in sas?
 For(i=30, j=1; i<=41, j<=12; i++, j++)
    (
    closure(i,j) /*calling function with input parameters I and j */
    );

I basically want to do the following macro calls using a loop with two counters I and J
%closure(30,201201);
%closure(31,201202);
%closure(32,201203);
%closure(33,201204);
%closure(34,201205);
%closure(35,201206);
%closure(36,201207);
%closure(37,201208);
%closure(38,201209);
%closure(39,201210);
%closure(40,201211);
%closure(41,201212);

Please note that I do not want to use a nested loop.
Tips are appreciated.

A: Doing this in SAS depends on how your data is structured.  It's possible to do this:
%do i = 1 to 12;
  %closure(%eval(29+i),%eval(201200+i));
%end;

That's a bit odd, but it should work fine.
You could also do it in the %closure macro.  Pass i and then determine the value of the other parameters inside the macro, if they always have this relationship.  If they always have some relationship, but the 2012 and 18 parts are variable, then you have several options:
Define 2012 and 29 as macro variables ahead of this step, and replace them in the code with such.
%let year=2012;
%let startrec=29;
%do i = 1 to 12;
  %closure(%eval(&startrec.+&i.),%eval(&year.00+&i.));
%end;

Use date functions to determine the value of j, if it is not always 01-12.
%closure(30,%sysfunc(intnx(month,'01JUN2011'd,&i.-1)))

(you may want to format the result in YYYYMM format, or you may be just as well off using the date result, depending on %closure)
Define all of these terms in a dataset, and call the macro from the dataset.
data to_call;
input i j;
datalines;
30 201201
31 201202
.... ;
run;

proc sql;
 select cats('%closure(',i,',',j,')') into :calllist separated by ' ' from to_call;
quit;

&calllist.

That's a more 'SAS'sy way to do things, making the process data driven.  Most commonly used when the i and j parameters are stored as data element somewhere (in a control table, for example, or derived from some other data source).

A: So If you want

*

*%closure(30,201201);

*%closure(31,201202);

*%closure(32,201203);

*%closure(33,201204);

*%closure(34,201205);

*%closure(35,201206);

*%closure(36,201207);

*%closure(37,201208);

*%closure(38,201209);

*%closure(39,201210);

*%closure(40,201211);

*%closure(41,201212);

then it would be better either you calculate the value of J and bring it to 201200 aur something near about.
Or you should start the j loop with 201201 and end it to 201212
simply go for
For(i=30, j=201201; i<=41, j<=201212; i++, j++)
(
  closure(i,j)

);


text:
Q: What is the "DNS timeout value" relevant to a Salesforce Site Switching? We are about to undergo Salesforce Site Switching and the notification cautions that we should set our "DNS timeout value to 5 minutes (default setting)"  [See point #4 here: https://help.salesforce.com/articleView?id=Site-Switching-Overview&language=en_US&type=1 ]
I would like to confirm this setting, but I'm not certain what they mean.  Is this a setting internal to Salesforce or are they referring to TTL on some external DNS provider (but then what would they mean by default setting of 5 minutes)?
I'd be most grateful to anyone who could clarify the meaning and point us to the right place.  Thanks!

A: They are indeed referring to DNS server resource records with a Time To Live (TTL) value of 300 seconds.
Salesforce sets the TTL for 300 seconds (5 minutes) on the resource records that they are the authority on and the recommendation is that an upstream caching server (for instance, one within your enterprise infrastructure) should also use this value and not cache these records for more than 300 seconds. 86400 seconds (24 hours) was common in the past.
In short, don't keep these records longer than 300 seconds and your users are not likely to notice the site switch.


text:
Q: BigQuery FARM_FINGERPRINT Collision case The farm_fingerprint value in BigQuery is same for two different strings. Any Ideas why? It returns -2660876244907183769
SELECT id1, id2, id1=id2 AS is_equal
FROM (SELECT FARM_FINGERPRINT(TO_JSON_STRING(STRUCT('19BD0AF0854E2B90E10080000A802438','599D7E2A47B31E20E10080000A7824B8','001','020','100'))) AS id1,
FARM_FINGERPRINT(TO_JSON_STRING(STRUCT('DCE500729B5800F0E10080010A7824BA','5AF0A97293195320E10080010A782421','001','001','110'))) AS id2)

A: In general it is rather trivial to find collisions in any 64 bit hash. So, none of 64 bit hashes can guarantee you uniqueness when large amount of values is indexed. FARM_FINGERPRINT uses Fingerprint64 function in farmhash library which is a 64bit hash algorithm, so you might as well use a different hashing function like MD5, SHA256, SHA512, etc. as it's more standardized. See more hashing functions.
Also a public issue tracker was opened regarding this similar issue but it was eventually closed since collisions using any hash algorithm is bound to happen. But it might still be a very long time. See https://crypto.stackexchange.com/questions/47809/why-havent-any-sha-256-collisions-been-found-yet


text:
Q: How do i put two pie charts side by side on matplotlib I have the following code below
plt.figure(figsize=(5,5))
plt.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%')
plt.title('Gender Composition in 1960')
labels = male_and_female_2016['level_1']
values = male_and_female_2016['value']
#settings and configs for the pie charts
colors = ['#FF8F33','#33FFDC']
explode = (0.1, 0)
plt.figure(figsize=(5,5))
plt.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%')
plt.title('Gender Composition in 2016')
plt.show()

it show me like this

How do i get it to be displayed side by side?
thank you very much

A: Instead of using plt.figure twice, plt.pie and plt.title, use:
fig, axs = plt.subplots(1, 2, figsize=(6, 3))
# ...
axs[0].pie(values,labels = labels, colors = colors, autopct = '%1.1f%%')
axs[0].set_title('Gender Composition in 1960')
# ...
axs[1].pie(values,labels = labels, colors = colors, autopct = '%1.1f%%')
axs[1].set_title('Gender Composition in 2016')
# ...

See this example for inspiration:
https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/categorical_variables.html#sphx-glr-gallery-lines-bars-and-markers-categorical-variables-py