text:
Q: Changing Str to Float Loses Digits I have a program where I get numbers like: 0.18869952857494354248046875
I need to change these from string to float, but when I do that, I get: 0.18869952857494354
Why does python cut off ~10 digits and how can I retain them in the transfer?

A: The limitations of floating point math mean that you can't have arbitrarily long floating point numbers: https://docs.python.org/3/tutorial/floatingpoint.html
You can get around this by using the decimal library (https://docs.python.org/3/library/decimal.html#module-decimal):
>>> from decimal import Decimal
>>> a = Decimal("0.18869952857494354248046875")
>>> a
Decimal('0.18869952857494354248046875')
>>> b = Decimal("0.111111111111111111111111")
>>> a + b
Decimal('0.29981063968605465359157975')
>>> a * b
Decimal('0.02096661428610483805338539570')

By default the decimal library has 28 places of precision but you can change this using getcontext().prec:
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')
>>> getcontext().prec = 60
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')

A: This happens because float datatype in python can show upto 16 digits precision.
For higher precision (to retain all digits) , use special packages like : mpmath
You can use it like:
from mpmath import *
mp.dps = 64       #64 decimal places
sqrt(5)/2 #64 digit, high precision


text:
Q: Android Emulator not connecting to internet (hyper-v device manager, win10, Xamarin development) My android emulator is not connecting to the internet. I discovered this when debugging my mobile application and seeing it crash when trying to connect to my web service.
I then opened the devices by themselves and tried to open a web page in the browser and the device is not connected.
This happens for my android device and my windows device.
windows device
Emulator 8.1 WVGA 4 inch 512MB.jwierzba
android device
VS Emulator 5-inch KitKat (4.4) XXHDPI Phone.jwierzba
I have not modified the network adapter settings. How can I find out why the device is not using my local pcs internet connection? (LAN and wireless)
running Windows 10 Pro x64

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create jsdoc types from json schemas I have tons of json schema for node.js project. Can I use them in any way for:

*

*Accessing them as jsdoc types from ".js" code files to increase webstorm intellisense accuracy

*Or for creating jsdoc type definitions automatically

?

A: I had the same question before and some time in 2017 created a json-schema-to-jsdoc utility in GitHub.
You can find it now in npm: https://www.npmjs.com/package/json-schema-to-jsdoc

A: The closest I have seen to what you suggest is VSCode's support for JSON Schema with regard to editing JSON files.
I would expect given they have started to support JSON Schema, that it would certainly be worth logging an issue with them regarding extending the capabilities of such support. If you did and let me know I would certainly support it!


text:
Q: Determine if user bought the app Is it possible to determine if the user bought the app or not?
I have an app which is not free. I plan to make app with no-fee with ads. But I don't want to show ads who already purchased the app. Is it possible to disable ads for the people purchased previously?
Thanks in advance...

A: Not through any official API.
The easiest solution would be to push out an update (still paid) which sets a flag in NSUserDefaults, wait a sufficient time for your users to update, and then use that to distinguish between original users (who paid) and new ones (who got it free).
However, there are a bunch of problems with that.  Just to name two:

*

*users don't update consistently, so you'll miss a bunch of people

*people who delete and reinstall the app will lose the flag

The way you would normally maintain a version of an app with ads and one without is either to use a 'Lite' version (discouraged) or remove the ads with In-App Purchases.
If you want to do the latter, though, you run into the same problem.  Have a look here for some more info on that approach.


text:
Q: Where does the xmm instruction "divsd" store the remainder In the statement:
divsd xmm0,xmm1

where is the remainder stored?  Do the xmm registers have a register for the remainder, like the integer registers?  Should I use FPREM in the x87 instructions instead?
As far as I've found, the Intel manuals are silent on this issue, and a lot of research has not produced a useful answer.

A: DIVSD handles scalar floating points and as such does not return a remainder. Instead it calculates as many decimals as possible for that type of floats.
From the Intel documentation:
# DIVSD (128-bit Legacy SSE version)
DEST[63:0] ← DEST[63:0] / SRC[63:0]
DEST[MAX_VL-1:64] (Unmodified)

Note that this is the same as the FDIV instruction.
You can of course use the usual-for-integer way of calculating the remainder by converting your result to integers, multiplying back, and then subtracting from the original number.
This can easily introduce huge rounding errors with floating point as this automatically produces catastrophic cancellation of most of the significant digits, if the divisor is much smaller than the dividend.  Avoiding this is why fprem is slower than fdiv + frndint + fmul + fsub.
Something like this (UNTESTED! Intel syntax)
; inputs: xmm1 divisor, xmm2 dividend
MOVAPS  xmm3, xmm2         ; xmm3 ← xmm2
DIVPS   xmm2, xmm1         ; xmm2 ← xmm2 ÷ xmm1
CVTPS2DQ xmm3, xmm2        ; xmm3 ← integers of xmm2
MULPS   xmm3, xmm1         ; xmm3 ← xmm3 × xmm1
MOVAPS  xmm4, xmm2         ; xmm4 ← xmm2
SUBPS   xmm4, xmm3         ; xmm4 ← xmm4 - xmm3
; xmm2 = xmm2 ÷ xmm1
; xmm4 = remainder (mathematically: frac(xmm2) × xmm1)

(Editor's note: does 4 packed single-precision floats in parallel.  Use PD (packed double) or SD (scalar double) if you want that.  Also note that SSE4.1 roundps/pd provides a safe way to round to the nearest integer for float values that might not fit in a 32-bit integer.)

A problem you may run into in using FPREM is the fact that you can't mix code using the Floating Point Unit and the MMX registers. They both end up using the same registers, but differently.
There is some documentation about that problem. If you don't use MMX registers, you'll be fine, though.

Source: Vol. 1 11-31 — PROGRAMMING WITH STREAMING SIMD EXTENSIONS 2 (SSE2)
11.6.7 Interaction of SSE/SSE2 Instructions with x87 FPU and MMX Instructions
The XMM registers and the x87 FPU and MMX registers represent separate execution environments, which has certain ramifications when executing SSE, SSE2, MMX, and x87 FPU instructions in the same code module or when mixing code modules that contain these instructions:
• Those SSE and SSE2 instructions that operate only on XMM registers (such as the packed and scalar floating-point instructions and the 128-bit SIMD integer instructions) in the same instruction stream with64-bitSIMD integer or x87 FPU instructions without any restrictions. For example, an application can perform the
majority of its floating-point computations in the XMM registers, using the packed and scalar floating-point instructions, and at the same time use the x87 FPU to perform trigonometric and other transcendental computations. Likewise, an application can perform packed 64-bit and 128-bit SIMD integer operations together without restrictions.
• Those SSE and SSE2 instructions that operate on MMX registers (such as the CVTPS2PI, CVTTPS2PI, CVTPI2PS, CVTPD2PI, CVTTPD2PI, CVTPI2PD, MOVDQ2Q, MOVQ2DQ, PADDQ, and PSUBQ instructions) can also be executed in the same instruction stream as 64-bit SIMD integer or x87 FPU instructions, however, here they are subject to the restrictions on the simultaneous use of MMX technology and x87 FPU instructions, which include:
— Transition from x87 FPU to MMX technology instructions or to SSE or SSE2 instructions that operate on MMX registers should be preceded by saving the state of the x87 FPU.
— Transition from MMX technology instructions or from SSE or SSE2 instructions that operate on MMX registers to x87 FPU instructions should be preceded by execution of the EMMS instruction.

Since you have quite many XMM/YMM/ZMM registers, it is often worth the trouble of doing such things in SSE/AVX. The FPU, on the other hand, uses a stack which is much harder to handle in assembly.


text:
Q: React Native - Tipsi-stripe Error - 'Cannot read property 'init' of undefined' I am trying to integrate Stripe into my React-Native project by following the Tipsi-stripe installation and linking guide:
https://tipsi.github.io/tipsi-stripe/docs/installation.html

*

*I started by npm i --save tipsi-stripe,

*Added Podfile and run cmd: pod install,

*Drag and dropped 'TPSStripe' folder from node_modules into my Xcode project file (this was a very vague step in the guide).

*Automatically linked the packages by running this cmd: react-native link tipsi-stripe
But now I get this error screen in my simulator:
Cannot read property 'init' of undefined

Error screenshot
I came across similar problems on other forums and I suspect it's a linking issue. I followed the exact instructions on the guide but cannot understand why I am still getting this error.
Here is a screenshot of my .xcodeproj file inside Xcode. The TPSStripe folder I inserted is also inserted as shown in the image. Is this in the right place??:
xcodeproj file
There appears to be a lot of files in the explorer highlighted Red which I don't understand why.
And here is a close-up of some errors showing in Xcode:
Error details
Does anyone have similar problems?

A: if you add the library to the pods you don't have to link them


text:
Q: How to transfer Values(items) from one Netsuit business system form to another Netsuit form automatically? Currently, I have to fill out 2 of the same forms with the same language & part numbers on the Web Based business system "Netsuit" made by Oracle (extremely annoying & waste of time). I need to use a software/code system to read one form entry and duplicate it to the other automatically, just still feeling out the best way to do this and get it to transfer/skim properly.
This is between 2 sister companies, each value(Part) has a different part number linked to them, but internally they cannot be linked due to reporting purposes and which company sales what.
One company starts with 100XXX-XX numbers and the other starts with 300XXX-XX numbers for the parts. Again, they are basically the same Parts.
Not sure if Tampermonkey or java will be able to do this properly as I don't even know where to start.
Any recommendations or walkthough on the best way to do this would be awesome, I know it might be a little hard since its 2 different item systems.
Maybe just pull the description of the items since they will be almost the same?

A: You can create a user event script on the first company and RESTlet on the second one.
The user event script on the first company will create a JSON object of the item that is being created and pre-process the changes in the part number(or any other changes that is required) for the second company and send it to the second company's RESTlet. The RESTlet will now then create the item for the second company.
By using this approach you don't need any 3rd party application to deal with.


text:
Q: AFNetworking POST request with array of JSON objects So I'm trying to do a post request with an array of JSON parameters sent to a server, here's the code for that
    for(USER_ACTIONS *ua in [USER_ACTIONS listRegisterdActions]){
        //Create a single JSON object here
         [array addObject:jsonString];
     }
     NSString *dataString = [NSString stringWithFormat:@"[%@]",array.count ?

     NSData* data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
     NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
     parameters[@"data"] = data;

     [self POST:@"?cmd=log" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

     } failure:^(NSURLSessionDataTask *task, NSError *error) {

     }];

This works with a single JSON object, but once there are more of them I get the following exception

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'

It's out of the question to do this with a multiple post requests so I need a way to do this with one, my search results on this have not gotten any clear results on how to do this with AFNetworking 2.x so I'd appreciate some pointers on where to go with this.

A: AFNetworking can automatically change paramter in NSDictionary to JSON.
change your manager's property requestSerializer to AFJSONRequestSerializer the default value is AFHTTPRequestSerializer
AFJSONRequestSerializer is a subclass of AFHTTPRequestSerializer that encodes parameters as JSON using NSJSONSerialization, setting the Content-Type of the encoded request to application/json.

A: For some reason just using the AFHTTPSessionManager Post function with the constructingBodyWithBlock parameter actually works for some reason. No idea why this is needed because there isn't actually anything in that block, if anyone could tell me why it would be nice.
    [self POST:@"?cmd=log"  parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //For some reason the request won't work unless this block is included in the function as well, even though nothing is actually done in it
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        //Success code here
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];


text:
Q: Attach tooltips on elements inside bootstrap buttons I am trying to apply Twitter Bootstrap tooltips on elements inside a Twitter Bootstrap button. For some reason, those tooltips never triggers (never show).
Markup:
<button title="Reset Pricing" type="button"
    class="btn btn-mini myButton"
    data-placement='bottom'>

</button>

js:
$(function() {
    $('.icon-refresh').tooltip();
});

Example jsfiddle: Trying with glyphicon
This applies to all browsers I've tested (Firefox, IE, Chrome on Windows 7). Preferably, I want it to work on all three.
Update #1: According to comments, it's showing outside jsfiddle display frame. However, still not getting it to work with Firefox, but Chrome and IE works.
Update #2: According to person behind accepted answer, there is a bug in bootstrap tooltip (2.3.2) that causes the problem. However, using an anchor tag instead of a button one, problem is solved.

A: The tooltip is working but you don't see it because is trying to show above the button. try adding data-placement="right"
jsFiddle

A: http://jsfiddle.net/JaPYg/6/

just changed so its shows at bottom instead of default top.
Are you sure you hover the icon and not just the button? And are you sure nothing is blocking the tooltip (ie. some div or whatever)?


text:
Q: Graphics and sound issues in Ubuntu 16.04 I recently installed Ubuntu 16.04 for development work and general usage. I plan to keep continue using windows for some other stuff. I have a HD 6950 (replacing it with something less antique and overpowered is on the list)  and I didn't know about the deprecation of fglrx, I have a few issues and I would like to know if I have any chance of solving them.

*

*I am unable to play any kind of video smoothly, audio and video cut out for 0.1 to 0.5 seconds, sometimes it has sync issues after that. This is system wide, even the speaker test had this issue once

*My video card fan is way louder than in Windows

*My PC uses about 30W more power in idle, I assume this is because my grapics card doesn't properly do power management, is there any way to solve or check this? The only think I have found is rovclock, but it outputs garbage and exits with a floating point exception.

Where do I start?


text:
Q: How to write single quote (') and double quote (") to a file from terminal? While writing to a file from terminal using 'echo', I could write everything except both quotes together. When trying to write/append lines of python code, to a file, that contains both single and double quotation marks like
echo "url = "http://mydummyurl.xyz"
names = ['name1', 'name2']" > somefile.txt

or
echo 'url = "http://mydummyurl.xyz"
names = ['name1', 'name2']' > somefile.txt

What is written in somefile.txt is either
url = http://mydummyurl.xyz
names = ['name1', 'name2']

or
url = "http://mydummyurl.xyz"
names = [name1, name2]

depending on what I am using to enclose the string after echo. Observe that in strings written in files are missing either single quote or double code used as python syntax. How can I write to file keeping all the necessary syntax intact including both single and double quotations?

A: you need escape the quotes:
kent$  echo  "single:''';double:\"\"\"" > foo

kent$  cat foo
single:''';double:"""


text:
Q: How to use a numerical reference in neglected set? I am trying to create a Regex expression with a numerical reference (to a capture group) in a neglected set.
Something like this:
 (["'])([^\1]*)(\1)

Basically it matches all strings with either a single or double quote surrounding it. For example:
"foo bar" "foobar" → "foo bar" and "foo bar"

The reason I can't just use the (["'])([^"']*)(\1) is the following scenario:
"foo bar's" "foobar"
Instead of matching "foo bar's" and "foobar" it matches " ".

How can I use numerical reference in a neglected set? If I can't how can I overcome this issue?


text:
Q: Insert empty line after line 7 This is my first C class. I need to write a program that copies one file content into another and add an empty line after line 7 in output file. I wrote a code that add empty line after each line, but I need only one line. Please, can anyone help. Here is what I got so far:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
   FILE *fp1,*fp2;
   char ch;

    fp1 =  fopen("input.txt","r");

    if(fp1==NULL)
    {
        printf("\nThe file was not found.");
        exit(1);
    }

    fp2 =  fopen("outfile.txt","w");

    if(fp2==NULL)
    {
        printf("The file was not opened.");
        exit(1);
    }

    while(1)
    {
       ch = fgetc(fp1);

       if (ch=='\n')
       putc(ch, fp2);

       if(ch==EOF)
          break;
       else
          putc(ch, fp2);
    }

    printf("File copied succesfully!");
    fclose(fp1);
    fclose(fp2);
}

A: You're correct that you are currently adding an extra newline character every time you find one. Instead, you need a way to identify only the 7th line. It sounds to me like you can count the newlines, then only do the extra newline placement after the seventh one. Maybe add another integer to the top of your main function:
int newline_count = 0;

Increment it in your loop, and only add the newline character when you need it:
if (ch == '\n'){

    ++newline_count; /* increments newline_count by 1 */

    if (newline_count == 7){

        putc(ch, fp2);

    }
}

A couple of notes:
1) You'll notice that I have brackets on my second IF statement that are technically unnecessary. It's purely a style choice on my part, and you can leave them off if you want, but if you should still indent the statement that the IF statement controls, like this:
    if (newline_count == 7)
        putc(ch, fp2);

In your code, your third IF statement has the same indentation as the statement it controls. It will be much more readable if you indent the second statement.
2) Your main function should never be void. You should at least have this:
int main(){

    /* ... stuff ... */

    return (0);
}

See the first answer to this question for more information about how main() should look and more importantly, why.
3) I think your whole loop could look a little cleaner if you reordered your if statements:
while(1)
{
   ch = fgetc(fp1);

   if (ch == EOF)
      break;

   if (ch == '\n'){
        ++newline_count; /* incremement count of newlines by 1 */

        if (newline_count == 7){
            putc('\n', fp2); /* insert a newline character */
        }
    }

     putc(ch, fp2);
}

By reordering things, you've gotten rid of an extra "else" statement. You didn't really need it in the first place since you would break out of the loop once EOF was reached. Also, by changing the putc(ch, fp2) to putc('\n', fp2) you've more clearly identified your intention to someone reading your code. Your goal isn't just to copy the same character again, it's to put a new line in there.


text:
Q: POSTMAN Assertion with IF ELSE statement not working I need to test the response code and if it is true do next api call.I am using below code to achieve the desired functionality. Let me know what am i doing wrong.
pm.test("response is valid", function(){
if(pm.response.code === 201){
    postman.setNextRequest("Auto-Deploy Manager Node 2");
}
else {
    setTimeout(function(){}, 10000);
}
});


text:
Q: Codeigniter 4th level route not working routes.php

    $route['admin/news'] = 'admin_news/index'; //working
    $route['admin/news/(:any)'] = 'admin_news/view/$1'; //working
    $route['admin/news/create'] = 'admin_news/create'; //working
    $route['admin/news/edit/(:any)'] = 'admin_news/edit/$1'; //not-working
    $route['admin/news/delete/(:any)'] = 'admin_news/delete/$1'; //not-working

controllers: admin_news.php

    if (!defined('BASEPATH'))
        exit('No direct script access allowed');

    class Admin_news extends CI_Controller {

    public function __construct()
            {
                    parent::__construct();
                    $this->load->model('news_model');
                    $this->load->helper('url');

                    if(!$this->session->userdata('is_logged_in')){
                redirect('admin/login');
            }
            }

    public function index()
    {
            $data['news'] = $this->news_model->get_news();
            $data['title'] = 'News archive';

            $this->load->view('admin/includes/header', $data);
            $this->load->view('admin/news/index', $data);
            $this->load->view('admin/includes/footer');
    }

    public function view($slug = NULL)
    {
            $data['news_item'] = $this->news_model->get_news($slug);

            if (empty($data['news_item']))
            {
                    show_404();
            }

            $data['title'] = $data['news_item']['title'];

            //$this->load->view('templates/header', $data);
            $this->load->view('admin/news/view', $data);
            //$this->load->view('templates/footer');
    }

    public function create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Create a news item';

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('admin/includes/header', $data);
            $this->load->view('admin/news/create', $data);
            $this->load->view('admin/includes/footer');

        }
        else
        {
            $this->news_model->set_news();
            $this->load->helper('url');
            $this->index();
        }
    }

    public function edit($slug)
    {
        $data['news_item'] = $this->news_model->get_news($slug);

        if (empty($data['news_item']))
        {
            show_404();
        }

        $data['title'] = 'Edit: '.$data['news_item']['title'];

        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('title', 'title', 'required');
        $this->form_validation->set_rules('text', 'text', 'required');

        if($this->form_validation->run() === FALSE)
        {
            $this->load->view('admin/includes/header', $data);
            $this->load->view('admin/news/edit', $data);
            $this->load->view('admin/includes/footer');
        }
        else
        {
            $this->news_model->update_news( $this->input->post('id'),
                                            $this->input->post('title'),
                                            $this->input->post('text'));

            $data['news_item'] = $this->news_model->get_news($slug);
            $this->load->view('admin/includes/header', $data);
            $this->load->view('admin/news/success');
            $this->load->view('admin/news/edit', $data);
            $this->load->view('admin/includes/footer');
        }
    }

    public function delete($id = NULL) {
            $this->news_model->delete_news($id);
            $this->load->helper('url');
            $this->index();
        }

    }

models: News_model.php

    class News_model extends CI_Model {

      public function __construct()
      {
        $this->load->database();
      }

      public function get_news($slug = FALSE)
      {
        if ($slug === FALSE)
        {
        $query = $this->db->get('news');
        return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
      }

        public function set_news()
      {
        $this->load->helper('url');

        $slug = url_title($this->input->post('title'), 'dash', TRUE);

        $data = array(
        'title' => $this->input->post('title'),
        'slug' => $slug,
        'text' => $this->input->post('text')
        );

        return $this->db->insert('news', $data);
      }

     /*public function update_news($slug = FALSE)
    {
        $this->load->helper('url');

        $slug = url_title($this->input->post('title'),'dash',TRUE);

        $data = array(
            'slug'  =>  $slug,
            'title' =>  $this->input->post('title'),
            'text'  =>  $this->input->post('text')
        );
        $this->db->where('slug', $slug);
        return $this->db->update('news', $data);
    }*/

    public function update_news($id, $title, $text) {
        $data = array(
            'title' => $title,
            'text' => $text
        );

        $this->db->where('id', $id);
        $this->db->update('news', $data);
    }

      public function delete_news($id = FALSE)
        {
            $this->db->delete('news', array('id' => $id));
        }
    }

views: admin/news/edit.php

Edit a news item

    <?php echo validation_errors(); ?>

    <?php echo form_open('news/edit/'.$news_item['slug']) ?>

    Title
    <?php echo form_input('title',$news_item['title']); ?>

    Text
    <?php echo form_textarea('text',$news_item['text']); ?>

    <?php echo form_hidden('slug',$news_item['slug']); ?>
    <?php echo form_hidden('id',$news_item['id']); ?>

    <?php echo form_submit('submit', 'Save Changes'); ?>

    <?php echo form_close(); ?>

When I am access `http://localhost/ciadmin/admin/news/edit/news-slug` showing 404 Page Not Found message!!

A: Put it this way:
$route['admin/news/delete/(:any)'] = 'admin_news/delete/$1';
$route['admin/news/edit/(:any)'] = 'admin_news/edit/$1';
$route['admin/news/create'] = 'admin_news/create';
$route['admin/news/(:any)'] = 'admin_news/view/$1';
$route['admin/news'] = 'admin_news/index';

Remember:

Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.

Docs.

A: I also had some problem with 4.0.4 and I was confused with that.
In ci4 just defined
myController extends BaseController

Then in routes.php
$routes->get('/', 'myController::index');

See more https://codeigniter4.github.io/userguide/incoming/routing.html

A: Becase every request redirect to $route['admin/news/(:any)'].
Example: https://example.com/admin/news/edit/1. You have to change the order of routes as below
$route['admin/news/delete/(:any)'] = 'admin_news/delete/$1';
$route['admin/news/edit/(:any)'] = 'admin_news/edit/$1';
$route['admin/news/create'] = 'admin_news/create';
$route['admin/news/(:any)'] = 'admin_news/view/$1';
$route['admin/news'] = 'admin_news/index';


text:
Q: How to create dynamic links from database in Zend Framework? Basically I'm a bit stuck,
I've been following the quick start on Zend site, and wish to make a dynamic navigation to the framework, I've got layout.phtml with $this->render('navigation.phtml); this has static links, but I wish to make them pull from a database table could someone in plain english not geekcaneeze explain the correct way of doing this, IE page by page with simple step by step guide on what each page is doing, as I'm not a PHP FREAK or Zend Framework master but a web designer who wants to progress in to the world of framework development, I understand the concept the vaules of it's use.
I'm sure it will cure a lot of headaches for a lot of newbies to this. in other words after reading zend frame work referance I'm still none the wiser what they are going on about.
I've got it all working though Xampp and the file structure represent the same as
application/
config/
controllers/
layout/script/
models/
views/script/index/
views/script/error/
library/
public/

regards
Mal

A: Pull them out in a controller, pass them along (eg. as an array) to the view:
$this->view->yourListOfLinks = getListOfLinksFromDB();

In the view (the .phtml) example output them using foreach:
foreach($this->yourListOfLinks as $link) {
   echo "$link";
  }

A: Assuming you set up a class for your your database table (ZF - Create a Model and Database Table), you should be able to do something like this in your navigation.phtml file:
<?php
$table = new Links_Table();
$links = $table->fetchAll();
?>

<? foreach ($links as $link) { ?>
   <a href="<?= $link->url ?>"><?= $link->title ?>
<? ?>

If you're creating internal site links then you could also set up some router rewrite rules (ZF - The Standard Router).


text:
Q: UILabel with current time I have a UILabel that I want to show the current time (HH:mm) (the same time as in the status bar).
How do I update the label to change to the new time? If I schedule an NSTimer with an interval of 60 seconds, then label could be out of time by up to a minute, if the timer fires just before the system time's minute changes?
Would it be ok to set the timer's interval to 1 second, or will that use more resources than necessary? Or is there another way to make sure the label will stay in sync with the status bar clock (preferably exactly, but 1 second lee way is ok)?

A: Dispatch is your friend:
void runBlockEveryMinute(dispatch_block_t block)
{
    block(); // initial block call

    // get the current time
    struct timespec startPopTime;
    gettimeofday((struct timeval *) &startPopTime, NULL);

    // trim the time
    startPopTime.tv_sec -= (startPopTime.tv_sec % 60);
    startPopTime.tv_sec += 60;

    dispatch_time_t time = dispatch_walltime(&startPopTime, 0);

    __block dispatch_block_t afterBlock = ^(void) {
        block();

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 60), dispatch_get_main_queue(), afterBlock);
    };

    dispatch_after(time, dispatch_get_main_queue(), afterBlock); // start the 'timer' going
}

This will synchronize down to the nanosecond and only call when the minute changes. I believe that this is the optimal solution for your situation.

A:
Would it be ok to set the timer's interval to 1 second, or will that
  use more resources than necessary?

Depends on what you're doing.  If you're calculating the first million digits of pi, or rendering several hundred 3-D objects, you'll need every processor cycle you can spare.  If the CPU is idling most of the time, you may as well use those cycles to make your interface look nice.

A: //Create a timer...
timer = [NSTimer scheduledTimerWithTimeInterval:0.25
                                                 target:self
                                               selector:@selector(tick:)
                                               userInfo:NULL
                                                repeats:YES];
//Function to update time
- (void)tick:(NSTimer*)t
{
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSString *timeString = [dateFormatter stringFromDate:now];
    [uilabel setText:timeString];
}

your timer will always be "delayed" by some time, since there is no "delegate" functions to call to make such feature.
I would stick with timer, but dispatch as Richard J. Ross III mentioned is valid as well.

A: I think I would run a NSTimer with a 1 second delay in a background thread, have the method it runs check the current time (HH:mm) to the current time displayed in the label. If it matches throw it away, if it's new, update the label.
If you are concerned about performance, after you return the first time, find out how many seconds away from the next minute it is, and have it run the timer run for that long. Then after the fist update have the timer run on 60 second intervals.

A: one second is the right answer.

A: Maybe you can set two timers. The first one (fired once) is used to synchronize the second timer with interval of 60s, which make it fired when the system time comes to HH:00;

A: Second-precision synchronised updates without gettimeofday or blocks.
Weak pointer and dispatch_async prevent retain cycle.
- (void)updateTimeLabel
{
    if (!timeFormatter) {
        timeFormatter = [NSDateFormatter new];
        timeFormatter.dateStyle = NSDateFormatterNoStyle;
        timeFormatter.timeStyle = NSDateFormatterShortStyle;
    }
    NSDate *currentTime = [NSDate date];
    NSTimeInterval delay = [[currentTime nextMinute] timeIntervalSinceDate:currentTime];

    timeLabel.text = [timeFormatter stringFromDate:currentTime];

    __weak id weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf performSelector:@selector(updateTimeLabel) withObject:nil afterDelay:delay];
    });
}

Get next minute with 0 seconds.
@implementation NSDate (Utils)
- (NSDate *)nextMinute {
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *comps = [calendar components:(NSCalendarUnit) NSUIntegerMax fromDate:self];
    comps.minute += 1;
    comps.second = 0;

    return [calendar dateFromComponents:comps];
}
@end

I think there is a retain cycle with block in Richard's answer (it may be fixed with __weak+dispatch_async)


text:
Q: Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer I am getting this error while sending my form through Ajax in Django
Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer
in line
data= formdata

Can you help me figure out the solution.
    uploadBtn.addEventListener('click', e=>{
                e.preventDefault()
                progressBox.classList.toggle('not-visible', false)

                var formdata = new FormData()
                formdata.append('csrfmiddlewaretoken', csrftoken)
                formdata.append('fileA', FileA.files[0])
                formdata.append('a_year', year.value)

                $.ajax({
                    type: 'POST',
                    url: '',
                    enctype: 'multipart/form-data',
                    data = formdata,
                    success: function(response){
                        console.log(response)
                    },
                    error: function(response){
                        console.log(response)
                    },
                    cache: false,
                    contentType: false,
                    processData:false,
                })
            })

A: You need to use a colon not =.
Like so:
data: formdata,

not:
data = formdata,


text:
Q: Bytea data format in R shiny This is a sample table for the data I need to extract from a PostgreSQL database.
Sample data
As you can see, the iv_file (it's a hexadecimal number) column in is in Bytea format. So when I try to extract  onlu the iv_file column in R, I get the following.
`iv_file
1                                                                                \\x
2                                                                                \\x
3                                                                                \\x
4                                                                                \\x
5                                                                                \\x
6 \\x364630353037303036463035303830303646303530443030364530353142303036453035333730303643303535463030364230353838303036393035414530303638303544313030363630354634303036353035313630313634303533373031363330353537303136323035373730313630303539373031354630354236303135453035443630313544303546363031354330353136303235423035333430323539303535343032353930353733303235373035393130323536303542313032353530354430303235343035463030323533303530453033353230353245303335303035344430333446303536423033344530353842303334443035414130333443303543383033344130354538303334413035303830343438303532373034343730353435303434363035363530343434303538343034343430354132303434333035433230343431303545313034343030353031303533463035314630

The data is not the same as the original data. (Please note that the original data has a long number too)
So How do I use bytea data format in R? or how do I convert it?

A: I dont believe you can convert it. Bytea data is basically bite data. I would suggest just not pulling it into the rdata frame. Bytea is normally bitdata that is an image or something that can not be stored in a traditional format.
Another approach would be to use a JDBC, that normally takes care of the transformations. I would take a look at require(RPostgreSQL) to get a sense of how it can be done.
You might be able to convert it back once it is loaded into R. Try something like this
udecode <- function(string){
  uconv <- function(chars) intToUtf8(strtoi(chars, 16L))
  ufilter <- function(string) {
  if (substr(string, 1, 1)=="|") uconv(substr(string, 2, 5)) else string
 }
 string <- gsub("\\\\u([[:xdigit:]]{4})", ",|\\1,", string, perl=TRUE)
 strings <- unlist(strsplit(string, ","))
 string <- paste(sapply(strings, ufilter), collapse='')
 return(string)
}


text:
Q: What is the LayoutInflater in Android? How does it differs from findViewById? An example LayoutInflater code:
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.,parent,false);

Can't understand the work of LayoutInflater in Android. Tried to read the official documentation of the android but, couldn't get the concept.

A: The main difference between findViewById and LayoutInflater is that findViewById is used to access existing views in a layout, while LayoutInflater is used to create a new view hierarchy from an XML layout file.
FindViewById is a method of the Activity class, while LayoutInflater is a separate class on it's own.
FindViewById is used to access a view in the current layout, this means lets us find Views from layouts written in XML and returns a reference to their Java objects, while LayoutInflater is used to create a new view hierarchy from an XML layout file, so this class is the responsible for "inflating" the layouts.
Hope it helps.


text:
Q: Rails: Database records with custom route...? I have a model, target, that holds a number of records that are timestamped.  On the corresponding controller, I list the months of those records by doing the following:
In models/target.rb
def month
   self.recorded_on.strftime('%B')
end

In controllers/targets_controller.rb
@records = Target.find :all

In views/targets/index.html.haml
%ul
  - @records.group_by(&:month).sort.each do |month, data|
    %li= link_to month, ''

That all works great for listing the available months for the records that I have.  Next, I want to be able to click on the month and get a report of all the records for that month, at the following path generated with year and the month: /targets/2009/04
How would I do this?

A: Add some named scopes to your Target model to support finding by year and by month number. Something like:
class Target < ActiveRecord::Base
  named_scope :by_month,
    lambda { |month| { :conditions => ['MONTH(recorded_on) = ?',
                        month] }}

  named_scope :by_year,
    lambda { |year| { :conditions => ['YEAR(recorded_on) = ?', year] }}
  .
  .
  .
end

(Note that the conditions here are using MySQL syntax.)
Assuming you're using RESTful routes, set up a named route like the one below in your config/routes.rb file (make sure it's declared before the default route):
map.targets_by_month '/targets/:year/:month', :controller => 'targets',
                :requirements => { :year => /\d{4}/, :month => /\d{1,2}/ },
                :conditions => { :method => :get }

—You can use this route in your view like this:
<%= link_to 'Show April 2009 Targets', targets_by_month_path('2009', '04') %>

(Note that the leading zero for the month is optional because of the :requirements regular expression in the named route defined above)
Finally, in your TargetsController, set up the index action to use the named_scopes defined earlier:
def index
  @records = Target.by_year(params[:year]).by_month(params[:month])
  .
  .
  .
end


text:
Q: Setting up lighttpd server I'm attempting to setup a lighttpd server and when I try to install php-cgi I receive this error:
The following packages have unmet dependencies:
php7.2-cgi : Depends: php7.2-common (= 7.2.3-1ubuntu1) but
7.2.5-0ubuntu0.18.04.1 is to be installed
E: Unable to correct problems, you have held broken packages.


text:
Q: Access Control error when using twitter npm module I'm testing for a get response on a localhost, and have already verified that my Auth credentials are valid using postman. However when making get requests using the twitter npm library, the browser errors out.
(XMLHttpRequest cannot load. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.)
My current stack utilizes React.js/Gulp/Webpack
What sort of settings do I have to allow in order to get CORs data?

A: JSONP is the fallback solution for servers that restrict CORS or don't support OPTIONS calls for preflight checks.  jQuery has support for crossDomain scripting, that automatically converts to JSONP.


text:
Q: What does "they" refer to in this sentence? The following paragraph is from a book called "Conjectures and Refutations" by Karl Popper:

"THE ESSAYS and lectures of which this book is composed are variations upon one very simple theme--the thesis that we can learn from our mistakes. They develop a theory of knowledge and of its growth. It is a theory of reason that assigns to rational argument the modest yet important role of criticizing our often mistaken attempts to solve our problems. And it is a theory of experience that assigns to our observations the equally modest and almost equally important role of tests which may help us in the discovery of our mistakes. Though it stresses our fallibility it does not resign itself to skepticism for it also stresses the fact that that knowledge can grow, and that science can progress-- just because we can learn from our mistakes."

My question is, does the pronoun "They" in "They develop a theory of knowledge and of its growth." refer to "mistakes" in "we can learn from our mistakes" or "THE ESSAYS and lectures"?

A:
"THE ESSAYS and lectures of which this book is composed are variations upon one very simple theme--the thesis that we can learn from our mistakes. They develop a theory of knowledge and of its growth.

Let's examine both options (I've paraphrased them a little bit)

*

*The essays in this book develop a theory of knowledge and of its growth.

or

*Our mistakes develop a theory of knowledge and of its growth.

A series of essays could be used to develop or 'to elaborate or expand in detail' a theory of knowledge and how knowledge grows.
Our mistakes can teach us important lessons, and may increase our personal knowledge, but they do not "expand in detail a theory of knowledge". We might think of a theory because of mistakes we've made, but then we would have to write essays or give lectures to explain our theory. It wouldn't be our mistakes that explain the theory.
I think you may already understand now that "They" refers to the essays and lectures, but I will write it out in case it's not clear.


text:
Q: ¿Cómo hacer un inner join en linq? Tengo una api que me devuelve la tabla de los productos vendidos en su detalle, pero necesito hacer un 'inner join' con la finalidad de obtener el nombre de cada producto que se ha vendido.
Pero al código mostrado aquí debajo realmente no encuentro la forma de como agregarle la tabla de productos para poder lograr visualizar el nombre de cada item.
Gracias por la ayuda.
    [Route("api/PedidosDetalle/{PedCodigo}/{RepCodigo}")]

    public List<PedidosDetalle> Get(int PedCodigo, string RepCodigo)
    {

        using (ModelApi entidad = new ModelApi())

        {

            return entidad.PedidosDetalles.Where(e=> e.RepCodigo == RepCodigo && e.PedCodigo == PedCodigo).ToList();
        }

    }

Intenté con el siguiente código:
  [Route("api/PedidosDetalle/{PedCodigo}/{RepCodigo}")]
        public List<PedidosDetalle> Get(int PedCodigo, string RepCodigo)
        {
            using (ModelApi entidad = new ModelApi())
            {
                var q = (from s in entidad.Productos
                         join t in entidad.PedidosDetalles on s.ProCodigo equals t.ProCodigo

                         where t.RepCodigo == RepCodigo &&  t.PedCodigo == PedCodigo

                         select new
                         {
                             s.ProDescripcion

                         });

                return q.ToList();
            }

Pero me está dando el error que desglosa la imagen:

        }

A: así
var innerJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID
    select new { ProductName = prod.Name, Category = category.Name };

aca te dejo mas info

A: Tu error es porque tu método devuelve un List<Pedidos> y la consulta devuelve un nuevo objeto que no es del modelo Pedidos. Debes convertir tu objeto nuevo de la consulta a List<Pedidos>. Fácilmente podrías recorrer con un foreach y rellenar tu List<Pedidos>.


text:
Q: CSS creating a horizontal navigation bar - `li`s vs. `div`s Which is the semantically better way to do this? Floating li elements inside a ul or just float divs inside an 'outer' div?

A: Using a list would be more semantically correct, as the content represents a list of navigation items. Divs are just division/placeholder containers, often used for styling.

A: For html4 use a list as Mic said.
For new html5 there is a  element to wrap your list in, which is semanticaly better.

Menu item


text: Q: É possível ver a declaração de uma função interna do js? ex.: setInteval() Estava estudando um pouco sobre funções e gostaria de saber se é possível buscar a declaração de uma função interna em javascript assim como consigo fazer em objetos internos.


text: Q: How is an ofstream object and ofstream stream created? When I create an ofstream object, does it create an output file stream and associate it with the ofstream object? Whenever the ofstream object outputs, it outputs to that stream. Am I correct?


text:
Q: Rich TextView in SwiftUI I'm trying to do a simple notes app in SwiftUI and I'd like to know if there's any library for having a simple rich text view that allows users to write in bold, italics, strikethrough, underline, etc.
I've tried LEOTextView, but it is very buggy, and I'd like to see if there's a 100% SwiftUI way to achieve this so it would be easier to integrate with my project. I also don't know a lot of UIKit so it would be easier to add more features if it is made in SwiftUI.
Sorry if this is a stupid question and thanks in advance.
TL;DR: I just want something like this

I guess this would be the starting point:
import SwiftUI

// first wrap a UITextView in a UIViewRepresentable
struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UITextView {

        let textView = UITextView()
        textView.delegate = context.coordinator
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }

    class Coordinator : NSObject, UITextViewDelegate {

        var parent: TextView

        init(_ uiTextView: TextView) {
            self.parent = uiTextView
        }

        func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            return true
        }

        func textViewDidChange(_ textView: UITextView) {
            print("new text: \(String(describing: textView.text!))")
            self.parent.text = textView.text
        }
    }
}

struct ContentView: View {
     @State var text = ""

       var body: some View {
           TextView(
                text: $text)
       }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: There is a well documented library that for SwiftUI text editor. it supports iOS 13.0+ and macOS 10.15+, here is the link for it!
HighlightedTextEditor
It's also very simple to use.


text:
Q: Getting data from ActionClass to JSP in Struts 2 I'm currently working on a school project which consists of developing a game using Struts2/JSP.
The problem I have is I can't get Data from my ActionClass to my JSP using jQuery.
It works great the other way and I found multiple sources to do so.
Here is my minimized GameAction.class:
private String playerColor;
private Map<String,Object> applicationMap;

public String execute (){

playerColor = ((Joueur)applicationMap.get("joueur")).getPlayerColor();
    return SUCCESS;
}

NOTE: everything has a getter/setter.
game.js :
var $playerColor;
$(window).on('load', function () {

$.ajax({
    type : "GET",
    url : "gotoGameAction",
    data : "playerColor=",
    success : function (data) {
    $playerColor = data;
    var html = "
" + $playerColor.toString() + "
";
    $("#playerColor").html(html);
  }

})

});

Struts.xml:
<package name="default" extends="json-default" namespace="/">
    <action name="gotoGameAction" class="actions.logins.GameAction">
        <result name="success" type="json">/WEB-INF/views/game.jsp</result>
    </action>
</package>

This output I have on my JSP is : [object Object].
I really can't get what's going on there.

A: I found some of mistakes in your code. It may helpful to you.
In struts.xml
Its
<result name="success" type="json">playerColor</result>

instead
<result name="success" type="json">/WEB-INF/views/game.jsp</result>

Here type json so variable to be passed.
And playerColor should have getter method in GameAction.
In Ajax call simply
success : function (data) {
    $("#playerColor").html("
" + data + "
");
}

A: You might not understand what is a JSON result type and how the content is provided by the action which is executing this result type.
To get more about plugin and documentation see JSON Plugin.
You can also look in the source code for the class which is being executed the JSONResult. Then you see that

/**
 * This result type doesn't have a default param, null is ok to reduce noise in logs
 */
public static final String DEFAULT_PARAM = null;

However such noise sometimes is helpful if you are debugging the code.
That makes no any sense in your code
<result name="success" type="json">/WEB-INF/views/game.jsp</result>

The you need to dig into the tutorial and examples how to use this result. One of them you can find here.
Another link might help you to decide whether you need a json result or use any other result suitable for JSON response.
Combining all that together will make an idea to rewrite your code to get it working.


text:
Q: BadMethodCallException: Method year does not exist I want to create a set of tables in my database via migration. So, for one of the tables I have this line among others:
$table->year('year')->nullable(false);
...

and it seems that there is an issue with this line since I am getting the following error message after typing in php artisan migrate:fresh command:

[BadMethodCallException]
  Method year does not exist.

No typos on my part, tried a different column name, tried without nullable(false). YEAR type is available in my database (10.1.28-MariaDB).
The line in question is just like the others inside the closure creating the table.
I have come across lots of similar topics on the internet but they involve other methods (often custom users' methods, not Laravel built-in ones) and in those cases people tried to call methods in their controllers/models and basically they confused/missed objects which is not the case here. Laravel 5.5.22, localhost, Windows. So, how to fix this issue and make migration create the table?

A: So, the year type isn't listed in the API Docs for 5.5 for the Mysql Grammar Type
You can view that here
However, the github repository shows that it was added in this commit here
On this hash you can see Taylor has fixed some issues with some conflicts concerning the typeYear method.
So my conclusion is that you must manually use illuminate/database and 5.7-dev. As the current version listed in laravel/framework is self.version. which resolves to 5.5-dev which does not have the typeYear method in the MysqlGrammar, but 5.7-dev does.


text:
Q: Good work-flow plugin available in Grails I'm in search of good work flow plugin available for grails 2.0+ which is well documented and maintained. My application is called Training management System which for creating and maintaining  training's. on creation of training my workflow will start by sending email to trainer, participants and training owners.. and the process continues.
so please suggest me a good workflow plugins available .

A: GrailsFlow is a good one, regards to the grails integration (their website is sometimes very slow, though)

A: Try Grails Activiti Plugin at http://code.google.com/p/grails-activiti-plugin/.
P/S: I'm creator of the plugin. Your feedback is very much appreciated.


text:
Q: std::pair move not elided on definition? I noticed something very strange with Visual Studio 2012: Defining a pair object like so:
    auto objp = pair<int, LogMe>();

will not elide the copy/move of the pair in VC11, this call will print:
LogMe::LogMe - def.ctor!
LogMe::LogMe - move.ctor!
LogMe::~LogMe - dtor!

that is, a temporary pair will be created and then moved into the objp variable. (declaring it as pair<...> obj; only logs the default ctor)
I have cross checked with my LogMe test object alone:
cout << "# Construct Object via auto obj = ...\n";
auto obj = LogMe();

# Construct Object via auto obj = ...
LogMe::LogMe - def.ctor!

and here the assignment will be elided.
This seems to be specific to VC11, as testing it in IDEOne (which uses gcc 4.8.1) shows that the extraneous move is elided always there.
What's going on here? Not being able to rely on the initialization copy being elided makes me nervous.
Note: Tests for release vs. debug version show the same result. (Which I would have expected, as copy-elision is performed independently of optimization flags in MSVC.)

Full sourcecode to test (See also the ideone link):
#include "stdafx.h"
#include <iostream>
#include <map>

using namespace std;

struct LogMe {
    std::string member;

    LogMe() {
        cout << __FUNCTION__ << " - def.ctor!" << endl;
    }
    ~LogMe() {
        cout << __FUNCTION__ << " - dtor!" << endl;
    }
    LogMe(LogMe const&) {
        cout << __FUNCTION__ << " - cpy.ctor!" << endl;
    }
    LogMe& operator=(LogMe const&) {
        cout << __FUNCTION__ << " - cpy.assign.op!" << endl;
        return *this;
    }
    LogMe(LogMe&&) {
        cout << __FUNCTION__ << " - move.ctor!" << endl;
    }
    LogMe& operator=(LogMe&&) {
        cout << __FUNCTION__ << " - move.assign.op!" << endl;
        return *this;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    {
        cout << "# Construct Object via auto obj = ...\n";
        auto obj = LogMe();
        cout << "# Construct pair<int, object> via auto objp = ...\n";
        auto objp = pair<int, LogMe>();
        cout << "# Construct pair<int, object> via pair objp2; ...\n";
        pair<int, LogMe> p2;
    }
    return 0;

A: It appears it is not the move ctor, nor the templated move ctor that is causing the problem, but  the presence of enable_if<is_convertable<... in the templated move ctor:
Testing with just an object, throwing auto and pair out of the test:

*

*OK, copy/move elided:
        cout << "# Construct Object: auto obj = LogMe();\n";
        LogMe obj = LogMe();

        LogMe(LogMe&&) {
            cout << __FUNCTION__ ...
        }

And, with a test like so:
    cout << "# Construct Object: LogMeTempl obj = LogMeTempl();\n";
    LogMeTempl obj = LogMeTempl();
    cout << "# Construct Object: LogMeTempl obj2;\n";
    LogMeTempl obj2;

*

*OK, copy move also elided:
template<class Other>
LogMeTempl(Other&& rhs
//      , typename enable_if<is_convertible<Other, LogMeTempl>::value, void>::type ** = 0
) {
    cout << __FUNCTION__ << ...;
}

*Fail! Move ctor invoked!
template<class Other>
LogMeTempl(Other&& rhs
        , typename enable_if<is_convertible<Other, LogMeTempl>::value, void>::type ** = 0
) {
    cout << __FUNCTION__ << ...;
}

And note that the enable_if can be reduced to enable_if<true, void>::type** = 0 - if fact any additional defaulted parameter will do (e.g. , int defaulted_param_on_move_ctor = 0 and it will still prevent the move elision).
This also extends to a type with a copy-ctor only that has a default argument. It won't be elided either. A quick cross-check with gcc shows there doesn't seem to be any such problem there.
Short Answer
Types with defaulted arguments in their copy/move ctor don't have their initialization copy/move elided.
I have added a bug on MS.connect for this issue.
I have also added a test-case for (N)RVO to IDEone. Even without the default argument, *N*RVO seems to work better in gcc than VC++.


text:
Q: Something wrong with my delete button Image
I have a problem with my delete button. If I press delete in line 2, the data will be delete at the same line. But, in case. If I press the delete button in line 2, the data will be lost is data in the bottom. Not data in line 2. The error start when I add the javascript into my code.
My controller code
<?php

public function index()
{
    $data['result'] = $this->Magen->view();
    $config['menuagen'] = 'active';
    $this->load->view('element/header', $config);
    $this->load->view('agen/list_agen', $data);
    $this->load->view('element/footer');
}

public function manage($id=""){
    $submit = $this->input->post('submit');
    if($submit){
        $id = $this->input->post('id');
        $datainput = array(
            'id_agen' => $this->input->post('id_agen'),
            'nama_agen' => $this->input->post('nama_agen'),
            'alamat' => $this->input->post('alamat'),
            'no_telp' => $this->input->post('no_telp'),
            'keterangan' => $this->input->post('keterangan'),
        );

        if ($id){
            $this->Magen->update($id, $datainput);
        }else{
            $this->Magen->insert($datainput);

        }

        redirect('agen');
    }

    if ($id){
        $data['detail'] = $this->Magen->detail($id);
        $data['mode'] = 'Edit';
    }else{
        $data['mode'] ='Tambah';
    }

    $config['menuagen'] = 'active';
    $this->load->view('element/header', $config);
    $this->load->view('agen/form_agen', $data);
    $this->load->view('element/footer');
}

public function delete($id){
    $this->Magen->delete($id);
    redirect('agen');
}
}

My Model code
<?php

//query insert/save

public function insert($data){
    return $this->db->insert('agen', $data);
}

//update

public function update($id, $data){

$this->db->where('id_agen', $id);
return $this->db->update('agen', $data);
}

//delete

public function delete($id){
    return $this->db->delete('agen', array('id_agen' => $id));
}

//view

public function view(){
    return $this->db->get('agen')->result_array();
}

//query detail

public function detail($id){
    $this->db->where('id_agen', $id);
    return $this->db->get('agen')->result_array();
}

My HTML code

Kelola Agen

Daftar Agen

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

                                            No
                                            ID Agen
                                            Nama Agen
                                            Alamat
                                            No. Telp
                                            Keterangan
                                            Action

                                        <?php if(@$result):?>
                                            <?php $i = 1;?>
                                            <?php foreach ($result as $row):?>

                                                    <?php echo $i++;?>
                                                    <?php echo $row['id_agen'];?>
                                                    <?php echo $row['nama_agen'];?>
                                                    <?php echo $row['alamat'];?>
                                                    <?php echo $row['no_telp'];?>
                                                    <?php echo $row['keterangan'];?>

                                                    <a href="<?php echo base_url();?>index.php/agen/manage/<?php echo $row['id_agen'];?>"class="btn btn-xs btn-primary">Edit
                                                    Delete

                                            <?php endforeach?>
                                        <?php endif?>

My Javascript code

I hope someone can fix this problem. Thanks before :)

A: In php code, $result iterated, you can echo out EACH $row['id_agen']
<?php foreach ($result as $row):?>

  <?php echo $i++;?>
  ...

    <a href=..<?php echo $row['id_agen'];?...>Edit
    ...

<?php endforeach?>

But in js code, how $row[id_agen] binded to EACH single one
$.post('<?php echo base_url();?>index.php/agen/delete/<?php echo $row['id_agen'];?>', data);


text:
Q: has sqlite been renamed to sqlite3? I use sqlite for lightweight programming here and there in the Ruby language.  I've noticed something odd.  I use ruby gem sqlite3 to interact with the sqlite db.
I recently checked out the versions that I have.
sqlite3 -version gives me
3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2alt1
Not necessarily the most recent version but it's listed on the sqlite website.
gem list sqlite3 gives me
sqlite3 (1.4.0, 1.3.13)
But sqlite -version gives me
2.8.17
I try to update to sqlite --version 3.28.0 with
sudo apt upgrade sqlite but this gives me:
sqlite is already the newest version (2.8.17-14fakesync1).
I then head over to the ubuntu site and read the summary for this piece of software.  It is designed for sqlite2.  So my question is has sqlite changed its name to sqlite3.  I do not see any mention of this change? Perplexed.

A: Current Sqlite is version 3.28...
Versions (2.x versus 3.x) can have incompatibilities and so can coexist for a while.

*

*SQLite V3 appeared in 2004.

*The last release of SQLite V2 (2.8.17) was in December 2005. This seems to be your sqlite. I would be wary of any application that still uses it, though :)

*SQLite V1 was too short-lived to stick around.

The full (his)story.
So:

*

*sqlite -version gives you the version/release of an SQLite V2 command line to handle SQLite V2 databases, which is also likely the version of your SQLite library.

*sqlite3 -version is the same for an SQLite V3 command/library.

*gem list sqlite3 gives you the version of the language binding for SQLite V3, which is versioned independently of the releases of the SQLite V3 library, the binging being assumed to work with any SQLite V3 release that you may have installed.


text:
Q: Android MutlicastSocket constructor problems I'm writing an app to do some basic communication via multicast.  I'm running into a problem and can figure why.  I'm defining the socket according to the constructor in the API, yet it's not actually setting the variables as specified.  Here is a basic code snippet with a bunch of the extra stuff removed:
import java.net.MulticastSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
...

private InetAddress groupInetAddr = InetAddress.getByName("239.42.42.42");;
private int groupPort = 42000;
private MulticastSocket groupSocket;

netInt = NetInfo.getInterface();
//This is a custom method that chooses a candidate NetworkInterface
//from available options.  Returns a NetworkInterface object

try{
   groupSocket = new MulticastSocket(groupPort);
   groupSocket.setNetworkInterface(netInt);
   groupSocket.joinGroup(groupInetAddr);
   groupSocket.setTimeToLive(64);
}
catch (Exception e){
   Log.i(TAG, "FAILED");
}

I have some test code immediately following this code to confirm that the socket has been created properly, and it isn't...
Log.i(TAG, "groupInetAddr: " + groupInetAddr.toString());
Log.i(TAG, "groupPort: " + groupPort);
Log.i(TAG, "groupSocket.getInetAddress: " + groupSocket.getInetAddress());
Log.i(TAG, "groupSocket.getPort(): " + groupSocket.getPort());

The log results of the test:
GroupSender﹕ groupInetAddr: /239.42.42.42
GroupSender﹕ groupPort: 42000
GroupSender﹕ groupSocket.getInetAddress: null
GroupSender﹕ groupSocket.getPort(): -1

So, as you can see, the InetAddress is being created properly, so that's not the problem, but the socket isn't assigning the InetAddress as the destination.  Additionally,  when I check Wireshark, there is no IGMP message send out over the LAN to that address.
Additionally, I've added the following permissions to the AndroidManifest.xml to allow access to necessary services.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-feature android:name="android.hardware.wifi" />

Any ideas?  Hopefully I'm just missing something small.

A: The socket has been constructed correctly. You didn't connect it, so its getInetAddress() returns null and its target port is -1.
That doesn't have anything to do with which multicast groups it has joined. Your expectations are at fault.
The IGMP message is only sent if this host isn't already a member of that group.

A: It turns out that this code works as intended.  The problem is with the Android emulator.  It doesn't send out the IGMP message as required.
I was trying to communicate between the emulator and an actual device.  I installed the app on 2 devices and they are able to communicate between each other.


text:
Q: Confusion Matrix only considering predictions > threshold The output layer of my network is
model.add(Dense(2, activation=activations.softmax))

outputting a one hot encoded category prediction.
model.predict therefore returns n predictions like
[9.9584144e-01, 4.1585001e-03],
[7.5779420e-01, 2.4220583e-01],
...

I now not only want the full confusion matrix provided by sklearn through
metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred')

but I'd like to see how the confusion matrix looks only for the cases where the max prediction is larger than a given threshold.
Something like
metrics.confusion_matrix(y_TEST.argmax(axis=1), y_pred.argmax(axis=1), normalize='pred',
                         min_confidence_threshold='0.9')

Does sklearn or any of the standard tools here provide a functionality like that?
If not, how would I filter two arrays (y_TEST, y_pred) based on a condition of one of the arrays?

A: Here's a function that can do this:
def threshold_matrix(labels,probs,threshold=0):
    assert 0 <= threshold <= 1
    t_map = lambda x : 1 if tf.math.reduce_max(x) > threshold else 0
    thres = tf.map_fn(t_map, probs)

    pred  = tf.boolean_mask(tf.argmax(probs,1),thres)
    labs  = tf.boolean_mask(tf.cast(labels, tf.int64),thres)

    return tf.math.confusion_matrix(labs,pred)


text:
Q: Vuex modules with typescript EDIT:
Since vue conference Toronto (late 2021), Vue has officially switched over to Pinia for typescript support, instead of Vuex. They also acknowledge that Vuex was notoriously difficult to work with, while trying to use TypeScript and splitting a store into multiple modules, while retaining most benifits of TypeScript. Therefore this question is no longer relevant.

Original post:
I'm trying to create a staticly typed vuex store with multiple modules. I've read several articles, but must admit that I'm stuck, which is why I'm hoping someone here could help me out.
I have currently have 2 modules; documentation and workAgreement, with strongly typed commits and dispatch methods in ..store/modules/{module}/types.ts.

export type AugmentedWorkAgreementContext = {
    commit: WorkAgreementStore["commit"],
    dispatch: WorkAgreementStore["dispatch"]
  } & Omit < ActionContext < IWorkAgreementState, RootState > , 'commit' | "dispatch" >

  export type WorkAgreementStore < S = IWorkAgreementState > = Omit < Store < S > , "commit" | "getters" | "dispatch" >
  &
  {
    commit < K extends keyof IWorkAgreementMutations,
    P extends Parameters < IWorkAgreementMutations[K] > [1] > (
      key: K,
      payload: P,
      options ? : CommitOptions
    ): ReturnType < IWorkAgreementMutations[K] > ;
  } & {
    dispatch < K extends keyof IWorkAgreementActions,
    P extends Parameters < IWorkAgreementActions[K] > [1] > (
      key: K,
      payload: P,
      options ? : DispatchOptions
    ): ReturnType < IWorkAgreementActions[K] > ;
  } & {
    getters: {
      [K in keyof IWorkAgreementGetters]: ReturnType < IWorkAgreementGetters[K] >
    }
  }

This is then made into a type in ..store/index.ts with the following code.

export type RootState = {
  workAgreement: IWorkAgreementState
  documentation: IDocumentationState
}

export const store = createStore({
  modules: {
    documentationStore,
    workAgreementStore,
  }
})

type Store = DocumentationStore < Pick < RootState, 'documentation' >> & WorkAgreementStore < Pick < RootState, 'workAgreement' >>

  export function useStore(): Store {
    return store as Store
  }

From here I'm trying to use it in a component, and it workes to some extend, my problem is that it dosen't help me with the intellisense on one of the modules, specifically whichever one is the last at

type Store = DocumentationStore<Pick<RootState, 'documentation'>> & WorkAgreementStore<Pick<RootState, 'workAgreement'>>

The code within the component let's me use the available getters from both with autocompletion, so I'm a bit confused as to what I'm doing wrong. It looks like I have 2 overloads, but the second one looks pretty scoffed.
Here's the code in the component for reference and picture's of the issue I'm having.

import {
  defineComponent
} from 'vue'
import {
  useStore
} from "@/store";
import {
  computed
} from "vue";

export default defineComponent({
  data() {
    return {
      store: useStore()
    }
  },

  setup() {
    const store = useStore()

    const thisIsATest = computed(
      () => store.getters.GetAnotherDocumentation
    )
  },
  yetAnotherTest() {
    this.store.commit()
  }
})
`enter code here`

The one with intellisense
The one without intellisense


text:
Q: Multiple 74HC595 chained together won't light all LEDs I'm new to Arduino - and electronics in general - and am having a frustrating problem with two serial-to-parallel 74HC595 chips trying to drive two 7-segment LED displays. The LEDs are both common cathode, and each LED input has its own 510 ohm resistor, connected up to an output of a 74HC595. If I unplug the common cathode from A, I see the correct display in B. If I unplug the common cathode from B, I see the correct display in A. But when both common cathodes are plugged in, B starts displaying rubbish (mostly it's just blank though) while A displays correctly. It's like there's not enough power to go around. I'm using the 5V power output, because that's what the 74HC595 chips need (actually it can be between 2V and 6) and I don't want to start frying chips.
If anyone can point out what I'm doing wrong (or what I could potentially try to get it working) that would be great. I am working on a hobby project where I was hoping to have 6 of these LED and 74HC595 chips hooked up.

A: From what you said about the resistor, figuring nearly-to-the-rail output from the CMOS 74hc595 and about 1.25V diode drop, each segment probably is pulling about 7mA. If you get two full displays going that's starting to add up. Just 14 segments at this current (not even two full digits worth) you're already breaking 100mA. Not to mention that if you are powering the 74HC595's off the same 5V source that's still more current, though thankfully not too much since it is a CMOS device.
I'd have to look at the specs of the arduino to be sure, but it wouldn't be surprising if the tiny little regulated supply on the arduino isn't up to it. Even if it were rated for it, I'd probably try to at least feed the 74HC595's with a separate 5V supply. To use a separate supply, be sure to tie the grounds together.
If you plan on running 6 digits, accounting for all segments on, you'd want something with at least 500mA or even better 1000mA. It's better to have the amp-capacity and not need it, than need it and not have it.


text:
Q: Check an Image URL is valid My goal is to check an image source url to check whether it is valid or not. If it is valid, display the React Native Image as normal and if not, replace it with a local placeholder image. However, the following typescript function never seems to return anything and nothing is displayed.
renderImage(): JSX.Element {
    fetch(this.props.imageUrl)
    .then(res => {
      if(res.status == 404) {
        return (
          <Image
            source={require('../images/nasa-logo.png')}
            style={styles.imageThumbnail}
          />
        )
      } else {
        return (
          <Image
            source={{uri: this.props.imageUrl}}
            style={styles.imageThumbnail}
          />
        )
      }
    })
    .catch(err => {
      return (
        <Image
          source={require('../images/nasa-logo.png')}
          style={styles.imageThumbnail}
        />
      )
    })

    return null // <-- skips to here
  }

A: You don't need fech you can use onError fallback
    this.state = ({
     image:{uri: this.props.imageUrl}
    })
    const setimage = () => {
     this.setState=({image:  require('../images/nasa-
   logo.png')  })
    }
    <Image
            source={this.state.image}
            style={styles.imageThumbnail}
             onError={()=>setimage()}
          />

PS: I am using my phone to answer, sorry for  bug if you found a typo and for the format

A: I created an example component that should more or less do what you request

*

*we keep a loading state, to indicate whether we are still check if the image exists

*we keep a valid state: to indicate whether the imageUrl is valid

*we initiate a fetch using useEffect and set the above states accordingly.

Only downside of this approach is that you will download the image twice if it exists: once the check for its existence, once by react-native to actually render the image
import { useEffect, useState } from 'react';
import { Image } from 'react-native';

import NasaImage from '../images/nasa-logo.png';

const ImageFallback = ({ imageUrl }) => {
  // start off in the loading state
  const [loading, setLoading] = useState(true);

  // keep track whether imageurl returns valid result
  const [isValid, setIsValid] = useState(null);

  // use effect to check for access to imageUrl,
  // run the effect when the component mounts
  useEffect(() => {
    fetch(imageUrl).then(res => {
      setIsValid(res.status === 200);
      setLoading(false);
    });
  }, []);

  // if still loading or invalid: return fallback image
  if (loading || !isValid) {
    return <Image source={NasaImage} style={styles.imageThumbnail} />;
  }

  // return the image with the provided value
  return <Image source={{ uri: imageUrl }} style={styles.imageThumbnail} />;
};

export default ImageFallback;

A: Just handle it with state
const [defaultImage, setDefaultImage] = useState(true);
// call this method inner componentDidMount
renderImage() {
    fetch(this.props.imageUrl)
    .then(res => {
      if(res.status == 404) {
        setDefaultImage(true);
      } else {
        setDefaultImage(false)
      }
    })
    .catch(err => {
      setDefaultImage(true)
    })
  }
   // use where u want
   const myImage = defaultImage? <Image
            source={require('../images/nasa-logo.png')}
            style={styles.imageThumbnail}
          /> : <Image
            source={{uri: this.props.imageUrl}}
            style={styles.imageThumbnail}
          />;

A: I took Redwan Abbs answer as a template, but the issue with this is that the image can be stuck in a continuously rendering loop. The other answers are fine, they just take a lot more code to implement. I used the onError prop and used a boolean toggle to ensure it wasn't just getting continuously re-rendered.
    ...

    // state type declaration
    imageSrc: ImageSourcePropType
    imageError: boolean

    ...

    // state initialisation
    this.state = {
      imageSrc: {uri: this.props.imageUrl},

         imageError: false
        }

     ...

     onImageInvalid () {
       const placeholderImagePath: string = '../images/nasa-logo.png'

       if (!this.state.imageError) {
         this.setState({
           imageSrc: require(placeholderImagePath),
           imageError: true,
         });
       }
    }

    ...
    //render method

    <Image
      source={this.state.imageSrc}
      style={styles.imageThumbnail}
      onError={() => this.onImageInvalid()}
    />


text:
Q: Advanced splitting of search term with regex, respecting rules for hyphens and dots when part of words I did some research but I could not find the solution to a problem which I assume to be very common:
I want to split the search terms, supporting quotation marks and in a smart way handle dots and hyphens.
I could write a long list of requirements, but I think the following example which contains all problematic aspects is more simple and clear:
My test, one. two ASP.net 030-333-12345 end

Should split to:
My
test
one
two
ASP.net
030-333-12345
end

I could achieve this with some substitutes and re-substitute after the splitting but I guess a pro in regex would solve this more efficient and elegant in one step.
I came to this but this does not handle the . and - correctly.
var words = Regex
    .Matches(keywords, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
    .Cast<Match>()
    .Select(m => m.Groups["match"].Value)
    .ToList();

The result is wrong, as it gives:
My
test
one
two
ASP
net
030
333
12345
end

The problematic part is the \w, I think, because its definition of a word does not match my requirement.

A: You are trying to match word characters and any non-word characters if they are followed by at least one word character:
\w+(?:\S+\w+)*

Live demo
Note: if you only want to include - and . then replace \S with [.-]:
\w+(?:[.-]+\w+)*


text:
Q: jquery generic select code - how I need to do this:
$("#textarea1").mouseup(function () {
    // how to catch the "1" and set it inside inner selectors?
    $('#id_generator_textbox1_x').val(Math.round($(this).position().left));
    $('#id_generator_textbox1_y').val(Math.round($(this).position().top));
    $('#id_generator_textbox1_w').val($(this).width());
    $('#id_generator_textbox1_h').val($(this).height());
});

multiple times. the textarea1 can be textarea2 etc .. the same for inner selectors.
how can I make it select genericly without repeating this code 10 times?

A: $("[id^='textarea']").mouseup(function () {
    var idSelector = '#id_generator_' + this.id.replace('textarea','textbox');
    $(idSelector + '_x').val(Math.round($(this).position().left));
    $(idSelector + '_y').val(Math.round($(this).position().top));
    $(idSelector + '_w').val($(this).width());
    $(idSelector + '_h').val($(this).height());
});


text:
Q: The PDO extension is required for this adapter but the extension is not loaded I am getting the following exception when i try to use the fetchall method of the Zend_Db_Table_Abstract class...
An error occurred4545
EXCEPTION_OTHER
Exception information:
Message: The PDO extension is required for this adapter but the extension is not loaded

Stack trace:
#0 D:\www\TestProject\library\Zend\Db\Adapter\Pdo\Mysql.php(96): Zend_Db_Adapter_Pdo_Abstract->_connect()
#1 D:\www\TestProject\library\Zend\Db\Adapter\Abstract.php(448): Zend_Db_Adapter_Pdo_Mysql->_connect()
#2 D:\www\TestProject\library\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('DESCRIBE `album...', Array)
#3 D:\www\TestProject\library\Zend\Db\Adapter\Pdo\Mysql.php(156): Zend_Db_Adapter_Pdo_Abstract->query('DESCRIBE `album...')
#4 D:\www\TestProject\library\Zend\Db\Table\Abstract.php(823): Zend_Db_Adapter_Pdo_Mysql->describeTable('albums', NULL)
#5 D:\www\TestProject\library\Zend\Db\Table\Abstract.php(862): Zend_Db_Table_Abstract->_setupMetadata()
#6 D:\www\TestProject\library\Zend\Db\Table\Abstract.php(969): Zend_Db_Table_Abstract->_setupPrimaryKey()
#7 D:\www\TestProject\library\Zend\Db\Table\Select.php(100): Zend_Db_Table_Abstract->info()
#8 D:\www\TestProject\library\Zend\Db\Table\Select.php(78): Zend_Db_Table_Select->setTable(Object(Application_Model_Albums))
#9 D:\www\TestProject\library\Zend\Db\Table\Abstract.php(1005): Zend_Db_Table_Select->__construct(Object(Application_Model_Albums))
#10 D:\www\TestProject\library\Zend\Db\Table\Abstract.php(1303): Zend_Db_Table_Abstract->select()
#11 D:\www\TestProject\application\controllers\IndexController.php(17): Zend_Db_Table_Abstract->fetchAll()
#12 D:\www\TestProject\library\Zend\Controller\Action.php(513): IndexController->indexAction()
#13 D:\www\TestProject\library\Zend\Controller\Dispatcher\Standard.php(289): Zend_Controller_Action->dispatch('indexAction')
#14 D:\www\TestProject\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#15 D:\www\TestProject\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#16 D:\www\TestProject\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#17 D:\www\TestProject\public\index.php(26): Zend_Application->run()
#18 {main}
Request Parameters:
array (
  'controller' => 'index',
  'action' => 'index',
  'module' => 'default',
)

I have added the following lines in the php.ini file
extension=pdo.so
extension=pdo_mysql.so

extension=php_pdo.dll
extension=php_pdo_mssql.dll

Also i have The PDO MySQL package installed in my system. But still I am getting the above exception.... (Also restarted the Apache server)

A: First of all, you cannot have both :
extension=pdo.so
extension=pdo_mysql.so

Which are for Linux, and :
extension=php_pdo.dll
extension=php_pdo_mssql.dll

Which are for windows : you've got to choose, depending on the system you are using.
As you are on windows, you should use the .dll version.

But note that you used :
extension=php_pdo_mssql.dll

i.e. you loaded the pdo_mssql extension -- which is for Microsoft SQL Server, and not MySQL.
Instead, you should load the extension for MySQL :
extension=php_pdo_mysql.dll

After correcting that, restart Apache ; and things should get better.

If things don't get better, you should check the output of phpinfo() :

*

*At the beginning of phpinfo()'s output, it indicates which php.ini file is loaded ; make sure you modified the right one.

*Check, lower in the file, if there is a section about pdo_mysql

*

*If not, check Apache's error_log, just in case ;-)

A: Mabe swich backed from PDO to Mysqli helps, they're swichable in ZF (i did so).

A: Today I have moved one website from our testing server to the client server and getting such kind of the error that The PDO extension is required for this adapter but the extension is not loaded. I was thinking that there must be pdo.so php extension which is not installed on the server. After recogniging the problem, I was looking for the php.ini file to check the extension but due to the shared hosting they did not provide me the ini file.
Here in this post I am trying to describe how to solve the such kind of the problem it is very easy and you can solve the problem by using the steps given below:
If you want to know more regarding the PDO look at http://php.net/manual/en/ref.pdo-mysql.php
If you have access of the php.ini file then check
;extension=pdo_mysql.so

Just you need to uncomment the line to activate so it looks like as
extension=pdo_mysql.so

Save the file and restart the server.
If you have no access of the php.ini file, follow the following steps
Step 1. Please check your Magento installation directory there must me a file named as php.ini.sample.
Step 2. Now rename the file from php.ini.sample to php.ini
Step 3. Put the below code into it
extension = pdo.so
extension = pdo_sqlite.so
extension = sqlite.so
extension = pdo_mysql.so

Step 4. Now refresh your browser cache and the problem has been solved.

A: If your on godaddy hosting account and you can't do anything because of the restriction to main configuration files of the server and you cant restart apache. You can bypass this problem by changing the php version from "Select PHP Version" this way you will restart settings. In my case I tryied to edit php.ini than php5.ini also added .user.ini file and in result of that i got this error:
PDO extension is required for this adapter but the extension is not loaded
Now my problem is solved, this solution can work on other hostings not only godaddy if you are not a system administrator!!!


text:
Q: Problem when reading backslash in Prolog I'm writing a lexer in Prolog which will be used as a part of functional language interpreter. Language spec allows expressions like for example let \x = x + 2; to occur. What I want lexer to do for such input is to "return":
[tokLet, tokLambda, tokVar(x), tokEq, tokVar(x), tokPlus, tokNumber(2), tokSColon]

and the problem is, that Prolog seems to ignore the \ character and "returns" the line written above except for tokLambda.
One approach to solve this would be to somehow add second backslash before/after every occurrence of one in the program code (because everything works fine if I change the original input to let \\x = x + 2;) but I don't really like it.
Any ideas?
EDIT:
If anyone should have similar problems, that's how I solved it:
main(File) :-
  open(File,read,Stream),
  read_stream_to_codes(Stream, Codes),
  lexer(X,Codes,[]),
    ... invoke other methods

A: Where did you get the string let \x = x + 2; from?

*

*If it is in your Prolog program: yes, you have to double the backslashes.

*If it is from an external file: How do you read it from there? Maybe that predicate is interpreting the backslash specially.

I got inspired by that problem and wrote a bit of code, which should be portable to all Prolog implementations:
% readline(-Line)
%
% Reads one line from the current input. The line is then returned as a list
% of one-character atoms, excluding the newline character.
% The returned line doesn't tell you whether the end of input has been reached
% or not.
readline(Line) :-
    'readline:read'([], Reversed),
    reverse(Line, Reversed).

'readline:read'(Current, Out) :-
    get_char(C), 'readline:append'(C, Current, Out).

'readline:append'(-1, Current, Current) :- !.
'readline:append'('\n', Current, Current) :- !.
'readline:append'(C, Current, Line) :-
    'readline:read'([C | Current], Line).

I tried it, and it worked for me.
Of course, as explained in question 1846199, you can also use read_line_to_codes/2.


text:
Q: Tag helper field is encoded wrong Consider the following tag helper (non-relevant parts hidden)
[HtmlTargetElement("*", Attributes = "optional-field-checkbox")]
public class OptionalFieldCheckbox : TagHelper
{
    // [...]

    [HtmlAttributeName("checkbox-label")]
    public string CheckboxLabel { get; set; }

    public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        // [...]
    }
}

with a call to the above tag helper as follows
<div optional-field-checkbox checkbox-label="L'évènement se déroule sur plusieurs jour ?">
    <!-- [...] -->
</div>

When I retrieve the value from the CheckboxLabel property in the ProcessAsync method I get the following, wrongly encoded, string:

L'�v�nement se d�roule-t-il sur plusieurs jour ?

The expected value would be

L'évènement se déroule-t-il sur plusieurs jour ?

I have:

*

*Googled this problem and it seems this is due to double-encoding of the value by the TagHelper, but I couldn't find any solution

*Tried bypassing the encoding by using an HtmlString as the CheckboxLabel's property's type, but it didn't change anything

*Tried using WebUtility.HtmlDecode and WebUtility.UrlDecode to get the original string back, to no avail

How can I get the raw string in the ProcessAsync method and, if it's impossible, how can I encode the string back to its original form ?

A: I think your cshtml razor file was saved with a non-UTF8 encoding.
To change the encoding, click File > Save yourfile.cshtml as... > Save with encoding; then select Unicode (UTF8).
This will probably solve your issue.


text:
Q: Error al enviar una petición Post por Guzzle en laravel 7 Me marca este error al enviar un archivo a una api,
Envió el archivo por POST por medio de la librería guzzle, este es el codigo donde envio el archivo
$client = new Client([

        'base_uri' => 'http://192.168.2.10:8000/api/archivos',

        'timeout'  => 10.0,
    ]);

    $response = $client->request('POST', 'http://192.168.2.10:8000/api/archivos', [
        'multipart' => [
            [
                'name' => '123.pdf',
                'contents' => fopen('archivos/123.pdf', 'r')
            ],
        ]
    ]);

Estoy enviando el archivo fijo pero la intención es enviarlo mediante un request con INSOMNIA.
Este es el error:

Una vez que se pueda enviar el archivo, lo debó recibir en la otra api, pero no se como responder a la petición que realizo, es decir enviar el archivo y después guardarlo en la otra api y por ultimo retornarlo.
Graciass

A: El base_uri es aquello común que tienen tus rutas, usualmente es el dominio. Por ejemplo, si quieres acceder a estas rutas:
https://foo.com/api/clients
https://foo.com/api/workers
^^^^^^^^^^^^^^^^^^^
       base_uri

Como ves, la base es lo que está subrayado ya que es algo común entre esas dos rutas. Por ende crearías el cliente así:
$client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);

Posteriormente, dado que ya tienes la base, sólo te queda añadir la ruta relativa, que será a donde quieres ir:
$response = $client->request('GET', 'clientes'); // https://foo.com/api/clients
$response = $client->request('GET', 'workers');  // https://foo.com/api/workers

En tu caso, tu base_uri es una ruta completa y luego, al hacer la petición, vuelves a poner la misma ruta.
Dada la explicación anterior, tu Guzzle debería quedar de la siguiente manera:
$client = new Client(['base_uri' => 'http://192.168.2.10:8000/api/']);

$response = $client->request('POST', 'archivos', [...]);


text:
Q: Fatal error: require(): Failed opening required '{filename}' While loading my blog, I see the following wrrors on the console and white screen as a result:

Warning:
require(/home/u8070024/public_html/wp-content/themes//css/critical_css.php):
failed to open stream: No such file or directory in
/home/u8070024/public_html/wp-content/themes/azurelo/functions.php on
line 49
Fatal error: require(): Failed opening required
'/home/u8070024/public_html/wp-content/themes//css/critical_css.php'
(include_path='.:/opt/alt/php74/usr/share/pear') in
/home/u8070024/public_html/wp-content/themes/azurelo/functions.php on
line 49

So I can't acces my blog...
how to solve this problem?.
please somebody help me:(
[

A: As @scunlife mentioned, you have // where you should have / and to avoid these kind of issues, you might use this function: https://stackoverflow.com/a/15575293/3735825
And replace the reuired with the joined path from the function mentioned above.


text:
Q: Jasper Reports : How to suppress a footer completely after 1st page I have designed a jasper report in iReports. My requirement is to show the footer only on the first page. I have put a boolean condition on the footer band to show it only on the 1st page but still after doing this, footer section takes a blank space in each page.
How to suppress a footer completely after 1st page ???
BR
Majid

A: you can use printWhenExpression , and evaluate to true when pageCount = 1 , pageCount is an implicit parameter available in jasperreport.

A: U can Use printWhenExpression attribute. This would print the elements only if its evaluated to true and u can use pageCount expression here


text:
Q: docker compose inside docker causes error I am working in a task where I am having to use docker compose inside a docker container. When I perform docker compose --file setup.yaml, I get the following error.

no valid drivers found: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Is there a way to resolve this error?
What I have tried:
I looked at a few documentation on the internet and I am performing a volume mount of the path to socket daemon as follows,
 docker run -v /var/run/docker.sock:/var/run/docker.sock -it -d <container_id>

But after this command, the container exits after a while. Not sure if the approach is correct.


text:
Q: Unable to find element using Xpath and CSS I am unable to find Element using XPATH and CSS
Using firefox i am executing the code, i have tried every method for finding the element mentioned here but always i get the error mentioned below.

1500539792269 geckodriver INFO    geckodriver 0.18.0
  1500539792279 geckodriver INFO    Listening on 127.0.0.1:18947
  1500539793062 geckodriver::marionette INFO    Starting browser C:\Program
  Files (x86)\Mozilla Firefox\firefox.exe with args ["-marionette"]
  1500539798479 Marionette  INFO    Listening on port 64608 Jul 20, 2017
  2:06:39 PM org.openqa.selenium.remote.ProtocolHandshake createSession
  INFO: Detected dialect: W3C JavaScript warning:
  https://login-qa.ihg.com/forms/iam/responsiveV3/js/jquery.min.js, line
  1: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use
  //# instead Exception in thread "main"
  org.openqa.selenium.NoSuchElementException: Unable to locate element:
  sidebar-button For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html Build info:
  version: 'unknown', revision: 'unknown', time: 'unknown'

Code:
driver.findElement(By.id("sidebar-button")).click();
Thread.sleep(2000);
Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath("//*[@id='reservations']/a"));
action.moveToElement(we).build().perform();

Please help me out in resolving this problem

A: Give some wait time before  driver.findElement(By.id("sidebar-button")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("sidebar-button")));

as you got 'NoSuchElementException' for first line


text:
Q: Drools Database I am developing a rating system based on Drool Rules to replace a old one made with ASP and a relational DB.
Everything is running very good as expected, but  some rules become very extensive because the rating system needs to compare a lot of constant values with the input - I do not want to back to the solution of using an external database.
A this moment, there is some standard data structure that should be use to persist lot of constant values? I know it is possible to construct a Java structure for that ... but my objective is to give the rules file to the sales team, who barely understand Java but they are very good with ratios.
For example, I want to replace this with something more clean:
if("A".equals($inpt)) { $outpt = 0.1; }
else if("B".equals($inpt)) { $outpt = 0.2; }
else if("C".equals($inpt)) { $outpt = 0.3; }

A: I'll have to guess a little. Let's say you have
rule "set output"
when
    $s: Something(  $input: input )
    InToOut( input == $input, $output: output )
then
    modify( $s ){ setOutput( $output ) }
end

Your sales team members will surely understand if you give them the skeleton
rule "setInToOut"
salience 999999999
when
then
    insert( new InToOut( "A", 0.1 ) );
    insert( new InToOut( "B", 0.2 ) );
     ...
end

You can simplify this with a function.


text:
Q: view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.
from flask import Flask, jsonify, request
from pytube import YouTube
app = Flask(__name__)

@app.route('/youtube', methods=['POST'])
def hello_world():
    url = request.form['d_url']
    yt_video = YouTube(url)
    videos = yt_video.streams
    res_list = list(enumerate(videos))
    return res_list

if __name__ == "__main__":
    app.run(debug =True)

A: you cannot return a list directly from flask.view you have to convert it to json object.
Apparently directly using jsonify from Flask did not as it could not serialize the Stream object in res_list. When doing jsonify(res_list) I got the following error:
TypeError: Object of type Stream is not JSON serializable

Using jsonpickle did the job. Below code is working:
from flask import Flask, jsonify, request
from pytube import YouTube
import jsonpickle

app = Flask(__name__)

@app.route('/youtube', methods=['POST'])
def hello_world():
    url = request.form['d_url'] #'http://youtube.com/watch?v=9bZkp7q19f0'
    yt_video = YouTube(url)
    videos = yt_video.streams
    res_list = list(enumerate(videos))
    return jsonpickle.encode(res_list)

if __name__ == "__main__":
    app.run(debug =True)