text:
Q: USB Printer not showing up on `control printers`, but showing up on `devmgmt.msc` I have a USB printer (D110a) that was installed using the HP official driver pack previously, and worked fine. It has no operating failure.
When I connect it to the Windows 7 PC it always worked with, I can hear the sound of a new USB device being recognized, and can see it correctly listed on devmgmt.msc.
But control printers remains blank, and I CAN print using that printer, through the print dialog called by every program.
What could be preventing me from seeing it on control printers? It is annoying and I would like to be able to fix it.

A: One way to fix this (perhaps you might see it as a workaround) is as follows:
Uninstall (Control Panel, Programs and Features) all D110a printer apps. There may be more than one. Unplug the printer. Restart the computer.
Plug in the Printer.  Open Devices and Printers and Select Add a Printer. Select the D110a and let Windows add the printer.
The printer should now appear in Devices and Printers and also it should print (do a test page).
This method of letting Windows add printers normally works very well.
You can also try reinstalling the Printer Driver.  Uninstall completely as I noted above. Restart, Now reinstall the D110a.
The Windows drivers (Microsoft Catalogue) are supplied by the printer manufacturer anyway.


text:
Q: Margin/width not rending properly on a div element position: fixed; display: table-cell; set I need my .nav-container position: fixed; so that content doesn't move on scrolling up or down. But doing this creates a gap between the .nav-container and the .page-content, a certain window widths. At these widths there appears to be a small white line between the red background of the .nav-container and the brown border to its right.
If I get rid of the position: fixed; the margins render perfectly but I need that content fixed.
Does anyone know of a work around?
Would it best / possible to leave off the position: fixed; and use Javscript to move all the content in the .nav-container down and up as the window scrolls so that it appears the content is not moving at all?
live link: https://webzume.herokuapp.com/
relevant css:
#content {
width: 100%;
display: table; }

#index {
  display: table-row; }

#index .nav-container {
position: fixed;
background-color: rgba(222, 89, 58, 0.95);
box-sizing: border-box;
padding-top: 2.5rem;
vertical-align: top;
width: 22.6%;
display: table-cell;}

A: Never use table formatting for layout! Especially not in combination with position!
Heres how to fix it without the table layout:

*

*Remove display: table from #content

*Remove display: table-row from #index

*Remove position: fixed from #index .nav-container
On both #index .nav-container and #index .page-content, do the following:

*Remove display: table-cell

*Add float: left

*Add height: 100%

*Add overflow: auto

A: Have you set page Margin and Padding to zero?
html, body { margin:0; padding:0; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to check if boost::deadline_timer is active any way to check if deadline_timer is active? e.g. if it's in async_wait state and wasn't cancelled?

A: The handler for the timeout will be called with an error condition if the timer was canceled (as well as a normal timeout). So could you not simply set a bool before calling async_wait and then reset that in the handler if the error condition is set?

A: Three options come to mind:

*

*Create your own timer class (by using the deadline_timer of course) that has its own do_async_wait member. In this member you set a member variable which can then be returned from a bool isWaiting() member or similar, before you call the async_wait on the internal deadline_timer. Note that I don't think that the async_wait member is virtual, so you can't just inherit from deadline_timer and override. Note that you would also need to reset the flag when your handler is called (by making your own timer the handler that then forwards to any other handler) or when cancel is called.

*Edit the boost code to do what you want. This is perfectly legal as far as I am aware, however this is of course not a very good option.

*Alter your requirements/design so that you don't need to know this.

A: How about this?
boost::asio::deadline_timer mTimer;
const bool timerExpired = (mTimer.expires_at()
  <= boost::posix_time::second_clock::local_time());

A: I know that this is a bit old at this point, but I have another possible suggestion: how about getting the implementation and then requesting if there are possibly pending waits.  It would look like this:
mTimer.get_implementation().might_have_pending_waits


text:
Q: bin log dump - mysql master and slave I have some issues regarding the master-slave data replication, is there any chance to re-sync them in order to have the same data in both master and slave without trying to add manually data on slave to be the same with master?

A: One option is to make a backup of the master and use it to replace the data on the replicaslave entirely. This is reinitializing the replica.
The other option is to use Percona Toolkit tools like pt-table-checksum and pt-table-sync to do an incremental replacement of only the data that needs fixing.
See

*

*https://www.percona.com/blog/2015/08/12/mysql-replication-primer-with-pt-table-checksum-and-pt-table-sync/

*https://www.percona.com/blog/2016/03/17/mysql-replication-primer-with-pt-table-checksum-pt-table-sync-part-2/


text:
Q: Font Awesome Icons with colours more than one Can I use more than one color for a fontawsome icon?
For example, can I do this when I want to use a yellow, black lined and shaded light bulb (fa-lightbulb-o)?
Thank you very much for your help already.

A: There is no way to do that with css, as font awesome is a font, and you can only chose one colour for your font. You can get the svg easily from this site


text:
Q: dd-wrt Bonjour/ netbios etc on two subnets I have a network setup with two different subnets 192.168.1.0 and 192.168.0.0. One router is connected to a VPN (via OpenVPN) the other is not. Both routers have static routes to each other and a device on one can communicate to another without issues when using IP addresses.
My problem is I want to use services like Bonjour, Netbios and Apple Talk across the two networks, which currently does not work. A laptop connected on one subnet will not see a laptop connected on another. Is there anyway that you can connect the two networks together so these sort of local service will work?

A: Appletalk is a nonroutable protocol. Netbios has to be reconfigured to allow routing by setting up servers on both sides (don't remember the exact procedure, it's been a while).
Never played with Bonjour but a quick Google also indicates it is nonroutable.

A: To use NetBIOS across subnets, you need a WINS server.
Any Samba server can act as one with just wins support = yes added to the [Global] section of smb.conf. Then distribute that address to clients using option netbios-name-servers 192.168.1.100; in dhcpd.conf (for example).
If you want another Samba server to use another WINS server, tell it wins server = 192.168.1.100 in the [Global] section of smb.conf.

A: Back in the day when I was trying to get my mt-daapd server visible for iTunes clients over VPN, I used RendezvousProxy. This thing is pretty much deadpooled development wise, but I think even the ancient version might still work.


text:
Q: LCR meter and iron core inductors I am trying to wind some coils for a RF transmitter, so to get the values right, I though of using a LCR meter, but there is a problem with the measurements.
If I use air core inductors the measured values don't differ that much when switching from different frequencies of operation. But if I want to measure an inductor with a iron core (from a nail) I get the following results:

*

*100Hz:  16uH

*120Hz:  16uH

*1kHz:   11.1uH

*10kHz:  4.59uH

*100kHz: 1.708uH

I've read somewhere that inductors below 2mH should be measured with 1kHz, so the 100Hz and 120Hz are off, that I can understand. But 10kHz and 100kHz measurement frequencies shouldn't be that much off from 1kHz, shouldn't they? What am I doing wrong?

A: A simple LCR meter will not give accurate measurements if the core is very lossy.
It it's truly an iron core (not iron powder) then the eddy current losses will be significant- like a resistor in parallel with the coil. That translates to a lower impedance which the LCR meter will interpret as a lower inductance since it is not measuring the phase angle of the result. Iron powder is also lossy.
An LCR bridge would sort this out for you (and show you the equivalent parallel resistance as well as the inductance), but the bottom line is that your core is going to be way too lossy to use at RF frequencies and you should use a ferrite core or air core that is suitable for RF.

A: When exposing a conductor (such as the iron nail) to a changing magnetic field, eddy currents develop. The iron core acts like a short-circuit transformer winding. This means that some energy is dissipated in the core.
This worsens as frequency increases, hence massive iron cores are rarely chosen for any transformer/inductor related applications. Grid transformers working at 50/60 Hz are frequently built with laminated (isolated) sheets of iron, so as to prevent eddy currents from developing.
High-frequency inductor and transformer cores employ ferrite ceramics
 to minimize core losses.
You should consider using a ferrite core.

A: Another way to measure inductance that I think should be quite accurate would be to breadboard a trivial inductor capacitor notch filter circuit like:

simulate this circuit – Schematic created using CircuitLab
Feed noise into the circuit and look at the notch frequency with some audio interface software that can to an FFT. Adjust the capacitor so that the notch is in a spot that can be accurately measured like 1kHz - 10kHz. Then take the values of the resistor and capacitor and guess as to what the inductor value might be and plug them into a spice simulation. Adjust the inductor value in the sim until the frequency of the notch in the sim exactly matches the frequency measured in your hard circuit. Then you know the inductor value.

A: For iron core inductance measurements, drive the coil with a 60Hz voltage; read the voltage and current simulaneously and make the following calculations.
$$Z = \frac{e}{i}$$
$$X_L = \sqrt{Z^2-R^2}$$
$$L = \frac{X_L}{2 \pi 60}$$
R is the d.c. resistance of your coil.


text:
Q: Flickering during resizing of HTML5 canvas I'm observing some flickering during the resizing of an animated canvas control.
You can see it in action at this page. Drag the 'width' slider left and right to try it for yourself. I see this flickering in Chrome 26.0.1410.43 running on Linux. Currently this page won't work in Firefox until it supports HTML5's <input type="range">.
I've tried to reproduce the issue on a smaller scale in this jsFiddle. It's not as noticeable, but occurs for me when the canvas is around 90% of the available width wide.
The code traps requestAnimationFrame, and resizing wipes the canvas. I would hope that the render callback would be called before the browser's frame was painted. This doesn't seem to be the case, as the white background shows through occasionally during resizing.
Is there anything that can be done to avoid this?

A: When you set canvas.width or canvas.height it clears the canvas, combined with the redrawing this causes the flicker you see.
You can mitigate this to a reasonable extent by saving the canvas to a temporary canvas before resizing and then drawing it back again afterwards.
Here's my resize function:
    function resize(width, height) {
        //Create temp canvas and context
        var tempContext = Utils.Canvas.Create2DContext(context.canvas.width, context.canvas.height);

        //Draw current canvas to temp canvas
        tempContext.drawImage(context.canvas, 0, 0);

        //Resize current canvas
        context.canvas.height = height;
        context.canvas.width = width;

        //Draw temp canvas back to the current canvas
        context.drawImage(tempContext.canvas, 0, 0);
    }

If you resize to a smaller size then the temp canvas is "overdrawn" so it'll completely fill the current canvas. However if you resize to a larger size then your temp canvas will only fill part of the current canvas. The part it doesn't fill will still flicker as it's redrawn.
If you wanted to get a bit more fancy you could try drawing a temp canvas of the correct (final) size rather than simply copying the current canvas. This would be slower but could well eliminate all flicker.
In my case I'm resizing to fill a div, so having a little flicker along the bottom and right edges is tolerable, and certainly much better than the whole thing flickering.
EDIT:
Here's an update of your jsFiddle with my changes applied:
jsfiddle.net/Uz5Pt/13
It seems to work better than where I'm using it in my app! You can hardly see any flashing on any newly created bits of canvas.


text:
Q: Can the "How to Ask" Sidebar be edited? When you ask a question on any SE site, you get a sidebar like this one:

Who is allowed to edit this text for each community? This is visible to anyone who asks a question, even if they have ignored the FAQ and the About page, and is a very useful tool to getting direct advice across.
I can't find anything else on Meta about this beyond this blog post which just redirects new users to a different page when they ask, rather than allowing that sidebar text to be customized.

A: Only developers can edit that text. That part of the site is not community-driven.
It's there for a good reason: to point people to resources on how to ask questions. Like you say, it's a very useful tool. However, it is probably fine in its current state.
If you would like to suggest an edit, post here on Meta with a feature-request, and see what response you get.


text:
Q: Проблема с Maven Пытаюсь использовать прогрессбар из этого репозитория
Подключаю его с помощью Maven, но ничего не получается. Целиком копирую этот код в свой pom.xml
<dependency>
    <groupId>com.github.lzyzsd</groupId>
    <artifactId>circleprogress</artifactId>
    <version>1.1.0</version>
    <type>apklib</type>
</dependency>

и получаю ошибку
Missing artifact com.github.lzyzsd:circleprogress:apklib:1.1.0

Как решить эту проблему? С Maven знаком слабо, прошу не ругать сильно.

A: Убедитесь, что у вас указан следующий Maven-репозиторий:
<repository>
    <id>central</id>
    <url>http://repo1.maven.org/maven2/</url>
</repository>

A: Самостоятельно скачать из web репозитория и ручками положить/зарегистрировать в локальном депозитории.


text:
Q: get value of hidden input field in c# I have a charts program that works in js, but I need to update excels with the data using c#. So, what I've done so far is to create hidden input fields whose values are updated with the js variable:
<input type="hidden" name="baselineInput"  id="baselineVariable" />
<input type="hidden" name="goalInput" runat="server" id="goalVariable" />
<input type="hidden" name="currentInput" runat="server" id="currentVariable" />

//do some things here
var MTDGauge = new Array(5,5,5);

document.getElementById("baselineVariable").value = MTDGauge[0];
document.getElementById("goalVariable").value = MTDGauge[1];
document.getElementById("currentVariable").value = MTDGauge[2];

The problem I'm having is reading these values back to the c# variable. Here's what I've tried (placed after the code above):
    List<string> OverallData = new List<string>();

    OverallData.Add(Request["baselineInput"]);
    OverallData.Add(Request["goalInput"]);
    OverallData.Add(Request["currentInput"]);

This is just adding null values (assuming so because the c# is loading before the javascript and the initialized values for the text fields are null?). I thought of creating a c# function that could be called using the onchange option in the input field, but that didn't get me anywhere. Is there something I'm missing? Do I have to do a post?
Thanks

A: Yes, to get your data back to the server (where your C# is running) you need to send it back.
POST is one way, or GET to add the values to the query string.
Javascript is only running in the browser, until you send something back to the server, your ASP.NET app will not have any information.
Of course, if you want to do it asynchronously you could use jQuery.ajax to send the data to a server URL without refreshing the whole page.


text:
Q: Ping a IP especifica Tengo el siguiente script, lo que deseo es enviar un ping sostenido a la IP señalada y me lo guarde en un .txt , pero solo me guarda la primer linea.
@echo off

:bucle

set a1=.
set a2=.
set /p IP=ESCRIBE IP;

ping -n 1 10.10.222."%IP%" | find "Respuesta" > a1.txt
ping -n 1 10.10.222."%IP%" | find "Tiempo de espera agotado" > a2.txt
set /p p1=< a1.txt
set /p p2=< a2.txt

echo %date% %time% %a1% %a2%
echo %date% %time% %a1% %a2% >> C:\Users\METAL\Desktop\log.txt

break >a1.txt
break >a2.txt

ping 127.0.0.1 -w 1000 -n 2 > NUL

GOTO bucle

pause

A: El problema reside en 2 cosas:
cuando usas la variable IP no la estás usando como tal  sino que esa variable según tu código representa el último número de una IP, me refiero a estas líneas:
ping -n 1 10.10.222."%IP%" | find "Respuesta" > a1.txt
ping -n 1 10.10.222."%IP%" | find "Tiempo de espera agotado" > a2.txt

Aquí tendrías dos opciones:
Cambiar el nombre de tu variable y lo que le pides al usuario con por ejemplo ultimoNumeroIp
ping -n 1 10.10.222."%ultimoNumeroIp%" | find "Respuesta" > a1.txt
ping -n 1 10.10.222."%ultimoNumeroIp%" | find "Tiempo de espera agotado" > a2.txt

O le quitas los numeros a estas dos lineas y usas de verdad la variable IP de tal manera que quedaría así:
ping -n 1 "%IP%" | find "Respuesta" > a1.txt
ping -n 1 "%IP%" | find "Tiempo de espera agotado" > a2.txt

y el otro problema que veo es el uso de las variables %a1% y %a2% cuando deberían de ser %p1% y %p2% según la definición que has hecho en las líneas:
set /p p1=< a1.txt
set /p p2=< a2.txt

Resumiendo el código de tu script quedaría así:
@echo off

:bucle
set a1=.
set a2=.
set /p IP=Escribe la IP a la que quieres hacer Ping:

ping -n 1 %IP% | find "Respuesta" > a1.txt
ping -n 1 %IP% | find "Tiempo de espera agotado" > a2.txt

set /p p1=< a1.txt
set /p p2=< a2.txt

echo %date% %time% %p1% %p2%
echo %date% %time% %p1% %p2% >> log.txt

break > a1.txt
break > a2.txt

ping 127.0.0.1 -w 1000 -n 2 > NUL

GOTO bucle

NOTA: lo que pensabas que era la última línea no lo era sino que era el resultado de
echo %date% %time% %a1% %a2%

que como %a1% %a2% no tenían nada te escribía la fecha y la hora
un saludo y espero haberte ayudado

A: error,de esa forma el bucle te pediria que escribas la ip en cada ciclo, mas abajo el script corregido, agregue al nombre del archivo por defecto la ip sobre la que estas escaneando para una mas facil identificacion de los logs que generes, saludos
@echo off

set /p IP=Escribe la IP a la que quieres hacer Ping:

:bucle
set b1=.
set b2=.

ping -n 1 %IP% | find "Respuesta" > b1.txt
ping -n 1 %IP% | find "Tiempo de Espera Agotado" > b2.txt
set /p p1=< b1.txt
set /p p2=< b2.txt

echo %date% %time% %p1% %p2%
echo %date% %time% %p1% %p2% >> log%IP%.txt

break >b1.txt
break >b2.txt

ping 127.0.0.1 -w 1000 -n 2 > NUL

GOTO bucle

pause


text:
Q: How do I fix a microphone problem in Skype? I have a problem that my voice sounds stutterred or certain bits are skipped when using Skype.
I found the solution here:
https://superuser.com/questions/728164/skype-cutting-out-and-skipping-my-voice
but I can't find the option of removing the ambient noise cancellation anywhere on my mac! Reading about it on the web, it seems like it was removed from the newer macOS.
How can I then fix the problem, which seems to come from that "feature" of canceling ambient noise?


text:
Q: Interpreting Number Ranges in Python In a Pylons webapp, I need to take a string such as "<3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on.
Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.
The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]

A: I've created a version of @vartec's solution which I feel is more readable:
def _parse_range(numbers: str):
    for x in numbers.split(','):
        x = x.strip()
        if x.isdigit():
            yield int(x)
        elif x[0] == '<':
            yield from range(0, int(x[1:]))
        elif '-' in x:
            xr = x.split('-')
            yield from range(int(xr[0].strip()), int(xr[1].strip())+1)
        else:
            raise ValueError(f"Unknown range specified: {x}")

In the process, the function became a generator :)

A: Use parseIntSet from here
I also like the pyparsing implementation in the comments at the end.
The parseIntSet has been modified here to handle "<3"-type entries and to only spit out the invalid strings if there are any.
#! /usr/local/bin/python
import sys
import os

# return a set of selected values when a string in the form:
# 1-4,6
# would return:
# 1,2,3,4,6
# as expected...

def parseIntSet(nputstr=""):
    selection = set()
    invalid = set()
    # tokens are comma seperated values
    tokens = [x.strip() for x in nputstr.split(',')]
    for i in tokens:
        if len(i) > 0:
            if i[:1] == "<":
                i = "1-%s"%(i[1:])
        try:
            # typically tokens are plain old integers
            selection.add(int(i))
        except:
            # if not, then it might be a range
            try:
                token = [int(k.strip()) for k in i.split('-')]
                if len(token) > 1:
                    token.sort()
                    # we have items seperated by a dash
                    # try to build a valid range
                    first = token[0]
                    last = token[len(token)-1]
                    for x in range(first, last+1):
                        selection.add(x)
            except:
                # not an int and not a range...
                invalid.add(i)
    # Report invalid tokens before returning valid selection
    if len(invalid) > 0:
        print "Invalid set: " + str(invalid)
    return selection
# end parseIntSet

print 'Generate a list of selected items!'
nputstr = raw_input('Enter a list of items: ')

selection = parseIntSet(nputstr)
print 'Your selection is: '
print str(selection)

And here's the output from the sample run:
$ python qq.py
Generate a list of selected items!
Enter a list of items: <3, 45, 46, 48-51, 77
Your selection is:
set([1, 2, 3, 45, 46, 77, 48, 49, 50, 51])

A: rng = "<3, 45, 46, 48-51, 77"
ids = []
for x in map(str.strip,rng.split(',')):
    if x.isdigit():
        ids.append(int(x))
        continue
    if x[0] == '<':
        ids.extend(range(1,int(x[1:])+1))
        continue
    if '-' in x:
        xr = map(str.strip,x.split('-'))
        ids.extend(range(int(xr[0]),int(xr[1])+1))
        continue
    else:
        raise Exception, 'unknown range type: "%s"'%x

A: First, you'll need to figure out what kind of syntax you'll accept.  You current have three in your example:

*

*Single number: 45, 46

*Less than operator

*Dash ranging: 48-51
After that, it's just a matter of splitting the string into tokens, and checking the format of the token.

A: I also had to do something similar for an app lately.
If you don't need concrete numbers but just a way to see whether a given number is in the range, you might consider parsing it to a Python expression you can eval into a lambda. For example <3, 5-10, 12 could be func=(lambda x:x<3 or (5 <= x <= 10) or x==12)). Then you can just call the lambda, func(11) to see if 11 belongs in there.

A: >>> print range.__doc__
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
>>> range(33,44)
[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]
>>> range(1,3)
[1, 2]

I imagine you could iterate your list, and call range appropriately.
>>> def lessThan(n) :
...  return range(n+1)
...
>>> lessThan(4)
[0, 1, 2, 3, 4]
>>> def toFrom(n,m):
...  return range(n,m)
...
>>> toFrom(33,44)
[33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]

Then split the string on commas, and for each bit, parse it enough to figure out what function to call, catenating the lists returned.
Anything more and I'd have written it for you.


text:
Q: Multiple javascript frameworks in one webpage conflict <link rel="stylesheet" type="text/css" href="css/accordion_glam.css">
<script type="text/javascript" src="jquery-latest.txt"></script>
<script type="text/javascript">
$(document).ready(function(){

$("a.switch_thumb").toggle(function(){
    $(this).addClass("swap");
    $("ul.display").fadeOut("fast", function() {
        $(this).fadeIn("fast").addClass("thumb_view");
    });
}, function () {
    $(this).removeClass("swap");
    $("ul.display").fadeOut("fast", function() {
        $(this).fadeIn("fast").removeClass("thumb_view");
    });
});

});
</script>
<script type="text/javascript" src="js/prototype.js"></script>
<script type="text/javascript" src="js/scriptaculous.js"></script>
<script type="text/javascript" src="js/accordion.js"></script>

two scripts in one page out of which only one works..pls help...wat to do..??

A: You are including both jquery and prototype. Check out the post about using jQuery with other libraries


text:
Q: Wordpress get attachment image src using foreach Using wordpress get_post_meta $key. I was able to output attachment image in single.php using Function Reference/wp get attachment image src for single attachment id:
<?php
$attachment_id = get_post_meta($post->ID, 'attachment-id', true); // attachment ID

$image_attributes = wp_get_attachment_image_src( $attachment_id ); // returns an array
if( $image_attributes ) {
?>
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">
<?php } ?>

Since I am coding image gallery, I intend to use php foreach function to html output multiple images html code replacing the single post_meta $key with multiple ids array like (55,32,34).
I need help with the code required to restructure the output due to my lack of PHP knowledge.

A: You need to know which IDs you will look for, considering you have an array of ids :
$attachmentIds = [55,32,34];

You can then loop trough them with the foreach function and perform the same thing as what you did :
foreach ($attachmentIds as $id) {
    $image_attributes = wp_get_attachment_image_src( $id );
    if( $image_attributes ) {
        echo '';
    }
}


text:
Q: ConstraintConfiguration not used by ConstraintVerifier in testing class? I am currently working with dynamic weights configured in a ConstraintConfiguration class. But the class doesn't seem to be used while executing my tests that I wrote. It is however used while actually executing the solver.
For example: one of the weights in the configuration class is 16. While testing for a score of 1, it will not be multiplied with the weight and the result will be 1. But while actually solving, it will use it and it will be 16 as expected.
I am guessing that I'm missing something in my testing class.
Do you have to tell the ConstraintVerifier or the testing methods in the testing class that there is a ConstraintConfiguration? Or am I missing something else?
Thanks in advance.
My current constraintverifier:
ConstraintVerifier<ExamScheduleConstraintProvider, ExamSchedule> constraintVerifier = ConstraintVerifier.build(
            new ExamScheduleConstraintProvider(), ExamSchedule.class, Exam.class);

Example of test code that won't pass:
constraintVerifier.verifyThat(ExamScheduleConstraintProvider::TestConstraint)
                .given(firstExam, secondExam)
                .penalizesBy(16);

A: The ConstraintVerifier offers two verification methods:

*

*verifyThat(constraintFunction);

*verifyThat();

verifyThat(constraintFunction) accepts a method reference to an individual constraint and verifies that the constraint, given certain entities and facts or an entire solution, penalizes or rewards by the expected match weight. Important to note, this verifier ignores constraint weight completely.
verifyThat() does not accept any argument and checks the score impact (including constraint weight coming from ConstraintConfiguration) of all the constraints defined in the ConstraintProvider implementation for the provided entities and facts or an entire solution.

A: In addition to Radovan's response, I will provide some rationale for why ConstraintVerifier works the way it does.
For individual constraints, it does not take ConstraintConfiguration into account. That is because ConstraintConfiguration is solution-specific, and we want to be able to test consraints individually and independently. In this case, we only test match weights; match weights exist regardless of the solution, and regardless of constraint configuration. This would be your typical unit test. (If you prefer another way of thinking about this, consider the fact that constraint configuration is optional and most do not, in fact, use it.)
For integration testing, we support testing an entire solution. And when you test all the constraints as a whole, that is where we take your ConstraintConfiguration into account.


text:
Q: Should I be using LINQ queries on RavenDB? I'm learning RavenDB and I am rather confused. As far as I understand, one should create indexes in order to have really efficient queries. However, it is possible to simply make LINQ queries, such as
using(IDocumentSession session = _store.OpenSession())
{
    MyDocument doc = session.Query<MyDocument>()
                            .Where(d => d.Property == value)
                            .Single();
}

This type of query works perfectly fine. I have, however, never created an index for it (and never reference an index when making the query, of course).
Should I be using this kind of query when working with RavenDB? If not, why is it even available in the API?

A: There's two things you are asking, here.

*

*Can we use Indexes .. which are suppose to be more efficient than dynamic queries?

*If we use indexes .. then should we use Linq and chaining?

Indexes
As Matt Warren correctly said, you're not using any indexes in your sample query. Right now, with your sample query, RavenDb is smart enough to create a temp (dynamic) index. If that dynamic index is used enough, it get auto-promoted to a static / perminent index.
So .. should you use indexes? If you can, then yeah!
here's your statement again, this time with an Index defined.
using(IDocumentSession session = _store.OpenSession())
{
    MyDocument doc = session.Query<MyDocument>("ByProperty")
                            .Where(d => d.Property == value)
                            .Single();
}

In this case an index called MyDocument_ByProperty was created somewhere. I'm not going to explain the details of indexes .. go and read all about them here.
Linq and chaining
(Not sure if that is the correct terminology ... )
If you create a linq statement (which I did above) with OR without an index .. a query is still generated .. which then is translated into an HTTP RESTful request to the RavenDB Server. If you have an index .. then the query is smart enough to ask to use that. None? Then the server will create a dynamic index .. which means it will also have to go through the motions of indexing first, then retrieving your results.
TL;DR;
Yes use indexes. Yes use Linq chaining.

A: RavenDb comes with a native support for .Net and Linq.
The Linq provider, under the hood, does normal REST calls to the ravendb server, but for you it's easier to code on it since you can use IQueryable<T> with strongly typed classes.
So yes, you can and you should use linq/lambda to work with RavenDB in a .Net envorinment.

A: Something to be aware of that caught me out is that if you include a linq statement such as .Where(d => d.SomeProperty == null) then you might expect that if the document does not have the property then you would return a match. However this is not the case. If the document does not have the property then its value is not considered to be null (or any other value).


text:
Q: How to control iPhone System volume? I am trying to control iPhone System volume from my iOS App using Swift. I am following this below link but I can't do it.
https://github.com/ioscreator/ioscreator/tree/master/IOS8SwiftVolumeTutorial/IOS8SwiftVolumeTutorial
After using this I am able to change the volume control of custom audio file and I can also control the volume of other applications such as Youtube. But I can't control iOS Clock App's alarm volume and ringtone volume. How can I control all kinds of system volume including alarm and ringtone?

A: As far as I know there is no way to do this on iOS. You generally do not have control over a lot of things outside of your app. Ringtone and alarm volume is one of the things you cannot control.


text:
Q: Can Riven jump over skillshots with her 3rd Q? Riven's 3rd Q launches her into the air briefly, allowing her to leap over thin walls and minions.
Can Riven use her 3rd Q to leap over skillshots like Jinx's Super Mega Death Rocket, Lux's Final Spark, or Veigar's Event Horizon?

A: No you can't jump over a skillshot with riven, however her Q (and E) are still good tools to simply dodge enemy abilities.
In League of Legends you have to differentiate between blinks and dashes.
Blinks will cause you to be teleported from point A to B instantly whereas with a dash you will travel from point A to B really quickly.
Since every instance of Riven's Q is a dash in which she remains vulnerable (unlike Maokai W for example), she will get hit by a damaging ability if she tries to pass through it.
It's even possible to knock her out of her animation using a knockup at the right time (Thresh E, Maokai Q), causing her Q to have absolutely no effect while still going on cooldown.

A: Riven's Q leap is a displacement, not a blink - so she will still get snared by Event Horizon.
As for the other two, I'm not 100% certain but it doesn't make her untargetable, so the Q shouldn't allow to dodge those skillshots without moving away from the line of fire.

A: Even tho the answer has been already given, I'll add an important thing: League of Legends is 2D, despite looking 3D! - This is important for any "jump" ability like Rivens last Q or Tristanas W. The hitbox is still a straight line from the starting point to the arriving point, despite looking like a jump.
The only way to evade such skills are either blinks like Flash or Ezreals E or spells like Maokais W which make you invulnerable for the duration of travel.


text:
Q: REGEXP Substring Oracle I'm looking for a regexp to get the correct file name from the below string.
Input
Report_18072014.pdf

Expected Output
Report.pdf

The query so far which gives me the correct output.
REPLACE(FILENAME, '_' || TRIM(REGEXP_SUBSTR (FILENAME, '[^_.]+',1,2)))

My question is if there is a better regexp I can use to avoid concatenating _ to the substring in the replace function.

A: With your file format, you can use something like this:
REGEXP_REPLACE(FILENAME, '^([[:alnum:]]+)_[^.]+(\.[^.]+)',
                         '\1\2',
                         1, 0, 'c')

Explanation

*

*The ^ anchor asserts that we are at the beginning of the string

*([[:alnum:]]+) captures letters to Group 1.

*[^.]+ matches any chars that are not a .

*(\.[^.]+) captures the extension to Group 2 (the dot and any chars that are not a dot)

*\1\2 replaces with Group 1, Group 2

A: Try using this [untested]:
REGEXP_REPLACE(FILENAME, '_[[:digit:]]*\.', '.')

I really enjoy using regular expressions, but I wish that Oracle used the PCRE format instead of the POSIX format.
Explanation:

*

*_[[:digit:]]* matches the underscore and 0 or more digits.

*. matches the period to make sure that you are beside the file extension

*The final , '.' replaces everything with a period so that you have still have the .PDF

I would have changed the replacement to '.PDF', but I don't want to force your file names to mixed case files.


text:
Q: How can I prevent the `private` access modifier from being added in VS Code for C# when generating members? How can I prevent the private access modifier from being added in VS Code for C# when generating members?
E.g. I have the error:

The name 'foo' does not exist in the current context [Assembly-CSharp]csharp(CS0103)

I focus the caret at the foo(); with the help of the cursor, press Ctrl+. and select the

Generate method 'MyClass.foo'

Here is the method which gets generated:
private void foo()
{
    throw new NotImplementedException();
}

As you can see I am getting the private modifier being added.
Here is what I want to be generated instead of the one I showed above:
void foo()
{
    throw new NotImplementedException();
}

I tried searching for the private, accessibility settings in VS Code but found nothing. Given that VS Code is quite configurable, I am expecting to be able to set up this config as well. If you know how to do that, could you share it with me, please?

A: I don't believe that what you are asking for is possible today. The access modifier is set in Roslyn here, which is called from here. As you can see in the code, this setting is not exposed to any layer above, and you're going to get either public or private:
var accessibility = member.Name == memberName || generateAbstractly
      ? Accessibility.Public
      : Accessibility.Private;

Given that it is not possible today, you could file an issue with Roslyn and/or OmniSharp to request this functionality, or you could look at building a custom Roslyn Analyzer.
There is a tutorial available that includes information on how to provide a code fix for quickly handling violations.


text:
Q: Forecasting future batch sizes to balance throughput capacity? I've a data streaming platform (Nifi) where I need to transfer tables of data between databases on given schedules. I want to be able to calculate in advance the optimum batch/schedule size i should use.
Assume I've three databases with different number of tables, each with a specific row count and row size. The schedules are 30mins, 2hours, 8 hours. Lets assume I have a three maps with the table row count and size for each flow.
Is there an algorithm which over a 24hour period will plot the peaks and lows of the number of 10,000K data packets that will be processed by the platform in a give 30min period?. I realise that when the 30min, 2h and 8h schedules align i'll have a peaks.
The second question is if then want to try and balance to peaks. Let's assume there is a priority on the 30m and 2 hour schedules. Rather than releasing all the tables of the 8 hour schedule in one go, is there an algorithm that will say how long the total data of the 8 hour schedule will take to process?
Any advise would be appreciated.


text:
Q: TextView link to new layout view Android Trying to understand how to have it so that when users click a specific TextView that they are linked to a new layout, in this example, signup.
ie.,
<!--Not have account? Signup-->
    <TextView
        android:id="@+id/noAccountTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_account"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:padding="5dp"
        style="@style/TextAppearance.MaterialComponents.Caption"
        />

The layout file is activity_sign_up.xml, - i'm used to react and html etc, so this is all a bit new to me :) thanks!

A: You should check this. But basically, what you need is an intent. So, you want to do something like this
noAccountTv.setOnClickListener {
        val intent = Intent(this,ActivitySignUp::class.java)
        startActivity(intent)
    }

You will have to send an intent to the activity class that uses the layout file activity_sign_up.xml


text:
Q: Why can you have statefulness inside a static class in java? I was playing around with Java today and I read about static inner classes. Why can you have 'statefulness' inside of a static inner class. For instance:
class outerClass {
        static class Test {
        private String a;

        String getA() { return a; }

        void setA( String newA) {a = newA; }

    }
}

Am I misunderstanding something? It seems like you should not be able to keep mutable state inside of a class that is labled at static. Moreover it seems like you should not be able to instantiate something that is a static class, it should be a static singleton. Perhaps someone could correct me if I am making an incorrect assumption or enlighten me to why the Java authors decided to make this possible.
EDIT: I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

A: A static inner class is the same as a non-inner class. Your example is equivalent to:
class outerClass {}

class Test {
    ...
}

The static in static inner classes means that instances of the inner class aren't associated with an instance of the outer class. Without static, an instance of Test is always attached to an instance of outerClass - you'd need to construct an instance of outerClass before you can construct an instance of Test and the instance of Test would have access to the members of outerClass.

A: static things aren't always stateless.  Instead, static refers to the ability to access the instance variables and methods in an object.
With nested classes in Java, the static modifier on the inner class refers to its access to the outer class.
A static inner class does not have access to the instance variables of its enclosing class (just like a static method doesn't have access to the instance variables).  A further implication of this is that because the static inner class doesn't have the ability to access the instance variables it can be instantiated separately from the outer class. However, there is nothing in this definition that implies the lack of state.
The reason to use a static inner class is to further encapsulate it so that it can't tinker with its outer class member variables or methods.

With a later edit and some confusion about static, final and state:

I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

I must point out that final variables have state too. It is just a state that can be assigned once and only once.  Consider:
final int foo;
if(bar) {
    foo = 42;
} else {
    foo = 4;
}

Perfectly valid and stateful code on a final variable.
A static inner class that you can't instantiate is a situation that I can't quite find a use case for. Yes, the Java designers used static in yet another way (import, class, block, field, method, and inner class too). Each different use of static is distinct and should be considered to be separate concepts that sometimes interact.
In this case, the static inner class is more akin to a static method than a static class.

A: You can keep static state.  It is just associated with the class, rather than with the object instance.  So every object instance sees the same state value.

A: The keyword "static" in Java just means objects of that class are not tied to the enclosing class.  It has nothing to do with static methods and fields.  A static class is even more normal than a normal Java nested class.
You may be thinking in terms of the C# static class, which does not allow state, and contains only static members.  (C# is a bit more consistent with the term.)  I have heard people, even when talking about Java, refer to classes with no state as "static", so it pays to check what people mean when they use the term.
If you are familiar with C#, be aware that, deep down, Java and C# are very different languages, and their superficial similarities will trip you up badly if you're not careful.


text:
Q: Php include, index.php and CSS file problems Hello guys can anyone tell me how this code works:
<?php
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "pages/include/headertop.php";
   include_once($path);
?>

Someone recommended this to me. Since I have trouble with my include files when I transferred it inside the sub-folder/directories:
pages/include/headertop.php

Another problem is that the CSS linked to the include files don't work with the index.php file since I've transferred the include file to the sub-folders.
These codes below works half-way actually. Problem is that the CSS is not working with it. And if I relink the CSS for the index.php file, the files left in the subfolders gets messed up because of the redirected links.
<?php
include ("pages/include/headertop.php");
include ("pages/include/header.php");
include ("pages/include/nav.php");
?>

By the way, my index.php file is in the root directory/main folder.
Thanks guys! I really need your help.

A: I think $_SERVER['DOCUMENT_ROOT'] returns no slash add the end. So your $path is missing a trailing slash.
Maybe this works?
$path .= "/pages/include/headertop.php";

A: $_SERVER is an array containing information such as headers, paths, and script locations. it defines the path to a file
 and
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
detail here

after
that you have added the path to your folder
$path .= "pages/include/headertop.php";

and at the end
include_once is added to eliminate duplication of included file.


text:
Q: clean install sublime text I'm trying to re-install Sublime Text (3), but I keep getting back the old settings. To my (limited) knowledge, I only hae to delete the user settings in C:\Users\pc\AppData\Local\Sublime Text 3. (I'm on Win7)  I tried that, also uninstalling Sublime, removing the AppData folder too. But I keep getting the old settings back, again and again.
How do I do it correctly?

A: Try removing the folder under %APPDATA% per http://www.sublimetext.com/docs/2/revert.html


text:
Q: Magento 2 Curl Rest Endpoints I'm trying to access the REST Endpoints:
POST /V1/products/special-price
POST /V1/products/special-price-information
POST /V1/products/special-price-delete

I want to achieve this through PHP code however i'm finding it hard to understand just how to access them. I want to be able to GET the special prices of specific products. Any direction would be a help.

A: Try below code.
$url="http://localhost/magento/index.php/";
$tokenUrl=$url."rest/V1/integration/admin/token";
$productSpecialUrl=$url. "rest/V1/products/special-price";
$username="admin";
$password="password";

//get admin access token
$ch = curl_init();
$data = array("username" => $username, "password" => $password);
$dataString = json_encode($data);

$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($data_string))
    );
$token = curl_exec($ch);
$requestPayload = json_encode(array(array('price' => 100, 'store_id' => 1, 'sku' => 'sku123', 'price_from' => date, 'price_to' => date )));
$ch = curl_init($productSpecialUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestPayload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);

Let me know if you need further help.


text:
Q: Google Calendar to Google Sheets, Script does not pick up time correctly For some reason, the script I run is pulling the event times an hour off. If I have a time of 4pm, it brings it up as 3pm. The event dates and times are pulling as CST, but it is not displaying correctly. Does this line need to be changed somehow to bring up the local time?
I am not sure what to try.  Right now the date/time are pulled using CST, but the output from the script line brings the wrong time.  Could there be something different I have to add to this?
var events = cal.getEvents(new Date("October 20, 2019 00:00:00 CST"), new Date("November 2, 2019 23:59:59 CST"), {search: ''});

var sheet = SpreadsheetApp.getActiveSheet();
// Uncomment this next line if you want to always clear the spreadsheet content before running - Note people could have added extra columns on the data though that would be lost
// sheet.clearContents();

// Create a header record on the current spreadsheet in cells A1:N1 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
sheet.clearContents();
var header = [["EVENT / SHOW", "VENUE / LOCATION", "DELIVERY NOTES", "DATE", "TIME"]]
var range = sheet.getRange(1,1,1,5);
range.setValues(header);

// Loop through all calendar events found and write them out starting on calulated ROW 2 (i+2)
for (var i=0;i<events.length;i++) {
var row=i+2;
var myformula_placeholder = '';
// Matching the "header=" entry above, this is the detailed row entry "details=", and must match the number of entries of the GetRange entry below
// NOTE: I've had problems with the getVisibility for some older events not having a value, so I've had do add in some NULL text to make sure it does not error
var details=[[events[i].getTitle(), events[i].getLocation(), events[i].getDescription(), events[i].getStartTime(), Utilities.formatDate(events[i].getStartTime(), Session.getScriptTimeZone(), "hh:mma")]];
var range=sheet.getRange(row,1,1,5);
range.setValues(details);

Expected results are to have this pull the exact time that shows on the Google Calendar.

A: Just for your reference this is the code I was using to test your format strings.
function runTwo() {
  var ss=SpreadsheetApp.getActive();
  var calA=CalendarApp.getAllCalendars();
  var html='';
  var today=new Date();
  var s=new Date(today.getFullYear(),today.getMonth(),today.getDate());
  var e=new Date(today.getFullYear(),today.getMonth(),today.getDate()+15);
  calA.forEach(function(c){
    var events=c.getEvents(s,e);
    if(events.length>0) {
      html+=Utilities.formatString('
%s
',c.getName());
    }
    html+='
';
    if(events.length>0) {
      html+=Utilities.formatString('
%s	%s	%s	%s	%s	',"EVENT/SHOW","VENUE/LOCATION","DELIVERY NOTES","DATE","TIME");
    }
    events.forEach(function(ev){
      var sd=Utilities.formatDate(new Date(ev.getStartTime()),Session.getScriptTimeZone(),"E MM dd, yyyy");
      var st=Utilities.formatDate(new Date(ev.getStartTime()),Session.getScriptTimeZone(),"hh:mma");
      html+=Utilities.formatString('
%s	%s	%s	%s	%s
',ev.getTitle(),ev.getLocation(),ev.getDescription(),sd,st);
    });
    html+='
';
  });
  if(html) {
    var userInterface=HtmlService.createHtmlOutput(html).setWidth(1000);
    SpreadsheetApp.getUi().showModelessDialog(userInterface, "My Event Data");
  }else{
    SpreadsheetApp.getUi().alert('No Events Found');
  }
}

It loads all event data for each individual calendar in a separate little html table and displays all of them in a modeless dialog.


text:
Q: Recursive function, which writes integer digits in an array(vector) in C++? I have a C++ program, in which I have to create a recursive function that writes all the digits of a given positive integer in an array  - in this case a vector.
However, when I compile the program and enter a number, it stops working. I want to ask why  this happens?
    #include <iostream>
    #include <vector>
    using namespace std;
    vector <int> arr;
    int temp;
    int fill_Array(int num)
    {
        if(num>=1 && num<=9)
        {
            arr.push_back(num);
        }

        temp = fill_Array(num)%10;
        arr.push_back(temp);
        num/=10;

    }
    int main()
    {
        int n;
        cin>>n;
        fill_Array(n);
        for(int i=0; i<arr.size(); i++)
        {
            cout<<arr[i]<<endl;
        }

        return 0;
    }

A: A couple of reasons I can see:

*

*There is no conditional to stop the recusion so it will keep going until it runs out of stack or memory. I presume you want to stop when num is zero

*fill_Array has no return value so will assign temp with some random value which will be pushed into the array

Also why use recursion for this when iterative would be easier and more obvious what it is doing

A: In the given code, recursion function does not returning any value, so return type for that function have no use.
calling the function for recursion is in the wrong place. Correct code given below:
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
void fill_Array(int num)
{
    if(num>=1 && num<=9)
    {
        arr.push_back(num);
    }
    else{
        temp = num%10;
        arr.push_back(temp);
        fill_Array(num/=10);
    }
}
int main()
{
    int n;
    cin>>n;
    fill_Array(n);
    for(int i=0; i<arr.size(); i++)
    {
        cout<<arr[i]<<endl;
    }

    return 0;
}


text:
Q: How can I most accurately calculate the execution time of an ASP.NET page while also displaying it on the page I want to calculate the execution time of my ASP.NET pages and display it on the page. Currently I'm calculating the execution time using a System.Diagnostics.Stopwatch and then store the value in a log database.
The stopwatch is started in OnInit and stopped in OnPreRenderComplete. This seems to be working quite fine, and it's giving a similar execution time as the one shown in the page trace.
The problem now is that I'm not able to display the execution time on the page because the stopwatch is stopped too late in the life cycle.
What is the best way to do this?

A: Here a working solution that redefine Page_Init() and Page_preRender() methods to get the differences in time.
private int startTime;

protected void Page_Init(object sender, EventArgs e)
{
    startTime = Environment.TickCount;
}
protected void Page_PreRender(object sender, EventArgs e)
{
    int endTime = Environment.TickCount;
    double executionTime = (double)(endTime - startTime) / 1000.0;

    lblLabel.Text = "Page Execution time is " + executionTime + " seconds.";
}

A: Persist the execution time information to the server (database, filesystem, cache) and then use ajax or jquery to pull it in off the server into an area of the page asynchronously.

A: I would get the elapsed time from the stopwatch during render time. Most (likely almost all) of the page execution time has elapsed at this point. Go ahead and stop the stop watch where you are now and use that number to log to your DB. I'd bet it won't be much different from what gets displayed on the page.


text:
Q: Mongo db role with find privilege can insert and modify I've created role designer for database M that want to just read col1 collection
but when I login to database it can insert and find and modify col1, and even create new collection and findAndModify col1, but can't remove any data or collection.
What's the problem, I just want to read col1 and do not want to modify col1, and want to insert and read and update other collections and don't want to delete any data from other collections too.
db.createRole(
   {
     role: "designer",
     privileges: [
       { resource: { db: "M" ,collection:"col1" }, actions: [ "find"] },
     ],
    roles:[]
   },
   { wtimeout: 5000 }
)

db.createUser( { user: "U",
                 pwd: "123456",
                 roles: [ { role: "designer", db: "M" }]},
               { w: "majority" , wtimeout: 5000 } )


text:
Q: Голосовое управление Всем добра! Ребят, нужна Ваша помощь. Я хочу добавить голосовое управление в приложении. Возможно ли это вообще? Если да, то что использовать и с чего начать вообще? Буду рад любым советам!

A: Попробуйте начать с Google Cloud Speech API.
Есть примеры использования на Java.
На последнем Google I/O был доклад, на котором показывали робота, управляемого голосом. Ну и вообще на YouTube туториалов уже много.


text:
Q: Python Selenium Error - Nothing happening when webdriver
As the image shows. SublimeText3, I have installed the selenium package but it still won't work. Anyone could help me?
It suppose to open a browser but it did nothing.

A: Did you download and apply chromedriver or geckodriver (Firefox) to your project ?


text:
Q: How to remove loading product images from cache in magento? Due to some problems product images in cache folder turned empty (file is there but empty).Magneto loads product images from cache folder only.
For example: http://example.com/media/catalog/product/cache/54/small_image/295x295/9df78eab33525d08d6e5fb8d27136e95/b/r/br7462vi_1.png
here  br7462vi_1.png  turned empty.(0 bytes).
but http://example.com/media/catalog/product/b/r/br7462vi_1.png works fine.
How can I stop magento loading product images from cache?

A: No need to worry. Simply Login to admin panel.
Goto Admin ->System ->Cache management click on Flush Catalog Images Cache
And also flush all magento cache.
Now all image urls should work.
If you have still problem then just give 777 permission on media/catalog/product directory.
I hope it works.

A: Replace this from list.phtml and all your custome template where you want to load from main media folder
<img id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(236,193); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

With This Code:
<img width="236" height="193" id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage()); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

it only for grid mode you can change for list mode also and product details page medai.pthml file only change on this file src tag src="<?php echo Mage::getModel('catalog/product_media_config')->getMediaUrl( $_product->getSmallImage()); ?>"
Reference: How to remove the cache url for product images in magento


text:
Q: ionic android : when choose image from gallery the app crash When I click on choose file(input="file") to choose an image from gallery , after select the image on android the app crash , and also on ios (iphone).
I already add the permissions on the androidmanifest.xml:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.autofocus" />

and still not working.

A: I was getting the same issue in iOS.
Try adding these data to info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires access to the photo library.</string>
<key>NSCameraUsageDescription</key>
<string>This app requires access to the camera.</string>

For android can you share the logcat output.

*

*How are you building the app, if you don't have Android Studio? Are you using phonegap?

*If you have Android Studio, then a tool Monitor is pre installed with Android Studio. When you open Monitor, then the logs for the app can be seen

If phonegap is used, can u share the id, I can take a look if you want

A: If you only targeting images, I suggest to use the Cordova / Ionic Native plugins instead of using the file input. It will be easier and you will get more control in accessing images and its properties.
You can use either Camera plugin or Photo Library Plugin. You can use the requestAuthorization function to request the permissions from the user.
You may need to add permissions inside your config.xml. For example, as mentioned in the Camera Plugin Ionic's page

[Warning] Since IOS 10 the camera requires permissions to be placed in your config.xml add

<config-file parent="NSCameraUsageDescription" platform="ios" target="*-Info.plist"><string>You can take photos</string></config-file>

Please note that it is always the best idea to have all the permissions inside your config.xml file and not in the AndroidManifest.xml / info.plist, as it will always be added automatically once you add / run your build on the native platforms.


text:
Q: How do I make something Rotate towards mouse? I am trying to solve a question which has been bugging me for a while, can someone explain to me how to make the *red rectangle face/aim towards my mouse and explain to me how it works it would be awesome!!!
Here is the Fiddle

var canvas = document.getElementById('canvas');

var context = canvas.getContext('2d');

var player = {
  x: 200,
  y: 200,
}

drawPlayer = function(something) {
  context.beginPath();
  context.fillStyle = "blue";
  context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
  context.fill();

  context.fillStyle = "red";
  context.fillRect(something.x, something.y - 10, 50, 20);
  context.restore();
}

update = function() {
  context.clearRect(0, 0, 500, 500)
  drawPlayer(player);
}

setInterval(update, 20);
<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>

A: Use context.translate to translate coordinates to the center of your player and then context.rotate to rotate the rectangle.
To find the angle between the mouse position and the center of the player you can use Math.atan2 function.

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var player = {
    x: 200,
    y: 200,
}

drawPlayer = function(something, angle) {
    context.clearRect(0, 0, 500, 500);
    context.beginPath();
    context.fillStyle = "blue";
    context.arc(something.x, something.y, 30, 0, 2 * Math.PI);
    context.fill();

    // save the untranslated context
    context.save();
    context.beginPath();
    // move the rotation point to the center of the player
    context.translate(something.x, something.y);
    context.rotate(angle);

    context.fillStyle = "red";
    // note that coordinates are translated,
    // so 0 is player.x and -10 is player.y - 10
    context.fillRect(0, - 10, 50, 20);
    // restore the context to its untranslated state
    context.restore();
}

drawPlayer(player, 0);

document.onmousemove = function(e) {
    var angle = Math.atan2(e.pageY - player.y, e.pageX - player.x)
    drawPlayer(player, angle);
}
<canvas id="canvas" style="outline: 1px solid #ccc" width="500" height="500"></canvas>


text:
Q: how do I change the icon of blank page? When I open one of my HTML documents in Google Chrome, the left of opened tab doesn't have any ICON on the tab, how do I set that?

A: You need to set title and favicon for your html in the head section of html:
<head>
<title>Your custom title</title>
<link rel="shortcut icon" type="image/png" href="favicon.png">
</head>

and put the favicon.png in same folder of html page.

A: You need to add a favicon image with .ico at the end.
Add it like:
<head>
<title>~~~~</title>
<link rel="shortcut icon" type="image/png" href="favicon.ico">
</head>


text:
Q: Jenkins how to execute particular shell command from the git commit message I have 3 test commands to run on post build but I want to run these commands based on keyword in the git commit message.
Commit message: 'New changes [CoreTest]'

if(CoreTest){
   Run coreTest shell command for spoon
}else if(CloudTest){
   Run CloudTest shell command for spoon
}
else{
   AllTests shell command for spoon
}

A: Try parametrized plugin to do this job
( pass Coretest value as parameter )


text:
Q: Average score facing some technical issues I have followed everything in the book, yet my average score fails me, every single time. I have debugged my program multiple times, in vain.
My minimal executable code:
#include <limits.h>

#include <stdbool.h>

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#include <string.h>

#define MAX_TESTS 5
#define MAXQUESTION 10000

bool myread(const char * format, void * address) {
  char buffer[1024];
  fgets(buffer, sizeof buffer, stdin);
  return sscanf(buffer, format, address) == 1;
}

struct struc {
  int a;

  int b;

  int c;

  int add;

  int grade;
};

int sj(int n) {
  int t;

  t = rand() % n;

  return t;
}

void ctm_i(struct struc * t) {
  {
    t -> a = sj(101);
    t -> c = sj(4);
    if (t -> c == 1) {
      t -> b = sj(101 - (t -> a));
      t -> add = (t -> a) + (t -> b);
    } else {
      t -> b = sj((t -> a) + 1);
      t -> add = (t -> a) - (t -> b);
    }
    t -> grade = 0;
  }
}

void tcm_i(struct struc * t, int n) {
  int ad;

  printf(" ***********************************************************************"
    "*********\n");

  printf(" ......................................................................."
    ".........\n");

  printf(" Question %d\n\n", n + 1);

  printf(" You have 3 attempts for this question\n\n");

  if (t -> c == 1)
    printf(" %d+%d= ", t -> a, t -> b);
  else
    printf(" %d-%d= ", t -> a, t -> b);

  myread(" %d", & ad);
  if (ad == t -> add)

  {
    t -> grade = 10;

    printf(" You earned 10 marks\n\n");
  } else {
    printf("\n Incorrect, you have 2 attempts remaining\n\n");
    printf(" ");
    myread(" %d", & ad);

    if (ad == t -> add)

    {

      t -> grade = 7;

      printf(" You earned 7 marks\n\n");
    } else {
      printf("\n Incorrect, you have 1 attempt remaining\n\n");
      printf(" ");
      myread(" %d", & ad);

      if (ad == t -> add)

      {

        t -> grade = 5;

        printf(" You earned 5 marks\n\n");
      } else {
        t -> grade = 0;

        printf("\n Failure, 0 mark\n\n");

        printf("\n The correct answer is %d\n\n", t -> add);
      }
    }
  }

  printf(" ......................................................................."
    ".........\n");

  printf(" ***********************************************************************"
    "*********\n");
}

void quiz(char name[]) {
  int rounds = 0;
  int highest = 0;
  int lowest = INT_MAX;
  float allScore = 0;
  float avg = 0.0;

  int i, j, g = 0;
  struct struc test[MAX_TESTS];

  srand((unsigned) time(NULL));

  for (;;) {
    rounds++;
    for (i = 0; i < MAX_TESTS; i++) // generate all questions
    {
      ctm_i( & test[i]);

      for (j = 0; j < i; j++)

        if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
          //if question is already present
          ctm_i( & test[i]); //then re-generate
    }
    printf("\n Are you ready? Press Enter key to continue. ");
    myread("", NULL);

    for (i = 1; i <= 5; i++) {
      printf(" *******************************************************************"
        "**"
        "***********\n");

      printf(" ..................................................................."
        ".."
        "...........\n");
    }

    // Take quiz
    for (i = 0; i < MAX_TESTS; i++)
      tcm_i( & test[i], i);

    printf(" End\n\n");

    bool done = false;
    bool unsure = true;
    bool showS = true;

    while (unsure) {
      unsure = false;
      puts("\n");
      if (showS) {
        puts(" Enter 'S' to show results");
      }
      puts(" Enter 'P' to play another round");
      puts(" Enter 'R' to return to main menu");
      char choice;
      printf(" ");
      myread(" %c", & choice);
      printf("\n");
      if (choice == 'r' || choice == 'R') {
        done = true;
      } else {

        ///////////////////////// Changes    /////////////

        g = 0;
        // calculate total score for current round
        for (i = 0; i < MAX_TESTS; i++) {
          g += test[i].grade; //add score of each question
        }
        allScore += g; //add current round's score to total
        avg = allScore / rounds; //average of all rounds

        if (g > highest) {
          highest = g;
        }

        if (g < lowest) {
          lowest = g;
        }

        if (choice == 'S' || choice == 's') {
          showS = false;
          if (rounds == 1) {
            printf(" Final score: %d/100\n", g); //display round score
            printf(" ****** Player: %s ******\n", name);
          } else {
            printf(" Round %d score: %d/100\n", rounds, g); //display round score
            printf(" Highest score: %d/100\n", highest);
            printf(" Lowest score : %d/100\n", lowest);
            printf(" Average score: %f/100\n", avg);
            printf(" ****** Player: %s ******\n", name);
          }
          unsure = true;
        } else if (choice == 'P' || choice == 'p') {
          /// nothing to be done here
          //we will display next test
        } else {
          puts(" Invalid input!");
          unsure = true;
        }

        ////////////////////////////////////

      }
    }
    if (done)
      break;
  }
}

int main() {
  char i1 = '1';
  char name[25]; // ig;
  printf("\n Welcome");

  printf("\n");
  while (i1 != 0) {

    printf("\n");
    //printf(" **********************Welcome %s! *********************\n", name);
    printf(" ************************ Main Menu of Maths Quiz ***************************\n");
    printf(" * 1.Enter Quiz                                                             *\n");
    printf(" * 2.Quit                                                                   *\n");
    printf(" ****************************************************************************\n");
    printf(" Please choose one from 1-2:\n");
    printf(" ");
    myread(" %c", & i1);
    switch (i1) {
    case '1':
      printf("\n Enter Quiz:\n");
      quiz(name); // calling quiz function defined in file "maincode.c"
      break;
    case '2':
      printf(" Quit.\n\n");
    }
  }
  return 0;
}

Hope that fulfilled the definition of an MRE.
So I have snipped off some bombastic lines, and the ones left are the important ones, I think.

A: The problem is in your function quiz, and in particular in the while (unsure) loop. In this loop, you add the most recent score to the running total:
allScore += g; //add current round's score to total

This should happen once per round played. But if the user inputs "S" or something invalid, your program sets
unsure = true;

which means the loop will run again, before the next round is played. It then adds the most recent score a second time to the grand total.
The most logical solution would be to move all the calculations of totals, maximum, minimum, average out of the while-loop. The loop serves a different purpose: it is for user interaction and reporting, not for processing results.

A: possible chance of multiple avg calculation for same round again. Keep flag to track accounting of score, so we will not do the same more than once till the game is not played again.
    #include <limits.h>

    #include <stdbool.h>

    #include <stdio.h>

    #include <stdlib.h>

    #include <time.h>

    #include <string.h>

    #define MAX_TESTS 5
    #define MAXQUESTION 10000

    bool myread(const char * format, void * address) {
      char buffer[1024];
      fgets(buffer, sizeof buffer, stdin);
      return sscanf(buffer, format, address) == 1;
    }

    struct struc {
      int a;

      int b;

      int c;

      int add;

      int grade;
    };

    int sj(int n) {
      int t;

      t = rand() % n;

      return t;
    }
    void ctm_i(struct struc * t) {
      {
        t -> a = sj(101);
        t -> c = sj(4);
        if (t -> c == 1) {
          t -> b = sj(101 - (t -> a));
          t -> add = (t -> a) + (t -> b);
        } else {
          t -> b = sj((t -> a) + 1);
          t -> add = (t -> a) - (t -> b);
        }
        t -> grade = 0;
      }
    }

    void tcm_i(struct struc * t, int n) {
      int ad;

      printf(" ***********************************************************************"
"*********\n");
      printf(" ......................................................................."
".........\n");

      printf(" Question %d\n\n", n + 1);

      printf(" You have 3 attempts for this question\n\n");

      if (t -> c == 1)
        printf(" %d+%d= ", t -> a, t -> b);
      else
        printf(" %d-%d= ", t -> a, t -> b);

      myread(" %d", & ad);
      if (ad == t -> add)

      {
        t -> grade = 10;

        printf(" You earned 10 marks\n\n");
      } else {
        printf("\n Incorrect, you have 2 attempts remaining\n\n");
        printf(" ");
        myread(" %d", & ad);

        if (ad == t -> add)

        {

          t -> grade = 7;

          printf(" You earned 7 marks\n\n");
        } else {
          printf("\n Incorrect, you have 1 attempt remaining\n\n");
          printf(" ");
          myread(" %d", & ad);

          if (ad == t -> add)

          {

            t -> grade = 5;

            printf(" You earned 5 marks\n\n");
          } else {
            t -> grade = 0;

            printf("\n Failure, 0 mark\n\n");

            printf("\n The correct answer is %d\n\n", t -> add);
          }
        }
      }

      printf(" ......................................................................."
".........\n");

      printf(" ***********************************************************************"
"*********\n");
    }

    void quiz(char name[]) {
      int rounds = 0;
      int highest = 0;
      int lowest = INT_MAX;
      float allScore = 0;
      float avg = 0.0;

      int i, j, g = 0;
      struct struc test[MAX_TESTS];

      srand((unsigned) time(NULL));

      for (;;) {
        rounds++;
        for (i = 0; i < MAX_TESTS; i++) // generate all questions
        {
          ctm_i( & test[i]);

          for (j = 0; j < i; j++)

            if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
              //if question is already present
              ctm_i( & test[i]); //then re-generate
        }
        printf("\n Are you ready? Press Enter key to continue. ");
        myread("", NULL);

        for (i = 1; i <= 5; i++) {
          printf(" *******************************************************************"
    "**"
    "***********\n");

          printf(" ..................................................................."
    ".."
    "...........\n");
        }

        // Take quiz
        for (i = 0; i < MAX_TESTS; i++)
          tcm_i( & test[i], i);

        printf(" End\n\n");

        bool done = false;
        bool unsure = true;
        bool showS = true;
        bool acct = false;

while (unsure) {
  unsure = false;
  puts("\n");
  if (showS) {
    puts(" Enter 'S' to show results");
  }
  puts(" Enter 'P' to play another round");
  puts(" Enter 'R' to return to main menu");
  char choice;
  printf(" ");
  myread(" %c", & choice);
  printf("\n");
  if (choice == 'r' || choice == 'R') {
    done = true;
  } else {

    ///////////////////////// Changes    /////////////
    if (false == acct) {
    g = 0;
    // calculate total score for current round
    for (i = 0; i < MAX_TESTS; i++) {
      g += test[i].grade; //add score of each question
    }
    allScore += g; //add current round's score to total
    avg = allScore / rounds; //average of all rounds

    if (g > highest) {
      highest = g;
    }

    if (g < lowest) {
      lowest = g;
    }
    acct = true;
    }
    if (showS &&(choice == 'S' || choice == 's')) {
      showS = false;
      if (rounds == 1) {
        printf(" Final score: %d/100\n", g); //display round score
        printf(" ****** Player: %s ******\n", name);
      } else {
        printf(" Round %d score: %d/100\n", rounds, g); //display round score
        printf(" Highest score: %d/100\n", highest);
        printf(" Lowest score : %d/100\n", lowest);
        printf(" Average score: %f/100\n", avg);
        printf(" ****** Player: %s ******\n", name);
      }
      unsure = true;
    } else if (choice == 'P' || choice == 'p') {
      /// nothing to be done here
      //we will display next test
    } else {
      puts(" Invalid input!");
      unsure = true;
    }

    ////////////////////////////////////

  }
}
if (done)
  break;
      }
    }

    int main() {
      char i1 = '1';
      char name[25]; // ig;
      printf("\n Welcome");

      printf("\n");
      while (i1 != 0) {

printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz                                                             *\n");
printf(" * 2.Quit                                                                   *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
          printf("\n Enter Quiz:\n");
          quiz(name); // calling quiz function defined in file "maincode.c"
          break;
        case '2':
          printf(" Quit.\n\n");
        }
      }
      return 0;
    }

Output:
     Enter 'S' to show results
      Enter 'P' to play another round
      Enter 'R' to return to main menu
      s

      Round 2 score: 47/100
      Highest score: 50/100
      Lowest score : 47/100
      Average score: 48.500000/100
      ****** Player:  ******


text:
Q: Angular JS $http Post with REST query parametres I am  pretty new to Angular JS technology.
I want to call following protected REST URL.
 http://localhost/rest/bpm/wle/v1/search/query?condition=taskActivityName|Equals|Cashier Review&condition=taskStatus|Equals|Received&organization=byTask&run=true&shared=false&filterByCurrentUser=false

Following code is not working for me. It is   taking only `http://localhost/rest/bpm/wle/v1/search/query .Please suggest.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
var URLBASE = "http://localhost/rest/bpm/wle/v1";
var userid = "harish.puli";
var password = "Password1";
 // End of buildAuthorization
  var options =$.param ({
    query : {
                organization : "byTask",
                condition : [ "taskActivityName|Equals|Cashier Review", "taskStatus|Equals|Received" ]
            },
            handleAs : "json",
            user: "harish.puli",
            password: "Password1"
        });
  var url=URLBASE+"/search/query";
  $http.post(url,options).success(function (response) {
    console.log(response);
    $scope.tasks = response.data.data;
    });
});

A: I believe you're missing a '?' after query based on the URL you provided.
Try:
var url=URLBASE+"/search/query?";

A: Your code is only calling http://localhost/rest/bpm/wle/v1/search/query because you're using post instead of get. In get you transmit the parameters in the URL but in post they are transmitted in the body of the request.


text:
Q: How to check whether a type is string in C#? I want to go through all the properties of a type and want to check whether a property type is not a string, how can I do it ?
My class is:
public class MarkerInfo
{
    public string Name { get; set; }
    public byte[] Color { get; set; }
    public TypeId Type { get; set; }
    public bool IsGUIVisible { get; set; }

    public MarkerInfo()
    {
        Color = new byte[4]; // A, R, G, B
        IsGUIVisible = true;
    }
}

the code I am using to check for type is:
foreach (var property in typeof(MarkerInfo).GetProperties())
{
    if (property.PropertyType is typeof(string))
}

But this code is not working, any idea how to do that  ?

A: use == and not is or is String (leave the typeof)

A: if (property.PropertyType == typeof(string))

A: Use the following instead:
foreach (var property in typeof(MarkerInfo).GetProperties())
{
    if (property.PropertyType == typeof(string))
}


text:
Q: 320gb hdd all ubuntu, want to partition and add win 7 I am using Ubuntu 14.04
blkid=
/dev/sda1: UUID="05cd7e6a-caf1-44bc-9900-92ec14c5ea34" TYPE="ext2"
/dev/sda5: UUID="J450yI-3go9-4Ps2-kdQm-lNH7-Go3J-FrvhOm" TYPE="LVM2_member"
/dev/mapper/ubuntu--vg-root: UUID="9cd5d111-ec03-4298-803a-a65fdc8790ea" TYPE="ext4"
/dev/sdb: LABEL="UDF Volume" TYPE="udf" /*This is Win 7 install*/

This is system monitor file system output:
Device                         Directory     Type  Total   Available
/dev/mappper/ubuntu--vg-root   /             ext4  310.6GB 240.1GB
/dev/sda1                      /boot         ext2  246.8MB 135.3MB
/dev/sdb                       /media/name/udf     3.2GB   0 bytes

I would like to partition the first drive and install win 7 from sd card at /dev/sdb
I am novice level, but am comfortable and competent to cut and paste into terminal.
Open for suggestions for another method, no floppy drive but plenty of blank cd's and usb drives and sd card capacity.

A: If I were you, I would do the following:

*

*Boot into Ubuntu or GParted Live CD/DVD

*(Ubuntu only) Install GParted (sudo apt-get update && sudo apt-get install gparted)

*Graphically shrink the Ubuntu to partition the amount you want to use with Windows

*Reboot, boot into Windows 7 disc/card/what have you

*Partition the now completely unused space via installer and install Windows 7

WikiHow GParted Live CD/DVD Guide
You may need to recover your bootloader in order to be able to choose between Ubuntu and Windows at boot. Official Guide to Repairing Bootloader
Always backup any files you want to keep before partitioning, stuff happens.


text:
Q: Wrong file version in requirement package A file seems to be outdated in requirements package synergine-0.0.1.9 when environment is build.
.travis.yml
language: python
python:
  - "3.4"
install:
  - "pip install -r tests_requirements.txt --upgrade"
  - "pip install python-coveralls"
script:
  - coverage run tests.py --rcfile=.coveragerc -v && coverage report -m && python3.4 tests.py
after_success:
  - coveralls

tests_requirements.txt
synergine>=0.0.1
synergine_xyz>=0.0.1

travis-ci.org build log:
[...]
pip 6.0.7 from /home/travis/virtualenv/python3.4.2/lib/python3.4/site-packages (python 3.4)
install.1

1.74s $ pip install -r tests_requirements.txt --upgrade

You are using pip version 6.0.7, however version 7.0.3 is available.

You should consider upgrading via the 'pip install --upgrade pip' command.

Collecting synergine>=0.0.1 (from -r tests_requirements.txt (line 1))

  Downloading synergine-0.0.1.9.tar.gz

    pypandoc not found

Collecting synergine-xyz>=0.0.1 (from -r tests_requirements.txt (line 2))

  Downloading synergine_xyz-0.0.1.9.tar.gz

Installing collected packages: synergine-xyz, synergine

  Running setup.py install for synergine-xyz

  Running setup.py install for synergine

    pypandoc not found

Successfully installed synergine-0.0.1.9 synergine-xyz-0.0.1.9

[...]

[...]
0.31s$ coverage run tests.py --rcfile=.coveragerc -v && coverage report -m && python3.4 tests.py

[...]

  File "/home/travis/virtualenv/python3.4.2/lib/python3.4/site-packages/synergine/core/simulation/MetaValue.py", line 19, in unset

    del (state[subject])

NameError: name 'state' is not defined

The synergine/core/simulation/MetaValue.py", line 19, in unset on travis-ci build is:
del (state[subject])

If we look synergine/core/simulation/MetaValue.py", line 19, in unset
 available on pypi:
del(metas[subject])

Files are not identicals. Problem is in a travis-ci cache ? How can i fix that ?
Build page available here.

A: After discuss with travis-ci support by email, we think problem do not come from travis-ci but maybe from pypi (strange specific cache rule ?).


text:
Q: sales_flat_quote_* vs enterprise_customer_sales_flat_customer_quote_* I'm looking to remove old quotes from the database via a Magento shell script, and I see enterprise_customer_sales_flat_quote and enterprise_customer_sales_flat_quote_address whose purpose is unclear to me. These are don't have any key constraint on them to the native Mage tables.
In the Enterprise_Customer module, under which the models for these tables are, there is not much responsible code. What are these for, and are they safe to remove along with the "associated" sales_flat_quote/_address records? ("associated" because there is no formal constraint but they seem to have the same entity_ids.

A: These tables are mainly used when events are called, and there are a lot of them, all found in app/code/core/Enterprise/Customer/etc/config.xml:
<sales_quote_load_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesQuoteAfterLoad</method>
        </enterprise_customer>
    </observers>
</sales_quote_load_after>
<sales_quote_address_collection_load_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesQuoteAddressCollectionAfterLoad</method>
        </enterprise_customer>
    </observers>
</sales_quote_address_collection_load_after>
<sales_quote_save_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesQuoteAfterSave</method>
        </enterprise_customer>
    </observers>
</sales_quote_save_after>
<sales_quote_address_save_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesQuoteAddressAfterSave</method>
        </enterprise_customer>
    </observers>
</sales_quote_address_save_after>
<sales_order_load_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesOrderAfterLoad</method>
        </enterprise_customer>
    </observers>
</sales_order_load_after>
<sales_order_address_collection_load_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesOrderAddressCollectionAfterLoad</method>
        </enterprise_customer>
    </observers>
</sales_order_address_collection_load_after>
<sales_order_save_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesOrderAfterSave</method>
        </enterprise_customer>
    </observers>
</sales_order_save_after>
<sales_order_address_save_after>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>salesOrderAddressAfterSave</method>
        </enterprise_customer>
    </observers>
</sales_order_address_save_after>
<enterprise_customer_attribute_before_save>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>enterpriseCustomerAttributeBeforeSave</method>
        </enterprise_customer>
    </observers>
</enterprise_customer_attribute_before_save>
<enterprise_customer_attribute_save>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>enterpriseCustomerAttributeSave</method>
        </enterprise_customer>
    </observers>
</enterprise_customer_attribute_save>
<enterprise_customer_attribute_delete>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>enterpriseCustomerAttributeDelete</method>
        </enterprise_customer>
    </observers>
</enterprise_customer_attribute_delete>
<enterprise_customer_address_attribute_save>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>enterpriseCustomerAddressAttributeSave</method>
        </enterprise_customer>
    </observers>
</enterprise_customer_address_attribute_save>
<enterprise_customer_address_attribute_delete>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>enterpriseCustomerAddressAttributeDelete</method>
        </enterprise_customer>
    </observers>
</enterprise_customer_address_attribute_delete>
<core_copy_fieldset_sales_convert_quote_to_order>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetSalesConvertQuoteToOrder</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_convert_quote_to_order>
<core_copy_fieldset_sales_convert_quote_address_to_order_address>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetSalesConvertQuoteAddressToOrderAddress</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_convert_quote_address_to_order_address>
<core_copy_fieldset_sales_copy_order_to_edit>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetSalesCopyOrderToEdit</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_copy_order_to_edit>
<core_copy_fieldset_sales_copy_order_billing_address_to_order>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetSalesCopyOrderBillingAddressToOrder</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_copy_order_billing_address_to_order>
<core_copy_fieldset_sales_copy_order_shipping_address_to_order>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetSalesCopyOrderShippingAddressToOrder</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_copy_order_shipping_address_to_order>
<core_copy_fieldset_customer_account_to_quote>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetCustomerAccountToQuote</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_customer_account_to_quote>
<core_copy_fieldset_customer_address_to_quote_address>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetCustomerAddressToQuoteAddress</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_customer_address_to_quote_address>
<core_copy_fieldset_checkout_onepage_quote_to_customer>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetCheckoutOnepageQuoteToCustomer</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_checkout_onepage_quote_to_customer>
<core_copy_fieldset_sales_convert_quote_address_to_customer_address>
    <observers>
        <enterprise_customer>
            <class>enterprise_customer/observer</class>
            <method>coreCopyFieldsetQuoteAddressToCustomerAddress</method>
        </enterprise_customer>
    </observers>
</core_copy_fieldset_sales_convert_quote_address_to_customer_address>

It appears that what magento have done here is to latch onto the events rather than rewrite the community classes, which I think it a good solution from them.
If you look closely into one of these observers, we will take salesQuoteAfterLoad, it takes the quote from the observer and loads the enterprise version of it. It then calls attachAttributeData which simply adds all the data from the original quote into that enterprise quote.
public function salesQuoteAfterLoad(Varien_Event_Observer $observer)
{
    $quote = $observer->getEvent()->getQuote();
    if ($quote instanceof Mage_Core_Model_Abstract) {
        Mage::getModel('enterprise_customer/sales_quote')
            ->load($quote->getId())
            ->attachAttributeData($quote);
    }

    return $this;
}

I would suggest looking at this observer you are fairly safe. If you are clearing the community tables then you can also clear the enterprise tables. But obviously backup your data first :)


text:
Q: Mask value offset in input and shown formatted in Datatable using Material UI I'm having a problem with formatting the monetary mask in my input. I installed the ng2-currency-mask package
But my input does not show the value entered as follows:
$4.00
Where the $ symbol must appear whenever I inform some value and I'm also not able to set the maximum value of $999,999,999.99
always appears: 9,999,999,999.9
And it is allowing to enter negative values
And in the grid when I add the record, it doesn't format in the pattern informed in the input
What do I need to do to correctly show the data.
Input currencyMask
<mat-form-field appearance="outline" class="w-100 mat-form-field-label-out" floatLabel="never"
                color="accent">
                <input formControlName="valueT" matInput
                currencyMask [options]="{ prefix: '', decimal: '.', thousands: '.', precision: '1', allowNegative: true }"
                max="999.999.999,99" [maxlength]="20">

            </mat-form-field>

Table
<mat-table [dataSource]="dataSource" matSort class="w-100">

        <ng-container matColumnDef="value">
            <mat-header-cell *matHeaderCellDef mat-sort-header>Value</mat-header-cell>
            <mat-cell *matCellDef="let element" data-label="Value"> {{element?.value}} </mat-cell>

        </ng-container>

        <mat-header-row *matHeaderRowDef="colunas"></mat-header-row>
        <mat-row *matRowDef="let row; columns: coluns;"></mat-row>
    </mat-table>

Typscript
private popule(): MatTableDataSource<ValuesaDTO> {

        let value = this.form.controls['value']?.value; //value => number

            let valuesList = new ValuesDTO();

            valuesList.value = value;

            this.valuesList.push(valueList);

        this.dataSource = new MatTableDataSource(this.valuesList);

        return this.dataSource;
    }


text:
Q: Print from JavaScript function to HTML without document.write() I searched everywhere on here on an alternative on printing to HTML from a JavaScript function to HTML without using document.write() but document.getElementById() doesn't seem to work and I'm really not sure how to go about doing this.
I have this so far
JavaScript
function trials() {

    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            document.write(random[i]);
        }
    }
}

Where "random" is an array of letters
HTML

        **TRIALS HERE**

I'm also looking for a way to hide each letter after each iteration of the for-loop so that it doesn't just print as a long string of letters.

A: Basic idea is to use an interval to loop through the array so there is a delay. You want to set the text with innerHTML or textContent.

(function() {

    var outputElem = document.getElementById("outputSpot"),  //where to output the letter on the screen
        current = 0,  //start index in the array
        randomChars = ["W","E","L","C","O","M","E","!"],  //characters to show
        timer = window.setInterval(  //this is how we will loop with an interval
            function () {
                var letter = randomChars[current];  //get next letter
                if (letter) {  //if there is no letter, it will be undefined and we will be done
                    outputElem.innerHTML = letter;  //show the letter to the user
                    current++;  //update the index
                } else {
                    window.clearInterval(timer);  //cancel the timer since we ran out of things to display
                }
            }
        ,1000);  //number of seconds to wait between iterations

}());
Hello!

A: Javascript
I would try setting the div to a variable:
var div = $('#container');
function trials() {
    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            div.appendTo(random[i]);
    }
}

HTML
Then maybe hiding the container div (style='display:none;') would prevent the numbers printing out, but still accessible:

        **TRIALS HERE**

A: It may be very useful for you to use JQuery.

function trials() {

    while (num_trials > 0) {

        for (var i = 0; i < random.length; i++) {
            $('#iToWrite').html( $('#iToWrite').html() + random[i]);
        }
    }
}

        **TRIALS HERE**