text:
Q: Execute multiple php scripts with multiple callbacks Actually i have 10 php scripts (getlatest_t_s2.php, getlatest_h_s3.php...) and execute them in 10 separate javascripts and get an id from the callback function. Let's see what i mean.
HTML
Temperature

JS
var scriptToExecute="getlatest_t_s2.php";//php script

//any data that you might want to send to the php script.
var data ='anyData';

//call ajax function
makeAjaxRequest(scriptToExecute,data,callBack);
function callBack(data){
    $('#last_temp_s2').html(data);
}

function makeAjaxRequest(url,data,_callBack,_failure){
    $.ajax({
        url: '../php/',
        datatype:"php",
        type:'get',
        data: data,
        success:function(data){
            _callBack(data);
        },
        error:function(jqXHR, textStatus, errorThrown){
            if(!_failure){
                console.log(errorThrown);
            }
            else
            {
                _failure(jqXHR,textStatus,errorThrown);
            }
        }
    });
}

So my question is, instead of executing 10 different javascripts for each php-script, is it possible to just execute one javascript or at least less than 10?

A: What I'd suggest is to create one well-structured PHP file in which, you would process all the data into an array, then send that array (json encode($array)) to your JS, which could then handle all the JSON.
The fact that you'd send 10 request to possibly 10 line files creates alot of serverload if alot of people are visiting your website, thus one file will greatly optimize your website loading speed, this is good for SEO as well as your visitors, who won't have to wait 1, possible 2 seconds for the response from the server.
Modern browsers all have native methods to parse JSON, so does jQuery so you should be fine on processing the JSON data via JS by any means.
Credits Guilherme Sehn already pointed this out to make it clear.


text:
Q: Angular(4) router does not replace routes rather stacks them up when called from inside Google API load callback I am trying to use Google Authentication in my Angular 4 app. I loaded Google platform.js and api.js in index.html. Now onClick login button I do
gapi.load('auth2', () => {
  this.router.navigateByUrl('/home');
});

Now instead of replacing the previous route, Angular is stacking the new route over the old route (/login). I can see from web console that both my Login and Home components are present as below,
<app>
    <router-outlet><router-outlet>
    <home></home>
    <login></login>
</app>

Home is supposed to replace Login, but that didn't happen. Can anyone offer some help here?

A: Gapi client library does not go well with Angular, I used Rest API calls instead. That solved the issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoid overwriting of hostname by transient hostname at reboot My server is CentOS 7.1. After reboot the hostname is overwritten by the transient hostname (mail) and I can't find a way to avoid that.
Maybe AutoDNS and the MX record mail causes that?

*

*/etc/hostname contains the correct value

*hostnamectl --transient set-hostname my.desired.name is working but only until next reboot

So, after reboot:

*

*hostnamectl status shows the correct static hostname but the wrong transient hostname (mail).

*hostname -s or hostname -f shows the wrong hostname.

The file /etc/sysconfig/network is overwritten "by anaconda" and has the line HOSTNAME="mail". I tried to edit this file to configure the correct name but it's overwritten after reboot.
How can I prevent the transient hostname being set to mail after restarting?

EDIT:
I already tried to add DHCP_HOSTNAME="my.desired.name" to my /etc/sysconfig/network-scripts/ifcfg-e..... but with no success (line was removed after reboot).
And I tried to add execution of hostnamectl set-hostname "" --transient (which will set the transient to the value of static hostname) at reboot which failed either with activated /etc/rc.local and also as a service with chkconfig on (with # chkconfig: - 11 91 so that it should run after all other services).
Any further suggestions are welcome.

A: The transient hostname is initialised at startup to the static host name but it can be changed by DHCP or mDNS.
DHCP
If you're using DHCP, you should check that the wrong hostname hasn't been set in the configuration for your network device. Run ip addr show to check
which network device you're using. Then edit the appropriate configuration
script. E.g. if your network interface is eth0, you should edit its configuration file, /etc/sysconfig/network-scripts/ifcfg-eth0.
From Red Hat documentation on Configuring a Network Interface Using ifcfg
Files, there's an option to

configure an interface to send a different host name to the DHCP server.

DHCP_HOSTNAME=hostname

Check to make sure that your system doesn't have the hostname mail
configured in this script.
If that's not the issue you'll need to check that the local DHCP server isn't configured to set the hostname as mail. If you have a network administrator, who has configured your host as mail in the DNS / DHCP for a Local Area Network, you should talk to them. The best practice is to configure hosts with non-role based names and then to configure DNS CNAMES as aliases for the relevant servers.
If DHCP is the source of your problems and the above suggestions don't help, the other option would be to configure your network interface to use static IP addresses.

A: I know it's been a while but for anyone who's looking for an answer as to why it happens: Some providers (ISP, Company VPNs, etc) send a "Transient hostname" back to the host whenever making a request for an IP via DHCP, and depending on your machine's configuration, it gets set as the current machine's hostname
My problem (and the way I ended up here) was that I had the hostname set as the default localhost and according to the hostnamectl man page:

This tool distinguishes three different hostnames: the high-level "pretty" hostname which might include all kinds of special characters (e.g. "Lennart's Laptop"), the static hostname which is used to initialize the kernel hostname at boot (e.g. "lennarts-laptop"), and the transient hostname which is a default received from network configuration. If a static hostname is set, and is valid (something other than localhost), then the transient hostname is not used.

So a solution would be not to have the hostname set as localhost
Another solution is to make your dhcp configuration in /etc/dhcp/dhclient.conf not to request for a hostname by removing the host-name (and perhaps the domain-name) from the request property

A: Finally I got it.

Our Hosting Provider (Host Europe) has an option in the Controlpanel for each server (virtual root server). On the page "Hostname / RDNS" there is an input field "Hostname:". I changed it to the correct value and now it works as expected.

A: $ vi /etc/sysconfig/network-scripts/ifcfg-eth0

$ vi /etc/sysconfig/network

HOSTNAME="hostname<FQDN>"
DHCP_HOSTNAME="hostname<FQDN>"

$ vi /etc/rc.local

#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local
hostnamectl --transient set-hostname "hostname"

#exit vi <:wq>

$ chmod +x /etc/rc.d/rc.local <This will make the file unchanged even after reboot>

$ Reboot

*You are ready to go the Cpanel installation for CentOS7 :)*


text:
Q: Monitor connected through USB-C dock not detected I have an HP Pavilion 14-dv0000sl, which has a USB-C w/ SuperSpeed and DP1.4 output (confirmed through the manual, and the USB-C port itself having the SuperSpeed and DP/thunder icon). I have bought a USB-C dock with two HDMI outputs so I can connect two monitors to the laptop. I have tested the dock on another laptop I own (Legion Y540, which also has a USB-C w/ DP1.2 output support) and the dock works on Windows 11 correctly.
Here on Ubuntu 20.04, I cannot manage to get it working for video: if I plug it with a USB wireless dongle of my mouse and the HDMI of a monitor, the mouse works while the monitor doesn't (also the laptop produces some weird electric sound when the dock is plugged in, which is troubling, but didn't do so on the W11 laptop).
I have tried:

*

*Installing NVIDIA drivers (which admittedly didn't manage to, ended up black screening and having to remove them from root recovery)

*Blocking nouveau so the laptop would only use Intel graphics (didn't change anything)

*Waking the DP ports listed as disconnected with xrandr -d :0 --output DP-1 --auto
Nothing worked so far.
Here are some additional informations:
 ~ ❯ sudo inxi -F
System:    Host: croissant Kernel: 5.13.0-39-generic x86_64 bits: 64 Desktop: Gnome 3.36.9
           Distro: Ubuntu 20.04.4 LTS (Focal Fossa)
Machine:   Type: Laptop System: HP product: HP Pavilion Laptop 14-dv0xxx v:
Graphics:  Device-1: Intel driver: i915 v: kernel
           Device-2: NVIDIA driver: N/A
           Display: server: X.Org 1.20.13 driver: modesetting,nouveau unloaded: fbdev,vesa
           resolution: 1920x1080~60Hz
           OpenGL: renderer: Mesa Intel Xe Graphics (TGL GT2) v: 4.6 Mesa 21.2.6

~ ❯ xrandr
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 309mm x 174mm
HDMI-1 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
DP-2 disconnected (normal left inverted right x axis y axis)
DP-3 disconnected (normal left inverted right x axis y axis)
DP-4 disconnected (normal left inverted right x axis y axis)

 ~ ❯  sudo lshw -c video
  *-display
       description: VGA compatible controller
       product: Intel Corporation
       vendor: Intel Corporation
       physical id: 2
       bus info: pci@0000:00:02.0
       version: 01
       width: 64 bits
       clock: 33MHz
       capabilities: pciexpress msi pm vga_controller bus_master cap_list
       configuration: driver=i915 latency=0
       resources: irq:149 memory:56000000-56ffffff memory:60000000-6fffffff ioport:5000(size=64) memory:c0000-dffff memory:59000000-5fffffff
  *-display UNCLAIMED
       description: 3D controller
       product: NVIDIA Corporation
       vendor: NVIDIA Corporation
       physical id: 0
       bus info: pci@0000:01:00.0
       version: a1
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list
       configuration: latency=0
       resources: memory:57000000-57ffffff memory:40000000-4fffffff memory:50000000-51ffffff ioport:4000(size=128)

~ ❯ lspci -k | grep -EA3 'VGA|3D|Display'
0000:00:02.0 VGA compatible controller: Intel Corporation Device 9a49 (rev 01)
    DeviceName: Intel Tigerlake UHD Graphics
    Subsystem: Hewlett-Packard Company Device 884e
    Kernel driver in use: i915
--
0000:01:00.0 3D controller: NVIDIA Corporation Device 1f97 (rev a1)
    Subsystem: Hewlett-Packard Company Device 884e
    Kernel modules: nvidiafb, nouveau
0000:02:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS522A PCI Express Card Reader (rev 01)

EDIT: I've jumped through numerous hoops trying to get the NVIDIA drivers to work on my machine and see whether video through USB-C would work afterwards, but I failed.
I've tried:

*

*Installing from Additional Driver -> Black screen after GRUB

*Installing either the normal version or the server version of the recommended driver from command line -> Black screen

*Using nvidia-prime, setting options nvidia-drm modeset=1, adding nomodeset kernel parameter, just working through an innumerable amount of questions on this issue

While searching around, although not sure about it, I found that the issue might be related to LUKS encryption of my disk with the NVIDIA drivers, such as this bug and this one. I'm giving up for the time being on being able to use the dock on Ubuntu, sadly.


text:
Q: Vaadin и InlineDateField. Как отловить событие смены отображаемого месяца/года? Необходимо для компонента Vaadin InlineDateField http://demo.vaadin.com/sampler#DateInline обрабатывать событие смены отображаемого месяца/года, без смены даты (событие valueChange не возникает). У компонента средств для этого не нашёл.
Единственный способ, который приходит в голову - поменять клиентскую реализацию на свою. Как это сделать?
A: Вспомнил, что задавал здесь вопрос. Ответ нашёл, может, кому-то пригодится.
Как я и думал, решение оказалось простым. Есть расширенный компонент StyleCalendar.
Он передаёт события, связанные с перерисовкой календаря (смена месяца/года). Так что самому с клиентской реализацией заморачиваться не пришлось.


text:
Q: Localization testing, formatting all strings with XXXXX We are trying to look at optimizing our localization testing.
Our QA group had a suggestion of a special mode to force all strings from the resources to be entirely contained of X. We already API hijack LoadString, and the MFC implementation of it, so doing it should not be a major hurdle.
My question is how would you solve the formatting issues?
Examples -

CString str ;
str . LoadString ( IDS_MYSTRING ) ;

where IDS_MYSTRING is "Hello World", should return "XXXXX XXXXX"
where IDS_MYSTRING is "Hello\nWorld", should return "XXXXX\nXXXXX"
where IDS_MYSTRING is "Hello%dWorld", should return "XXXXX%dXXXXX"
where IDS_MYSTRING is "Hello%.2fWorld", should return "XXXXX%.2fXXXXX"
where IDS_MYSTRING is "Hello%%World", should return "XXXXX%%XXXXX"

So in summary the string should work if used in a printf or Format statement, it should honor escape characters.
So this is a pure code question, C++/MFC,
CString ConvertStringToXXXX ( const CString& aSource )
{
   CString lResult = aSource ;

   // Insert your code here

   return lResult ;
}

I know this could be done using tools on the .RC files, but we want to build English, then run like so -
application -L10NTEST

A: If this approach is to highlight formatted strings (or format sequences) in the application (i.e. all text appearing other than XXXX), you could locate the escape sequence (using regex perhaps) and insert block quotes around the formatted (substituted) values, e.g. Some\ntext -> Some[\n]text
You get readability (all strings as XXX might be hard to use the application) and also get to detect non-resource (hardcoded) strings.
Having said that, if you're looking to detect non resource loaded strings (hardcoded strings), instead of substituting Xs, why not just prefix the string?  You'll easily be able to tell resource loaded strings from hardcoded strings easily,
e.g. Some\ntext -> [EN]Some\ntext
Hope it helps?

A: The pseudo-localisation feature of appTranslator can help you there: It modifies untranslated strings to use diacritics, text widening or shortening and such. So far, you're not interested. Where it becomes interesting is that it optionally encloses such strings in brackets. The idea was to make it more obvious that a string is pseudo localized. You could use this to detect that the string actually comes from the string table rather than code.
And of course, since the pseudo-localized program must run properly, appTranslator preserves all formatters (including printf-like and FormatMessage-like formatters) and special chars such as % or \n. Which is what you're looking for.
You wouldn't even have to modify your code: Simply create a 'dummy' translation. By 'dummy', I mean a language into which you don't plan to translate your app. Set the language preference of your app to that language.
Wait, it's even better: The guys at QA can do it entirely on their own. They dont even have to bother you! :-)
Disclaimer: I'm the author of appTranslator.
Edit: answer to your comment:
Glad to read you already use appTranslator.
To avoid problems due to dialogs or strings not in the L10N DLL, you can simply re-build the DLLs (e.g. using a post-link step in your VS project). The process automatically re-scans the source exe and merges new and modified texts in the built resource dlls (doesn't affect the appTranslator project file, as opposed to 'Update Source'). This helps make sure your resource DLLs are always in sync with your exe.

A: You can apply compiler theory here and generate your scanner and parser using flex/bison (lex/yacc, or whatever tools). You can define \w+ as word, which can match both "Hello" and "World" etc..

A: I think what you need is an XXXX locale, if your software supports locales.
You develop it in English, then switch to the XXXX locale to make sure everything is translatable.

A: My final solution was prefixing the string like so "*[resource instance name]original string". It works really well, it shows likely strings that will not fit in say German.
Example:
Original string from appres.dll, "My Application"
New string from appres.dll, "*[appres]My Application".
Thanks for all the suggestions.

A: I prefer a mechanism that we used when I was at Microsoft for pseudo-localization, which involved putting braces around each localized resource. Resource => [-Resource-], for example. Then you can always tell you have a composed string, and formatting doesn't usually change, barring line breaking rules.
We also usually did some string expansion (add various characters around the original string), and some dictionary- or randomization-based character substition (convert "o" to "ö").
Some teams also put the literal resource identifier (the name) as the value of the localized resource, which was more useful for localizers than for testers, because they could see where the resource was actually used in the UI.


text:
Q: vs2019 C# console app does not run as expected Visual Studio 2019 is not creating and executing a console app like previous versions of VS.
If I open a new project, put this code in Main():
        Console.WriteLine("hello");
        Console.ReadKey();

and hit F5, the app appears to run, then exit with code 0. The console doesn't wait for a key input to close, and breakpoints in the source do not hit.
The EXE should be in this folder
    c:\projects\test-app\bin\debug\
but it is actually in:
    c:\projects\test-app\bin\debug\netcoreapp3.0
and when I run it from that location outside the IDE it opens a console and immediately closes it, apparently not running the code in Main().
Going through the exact same steps with Visual Studio 2017 runs the app as expected.
I can live with the final exe being located to a different folder but VS2019 doesn't even seem to be running any of my code. Am I missing something?


text:
Q: Simulation results structured for csv-compare Is there a function or an open-source library to generate simulation results of a tested Modelica library (test library) in csv format and structured to be directly suitable for csv-compare?
(https://github.com/modelica-tools/csv-compare)
So the function/library shall simulate all simulatable models (examples) of the test library and generate csv results structured according to the class tree (package structure) of test library. The generated results shall be processable by (not part of the function/library)
compare.exe --mode csvTreeCompare ...

P.S. I have not sufficient reputation to add a tag like "csv-compare". :-(

A: There is OpenModelicaLibraryTesting which generates library coverage results for OpenModelica.
It can take Modelica libraries and will compile, simulate and compare against reference files and generates HTML pages.
So for the Modelica Standard Library the tool uses reference results from https://github.com/modelica/MAP-LIB_ReferenceResults in mat format, but it can also handle CSV results.
If I remember correctly the compare results API function from OpenModelica used in the scripts of OpenModelicaLibraryTesting uses csv-compare in some form.

Maybe this is a bit more than you need. You can also write your own MOS / Python / Julia script and use diffSimulationResults.


text:
Q: Android How do I use the same native library (.so) for multiple projects and classes? I am making a android project with some native code . running javah results in header files which contain function prototypes with fully qualified java class name in their names. I assume this means that those functions and headers are generated to be called only by the java class which was used to create them using javah.
How do I go on making a native lib that I can use with other classes as well as other projects. Like say I made a library that has a function that I want to use in all my projects then how would I build it so that I can use just the .so file each time without recompiling it for the project. I think we call this dynamic library?
Is it possible? or do I have to create seperate jni headers for each class and then reuse the remaining c/c++ code?

A: if you want to reuse your native library from various Java projects, you should directly bundle your native library with a Java class that is independent from your initial project.
This way you'll be able to distribute it as an Android Library Project, and use it from your various classes and projects.


text:
Q: css background fixed fails after resizing window I have spent few hours of trying to make background fixed and in the center. I hope you could show where I made silly mistakes.
My code
#main_inside{
        float:right;
        margin-top:223px;
        width:700px;
        background:url("images/gidas.png") no-repeat fixed 496px 259px transparent;
        margin-bottom: 86px;
    }

The problem is when I re-size window with crtl + scroll. The image gets away.
I have also tried:
background-position:center;

and tried this:
background-origin:content-box;

and tried using % to set image distance.
Real problem URL http://lyderiai.net/tg2013/gidas.php

A: When you use "fixed" you are making the image fixed to the viewport of the website (a.k.a the window), so for example if you set it to "background-position: left 0" it won't take the div left postion, but the window left position.
So that's why when you resize your window, the image will move.


text:
Q: Связь многие ко многим Code-First Всем привет друзья. Реализую связь через промежуточную таблица.
Таблица Event и Car имеют результирующую таблицу Result
Вроде бы все работает да это и странно, подскажите друзья. Я правильно реализовал связь?
  using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace BaseModels
{
    public class BaseModelInfo
    {
       [Key]
        public int Id { get; set; }

        [Required]
        [MaxLength(100)]
        public string Name { get; set; }

    }

    public class User : BaseModelInfo
    {
        //Много
        public virtual ICollection<Car> Cars { get; set; }

    }

    public class Car : BaseModelInfo
    {
        //одын
        public virtual User Users { get; set; }
        public virtual Car Cars { get; set; }

        public virtual Result Results { get; set; }

        //public int? ResultId { get; set; }
        //***
        //***
        //public int User_id { get; set; }
        public virtual ICollection<Event> Events { get; set; }

    }

    public class Event :BaseModelInfo
    {
        public DateTime DateE { get; set; }
        //public DateTime DateEvent { get; set; }
        //public int Car_id { get; set; }
        //
        // public int? ResultId { get; set; }
        public virtual Result Results { get; set; }

       // public int? CarId { get; set; }
        public virtual Car Cars { get; set; }

    }

    public class Result : BaseModelInfo
    {
        public DateTime DateR { get; set; }
        public virtual ICollection<Car> Cars { get; set; }
        public virtual ICollection<Event> Events { get; set; }
    }

}


text:
Q: CSS aligned rows without wrapper div This is what I have:

and this is what I want:

I have a container div around all of the smaller divs, and the smaller divs are floated left. How can I get them to align in perfect rows like the bottom image? This would be easy but the catch is I don't want to use a container div for each row since I want the number of images per row to be fluid (container width is variable). Is this even possible without JS hacks?

A: You could just change the float:left to display:inline-block. That will lay the images out in rows, just like text layout, which sounds like what you want to do.

A: I post this with some apprehension because I don't know what you qualify as a Javascript hack... There is a plug-in that would work well for this, Masonry JS. But if you consider a plug-in a hack then I would suggest applying a display:inline-block; to the elements that you want in a line and removing the float:left; property.


text:
Q: django factory boy test gives __str__ returned non-string I'm adjusting tests to use factory boy instances instead of models.objects.create(..)
It's going well, but now I've run into an error and I can't seem to find the source. Can anyone help?
models.py
class Regelset(models.Model):  # todo: statussen?
    # todo: koppeling productiebestanden
    # todo: xml inlezen

    bon = models.ForeignKey(Bon)
    toepassing = models.ForeignKey(Toepassing)
    product = models.ForeignKey(Product)

    naam = models.CharField(max_length=500, blank=True, help_text="naam")
    originelen = models.DecimalField(max_digits=20, decimal_places=0, null=True, blank=True, help_text="originelen")
    oplage = models.DecimalField(max_digits=20, decimal_places=0, null=True, blank=True, help_text="oplage")

    breedte_in_cm = models.DecimalField(max_digits=20, decimal_places=3, null=True, blank=True,
                                        help_text="breedte in cm")
    hoogte_in_cm = models.DecimalField(max_digits=20, decimal_places=3, null=True, blank=True, help_text="hoogte in cm")

    # bedoeld om een extra formaat door te geven (bedoeld voor Repro items)
    breedte_in_cm2 = models.DecimalField(max_digits=20, decimal_places=3, null=True, blank=True,
                                         help_text="breedte in cm")
    hoogte_in_cm2 = models.DecimalField(max_digits=20, decimal_places=3, null=True, blank=True,
                                        help_text="hoogte in cm")

    strekkende_meters = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True)
    korting = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True)
    korting_invoer = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True, help_text="korting")
    type_korting = models.CharField(max_length=50, choices=MenusGlobals.type_korting_choices, blank=True,
                                    help_text="type korting")
    # nesting is een samengesteld veld van de printregel en mediaregel wat gezet wordt. Queries gaan niet over een
    # berekend veld
    nesting = models.CharField(max_length=500, blank=True)

    omslag_dubbelzijdig = models.BooleanField(help_text="omslag dubbelzijdig", default=False)
    binnenwerk_dubbelzijdig = models.BooleanField(help_text="binnenwerk dubbelzijdig", default=False)
    binnenwerk_kleur = models.BooleanField(help_text="binnenwerk kleur", default=False)
    omslag_kleur = models.BooleanField(help_text="omslag kleur", default=False)

    def __str__(self):
        return self.naam

    def get_verkoopprijs_ex_kort(self):
        return self.sum_gerelateerde_regelwaardes('verkoopprijs_ex_kort')

    def get_verkoopprijs_ex_kort_incl_productprijs(self):
        return self.sum_gerelateerde_regelwaardes('verkoopprijs_ex_kort_incl_productprijs')

    def get_verkoopprijs_incl_kort(self):
        return self.sum_gerelateerde_regelwaardes('verkoopprijs_incl_kort')

    def get_basisprijs(self):
        return self.sum_gerelateerde_regelwaardes('basisprijs')

    def get_korting(self):
        return self.sum_gerelateerde_regelwaardes('korting')

    def get_aantal(self):
        return self.originelen * self.oplage

    def get_oppervlakte_m2_per_stuk(self):
        if self.toepassing.afmeting_verplicht():
            return self.breedte_in_cm / 100 * self.hoogte_in_cm / 100
        return 0

    def sum_gerelateerde_regelwaardes(self, fieldname):
        # ondersteunende functie om alle getallen vanuit een veld uit de regel tabel bij elkaar op te tellen
        waardelijst = self.regel_set.all().aggregate(models.Sum(fieldname))  # output = {'<fieldname>_sum': waarde}
        return invoer_is_check_is_value(waardelijst.get('{0}__sum'.format(fieldname)), check=None, value=0)

Factories.py
import factory
from . import models

class ArtikelFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Artikel

class ToepassingFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Toepassing

class ToepassingRegelFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.ToepassingsRegel

    toepassing = factory.SubFactory(ToepassingFactory)

class ProductFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Product

    toepassing = factory.SubFactory(ToepassingFactory)

class RelatieFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Relatie

    firmanaam = "Nepper"
    code = "neppe"

class ProjectFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Project

    relatie = factory.SubFactory(RelatieFactory)

class BonFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Bon

    project = factory.SubFactory(ProjectFactory)

class RegelsetFactory(factory.DjangoModelFactory):
    class Meta:
        model = models.Regelset

    bon = factory.SubFactory(BonFactory)
    product = factory.SubFactory(ProductFactory)
    naam = "naam"
    get_oppervlakte_m2_per_stuk = factory.PostGenerationMethodCall('get_oppervlakte_m2_per_stuk')
    get_aantal = factory.PostGenerationMethodCall('get_aantal')

Tests.py
from django.test import TestCase

from decimal import Decimal

from .nesting import Nesting, FormaatError
from .import factories

class NestingTests(TestCase):
    def setUp(self):
        self.regelsetlijst = [factories.RegelsetFactory.create(naam="naam", originelen=1, oplage=3, breedte_in_cm=50, hoogte_in_cm=50),
                              factories.RegelsetFactory.create(naam="naam", originelen=1, oplage=1, breedte_in_cm=50, hoogte_in_cm=200),
                              factories.RegelsetFactory.create(naam="naam", originelen=1, oplage=1, breedte_in_cm=100, hoogte_in_cm=100)]

    def test_get_nesting_1_vel(self):
        self.assertEqual(Nesting(self.regelsetlijst, 1.37, 50, 0.5, maak_html=False).start_nesting(), (round(Decimal(3.52), 2), round(Decimal(2.75), 2)))

    def test_get_nesting_formaaterror(self):
        self.assertEqual(Nesting(self.regelsetlijst, 1.37, 2.5, 0.5, maak_html=False).start_nesting(), FormaatError)

    def test_get_nesting_2_vel(self):
        self.assertEqual(Nesting(self.regelsetlijst, 1.37, 3, 0.5, maak_html=False).start_nesting(), (round(Decimal(4.51), 2), round(Decimal(2.75), 2)))

Traceback:
Error
Traceback (most recent call last):
  File "C:\Users\SjoerdvanPoelgeest\Desktop\systeem\calculator\test_nesting.py", line 11, in setUp
    self.regelsetlijst = [factories.RegelsetFactory.create(naam="naam", originelen=1, oplage=3, breedte_in_cm=50, hoogte_in_cm=50),
  File "C:\Python34\lib\site-packages\factory\base.py", line 558, in create
    attrs = cls.attributes(create=True, extra=kwargs)
  File "C:\Python34\lib\site-packages\factory\base.py", line 400, in attributes
    force_sequence=force_sequence,
  File "C:\Python34\lib\site-packages\factory\containers.py", line 228, in build
    return stub.__fill__()
  File "C:\Python34\lib\site-packages\factory\containers.py", line 83, in __fill__
    res[attr] = getattr(self, attr)
  File "C:\Python34\lib\site-packages\factory\containers.py", line 105, in __getattr__
    val = val.evaluate(self, self.__containers)
  File "C:\Python34\lib\site-packages\factory\containers.py", line 160, in evaluate
    containers=containers,
  File "C:\Python34\lib\site-packages\factory\declarations.py", line 298, in evaluate
    return self.generate(sequence, obj, create, defaults)
  File "C:\Python34\lib\site-packages\factory\declarations.py", line 385, in generate
    return subfactory.simple_generate(create, **params)
  File "C:\Python34\lib\site-packages\factory\base.py", line 645, in simple_generate
    return cls.generate(strategy, **kwargs)
  File "C:\Python34\lib\site-packages\factory\base.py", line 612, in generate
    return action(**kwargs)
  File "C:\Python34\lib\site-packages\factory\base.py", line 558, in create
    attrs = cls.attributes(create=True, extra=kwargs)
  File "C:\Python34\lib\site-packages\factory\base.py", line 400, in attributes
    force_sequence=force_sequence,
  File "C:\Python34\lib\site-packages\factory\containers.py", line 228, in build
    return stub.__fill__()
  File "C:\Python34\lib\site-packages\factory\containers.py", line 85, in __fill__
    self.__log_ctx, utils.log_pprint(kwargs=res),
  File "C:\Python34\lib\site-packages\factory\utils.py", line 119, in log_pprint
    for key, value in kwargs.items()
  File "C:\Python34\lib\site-packages\factory\utils.py", line 119, in <listcomp>
    for key, value in kwargs.items()
  File "C:\Python34\lib\site-packages\factory\utils.py", line 103, in _safe_repr
    obj_repr = repr(obj)
  File "C:\Python34\lib\site-packages\django\db\models\base.py", line 496, in __repr__
    u = six.text_type(self)
TypeError: __str__ returned non-string (type NoneType)

A: try
def __str__(self):
    return '%s' % self.naam


text:
Q: JavaScript Fetch API JSON data inside a variable? JS newbie here. I would like to store the JSON data from an API call inside a variable in my .fetch method.
Here is my current code:
// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => console.log(data))

The data is being logged in the console succesfully, but I would like for them to be saved inside the database array.
Any idea how I would go about that?
Thank you all so much!

A: Sure, have your code changed to the following:
// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => {
    database.push(data)
    console.log(database)
})

I hope this solves your problem.

A: As fetch call is async database will always be [] till the api call is resolved in case you plan to assign data to database.
You can use Callbacks, Promises or async-await for dealing with async calls
Reference link - https://dmitripavlutin.com/javascript-fetch-async-await/


text:
Q: mock boto3 response for downloading file from S3 I've got code that downloads a file from an S3 bucket using boto3.
# foo.py
def dl(src_f, dest_f):
  s3 = boto3.resource('s3')
  s3.Bucket('mybucket').download_file(src_f, dest_f)

I'd now like to write a unit test for dl() using pytest and by mocking the interaction with AWS using the stubber available in botocore.
@pytest.fixture
def s3_client():
    yield boto3.client("s3")

from foo import dl
def test_dl(s3_client):

  with Stubber(s3_client) as stubber:
    params = {"Bucket": ANY, "Key": ANY}
    response = {"Body": "lorem"}
    stubber.add_response(SOME_OBJ, response, params)
    dl('bucket_file.txt', 'tmp/bucket_file.txt')
    assert os.path.isfile('tmp/bucket_file.txt')

I'm not sure about the right approach for this. How do I add bucket_file.txt to the stubbed reponse? What object do I need to add_response() to (shown as SOME_OBJ)?

A: Have you considered using moto3?
Your code could look the same way as it is right now:
# foo.py
def dl(src_f, dest_f):
  s3 = boto3.resource('s3')
  s3.Bucket('mybucket').download_file(src_f, dest_f)

and the test:
import boto3
import os
from moto import mock_s3

@mock_s3
def test_dl():
    s3 = boto3.client('s3', region_name='us-east-1')
    # We need to create the bucket since this is all in Moto's 'virtual' AWS account
    s3.create_bucket(Bucket='mybucket')

    s3.put_object(Bucket='mybucket', Key= 'bucket_file.txt', Body='')
    dl('bucket_file.txt', 'bucket_file.txt')

    assert os.path.isfile('bucket_file.txt')

The intention of the code becomes a bit more obvious since you simply work with s3 as usual, except for there is no real s3 behind the method calls.


text:
Q: About how to upload PDF file and show it I can't figure out how to do like this page http://service.citroen.com/ddb/modeles/c5/c5_c5/ed10-07/de_de/4_21_c5-al-ed10-2007.pdf I embed usually the PDF from slideside in my site but people cant dowload from because they need to have an accoount. So technically how ? Thanks

A: You will need a PDF viewer component for displaying the PDF. You will have to configure the PDF component so as to limit download and print options.

http://www.gnostice.com/nl_article.asp?id=329&t=Display_PDF_without_saving_file_to_disk_in_WinForms_and_ASP_NET


text:
Q: Can my Connected App be forced to use the stored redirect_uri? I would like to use the Amazon Alexa voice service to create a voice interface for Salesforce. But I've run into problems.
I am reading here:
http://blog.enree.co/2015/12/salesforce-amazon-echo-integrate-alexa.html
and I read:
"unfortunately when linking accounts Amazon's Alexa Skills page doesn't sends to the login page the redirect_uri parameter that is mandatory for successfull Salesforce OAuth process completion."
There might be a variable name conflict, since both SalesForce and Amazon use "redirect_uri" in the URLs they use as part of their Oauth process.
On the Amazon side, I believe I've done all I can to set this up.
I've gone to my Developer Portal:
https://developer.amazon.com/edw/home.html#/skill/amzn1.echo-sdk-ams.app.b9ae614ad/info
(Obfuscated for security)
Under "Account Linking or Creation", under "Domain List", I whitelisted this domain:
salesforce.com
If I take my iPhone and open the Alexa app, I can search for my skill, find it, and then I click "Enable".
Under "Authorization URL" I put:
https://alexa.salesvoiceapp.com/auth
(You might ask, why don't I go point straight to Salesforce? Well, I was hoping to harvest the Amazon user_id, so I went to my own server first. This was a failed idea.)
I've set this to "Implicit Grant".
When the user arrives on my server I harvest the Amazon user_id and then redirect to Salesforce:
https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=URAx31ViKQovfPPXrCvi9CAfzsJJ8AtoACYEWqeB_IMxBQ&redirect_uri=https%3A%2F%2Falexa.salesvoiceapp.com%2Fauth-callback&state=
And then in the Alexa app I see:
Not Found
The requested URL /&redirect_uri=https://alexa.salesvoiceapp.com/auth-callback was not found on this server
I believe that Amazon is causing this error? Or is this a SalesForce error?
Do I have to specify a "redirect_uri" as part of the URL? When I created my Connected App I specified this as the callback URL:
https://alexa.salesvoiceapp.com/auth-callback
Can I get SalesForce login to use that URL automatically, without me having to send it along as a parameter in the URL that I use to redirect users to SalesForce?

A: OK, completely updating this with code.  Basically you need to add a header and transform the request, and the munge instance_url to the access token and add an expiry to the response.  Note this uses their Auth Code flow.
Here's the endpoint I use for the token URI, using Node + Express:
app.post('/token',function (req, res) {

console.log(req.body);
  var sr = sync_request('POST', 'https://login.salesforce.com/services/oauth2/token',
                      {
                      headers: {'Content-Type':'application/x-www-form-urlencoded','Accept':'application/json'},
                      body: 'grant_type='+req.body.grant_type+'&code='+req.body.code+'&refresh_token='+req.body.refresh_token+'&client_id='+req.body.client_id+'&client_secret='+req.body.client_secret+'&redirect_uri='+req.body.redirect_uri
                      });
  console.log(sr.getBody('utf8'));
  response = JSON.parse(sr.getBody('utf8'));

  response.access_token = response.access_token + " " + response.instance_url;
  response.expires_in = 5400; //in seconds, set this to be less than your setting under session management.

  res.jsonp(response);
});

Then you can grab the token and instance url by splitting on the space.
I've done a write up on using it, including the Amazon setup side.

A: In my case, I was trying to do it with the UI that amazon provides under the skills(Account Linking). Everything was perfectly set up and I was not able link my skill to SF via the connected app. I noticed that I had to provide scopes as api and refresh_token. It worked fine after that and I was able to link my SF account to my alexa skill.


text:
Q: maximal ideals of polynomial ring For a maximal ideal $n$ of a polynomial ring $ R [x]  $ over a commutative ring $R$  with identity, are there conditions under which $m [x]\subset n$, for some maximal ideal $m$ of $R$?
Note: $m [x] $ is the ideal of $R [x] $, generated by $m $.
For example, if $R $ is a zero dimensional ring it is true.

A: This is equivalent to $m\subset n\cap R$ ; equivalently, it means that $n\cap R$ (which is a prime ideal of $R$) is maximal. This holds in particular if $R$ is a Jacobson ring, that is, every prime ideal is an intersection of maximal ideals; every finitely generated algebra over a field or over $\mathbb{Z}$ is a Jacobson ring. For all of this see for instance EGA I, §6.4.


text:
Q: Python or R, efficient seperate time series into zig zag If I have a list
l = [0, 0, 1, 2, 2, 2, 1, -1, -1, -1, 0]

I hope to obtain three zig-zag, a zig-zag is defined as local maxima (can be a plateau) and minima (can be a valley), as shown below, there are 3 zig zags, A, B, C while A and B overlap in the plateau, B and C overlap in the valley
A = [0, 0, 1, 2, 2, 2]
B = [2, 2, 2, 1, -1, -1, -1]
C = [-1, 0]

A: A solution in general Python, note that the l can be any iterator, and it is scanned only once.
l = [0, 0, 1, 2, 2, 2, 1, -1, -1, -1, 0]

def zigzag(l):
    if not l:
        return []

    last = l[0]

    # the elements in current rise
    current_rise = []

    # the elements in current drop
    current_drop  = []

    # return value
    zigzags = []

    # iterate over elements
    for i in l:
        # if we are growing...
        if i > last:
            # and the current_drop is longer than
            # current rise, then we just stopped a drop
            if len(current_drop) > len(current_rise):
                zigzags.append(current_drop)

            # in any case, a new drop can start here.
            current_drop = [i]

        else:
            # else just accumulate a current drop
            current_drop.append(i)

        # same for the other direction
        if i < last:
            if len(current_rise) > len(current_drop):
                zigzags.append(current_rise)

            current_rise = [i]

        else:
            current_rise.append(i)

        last = i

    # add the final segment
    if len(current_rise) > len(current_drop):
        zigzags.append(current_rise)
    else:
        zigzags.append(current_drop)

    return zigzags

print zigzag(l)
# result [[0, 0, 1, 2, 2, 2], [2, 2, 2, 1, -1, -1, -1], [-1, -1, -1, 0]]


text:
Q: sublime text (3200) not allowing git commit ,how to resolve sublime text git commit issue? I am using Ubuntu 18.04 ,I have removed previous version of sublime text through Ubuntu Software and then installed it through sublime text's official documentation given Here .
After that Whenever I am trying to git commit it gives the following message and does nothing .
git commit
hint: Waiting for your editor to close the file...
'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'
-n -w: 1: '/Applications/Sublime Text
2.app/Contents/SharedSupport/bin/subl' -n -w:
/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl:
not found
error: There was a problem with the editor ''/Applications/Sublime
Text 2.app/Contents/SharedSupport/bin/subl' -n -w'.
Please supply the message using either -m or -F option.

I want to understand what exactly this issue is and how to resolve it .my current installed version of sublime text is build 3200 . Kindly suggest a way to resolve this issue ,thank you !

A: If an editor is set in the git config git commit called without -m or -F will try to open this editor for you to provide a commit message, which is failing in your case. You can either only commit providing a commit message
git commit -m "my commit message"

or change the configuration, e.g. remove the editor lines with
git config --unset-all core.editor

or correct the setting with:
git config --global core.editor "subl -n -w"

Further reading:

*

*How can I fix git commit error "Waiting for your editor to close the file…" with VS Code?

*Associating text editors with Git


text:
Q: How to prompt user to turn on Location Services...again I want to have the same functionality as the Map app, where user is prompted every time they press the 'current location' button to turn on their Location Services if they are off:

*

*Turn off location services

*User presses 'getCurrentLocation' button

*App tries to get location using CLLocationManager

*User gets 'Turn On Location Services..." message that shows "Settings" and "Cancel" buttons.

*User taps 'Cancel'

*User presses ''getCurrentLocation' button again

*App tries to get location using CLLocationManager again

*User does not get 'Turn On Location Services..." message any more

In the Map app, the user gets "Turn On Location Services..." message every time.  How can I get my app to do the same?  I made user I am using a new instance of CLLocationManager, in case that was the problem, but it was not.  I can't see any settings that would affect this.
If I make my own Alert I cannot get the same 'Settings' button functionality.  Also, I don't want the user to see multiple Alerts that look the same.
Any ideas?

A: New in iOS 8 there is a constant called UIApplicationOpenSettingsURLString.
From the "What's new in iOS" document under UIKit is the line:

You can take the user directly to your app-related settings in the Settings app. Pass the UIApplicationOpenSettingsURLString constant to the openURL: method of the UIApplication class.

From Apple's documentation:

UIApplicationOpenSettingsURLString
Used to create a URL that you can pass to the openURL: method. When you open the URL built from this string, the system launches the Settings app and displays the app's custom settings, if it has any.

You can pass this into the UIApplication openURL: method.  It might look something like:
NSURL *settings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];

if ([[UIApplication sharedApplication] canOpenURL:settings])
    [[UIApplication sharedApplication] openURL:settings];

A: If you want to point the user back to the Location Services screen in the Settings app, you can do so by sending them to a special URL, like so:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"prefs:root=LOCATION_SERVICES"]];

A: You can query the shared CLLocationManager instance if the location service is enabled. The correct way is to respect the users choice to disable location services.
But if you want to, just start the location service anyway and the user will be prompted to start it again. If the user opts in on the request locations will begin to be reported on your delegate as usual. If the user instead denies your request you will get a failure callback to the locationManager:didFailWithError: delegate method. The error will have an error code of kCLErrorDenied.
I would strongly discourage you from doing this, but you can try to start the service again if the user says no, and the user will be asked again. Most users will hate you for it though.


text:
Q: Manifest Validates but App Opens with Blank Screen? I'm adding a manifest to my web app for the first time. My manifest validates successfully at manifest-validator.appspot.com. And the Chrome Application->Service Worker window shows the service worker as successfully registered. I am able to "Save to Home Screen" on my iPhone. But when I open the icon saved to the home screen, I get a blank screen.
Here's my myApp_manifest.json file:
{
  "short_name": "myApp",
  "name": "myAppLongName",
  "icons": [
    {
      "src": "images/app-images/myIcon-512-green_512px.png",
      "type": "image/png",
      "sizes": "512x512"
    },
    {
      "src": "images/app-images/myIcon-512-green_192px.png",
      "type": "image/png",
      "sizes": "192x192"
    }
  ],
  "start_url": "/?utm_source=progressive_web_app",
  "background_color": "#63aed5",
  "display": "standalone",
  "scope": "/",
  "theme_color": "#3367D6"
}

What am I missing?

A: It may be specific to your phone and iOS/Browser combination
Try it on someone else's device and/or the XCode Simulator
Manifest looks fine to me and works as expected for Android

A: iOS does not (yet?) use the launch image from the manifest file like android
See #PROTIP 2 here for how to make those work:
https://www.netguru.co/codestories/few-tips-that-will-make-your-pwa-on-ios-feel-like-native


text:
Q: youtube popup ran insecure content Good day,

I have a popup where i used youtube pop
http://lab.abhinayrathore.com/jquery_youtube/

The thing is that all was working good on IE, Chrome, firefox, opera

but now i have this error and all browsers stopped working except IE.
[blocked] The page at ../test.jsp ran insecure content from http://www.youtube.com/embed/BM3dQmvD5V0?rel=0&showsearch=0&autohide=2&autoplay=0&controls=1&fs=1&loop=0&showinfo=0&color=red&theme=light.

and this is the file where i have the error   (jquery.min.map.js:8)

i dont know where to start to search or what is the real error

can i have any advice?
thanks in advance


text:
Q: Passing a JS Array to a new Array sorry very basic question I'm new.
If I have an array and pass it to a new variable (newArray = oldArray) then remove an element from newArray, it seems to also effect oldArray.
my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?
If so how do I actually pass the elements from oldArray into newArray so that newArray is independent from oldArray?
Thanks in advance

A:
my guess is that it's simply creating a new reference to the same variable, so that data that was stored in oldArray now has two identifiers?

Right, both your new variable and your old one are pointing to the same array. Operations on the array through one reference (variable) are naturally visible through the other one, since there is just one array.
To avoid this, you'd have to make a copy of the array. There are several ways to do that, one of which is to use slice:
var newArray = oldArray.slice(0);

slice returns a shallow copy of an array starting at the given index. If you give it the index 0, it copies the entire array.

A: The quickest way is to use an array function to return a new array instance. Typically, I use:
var newArray = oldArray.slice(0);

A: In that case you have to clone the array using the slice method:
newArray = oldArray.slice(0);

A: As you've learned, when you copy an array variable, you copy a reference to the original.
Here's one idom to make a real copy - request a slice from the first element
 var newArray = oldArray.slice(0);


text:
Q: Access VBA textbox matrix I would like to insert 1-24 rows into a DB after some VBA precheck. I made an MSAccess form with textbox grid, and name them like this:

I would like only insert the rows with filled "Name". Code:
For i = 1 To 24
namegrid = "Name" & i & ".Value"
If IsNull(namegrid) Then
 Else
    InsertProduct = "Insert INTO Products (Productname, QTY, IncomingPrice, Desc) VALUES (Name" & i    & ".value, QTY" & i & ".value, Price" & i & ".value, Desc" & i & ")"
    DoCmd.RunSQL InsertProduct
 End If Next i

The If IsNull(namegrid) is not working properly (I think is check the variant instead of the referenced Textbox).
How to do it correctly? (cheking the lenght also tried with no success)
Maybe I have wrong conception...


text:
Q: Create an NSString with leading zeroes for minutes and seconds I need to constantly update the a playback time in a label. I am getting the time NSTimeInterval currentProgress = self.moviePlayerController.currentPlaybackTime; which returns a double value. But the format in which I need to display is "MM:SS" (00:00). I have tried the following code
NSTimeInterval currentProgress = self.moviePlayerController.currentPlaybackTime;

float min = floor(currentProgress/60);
float sec = round(currentProgress - min * 60);

When the progress time is 10 minutes and 10 seconds it displays perfectly fine, as "10:10". But the problem here is if the progress time is 1 minute and 7 seconds, it displays "1:7" in the label. My intended  display is "01:07". How can I do that?

A: NSString *time = [NSString stringWithFormat:@"%02d:%02d", (int)min, (int)sec];

Try this. Should just work!

A: This should do the trick:
int seconds = (int)currentProgress % 60;
int minutes = currentProgress / 60;

NSString *result = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];

The %02d format specifier will automatically pad with 0s so that the field as at least 2 characters wide.


text: Q: Solving for Unknown Radix If I have an equation like $$((34)_r + (24)_r) * (21)_r = (1480)_r$$How would I go about solving for r? Initially I tried to use the power series expansion to get the equation $$(5r + 8)(2r + 1) = r^3 + 4r^2 + 8r$$ but my answer comes out to be a decimal when the solution says r = 10. Any help?


text:
Q: The select command in the query I have two tables called Product and Unit, FieldID UnitID is a common field between the two tables.
In the form in which the product table is patched, there is a combo box that, when we give it, returns the UnitID value from the Unit table to the point where we have no problem.
My problem is when this Cambodox box is counted without the value, then it stores the 0 in the UnitID.
Now, when I want to SELECT, I will display all the values except that the UnitID is equal to 0.
Access Bank:
SQLcode:
SELECT Unit.UnitID, Product.*
FROM Unit INNER JOIN Product ON Unit.UnitID = Product.UnitID

One of the ways to write SELECT is to display the same UnitIDs that are equal to 0.

A: Simply chain a where clause to filter out the records that do have a UnitID of 0.
SELECT Unit.UnitID, Product.*
FROM Unit
INNER JOIN Product ON Unit.UnitID = Product.UnitID
WHERE Unit.UnitID <> 0

A: i am not sure your table structure, if you select which data where Unit.UnitID != 0
then
SELECT Unit.UnitID, Product.*
  FROM Unit INNER JOIN Product
  ON Unit.UnitID = Product.UnitID
  where Unit.UnitID != 0;

or if you want to not equal or less then
SELECT Unit.UnitID, Product.*
 FROM Unit
 INNER JOIN Product
 ON Unit.UnitID = Product.UnitID
 where Unit.UnitID > 0;

if your filed Unit.UnitID return 0 or more then need decide then
 SELECT * from
 (SELECT Unit.UnitID, Product.*
  FROM Unit INNER JOIN Product
  ON Unit.UnitID = Product.UnitID)
main where  main.UnitID != 0;

if you have not Unit.UnitID store then then use outer join which return all data if where condition not match so in this case if Unit.UnitID is not null then select all data
SELECT Product.*
FROM Product
LEFT OUTER JOIN Unit ON Product.UnitID = Unit.UnitID

last query not tested, if any problem then inform me


text:
Q: Array of Union on C I have declared this array of unions:
union Function {
    char* name;
    double (*fnct)();
    int args;
};

union Function functions[] = {
    {.name = "acos", .fnct = acos, .args = 1},
    {.name = "asin", .fnct = asin, .args = 1},
    {.name = "atan", .fnct = atan, .args = 1},
};

But, when I try to use it I get an Segmentation fault error.
for(int i = 0; i < sizeof(functions) / sizeof(union Function); i++) {
    printf("%d\n", functions[i].args);
    printf("%s\n", functions[i].name); //HERE!
}

A: For some reason you are using a union when you actually want to use a struct. You need to study what union means before you can use it.
The reason your code is crashing, is because of the initialization:
{.name = "acos", .fnct = acos, .args = 1},

This means that you write to all union members in turn, from left to right. But since all members are all stored at the same memory location, which is the whole point of using union, only the last one will be valid 1).
A decent compiler will give you a warning for this, since an initialization list like this does not make any sense.

1) Reference C11 6.7.9/17.

A: A union contains either of its members, not all of its members.
So the last initializer is the final one, meaning its value is just 1. So printing the name ( a string) results in a seg fault because printf tries to dereference the address 1.
If you want to have all of its members, use struct instead of union.

A: From K&R2:
"""
A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements.
"""
You're indeed using the incorrect data structure here. You should be using a 'struct' instead of a union.
A union is useful if you have a variable that could be one (and only one) kind of a choice of differing data types.
I find the name 'union' misleading since a mathematical union implies the entire collection of all its members, whereas a C union does not contain all its members at once. Furthermore, the syntax for a union is identical to a struct:
union u_tag {
    int ival;
    float fval;
    char *sval;
} u;

Infact, a union is a special case of a struct where all members have offset zero from the base and sufficient memory is allocated to hold the biggest member.
One rule of thumb to quickly decide whether to use a struct or a union is that all members of a union should have similar names, as they can all be used to represent the same kind of data (albeit with a differing data type). The fact that the members of your union have very different names (name, fnct, args) representing entirely different kinds of data, is a give away that a struct is the right choice of data structure.


text:
Q: GRPC client blocking vs async stub recommendation We are currently implementing a high throughput spring boot application using grpc-starter package https://github.com/yidongnan/grpc-spring-boot-starter, this is a client server based application. We are migrating our legacy REST end points CRUD operations to GRPC. For having best design for this service, we need help with following questions:

*

*If a single immutable GRPC blocking stub client instance is accessed by multiple threads, will this be a blocking call i.e. only one RPC call is executed at any given time.

*As per the google GRPC IO docs it is recommended not to use blocking stub to parallelize RPC call. Is this highlighting the case of multiple RPC call on same client object. https://grpc.io/docs/guides/performance/

*Will the blocking stub use new TCP connection for every call or same TCP connection is reused.

A:
If a single immutable GRPC blocking stub client instance is accessed by multiple threads, will this be a blocking call i.e. only one RPC call is executed at any given time.

No, RPCs will progress in parallel. The stub is a thin wrapper around the Channel and Channels will perform multiple RPCs simultaneously.

As per the google GRPC IO docs it is recommended not to use blocking stub to parallelize RPC call.

This is because blocking is a scaling concern. Each blocking RPC consumes a thread and threads are very large in Java (~1 MB). Async can also see reduced context switching overhead at high scale. gRPC Java is equally efficient for blocking vs async.
Note that this generally means you can use blocking without worry for any low-scale RPCs. You can choose to use async or future stubs only on the RPCs that will have many (100+) outstanding concurrently.

Will the blocking stub use new TCP connection for every call or same TCP connection is reused.

The TCP connection will be reused. gRPC Java uses the same Channel APIs for both blocking and async. So the only difference is the API you see.


text:
Q: Expectation of staying in same state for a simple MC Consider a simple dicrete-time Markov Chain $X_t$ with finite state $\Omega = \{1,2,3\}$. At time 0 the chain is with probability 1 in state 1 $\mathbb{P}(X_0 = 1) =1$. Then the transition probability matrix is as follows
\begin{array}{ccc}
p_{11} & p_{12} & 0 \\
0 & p_{22} & p_{23}\\
0 & 0 & 1
\end{array}
I would simply like to know the expectation of the time the chain stays in each state. For state 1 is it simply $\mathbb{E}(T_1) = \sum_{k > 0} k p_{11}^k$ ? Thank you !

A: Let $T_1 = \max\{i, X_i = 1\}$
$$P(T_1 = k) = p_{11}^{k}(1-p_{11})$$
$$E(T_1) = \sum_{k=1}^{+\infty}kP(T_1 = k)$$
You've forgotten the term $1-p_{11}$. Of course the result can be simplified if you want


text:
Q: A word for someone/something that is hopeless and 'incurable' I am looking for a word to describe something/someone that is inevitably going to collapse or die and there is no hope in sight to change that fact.
An example:

Yahoo is___anyway, no one could save it.

Edit: The closest word I can find is 'doomed', is that a idiomatic word to describe that situation?

A: Terminal, Cambridge English Dictionary

(of a disease or illness) leading to death:
His mother has a terminal illness.

By extension, one can use terminal as the OP did, to describe the condition of a company or an institution that cannot survive. Oxford English Dictionary:

c. fig. and in extended use: irreversible, irreparable; extremely
  severe; calamitous, disastrous.....
1981   Daily Tel. 21 Dec. 2/1   Another contest for Labour's deputy
  leadership next year could prove 'terminal' for the party, Mr Neil
  Kinnock..said.
....
1996   Big Issue 15 July 12/1   The business went into what many
  thought was terminal decline.
.....

And, in case a reader cannot access the OED, see this definition from Oxford Dictionaries

2.3 informal [--] Extreme and usually beyond cure or alteration (used for emphasis)
'an industry in terminal decline'
'you're making a terminal ass of yourself'

A: How about irredeemable?

Incapable of being redeemed or bought back.

*

*Oxford English Dictionary
Hence, redeem, note the original definition first and then the definition that would apply here.

1.a. to deliver (a person, a soul, etc.) from sin or damnation.
2.b. To make good (a loss).

*

*Oxford English Dictionary
Example uses:

Six months later, the damaging consequences of this fateful choice are undeniable–and I believe irredeemable.

*

*Forbes, 2009

Think Washington, D.C., and your statehouse are irredeemable and unproductive? Look to city hall for answers.

*

*Business Insider, 2017

So in your sentence, it would be

Yahoo is irredeemable anyway, no one could save it.

A: Perhaps fait accompli would work for you?
Per Oxford Dictionaries:

fait accompli
NOUN
A thing that has already happened or been decided before those affected hear about it, leaving them with no option but to accept it.
'the results were presented to shareholders as a fait accompli'

You would probably need to reword it a bit:

Yahoo's demise is a fait accompli anyway, no one could save it.


text:
Q: linux back up через timeshift Пытаюсь сделать резервную копию с помощью timeshift, использую команду
sudo timeshift --create
терминал предлагает ввести девайс, а девайсов нет :с
Что можно сделать? ubuntu wsl2


text:
Q: System.Net.Http type mismatch at compile Since updating a .Net Framework Web Api2 project to .Net Framework 4.7.1 and updating references to the now native System.Net.Http library, we now get the following error at compile time (not the typical runtime). Thus assembly binding redirects have no effect.

The type 'HttpResponseMessage' exists in both
  'System.Net.Http, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' and 'System.Net.Http,
  Version=4.2.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a'  SkinOnline.Web  C:_dev\MapsOnline.Web\API\Controllers\Utilites\LongProcessController.cs

I've no idea where the older version is coming from - perhaps one of the project dependencies.
Edit
So after adding the dll from

C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.7.1

Once under references the path has changed to

C:\VS2017\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net471\lib\System.Net.Http.dll

And that says the Version is 4.2.0.0

A: So in fact the new native file is version 4.2.0.0 (no idea what the folks were doing here given the latest version before this consolidation was 4.3.3).
Indeed we do require the binding redirect.
<dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
  </dependentAssembly>

Without it I get weird runtime errors

System.MissingMethodException Method not found:
  'System.Net.Http.HttpRequestMessage
  System.Web.Http.ApiController.get_Request()'.

A: The problem you are hitting is that even though the new System.Net.Http binary (4.2.0.0) is copied in the same folder of the app, the right binding redirects are not being generated automatically by the VS tooling. We recently fixed this with this pull request: https://github.com/dotnet/corefx/pull/25786
Once that fix is consumed by Visual Studio, the right binding redirect will be generated automatically for you and you won't see this issue anymore. This fix will be included in Visual Studio 15.6 Preview 3. For the time being, adding the binding redirect manually will do the trick.


text:
Q: Tesseract fine tuning Cant open lstmbox
im trying to fine tune tesseract 4.1.1 in my WSL shell. Doing that im following [this](https://www.statworx.com/en/content-hub/blog/fine-tuning-tesseract-ocr-for-german-invoices/)
tutorial.
I have created a number of .tiff files and now are trying to generate the corresponding .box files using lstmbox.
```
tesseract my_picture.tiff my_picture --psm 2 eng lstmbox
```
But instead of giving me the corresponding .box files i am hoping for, tesseract just returns the following:
```
read_params_file: Cant't open lstmbox
```
After looking trough some tesseract related content i think that I'm maybe just missing a part of tesseract that wasn't installed the right way. But I am not sure and can't find which one it might be.
Does somebody once had the same problem or just knows how to solve this problem?

A: Error read_params_file: Cant't open...  means that tesseract can not find defined configuration file (lstmbox). If your installation process did not installed it you can download it (and others) from https://github.com/tesseract-ocr/tesseract/tree/main/tessdata/configs and install it manually to your installation structure.


text:
Q: Pass multiple objects from Ajax to WebMethod I am passing information from my form to my WebMethod. The goal is to populate the UseInfo object with the data from the form and also populate some properties I have added on the NewUser class which are also passed from the ajax request.
When I have as an input parameter the UserInfo, the object populates successfully after the ajax post. However, if I have the NewUser object, only the property Relationship gets populated but the UserInfo object appears as Nothing.
Any ideas what I'm doing wrong? Do I need to give a different structure to my class NewUser?
NewUser class
 Public Class NewUser

        Public Property UserInfo As UserInfo
            Get
                Return _UserInfo
            End Get
            Set(value As UserInfo)
                _UserInfo = value
            End Set
        End Property
        Private _UserInfo As UserInfo

        Public Property Relationship As String
            Get
                Return m_Relationship
            End Get
            Set(value As String)
                m_Relationship = value
            End Set
        End Property
        Private m_Relationship As String

    End Class

WebMethod
    <HttpPost>
<ValidateAntiForgeryToken>
<DnnModuleAuthorize(AccessLevel:=SecurityAccessLevel.View)>
    Public Function AddUserDependant(<FromBody> oNewUser As NewUser) As HttpResponseMessage
        Try
            If Me.UserInfo.IsInRole("Carer") Then
                UsersControllerOmni.CreateDnnUser(oNewUser.UserInfo)

                Return Request.CreateResponse(HttpStatusCode.OK)
            Else
                Return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "")
            End If
        Catch ex As Exception
            Return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)
        End Try

    End Function

AJAX
$.ajax({
      type: "POST",
      cache: false,
      url: serviceUrl + "/ModuleTask/AddUserDependant",
      beforeSend: sf.setModuleHeaders,
      contentType: "application/json; charset=utf-8",
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      data: $("form").serialize()
  }).done(function (result) {

  }).fail(function (xhr, result, status) {
      alert(result);
  });

A: The problem is that you are sending and encoded form string to your WebAPI service with the $("form").serialize().  This will convert the form to a string "field1=value1&field2=value2&field3=value3" to an object on your WebAPI request.  So .NET will try to convert that to a simple object.
In order to get your request to fit into the object you have, I would suggest changing your ajax to send content type 'json'.
Then add a method to control the form serialization to the client object.
$.ajax({
      type: "POST",
      cache: false,
      url: serviceUrl + "/ModuleTask/AddUserDependant",
      beforeSend: sf.setModuleHeaders,
      contentType: "application/json; charset=utf-8",
      dataType: 'json',
      data: $('form').serializeUserRequest()
}).done(function (result) {
}).fail(function (xhr, result, status) {
      alert(result);
});

Notice the custom function, serializeUserRequest(), that produces the json request object that matches the server-side WebAPI parameter.
$.fn.serializeUserRequest = function()
{
    var requestObj = { "UserInfo": {}, "Relationship": {} };
    var formData = this.serializeArray();
    $.each(formData , function(i, fd) {
        if (fd.name.indexOf("rel_") == 0) {
          var fld = fd.name.substring(4);
          requestObj.Relationship[fld] = fd.value;
        } else {
          requestObj.UserInfo[fd.name] = fd.value;
        }
    });
    return requestObj;
};

For this to work, my assumption is that you make your form field names the same as the UserInfo/Relationship object properties (IE: "DisplayName", "FirstName", etc).  Also, in order to split the form attributes between those two root objects, I added "rel_" to the fields that map to the Relationship object and all other field names will map to the UserInfo.
Example:
<input type="text" name="rel_Name" maxlength="50" size="50"/>


text:
Q: ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'numpy.ndarray' I am creating a python script using pandas to read through a file which has multiple row values.
Once read, I need to build an array of these values and then assign it to a dataframe row value.
The code I have used is
import re
import numpy as np
import pandas as pd
master_data = pd.DataFrame()
temp_df = pd.DataFrame()
new_df = pd.DataFrame()

for f in data:

##Reading the file in pandas which is in excel format
#
file_df = pd.read_excel(f)

filename = file_df['Unnamed: 1'][2]

##Skipping first 24 rows to get the required reading values
column_names = ['start_time','xxx_value']
data_df = pd.read_excel(f, names=column_names, skiprows=25)

array =np.array([])

   for i in data_df.iterrows():
       array = np.append(array,i[1][1])

   temp_df['xxx_value'] = [array]
   temp_df['Filename'] = filename
   temp_df['sub_id']=
   temp_df['Filename'].str.split('_',1).str[1].str.strip()
   temp_df['sen_site']=
   temp_df['Filename'].str.split('_',1).str[0].str.strip()
   temp_df['sampling_interval'] = 15
   temp_df['start_time'] = data_df['start_time'][2]

   new_df= new_df.append(xxx_df)

   new_df.index = new_df.index + 1
   new_df=new_df.sort_index()
   new_df.index.name='record_id'

  new_df = new_df.drop("Filename",1)    ##dropping the Filename as it
  is not needed to be loaded in postgresql

 ##Rearrange to postgresql format
 column_new_df = new_df.columns.tolist()
 column_new_df.
 insert(4,column_new_df.pop(column_new_df.index('xxx_value')))
 new_df = new_df.reindex(columns = column_new_df)

 print(new_df)

This code is not working when I try to insert the array data into Postgresql.
It gives me an error stating:

ProgrammingError: (psycopg2.ProgrammingError) can't adapt type
  'numpy.ndarray'

A: I am not sure where the problem is, as I can't see in your code the part where you insert the data into Postgres.
My guess though is that you are giving Postgres a Numpy array: psycopg2 can't handle Numpy data types, but it should be fairly easy to convert it to native Python types that work with psycopg2 (e.g. by using the .tolist(method), it is difficult to give more precise information without the code).

A: In my opinion, the most effective way would be to make psycopg2 always aware of np.ndarray(s). One could do that by registering an adapter:
import numpy as np
from psycopg2.extensions import register_adapter, AsIs

def addapt_numpy_array(numpy_array):
    return AsIs(tuple(numpy_array))

register_adapter(np.ndarray, addapt_numpy_array)

To help working with numpy in general, my default addon to scripts/libraries dependent on psycopg2 is:
import numpy as np
from psycopg2.extensions import register_adapter, AsIs

def addapt_numpy_float64(numpy_float64):
    return AsIs(numpy_float64)

def addapt_numpy_int64(numpy_int64):
    return AsIs(numpy_int64)

def addapt_numpy_float32(numpy_float32):
    return AsIs(numpy_float32)

def addapt_numpy_int32(numpy_int32):
    return AsIs(numpy_int32)

def addapt_numpy_array(numpy_array):
    return AsIs(tuple(numpy_array))

register_adapter(np.float64, addapt_numpy_float64)
register_adapter(np.int64, addapt_numpy_int64)
register_adapter(np.float32, addapt_numpy_float32)
register_adapter(np.int32, addapt_numpy_int32)
register_adapter(np.ndarray, addapt_numpy_array)

otherwise there would be some issues even with numerical types.
I got the adapter trick from this other stackoverflow entry.

A: Convert each numpy array element to its equivalent list using apply and tolist first, and then you should be able to write the data to Postgres:
df['column_name'] = df['column_name'].apply(lambda x: x.tolist())

A: We can address the issue by extracting one element at a time. Here I'm assuming for a dataframe temp_df, sub_id of type numpy.int64, we can directly extract the values using the iloc and item as temp_df.iloc[0]['sub_id'].item() and we can push that in DB.


text:
Q: How do I know the length of instruction in assembly? I have come cross a segment of code like this:
jmp 0x26 #2 bytes
popl %esi #1 bytes
movl %esi,0x8(%esi) # 3 bytes
movb $0x0,0x7(%esi) # 4 bytes

.....

.string \"/bin/sh\" #8 bytes

I wonder how dose the author know how many bytes for each instruction?

A: I love how the first comment you get is essentially the answer... but it's not in the answer box! So I'll expand upon that.
So, as you've gathered, you have to "know" - and you know this by looking up the instruction in the Intel manual.
I'll give you a straightforward example If you want to work out the size of say mov rax, [rsp+8] you could assemble this in nasm:
 BITS 64
 mov rax, [rsp+8]

With the following command:
 nasm -fbin test.asm -o test.bin

Examining test.bin, you'll see in Hex it is:
 48 8B 44 24 08

Here 8B represents the mov instruction. The 48 preceding it is a REX prefix with the w property set (indicating a 64-bit target). The last byte, 08, represents the displacement from the previous register, which is 24, which indicates esp (except the targets are wide, because the REX prefix tells us so). Finally, 44 represents eax*2, which would be a 64-bit wide field.
The exact addressing mode used here is pretty complicated, but safe to say that common ones can quickly be worked out. For example, the 32-bit equivalent (mov eax, [esp+4]) is the 4-byte 8B 44 24 04.


text:
Q: primeng tree does not show items I have an primeng tree that shows the data that it reads in just fine.
the html has the following code snippet
     <!--style="width: 85%; height: 400px"-->
     <p-tree

             [value]="filesTree4"
             selectionMode="checkbox"
             [(selection)]="selectedFiles2">
     </p-tree>

Now I want to size the tree control. When I add the line above
         <p-tree
             style="width: 85%; height: 400px"
             [value]="filesTree4"
             selectionMode="checkbox"
             [(selection)]="selectedFiles2">
     </p-tree>

the commented one, now the image becomes
Anyone sees what I am doing wrong?

A: I think you've got two issues with the syntax you are using.
First, you have to bind to the style input for the primeng component, rather than trying to inline a style string.
Second, you pass a JSON object to the style input with your style properties.
So for example, this should work for you:
<p-tree
  [style]="{'width': '85%', 'height': '400px'}"
  [value]="filesTree4"
  selectionMode="checkbox"
  [(selection)]="selectedFiles2">
</p-tree>


text:
Q: Only get the H+W geometry of my screen without the later +x+y I am reading this article. There is a statement there that goes:
ffmpeg -f alsa -ac 2 -i hw:0,0 -f x11grab -s $(xwininfo -root | grep 'geometry' | awk '{print $2;}') -r 25 -i :0.0 -sameq -f mpeg -ar 48000 -s wvga -y sample.mp4

When I run the command I get an error with the section that says:
xwininfo -root | grep 'geometry' | awk '{print $2;}'

The reason is that when you use this command on my computer it outputs:
1360x768+0+0

How do I remove the last part of the screen resolution output to be 1360x768 instead of 1360x768+0+0?

A: My pure awk approach, splitting the string into fields based on spaces and plus signs:
xwininfo -root | awk -F'[+| ]' '/geometry/ {print $4}'

A similar method to Sylvain's Perl expression but with sed:
xwininfo -root | sed -nr 's/.*geometry ([0-9x]+).*/\1/p'

A: You could maybe use awk substr. In your particular case :
xwininfo -root | awk '/geometry/ {print substr($2,1,8);}'

Or if you want it to work in any case :
xwininfo -root | awk '/geometry/ {print $2;}' | cut -d'+' -f1

hope this help.

A: Others have already provided answers for the complete operation, but to answer only How do I get from 1360x768+0+0 to 1360x768? then I would recomment using cut as the simplest possible solution, e.g.
$ echo 1360x768+0+0 | cut -d+ -f1
1360x768
$

A: *

*You can use perl to get only the resolution:
xwininfo -root | perl -lne 's/.*geometry (\w+).*/$1/ or next; print'
1360x768

*Or even shorter with just GNU grep:
xwininfo -root | grep -oP '(?<=geometry )\w+'
1360x768

Explanation: The lookbehind (?<=geometry ) asserts that at the current position in the string, what precedes is the characters "geometry ". If the assertion succeeds, the engine matches the resolution pattern.
A lookbehind does not "consume" any characters on the string. This means that after the closing parenthesis, the regex engine is left standing on the very same spot in the string from which it started looking: it hasn't moved. From that position, then engine can start matching characters again.
Source: http://www.rexegg.com/regex-disambiguation.html#lookbehind

A: I also tried command line screen capture examples a few weeks ago. As an alternative solution you can use
 xdpyinfo  | grep dimensions | awk -F ' ' ' { print $2 } '

for detecting screen resolution.
To capture screen with internal audio and microphone, you can use
 avconv -f   pulse -i default -f x11grab -r 15 -s $(xdpyinfo  | grep dimensions | awk -F ' ' ' { print $2 } ' ) -i :0.0+0,0 -acodec libmp3lame -vcodec libx264  $(date +"%m%d%Y_%H%M%S_$HOSTNAME")_screencast.mp4


text:
Q: add multiple key and value in Dictionary I want to add multiple value in NSDictionary. They make me trouble.
I am newer in Swift.
 m=NSDictionary(objectsAndKeys:[self.getStringAt(selectStmt, column: 0)],"first",[self.getStringAt(selectStmt, column: 1)],"second",nil)

A: You can do it like this.
let interestingNumbers = [
                            "Prime"     : [2,3,5,7,11,13],
                            "Fibonacci" : [1,1,2,3,5,8],
                            "Square"    : [1,4,9,16,25]
                         ]

Hope this helps.

A: /* Collection Types: Dictionary */

var dic1 = ["math":89, "chemistry":90, "physics":79]

// Modifying

dic1["math"]
dic1["math"] = 70   // returns new value

A: NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:@"43.93838383",@"latitude",@"-3.46",@"latitude" nil];

NSMutableDictionary *eventData = [NSDictionary dictionaryWithObjectsAndKeys:eventLocation,@"eventLocation", nil];
[eventData setObject:@"Jun 13, 2012 12:00:00 AM" forKey:@"eventDate"];
[eventData setObject:@"hjhj" forKey:@"text"];
.
.
.
NSMutableDictionary *finalDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:eventData,@"eventData", nil];
[finalDictionary setObject:@"ELDIARIOMONTANES" forKey:@"type"];
[finalDictionary setObject:@"accIDENTE" forKey:@"title"];


text:
Q: Using react-navigation how do i trigger Navigate from Actions in the react - native app? Heres the gist of the Actions code: It doesn't trigger the route: AllFruits
Do I somehow have to provide the list of screens in the Actions file?
import { NavigationActions } from 'react-navigation'

export const Create = ({address, cell, phone, comments, shift, _id  }) => {

    return async ( dispatch, NavigationActions ) => {
      console.log(' 44-  NavigationActions = ', NavigationActions);
      console.log(' 45-  NavigationActions.getState = ', NavigationActions.getState);
        try {
            const token = await AsyncStorage.getItem('token');
            if (token !== null) {
                axios.defaults.headers.common['authorization'] = token;
                axios.post(ROOT_URL, {
                        address: address,
                        cell: cell,
                        phone: phone,
                        comments: comments,
                        // shift : shift
                    })
                    .then(response => {
                        console.log('43 -  response of FRUIT create   response.data = ', response.data);
                        dispatch({
                            type: FRUIT_CREATE,
                            payload: response.data
                        });

                })
                .then(response => {
                    dispatch(NavigationActions.navigate({ routeName: 'allFruits' }));
            });
            }
        } catch (error) {
            console.log(error);
        }
    }; // end return (dispatch)
};

Update after Alexander hint.
import { NavigationActions } from 'react-navigation'
export const Create = ({address, cell, phone, comments, shift, _id  }) => {
return async ( dispatch ) => {
  console.log(' 44-  NavigationActions = ', NavigationActions);
  console.log(' 45-  NavigationActions.getState = ', NavigationActions.getState);
    try {
        const token = await AsyncStorage.getItem('token');
        if (token !== null) {
            axios.defaults.headers.common['authorization'] = token;
            axios.post(ROOT_URL, {
                    address: address,
                    cell: cell,
                    phone: phone,
                    comments: comments,
                    // shift : shift
                })
            .then(response => {
                dispatch(NavigationActions.navigate({ routeName: 'allFruits' }));
        });
        }
    } catch (error) {
        console.log(error);
    }
}; // end return (dispatch)

};
Question: Do I have to provide the routes available in the Actions file ?  I wonder if im missing anything.
Structure of the Navigation,  ( The file names and other names have been changed but the code structure remains the same )
// App.js
import { AppLoading, Asset } from 'expo';
import { Font } from 'expo';
import React from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import { TabNavigator, StackNavigator } from 'react-navigation';
import { Provider } from 'react-redux';

import registerForNotifications from './services/push_notifications';
import store from './store';
import AuthScreen from './screens/AuthScreen';
import WelcomeScreen from './screens/WelcomeScreen';
import MapScreen from './screens/MapScreen';
import DeckScreen from './screens/DeckScreen';
import SettingsScreen from './screens/SettingsScreen';
import ReviewScreen from './screens/ReviewScreen';
import HomeScreen from './screens/homeScreens/HomeScreen';

// AND A LOT MORE SCREEN IMPORTS

export default class App extends React.Component {

  componentDidMount() {
    console.log(' App.js  componentDidMount called');
    Font.loadAsync({
      'morbi-rounded': require('./assets/fonts/2BF294_D_0.ttf'),
    });
  }

    async _loadAssetsAsync() {
        try {
          await Asset.loadAsync([ require('./assets/loginAssets/login1_bg.png'),require('./assets/loginAssets/login1_mark.png'),require('./assets/loginAssets/login1_lock.png'),require('./assets/loginAssets/login1_person.png'),      require('./assets/signupAssets/back.png'), require('./assets/signupAssets/signup_person.png') ]);
        } finally {
          console.log(' 97 - App   assetsAreLoaded: true ');
          this.setState({ assetsAreLoaded: true });
        }
      }

        async _loadFontsAsync() {
          try {

            await Font.loadAsync({
                  'morbi-rounded': require('./assets/fonts/2BF294_D_0.ttf')    });
          }
          catch(e) {
              console.log(' 123 Error occurred while loading FONT Assets');
          }
           finally {
            console.log('123 - App   FONT FAMILY assetsAreLoaded: true ');
            this.setState({ assetsAreLoaded: true });
          }
        }

        componentDidMount() {
            this._loadAssetsAsync().done();
            this._loadFontsAsync().done();
          }

  render() {

    const MainNavigator = TabNavigator({

    auth: { screen : AuthScreen },
    followup: { screen: FollowupScreen },
    signin: { screen : SigninScreen },
    Login: { screen : LoginScreen },
    signup: { screen : SignupScreen },
    signUp_2: { screen : SignUpScreen_2 },

    VerifyAccount: { screen : VerifyAccount },
    ForgotPassword: { screen: ForgotPasswordScreen },
    PasswordChange: { screen: PasswordChangeScreen },

    main: {
      screen: TabNavigator ({
        followup: { screen: FollowupScreen },
        Search: { screen: SearchScreen },
        Priceview: {
                screen: StackNavigator({
                  map: { screen: MapScreen },
                  priceScreen: { screen: priceScreen },
                  priceDetails: { screen: priceDetailsScreen },
                })
              },
        settings : {
          screen: StackNavigator ({
            settings: { screen: SettingsScreen },
            MyProfile: { screen: MyProfileScreen },
            Subscription: { screen: SubscriptionScreen },
            HelpSupport: { screen: HelpSupportScreen },
            Notifications: { screen: NotificationsScreen },
            Feedback: { screen: FeedbackScreen },
            EmailTemplate: { screen: EmailTemplateSetup },
            Signout: { screen: SignoutScreen }
          })
        },
        followup : {
          screen: StackNavigator ({
            followup: { screen: FollowupScreen },
            allFruits: { screen: AllFruitsScreen },
            createFruits: { screen: FruitsCreateScreen },
            editProperty: { screen: FruitsEditScreen },
            todayScreen: { screen: TodayScreen },
            Comment: { screen: CommentScreen },
            Email: { screen: EmailScreen },
          })
        }
      },{
        tabBarOptions: {
            labelStyle: {
              fontSize: 10,
            },
            showIcon: true,
            style: {
              overflow: 'visible'
            }
          },
          tabBarComponent: TabBarBottom,
          tabBarPosition: 'bottom'
      }) //screen: TabNavigator
    }
}, {
navigationOptions: {
    tabBarVisible: false
},
lazy: true,
});

return (
<Provider store={store}>
<MainNavigator />
</Provider>
);

}
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Store/index.js
 import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducers from '../reducers';

const store = createStore(
    reducers,
    {},
    compose (
      applyMiddleware(thunk)
  )
);

export default store;

A: Herre is how I fixed this issue, like @alexander suggested, I had to pass the this.navigation
   handleFormSubmit({ par1, par2 }) {
var nav_param =   this.props.navigation;

  this.props.fruitCreate(({ par1, par2, nav_param }), () => {
            console.log('118- in handleFormSubmit request send to the Actions');

            });
          }

when this calls Actions in the backend,
export const fruitCreate = ({ par1, par2, par3, nav_param  }) => {

    return async ( dispatch ) => {

      // MAKE THE BACKEND POST REQUEST AND ThEN

                .then(response => {
                    console.log('59 -  response of propertyCreate   response.data = ', response.data);
                    nav_param.navigate('allFruits')
                    }


text:
Q: How to change default local repository path in Phabricator? I'm trying to migrate my current Phabricator deployment (which is a Ubuntu VM) to a docker based container.
According Phab's documentation, I should use the following command line:
bin/config set --database repository.default-local-path /my/new/path

The command above fails with:
Usage Exception: Config key "repository.default-local-path" is locked and can
only be set in local configuration. To learn more, see "Configuration Guide:
Locked and Hidden Configuration" in the documentation.

When I try the command above without --database, it changes the local.json and successfully. However, it seems that properties in stored in DB have precedence over properties defined in JSON file. Therefore, the change made to JSON file has no effect.
If this is not a bug, how do I change repository.default-local-path? If it is bug, is there any workaround?

A: I don't think "locked" configuration options are ever meant to be set at the database level. This value should be provided in the local config.
Assuming that you have a value set in the database that is interfering with your local config, I'd say that is a bug. The easiest workaround that I know of is to unlock the config option by editing phabricator source. What you need to do is as follows:

*

*Unlock the config option. To do this, change the source code from setLocked(true) to setLocked(false) on line 25 of PhabricatorRepositoryConfigOptions.php.

*Set a value for repository.default-local-path in local.json as you already managed to do with bin/config set (leaving off the --database argument)

*Delete the database value with the following command: bin/config delete --database repository.default-local-path

*Once everything is set correctly, you can revert your change to PhabricatorRepositoryConfigOptions.php which will restore the option to the locked state.


text:
Q: Drop down view in cocoa I'm looking to create a 'drop down' view that falls in front of the main window. An example of this would be the window that drops down when you click 'Advanced' in System Preferences->Networking.
If someone could point me in the right direction documentation-wise that would be great. Thanks in advance.

A: That's called a sheet.  Here's a quick introduction and the Apple documentation.


text:
Q: Convert code to JS Object Literal Pattern I want to start writing better code and I have come to understand that putting everything relevant to a particular piece of functionality inside an object is a good idea.
Edit: I've tried to take on board the concept in @SoftwareEngineer171's answer. Now I have this:
var app = {
    audioCtx : new(window.AudioContext || window.webkitAudioContext)(),

    init : function () {
        oscillator = app.audioCtx.createOscillator();
        oscillator.type = 'square';
        oscillator.frequency.value = 3000; // value in hertz
        oscillator.start();
    }
} // app object close

app.init();

But it doesn't work. Can anyone explain why?
I want to use this code as part of an application, but placed inside an object literal:
var context = new AudioContext(),
    gainNode = context.createGain(),
    oscillator = context.createOscillator();

gainNode.connect(context.destination);
oscillator.frequency.value = 440;
oscillator.connect(gainNode);
oscillator.start();

However, when I have tried, I run into problems of the kind mentioned here.
I want the code to begin like this:
var app = {
    context : new AudioContext(),
    ...
}

Any help much appreciated as usual.

A: What you are trying to do is not a particular piece of functionality, but you can do it in several ways. For example, if you want to write the following object
var obj = {
    a: 5,
    b: 7,
    c: a + b
};

it will throw an ReferenceError. To avoid it, rewrite the syntax as following
var obj = {
    a: 5,
    b: 7,
    init(){
        this.c = this.a + this.b;
        return this;
    }
}.init();

You can also do it using class
var obj = new class{
    constructor(){
        this.a = 5;
        this.b = 7;
        this.c = this.a + this.b;
    }
}();

or even using constructor function
var obj = new function(){
    this.a = 5;
    this.b = 7;
    this.c = this.a + this.b;
}();

Edit
In your case, audio context script will look like this (see also JSFiddle):
var app = {
  context: new (window.AudioContext || window.webkitAudioContext)(),
  gainNode: null,
  oscillator: null,
  init(){
    this.gainNode = this.context.createGain();
    this.oscillator = this.context.createOscillator();
    this.gainNode.connect(this.context.destination);
    this.oscillator.frequency.value = 440;
    this.oscillator.connect(this.gainNode);
    this.oscillator.start();
  }
};

app.init();


text:
Q: how can i put a php variable into mysql command $id1 = $_POST['number']; //here i am getting a php variable called number

$result = mysqli_query($con, "SELECT id,main FROM first WHERE ?how can i put that number right here?");

I am getting a variable from another page using ajax and i should put it into mysql command.How can i do that?

A: Here's an example of using prepared statements:
   /* Create a new mysqli object with database connection parameters */
   $mysqli = new mysql('localhost', 'username', 'password', 'db');

   if(mysqli_connect_errno()) {
      echo "Connection Failed: " . mysqli_connect_errno();
      exit();
   }

   /* Create a prepared statement */
   if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
   AND password=?")) {

      /* Bind parameters
         s - string, b - blob, i - int, etc */
      $stmt -> bind_param("ss", $user, $pass);

      /* Execute it */
      $stmt -> execute();

      /* Bind results */
      $stmt -> bind_result($result);

      /* Fetch the value */
      $stmt -> fetch();

      echo $user . "'s level of priviledges is " . $result;

      /* Close statement */
      $stmt -> close();
   }

   /* Close connection */
   $mysqli -> close();

Source
I strongly suggest researching prepared statements early on.

A: option 1.Good to go for Prepared statements
option 2."SELECT id,main FROM first WHERE id=$id"
When a string is specified in double quotes, variables are parsed within it.

A: $result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = $id1");

OR
$result = mysqli_query($con, "SELECT id,main FROM first WHERE your_db_field = " . $id1 . ");

Should work just fine.
However you should consider using Stored Procedures to avoid any security vulnerabilities...

A: //Get ur name from Post Request
$number=$_POST['number'];
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='$number"; (or)
$query="SLEECT * FROM TABLE_NAME WHERE colunm_name='".$number."'";
$result=mysql_query($con,$query)

//Using Prepared Statement
$stmt = $dbh->prepare("SELECT * FROM TABLE_NAME where COLUMN_NAME= ?");
if ($stmt->execute(array($_GET['number']))) {
 while ($row = $stmt->fetch()) {

    print_r($row);

 }

}


text:
Q: recordset.sort invalid row handle I have a MySQL stored procedure generating a resultset. The query uses GROUP_CONCAT to select rows as columns.
SQL Code snippet
SELECT CONCAT(
 ' SELECT MDE_ID, MDE_CreatedOn, MDE_LastEditedOn '

,  GROUP_CONCAT(CONCAT(
   ' ,t', MDF_ID, '.MDEMDF_Value AS `', REPLACE(MDF_Label, '`', '``'), '`'
   ) SEPARATOR ' ')
Following, I want to sort the recordset on a column.
SQL = "CALL moduleentry_select(" & prjid & ",0,26,0)"
set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorLocation = 3
rs.LockType = 3
rs.Open SQL, Conn
rs.Sort = "volgnummer"
I have verified and the column is in the recordset.
I get the following error:
Microsoft Cursor Engine error '80040e04'
Row handle is invalid.
default.asp, line 176
Line 176 is rs.Sort = "volgnummer"
edit
The column 'Volgnummer' doesn't actually exist in the database. It is selected dynamically via a pivoting principle, using GROUP_CONCAT. Referring to this SA answer: joined table rows into columns with column titles from original rows


text: Q: Gstreamer RTP header I am sending RTP audio mono stream with S16LE at 8 ks/s using RTPL16PAY. One test is sending audiotestsrc at 440 Hz. This results in a continuous packet size of 566 bytes.  Wireshark says the protocol is SKYPE. The first word of the RTP payload is 0x8060 which agree with the specified load type of 96.  According to the RFC3550 there should be another 14 bytes of header information before the streamed data starts.  However the data starts 11 bytes later which is odd in a couple of ways. I have looked at a few packets   Any thoughts will be appreciated.