text:
Q: Store Zend OpCache as files in PHP 5.6? I'm trying to obfuscate and speed up my code using Zend OpCache, but OpCache doesn't seem to have the usual functions to store bytecode in a file like other older caching systems did. As OpCache is the native method of caching files in memory in opcode, I'd like to continue using it, but I need to be able to obscure my code in the case of a system breach. (Just another security precaution)
What options do I have available to me to store my PHP files as compiled code in opcode or bytecode?
EDIT: I think people misunderstood what I was looking for for the most part. Please read my comments on the posts. I'm a professional web developer of over 12 years, so I'm not new to this. I just wanted to change my tactics a bit and see if others knew of a way to pull this off that I didn't think of.

A: It's definitely not a good idea to start developing your own tools for obfuscating or protecting your PHP code.
For protected your code use SourceGuardian or Nu-Coder. Both tools, however, require installing special PHP extension on server, which is not an option for many webhosting companies. These tools provide possibility to lock your code to certain machine (hardware hash, IP binding, ..), control the number of licences, expiration etc.
If you are serious about protecting your code (not only obfuscation) use virtual server + one of the tools mentioned. In run-time, both extensions hold in-memory opcached decrypted low-level code, so besides protecting the code they provide also performance boost. I tested PHP 5.5.x with loaded both SourceGuardian and opcache and there were no conflicts.


text:
Q: UV divergence integral Could anyone please explain how to calculate integral such as
$$\frac{\Omega}{2}\int_{-\infty}^{+\infty} \frac{d^3k}{(2\pi)^3}\ln\left[{1+\frac{a^2}{k^2}}\right]=-\frac{\Omega a^3}{12\pi}+I_0~?$$ This integral doesn't converge.
I guess we have to use UV divergence cut-off, but I don't fully understand the technique of this method.
Reference:
Double screening in polyelectrolyte solutions: Limiting laws and crossover formulas
M. Muthukumar
http://dx.doi.org/10.1063/1.472362
Page 5187, formula 2.13

A: Have you tried differentiating wrt to $a$?  If $I=(2\pi)^3$ times your integral, I get
$$
\frac {dI}{da} = 8\pi a  \int_0^\infty k^2 d k  \frac{1}{k^2+a^2}\\=8\pi a  \int_0^\infty  d k  \frac{k^2+a^2}{k^2+a^2} -  8\pi a  \int_0^\infty  d k  \frac{a^2}{k^2+a^2},
$$
which is in the form of divergent constant together with  a convergent integral proprtional to $a^2$. Integrating back up suggests that his $I_0$ is propertional to $\Lambda a^2$ where $\Lambda$ is the large-$k$ cutoff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pointer arithmetic to change array values This is a follow on question to an earlier one.
I have learned some errors of my ways, but have extra questions. My objective is to have a local array in one method changed from another method without the use of any global variables.
void methodOne(){

        int myArray[10] = {0};
        int *pMyArray = myArray;

        methodTwo(&*pMyArray);
}

This should be declaring an array of null values and passing a reference to the second array as I was shown how to do so correctly here.
void methodTwo(int *passedPointer){

        int *localPointer =  passedPointer;

}

Next I'd like to change the values of myArray from methodTwo. So to change the first [0] element I would say:
*localPointer  = 1;

Is this correct?
Then to change the next element would I increment the pointer using:
localPoint++;
*localPointer = 2;

Would this change the second value in myArray? I'm not sure thats the correct way to do it is it?
TIA

A: Yes, this all looks like it should work. Generally when you're passing an array to a function, you don't assign to a local variable first though -- you just pass the name of the array as the parameter: methoTwo(myArray);. The compiler will automatically convert the name of the array to a pointer to the beginning of the array.
Also note that you can use array-style notation on the receiving end, something like:
localpointer[0] = 1;
localpointer[1] = 2;

...is also reasonable and will accomplish the same as your
*localpointer = 1;
++localpointer;
*localpointer = 2;

For what it's worth, another alternative would be:
*localpointer++ = 1;
*localpointer = 2;

A: First, you pass the array incorrectly. An array is nothing more than a pointer to the first, element, so you don't need to take it's address to pass it to MethodTwo. However, what you should do, is pass in the number of elements in that array to MehtodTwo:
 methodTwo(MyArray, 10);

Since an array is nothing other than a pointer to the first element, you can directly index into the array without requiring the use of pointer arithmetics:
void methodTwo(int passedArray[], size_t n)
// alternative void methodTwo(int *passedArray, size_t n)
{

  passedArray[0] =  passedPointer;

}

A: No, this is wrong. Very wrong. Array to pointer decay is really, really bad and you should never, ever, use it. Use a class-based wrapper like std::array, and pass in a pair of iterators to MethodTwo.


text:
Q: PHP - Convert this string to another date/time format I'm working with an API that returns timestamps in this format:
07/23/2017 23:39:21

The format is: MM/DD/YYYY HH:MM:SS
I need to covert this string so it displays in this format on my webpage:
23 July 2017, 11:39pm
Is this possible?

A: You can do this :
$date = new DateTime('07/23/2017 23:39:21');
echo $date->format('d F o, h:ia');

Output :
23 July 2017, 11:39pm

A: Take a look at  http://php.net/manual/de/datetime.createfromformat.php. You'll get a DateTime object which you can convert in the format you desire.
Like so:
<?php
$date = DateTime::createFromFormat('m/d/Y H:i:s', '07/23/2017 23:39:21');
echo $date->format('d M Y, h:ia');
?>


text:
Q: Laravel testing POST JSON I am writing test in laravel. I want o send JSON in post. Below is the image

How can i send the json data in postJson ?
/**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_create_attribute()
    {
        $response =  $this->postJson('/api/catalog/attributes?storeId=1000000006', How to send json data);

        $response->assertStatus(201);
    }

A: use Illuminate\Support\Facades\Http;

$response = Http::post('http://example.com/users', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

Source: https://laravel.com/docs/9.x/http-client


text:
Q: Can't install Apache 2.4 on ubuntu 14.10 I've tried multiple PPAs, none have worked, I checked the policy on the Caché, tried to clear it, it returns the same. It insists on trying to install Apache 2.2 when I need 2.4.
Here's the result of     sudo apt-cache policy apache2
apache2:
  Installed: (none)
  Candidate: 2.2.22-1ubuntu1.10
  Version table:
     2.2.22-1ubuntu1.10 0
        500 http://archive.ubuntu.com/ubuntu/ precise-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu/ precise-security/main amd64 Packages
     2.2.22-1ubuntu1 0
        500 http://archive.ubuntu.com/ubuntu/ precise/main amd64 Packages

Any help is much appreciated.
Thanks a lot.

A: please refer this Link
for installing apache 2.4 on your ubuntu machine.
may help you.

A: I did some changes on the distribution the packages were being gotten for inside Software Center -> Edit -> Software sources -> other sources.
Changed the distribution to Utopic, then performed a banish404 using the packages in this ppa, and things work now.
Thank you all for your answers.


text:
Q: How do I change image colors with JES programing? My goal is to double the picture size then change the left half to grayscale, then change the green value of the top right half and the blue value of the bottom right half. I have values that I found in my textbook for the grayscale but im not sure if thats what I actually use. And I also am unsure if I program each of these different values using for loops or just something different
So far my code is:
 def crazyPic(newGreen,newBlue,pic,file):
      show(pic)
      newPic = makeEmptyPicture(getWidth(pic)*2,getHeight((pic)*2
           for x in range(width):
              for y in range(height):
                  for px in getPixel(pic,0,100):
                  nRed = getRed(px) * 0.299
                  nGreen = getGreen(px) * 0.587
                  nBlue = getBlue(px) * 0.114
                  luminance = nRed + nGreen + nBlue
                  setColor(px,makeColor(luminance,luminance,luminance)

A: I shouldn't give full answers as JES is an application designed for students, but I think that three months later one can give a full working sample which can be used as reference for the others...
This should be close to what you attempted to do:
Note : your approach of a simple double loop over x and y was the right one.
def crazyPic(pic, newRed, newGreen, newBlue):

    w = getWidth(pic)
    h = getHeight(pic)
    new_w = w * 2
    new_h = h * 2
    newPic = makeEmptyPicture(w * 2, h * 2)

    for x in range(new_w):
      for y in range(new_h):
          new_px = getPixel(newPic, x, y)

          # Top-left: B&W
          if (x < w) and (y < h):
            px = getPixel(pic, x, y)
            nRed = getRed(px) * newRed #0.299
            nGreen = getGreen(px) * newGreen #0.587
            nBlue = getBlue(px) * newBlue #0.114
            luminance = nRed + nGreen + nBlue
            new_col = makeColor(luminance, luminance, luminance)

          # Top-right
          elif (y < h):
            px = getPixel(pic, x - w, y)
            nRed = getRed(px) * newRed
            new_col = makeColor(nRed, getGreen(px), getBlue(px))

          # Bottom-left
          elif (x < w):
            px = getPixel(pic, x, y - h)
            nGreen = getGreen(px) * newGreen
            new_col = makeColor(getGreen(px), nGreen, getBlue(px))

          # Bottom-right
          else:
            px = getPixel(pic, x - w, y - h)
            nBlue = getBlue(px) * newBlue
            new_col = makeColor(getGreen(px), getBlue(px), nBlue)

          setColor(new_px, new_col)

    return newPic

file = pickAFile()
picture = makePicture(file)
#picture = crazyPic(picture, 0.299, 0.587, 0.114)
# Here, with my favorite r, g, b weights
picture = crazyPic(picture, 0.21, 0.71, 0.07)

writePictureTo(picture, "/home/quartered.jpg")

show(picture)

Output (Painting by Antoni Tapies):

......From......

Here is a more detailed thread about greyscale.


text:
Q: Snap render list in Hamlet Given this little project I'm using to learn Haskell, I would like to move my request handler's code generation to a Hamlet template, but am unsure how to pass things around.
My current code generates the following error when lines are uncommented, which is the first blocker:

Couldn't match expected type `String -> String'
                with actual type `String'
    In the return type of a call of `renderHtml'
    Probable cause: `renderHtml' is applied to too many arguments
    In the expression: renderHtml ($ (shamletFile "fileList.hamlet"))
    In an equation for `myTemplate':
        myTemplate = renderHtml ($ (shamletFile "fileList.hamlet"))

Code:
site :: Snap ()
site =
    ifTop (writeBS "hello world") <|>
    route [ ("foo", writeBS "ba"),
            ("view_root_json_files", listRootFilesHandler)
          ] <|>
    dir "static" (serveDirectory ".")

--myTemplate :: String -> String
--myTemplate = renderHtml ( $(shamletFile "fileList.hamlet") )

toText :: [FilePath] -> Text
toText = foldMap (flip snoc '\n' . pack)

listRootFilesHandler :: Snap ()
listRootFilesHandler = do
    filenames <- liftIO $ getDirectoryContents "data"
    let filtered_filenames = filter (not . isPrefixOf ".") filenames
    writeText $ toText filtered_filenames

A: Ghc is telling you the correct type signature to put there. Just replace String -> String with String.


text:
Q: Showing certain levels in outlines in word In word, when we create an outline, is there a way to close lower levels from view. For instance, if the outline is

Then how can we just show the levels represented by the roman numbers (I, II), hiding the levels represented by the uppercase letters (A, B, C) and the arabic numerals (1, 2).

A: How can I expand/collapse outlines in Word?
This is a new feature introduced in Word 2013.

Word 2013 introduces a new feature that allows you to expand and
  collapse certain parts of your document. It reminds me very much of
  the kind of web page interactivity that lets you click on a brief
  summary of something to display a more detailed description. And
  that's precisely what this is.

Source Expand And Collapse In Word 2013

What if I have an older version of Word?
In older versions of Word there are addons that will do the same, for example
More Add-in (paid software):

Adds Expand and Collapse to Word Documents
With the More Word add-in installed, making part of a document expand-
  and collapse-able is as easy as formatting text as Bold or Italic:
Beyond creating and using simple collapsibles, More Add-in provides a
  lot of support for the collapsible "power user" - for example,
  automatic creation of collapsibles for all headings, or creating your
  own custom toggle buttons.

There are also two VBA scripts at Toggle Data Display which might be of interest:

This Microsoft Word Help & Microsoft Word Tips page provides some methods and techniques to allow the document user to show/hide (or expand/collapse) document content.


text:
Q: "A classmate and I was" vs "A classmate and I were" I'm writing a resume right now targeted towards a specific company. My girlfriend (a classmate) and I were (see, I don't know if that's the right word, hence this question!) the first from our school to be awarded a scholarship from this company.
Is it more correct to say:

Awarded such and such scholarship in 2011. A classmate and I were the first students from my college to be awarded this scholarship.

Or:

Awarded such and such scholarship in 2011. A classmate and I was the first students from my college to be awarded this scholarship.

The first seems much more correct when spoken, but the rule I've been taught is to take the other person out and use the words that make sense about just you.

A:
the rule I've been taught is to take the other person out and use the words that make sense about just you.

This rule should be applied to what pronoun you're going to use, not what verb form: should you say "Bob went to the store with Mary and I"?  Take Mary out of the sentence, and you're left with "Bob went to the store with I" which is obviously wrong.
For pluralization, if you can reasonably substitute a plural pronoun, then you should use a plural verb.  "A classmate and I" -> "we" -> "we were" -> "A classmate and I were".

A: The verb were agrees with the plural subject, "A classmate and I".  The singular "student" should be plural "students" in both examples.
You might say "I was one of the first two x students to be awarded this scholarship" (where x is name of college) to better emphasize your achievement and avoid the non-specific and distracting phrase, "a classmate".

A: And links two things (e.g. a classmate and I), and results in a plural subject (A classmate = 1, I = 1, so a classmate and I = 1 + 1 = 2), so were is correct:

Awarded such and such scholarship in 2011. A classmate and I were the first students from my college to be awarded this scholarship.

The rule you refer to applies only to figuring what case of pronoun to use (e.g. I or me), not to whether you should use singular or plural (e.g. was or were).  When you use the rule to figure out which of I or me is correct, you should alter the number of the verb (were becomes was) and direct object (students becomes student) when you take out the other person:

A classmate and I were the first students becomes I was the first student (correct).
A classmate and me were the first students becomes Me was the first student (incorrect).

When you add the classmate back into the sentence, you can be assured of the proper pronoun (I, not me).

A: A compound subject (e.g., classmate and I) requires a plural verb (e.g., were) because it refers to more than one person.
To simplify this and avoid technical terminology, let's replace the entire subject with a pronoun. Here, you replace "classmate and I" with "we." "We" and "a classmate and I" mean the same thing and are, therefore, interchangeable. (Notice that the previous sentence, too, has a compound subject: " 'we' and 'a classmate and 'I.' " That compound subject can be replaced with the pronoun "they," which requries a plural verb: "mean.")
You will say "we were" and not "we was." Now let's put the original subject back in place, giving us "a classmate and I were."
Compound subjects are always plural. On the other hand, if you use "or" rather than "and," you will need a singular verb.

A: If the subject of the phrase is in the form A and B, then the verb uses the form for the third person plural; if the subject of the phrase is in the form A or B, then the verb uses the form for third person singular.

Audrey and Patricia know her. (Both of them know her.)
  Audrey or Patricia knows her. (One of them knows her.)


text:
Q: How to link two Actionscript files to a .fla file? The .fla file only gives you the option to link one .src file in the 'Class' bit, is there any way to link two .as files to the .fla file?
Thank you!

A: You can only have one document class (which corresponds to a .as file), however every symbol can have a class associated with it as well. This gives you in essence an unlimited amount of .as files that are associated with the .fla file.
To create a document class:

*

*Go to the properties window; under the Publish section, there is an empty field where you can name your class.

*Name it whatever you'd like (most likely a similar name to your .fla file). Clicking the pencil will prompt the creation of this class, which will automatically open a new .as file for you.

To create a class for a symbol:

*

*Go to the Library tab; Right click where the symbols normally go and click 'New Symbol'.

*Name your symbol, then click the checkbox 'Export for ActionScript'. Fill in the Class field with what you want your .as file to be named.


text:
Q: javascript string localization in Laravel I'm having problems with the encoding of some localized strings in laravel.
In my localization file for Spanish I have (among many other strings):
"truck" => "camión"

In myView.blade.php, if I print the string directly:

{{trans('localizationFile.truck'}}

It works fine and prints camión
But if I try to use that same string in javascript:

It codifies the accented o and the alert reads: camión
How can I fix that?
Or am I doing something wrong?
Perhaps that's not the way to localize javascript messages...
Thanks in advance!

A: When outputting an alert, the HTML entities are not decoded so they are show as plain text. The simplest solution to fix this is to add the text to an HTML element and return its content via the text method, which will decode the HTML entities:

The above uses jQuery's html method, but this can be achieved with vanilla JS and innerHtml.

If you want to include an extra JS library you can use he, that takes care of decoding. So it would look something like this:


text:
Q: Extend the behavior of the finish method of the class WizardArchiveFileResourceExportPage1 I want to extend the behavior of the finish method of the class 'org.eclipse.ui.internal.wizards.datatransfer.WizardArchiveFileResourceExportPage1'. The finish method basically gets the list of type IResources to export. executeExportOperation(new ArchiveFileExportOperation(null,
                resourcesToExport, getDestinationValue())) I want to modify this list of resources(projects to export) in such a way, that resourcesToExport are first added to one folder(folder1) and then sent to executeExportOperation method for exporting.However, resourcesToExport  are of type IResource only. So, how can make folder1 and all its contents(the projects) as IResource?


text:
Q: Changing color in HTML table based on passed variable I am trying to create a table in python Flask, however I have a bit problem with changing color of each line of table. This is my HTML file content:

    Status
    {{ query.get("status") }}

where query is a python dictionary which holds two states for status:
query = {"status":"Success"} or query = {"status":"Fail"}
and this is my css file part:
tr.success {
    background-color: #21eaab !important;
}

tr.fail {
    background-color: #f56279 !important;
}

Problem:
all problem happens when I change HTML class from class=fail or class=success to class={{ query.get('status') }} as I wish to don't do it by hand and just pass the value of dictionary to it.
Attempts:
I also tried to change .css content a bit as:
tr.Success {
    background-color: #21eaab !important;
}

tr.Fail {
    background-color: #f56279 !important;
}

even
 or
 which non of these solutions were not applicable. The problem should be a tiny problem which I can't find.

A: Assuming that {{ query.get("status") }} prints "Success" or "Fail" exactly as stated, then this should work:

    Status
    {{ query.get("status") }}

tr.success {
    background-color: #21eaab !important;
}

tr.fail {
    background-color: #f56279 !important;
}

Keep in mind that !important will only help if you have CSS conflicts within that same scope of specificity. So it's quite possible that your code was working to begin with, but you have a more specific style selector that is overriding your intended result.
For instance you might need to do something like this:
tr.success td {
    background-color: #21eaab !important;
}

tr.fail td {
    background-color: #f56279 !important;
}

But this may result in a thin white line between the cells doing it this way. It will help you better troubleshoot if you are having a specificity scoping conflict, though.


text:
Q: Libgdx - Basic shader not working I'm new to Shaders, and to OpenGL in general. After reading some tutorials, I decided to create my first shader (using LibGDX).
The problem is that the screen is entirely black ...
My Java code :
public class Application extends
                        ApplicationAdapter {

    private ShaderProgram   mShaderProgram;
    private Mesh            mMesh;

    @Override
    public void create() {
        this.createMesh();

        if (Gdx.graphics.isGL20Available()) {
            this.createShaderProgram();
        }

        this.log("" + this.mShaderProgram.isCompiled()); // outputs "true"
    }

    private void createMesh() {
        this.mMesh = new Mesh(true, 3, 4, VertexAttribute.Position());

        this.mMesh.setIndices(new short[] { 0, 1, 2 });
        this.mMesh.setVertices(new float[] {
                -0.5f, -0.5f, 0,
                0f, 0.5f, 0,
                0.5f, -0.5f, 0
        });
    }

    private void createShaderProgram() {
        final FileHandle fragmentShader = Gdx.files.internal("fragment.txt");
        final FileHandle vertexShader = Gdx.files.internal("vertex.txt");

        this.mShaderProgram = new ShaderProgram(vertexShader, fragmentShader);
    }

    @Override
    public void dispose() {
        this.mMesh.dispose();
        if (this.mShaderProgram != null) {
            this.mShaderProgram.dispose();
        }
    }

    private void log(final String message) {
        Gdx.app.log("", message);
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        if (Gdx.graphics.isGL20Available()) {
            this.mShaderProgram.begin();
            this.mMesh.render(this.mShaderProgram, GL10.GL_TRIANGLES);
            this.mShaderProgram.end();
        }
        else {
            this.mMesh.render(GL10.GL_TRIANGLES);
        }
    }
}

My fragment shader :
void main() {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

My vertex shader :
void main() {
    gl_Position = ftransform();
}

Using gl_Vertex instead of ftransform() didn't change anything.

A: The reason you aren't seeing anything is because your vertex shader doesn't do anything. To make the code work correctly you would need to have it do the following at a minimum:
Vertex Shader:
#ifdef GL_ES
precision mediump float;
#endif

attribute vec4 a_position;

void main()
{
    gl_Position = a_position;
}

I would suggest you take a look at some shader tutorials to better understand how shaders work in OpenGL ES.
To quickly explain the above shader code, in your mesh you are setting vertex attributes for the "a_position" attribute. The vertex shader is simply passing that position information to the fragment shader. The fragment shader is then assigning white to all the fragments to be rendered.

A: After searching the web, I found that some GLSL built-in attributes & functions like gl_Vertex and ftransform() are deprecated in new versions of GLSL.
I didn't know that now you have to register even position & color attributes by yourself.


text:
Q: Dynamically created templates with Polymer in a Chrome app I'm working on a Chrome app which needs to do two main things:

*

*Automatically generate a UI from a list of fields and data types provided by an attached device.

*Allow users to define and share their own presentation for the UI and automatically apply that presentation when the device is attached.

I'm using Polymer, and I figure the best way to achieve #2 is with user-provided Polymer elements. Then, I can simply bind the variables from the device to the UI, and the user's template can determine how to display and style them.
Achieving #1, then, is a matter of automatically generating a polymer element from an input schema. This is somewhat different from the usual approach, where I'd presumably define a repeated template with conditional child templates for each type of widget.
My questions, then, are:

*

*How can I dynamically evaluate a polymer element/template from a remote source without violating the Chrome App's CSP, and without introducing significant XSS issues? (Hopefully, the former protects me from the latter?)

*What's the easiest way to dynamially generate markup for a Polymer element? Can I define a meta-template and use the generated markup?

A: I am not entirely sure why you rule out using a pre-defined Polymer element with (admittedly, complicated) <template> logic in it, but if you're sure that you need things to be dynamic and generate the element's content on the fly while still making use of Polymer's data binding, then injectBoundHTML() might be what you're looking for.
It's unfortunately not documented at the moment, but there are examples of how to use it in the open issue tracking the documentation.
You can fetch the "bound" HTML from any source, and while I'm not an expert on CSP, I don't believe that it will trigger any additional CSP consideration.


text:
Q: Google Stepped Area Chart bug with first step I was trying to build a Stepped Area google chart but I always get a bug with the first step not appearing...
This is my code
function drawChart() {
      // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'formatedDate');
        data.addColumn('number', 'Slices');
        data.addRows([
          [new Date(1576022400000), 3],
          [new Date(1576026000000), 1],
          [new Date(1576029600000), 1],
          [new Date(1576033200000), 1],
          [new Date(1576036800000), 2]
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div'));
        chart.draw(data, options);

Here is an example of the bug: https://jsfiddle.net/hm37Lyf9/1/
Any solutions?

A: according to the data format for a stepped area chart,
the first column, or x-axis column, should be a string.
since a date is being used, this is most likely the problem.
see following working snippet,
here, a data view is used,
which has a calculated column that converts the date to a time string.
as such, the first step is displayed.

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  // Create the data table.
  var data = new google.visualization.DataTable();
  data.addColumn('date', 'datatat');
  data.addColumn('number', 'Slices');
  data.addRows([
    [new Date(1576022400000), 3],
    [new Date(1576026000000), 1],
    [new Date(1576029600000), 1],
    [new Date(1576033200000), 1],
    [new Date(1576036800000), 2]
  ]);

  // Create a date formatter
  var formatDate = new google.visualization.DateFormat({
    pattern: 'HH:ss a'
  });

  // Create a data view, with calculated column for time string
  var view = new google.visualization.DataView(data);
  view.setColumns([{
    calc: function (dt, row) {
      return formatDate.formatValue(dt.getValue(row, 0));
    },
    label: data.getColumnLabel(0),
    type: 'string'
  }, 1]);

  // Set chart options
  var options = {
    title: 'How Much Pizza I Ate Last Night',
    width: 400,
    height: 300
  };

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.SteppedAreaChart(document.getElementById('chart_div'));

  // Draw chart with data view
  chart.draw(view, options);
});


text:
Q: How to calculate the verification digit of the Tax ID in the country of Paraguay (calcular digito verificador del RUC) In the country of Paraguay (South America) each taxpayer has a Tax ID (called RUC: Registro Único del Contribuyente) assigned by the government (Ministerio de Hacienda, Secretaría de Tributación).
This RUC is a number followed by a verification digit (dígito verificador), for example 123456-0. The government tells you the verification digit when you request your RUC.
Is there a way for me to calculate the verification digit based on the RUC? Is it a known formula?
In my case, I have a database of suppliers and customers, collected over the years by several employees of the company.
Now I need to run checks to see if all the RUCs were entered correctly or if there are typing mistakes.
My preference would be a Python solution, but I'll take whatever solutions I get to point me in the right direction.

Edit: This is a self-answer to share knowledge that took me hours/days to find. I marked this question as "answer your own question" (don't know if that changes anything).

A: The verification digit of the RUC is calculated using formula very similar (but not equal) to a method called Modulo 11; that is at least the info I got reading the following tech sites (content is in Spanish):

*

*https://www.yoelprogramador.com/funncion-para-calcular-el-digito-verificador-del-ruc/

*http://groovypy.wikidot.com/blog:02

*https://es.wikipedia.org/wiki/C%C3%B3digo_de_control#M.C3.B3dulo_11
I analyzed the solutions provided in the mentioned pages and ran my own tests against a list of RUCs and their known verification digits, which led me to a final formula that returns the expected output, but which is DIFFERENT from the solutions in the mentioned links.

The final formula I got to calculate the verification digit of the RUC is shown in this example (80009735-1):

*

*Multiply each digit of the RUC (without considering the verification digit) by a factor based on the position of the digit within the RUC (starting from the right side of the RUC) and sum all the results of these multiplications:
RUC:             8       0       0       0       9       7       3       5

Position:        7       6       5       4       3       2       1       0

Multiplications: 8x(7+2) 0x(6+2) 0x(5+2) 0x(4+2) 9x(3+2) 7x(2+2) 3x(1+2) 5x(0+2)

Results:         72      0       0       0       45      28      9       10

Sum of results:  164

*Divide the sum by 11 and use the remainder of the division to determine the verification digit:

*

*If the remainder is greater than 1, the the verification digit is 11 - remainder

*If the remainder is 0 or 1, the the verification digit is 0
In out example:
Sum of results:       164

Division:             164 / 11    ==>   quotient 14, remainder 10

Verification digit:   11 - 10     ==>   1

Here is my Python version of the formula:
def calculate_dv_of_ruc(input_str):
    # assure that we have a string
    if not isinstance(input_str, str):
        input_str = str(input_str)

    # try to convert to 'int' to validate that it contains only digits.
    # I suspect that this is faster than checking each char independently
    int(input_str)

    the_sum = 0
    for i, c in enumerate(reversed(input_str)):
        the_sum += (i + 2) * int(c)

    base = 11
    _, rem = divmod(the_sum, base)
    if rem > 1:
        dv = base - rem
    else:
        dv = 0

    return dv

Testing this function it returns the expected results, raising errors when the input has other characters than digits:
>>> calculate_dv_of_ruc(80009735)
1
>>> calculate_dv_of_ruc('80009735')
1
>>> calculate_dv_of_ruc('80009735A')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 8, in calculate_dv_of_ruc
ValueError: invalid literal for int() with base 10: '80009735A'


text:
Q: Inheritance of class variables to a subclass I'm having a huge nightmare with these subclasses and I can't figure out why this isn't working.
I have main class BODY with a subclass RECTANGLE. BODY has a function called SetWorld which does the following
function BODY:SetWorld( worldnum )

    self.world  = worldnum

end

Now, if I do this:
rect = RECTANGLE:new()
rect:SetWorld(1)

The value self.world is changed to 1 in the SetWorld function but if I try to use self.world in another function in BODY it always returns nil. Why is this? It works if I create a new BODY instead of a RECTANGLE, but that means I can't use my subclass.

A: When using a colon to call a method, the first argument is set the "self", and all other arguments are shifted.  If you had supplied more code it would be easier to resolve the issue, however, I believe this may be the issue:
    local x = {
    new = function(o, t)
        print("1st Arg", o)
        print("2nd Arg", t)
    end
}

x.new("Hello World")
x:new("Hello World")

Do you see how the arguments are shifted?


text:
Q: What is the best way to loop this program effectively? What is the best way to loop this program. I only started learning coding. I want it to keep looping after execution until the user press 5 to quit
here is my code
# Naira conversion calculations
def NG_USD(choice):
    print(str(user/350)+"USD")
def NG_GBP(choice):
    print(str(choice/400)+"GBP")
def NG_EUR(choice):
    print(str(choice/450)+"EUR")

# Dollar conversion calculations
def USD_NG(choice):
    print(str(choice*350)+"NG")
def USD_GBP(choice):
    print(str(choice*0.75)+"GBP")
def USD_EUR(choice):
    print(str(choice*0.85)+"EUR")

# Pounds conversion calculations
def GBP_USD(choice):
    print(str(choice/0.75)+"USD")
def GBP_NG(choice):
    print(str(choice*400)+"NG")
def GBP_EUR(choice):
    print(str(choice*1.13)+"EUR")

# Euro conversion calculations
def EUR_NG(choice):
    print(str(choice*450)+"NG")
def EUR_GBP(choice):
    print(str(choice/1.13)+"GBP")
def EUR_USD(choice):
    print(str(choice/0.85)+"USD")

def conversion_NG(user):
    if user == 1 and choice ==1:
        print("You can't convert to the same value")
    elif user == 2 and choice == 1:
        value = eval(input("Enter your value: "))
        return NG_USD(value)
    elif user == 3 and choice == 1:
        value = eval(input("Enter your value: "))
        return NG_GBP(value)
    elif user == 4 and choice == 1:
        value = eval(input("Enter your value: "))
        return NG_EUR(value)

def conversion_USD(user):
    if user == 2 and choice == 2:
        print("You can't convert to the same value")
    elif user == 1 and choice == 2:
        value = eval(input("Enter your value: "))
        return USD_NG(value)
    elif user == 3 and choice == 2:
        value = eval(input("Enter your value: "))
        return USD_GBP(value)
    elif user == 4 and choice == 2:
        value = eval(input("Enter your value: "))
        return USD_EUR(value)

def conversion_GBP(user):
    if user == 3 and choice == 3:
        print("You can't convert to the same value")
    elif user == 1 and choice == 3:
        value = eval(input("Enter your value: "))
        return GBP_NG(value)
    elif user == 2 and choice == 3:
        value = eval(input("Enter your value: "))
        return GBP_USD(value)
    elif user == 4 and choice == 3:
        value = eval(input("Enter your value: "))
        return GBP_EUR(value)
def conversion_EUR(user):
    if user == 4 and choice == 4:
        print("You can't convert to the same value")
    elif user == 1 and choice == 4:
        value = eval(input("Enter your value: "))
        return EUR_NG(value)
    elif user == 2 and choice == 4:
        value = eval(input("Enter your value: "))
        return EUR_USD(value)
    elif user == 3 and choice == 4:
        value = eval(input("Enter your value: "))
        return EUR_GBP(value)

print("This program exchanges currencies for you"
        "\n(1.) NG\n(2.) USD\n(3.) GBP\n(4.) EUR\n(5.) QUIT")
choice = int(input("What currency do you have?: "))
    if choice == 1:
        user = int(input("What currency would you like to convert to?: "))
        string = "\n[You're converting from Naira!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_NG(user)
    elif choice == 2:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from US Dollars!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_USD
    elif choice == 3:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from British Pounds!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_GBP
    elif choice == 4:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from Euro!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_EUR
    elif choice == 5:
        print("Thanks for using\n")
    else:
        print("Error! Invalid Input")

A: Try doing put the if-else ladder in an infinite loop until user enters 5, then exit the program
print("This program exchanges currencies for you"
    "\n(1.) NG\n(2.) USD\n(3.) GBP\n(4.) EUR\n(5.) QUIT")
choice = int(input("What currency do you have?: "))
while True:
    if choice == 1:
        user = int(input("What currency would you like to convert to?: "))
        string = "\n[You're converting from Naira!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_NG(user)
    elif choice == 2:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from US Dollars!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_USD(user)
    elif choice == 3:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from British Pounds!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_GBP(user)
    elif choice == 4:
        user = int(input("What currency would you like to convert to? "))
        string = "\n[You're converting from Euro!]"
        dotted = "\n" + len(string) * "-"
        print(dotted, string, dotted)
        conversion_EUR(user)
    elif choice == 5:
        print("Thanks for using\n")
        break                     #You could also use sys.exit()
    else:
        print("Error! Invalid Input")


text:
Q: How do I approach: Prove that L is regular, where L ={s $\epsilon$ {a,b}*| $\forall$ prefix $w$ of $s$ it is true that $| |w|_a -|w|_b | \leq$2 } My problem exercise: L ={s $\epsilon$  {a,b}*| $\forall$ prefix $w$ of $s$ it is true that $| |w|_a -|w|_b | \leq$2 } , prove that L is regular. $|w|_a$ indicates the number of 'a's in the prefix, $|w|_b$ - number of 'b's
I've been using Pumping Lemma to prove that a language is not regular, regular expressions/Brzozowski's algorithm to prove a language is regular, but I stumbled on a few problems in the form of the title's and I have no idea where to start from. I assume I need to design some regular expression, but I don't have the intuition for it, on the other hand, where would I even start with Brzozowski?
One thing I think might work is to consider that {a,b}* is regular and the language of all prefixes of a regular language= P is also regular, so I could write P = L ⋃ $L^c$, and since P is regular, than L and $L^c$ must also be regular?
Is there a specific approach to languages that are tightly dependant on prefixes and suffixes, or is it a standard exercise like any other?

A: Let $S_i$, $i = \overline{-2..2}$ be state corresponding to words in $L$ s.t. $|w|_a - |w|_b = i$ and $T$ be state corresponding to words not in $L$.
Than transitions are simple: $S_i \xrightarrow{a} S_{i + 1}$ if $i < 2$, $S_i \xrightarrow{b} S_{i - 1}$ if $i > -2$, and $S_{-2}\xrightarrow{2} T$, $S_2 \xrightarrow{b} T$. Say that $S_i$ are accepting states, $S_0$ is start state and you get DFA that recognizes $L$.
In general, to create DFA, you want to split words in finite numbers of sets (corresponding to states of DFA) such that if you know which set does current prefix belong to, and what is the next letter, you can determine which set does the next prefix belongs to.


text:
Q: DC-AC converter with GaN in Ltspice I'm simulating a DC-AC SPWM converter in Ltspice with a GaN E-HEMT (https://gansystems.com/gan-transistors/gs66516b/) but I'm having problems because I get the error for the time step to small. This is the circuit:

and this is the netlist:
    * C:\Users\Latini1\Desktop\CONVERTITORE\Conv_finale.asc
    V1 UE 0 400
    XX9 Vref PWM pwm params: f=400k Vhigh=1 Vlow=0
    R1 N007 UA 40
    L1 N007 UB 300µ
    A1 PWM 0 0 0 0 N021 0 0 BUF tau=5n
    A2 PWM 0 0 0 0 0 N018 0 BUF tau=5n
    V2 Vref 0 SINE(0.5 0.45 50)
    B1 N003 N008 V=(V(s1)*6)
    B2 N012 N016 V=(V(S3)*6)
    B3 N006 N009 V=(V(s3)*6)
    B4 N015 N017 V=(V(S1)*6)
    RG1 N004 N003 20
    RG2 N013 N012 20
    RG3 N006 N005 20
    RG4 N015 N014 20
    A3 0 N018 0 0 0 N020 N019 0 AND td=50n
    A4 0 N018 0 N019 0 0 S1 0 AND tripdt=5n
    A5 0 N020 0 N021 0 0 S3 0 AND tripdt=5n
    C1 N007 UA 100µ
    D5 N004 N002 Dideal
    D6 N013 N010 Dideal
    D7 N005 N001 Dideal
    D8 N014 N011 Dideal
    R2 N002 N003 5
    R3 N010 N012 5
    R4 N006 N001 5
    R5 N015 N011 5
    XU1 N004 UE UA N008 NC_11 0 GaN_LTspice_GS66516B_L3V4P1
    XU2 N013 UA 0 N016 NC_12 0 GaN_LTspice_GS66516B_L3V4P1
    XU3 N005 UE UB N009 NC_13 0 GaN_LTspice_GS66516B_L3V4P1
    XU4 N014 UB 0 N017 NC_14 0 GaN_LTspice_GS66516B_L3V4P1

    * block symbol definitions
    .subckt pwm Vin PWM
    V1 Vtri 0 PULSE({Vlow} {Vhigh-Vlow} 0 {1/(2*f)} {1/(2*f)} {1/(100*f)} {1/f})
    A1 Vin Vtri 0 0 0 0 N001 0 SCHMITT Vt=0.0001 Vh=0.0001 Td=5n
    G1 0 PWM N001 0 1
    R1 PWM 0 1
    C1 PWM 0 1f
    .param f=400k
    .param Vhigh=1
    .param Vlow=0
    .ends pwm

    .model D D
    .lib C:\Users\Latini1\Documents\LTspiceXVII\lib\cmp\standard.dio
    .tran 0 0.03 0.01
    .param D_Vto=0
    .param D_ron=0.1m
    .model Dideal D(Vfwd={D_Vto} Ron={D_ron})
    .option ITL1=500
    .option ITL2=500
    .option ITL4=500
    .option RELTOL=0.01
    .option ABSTOL=1E-09
    .option CHGTOL=1E-12
    .option VNTOL=1E-6
    .option GMIN=1E-15
    .option TRTOL=1
    .option noopiter
    .option gminsteps=0
    .option topologycheck=0
    .lib GaN_LTspice_GS66516B_L3V4P1.lib
    .backanno
    .end

I found .option commands on the site of the device and I want to test the converter for a load frequency of 50 Hz and 400 kHz frequency commutation. Output signals of the pwm generator are good because I've tested them. What you suggest to do? After this simulation I want to try to change some parameters (like Vin Rgate Vgate dead time or considerind the Tj) and study the results. Someone has already worked with this kind of transistor? Thanks a lot in advance.
UPDATE
@a concerned citizen @winny
I tried to change something using your comments: this is the new circuit

And this is the problem:in green there is the Vgs of the first transistor and in blu the Vgs of the second
The recomanded Vgs in the datasheet is 0 to 6V. I separeted the Rg on and off but it does't works.
This is the schematic maybe it can help (hope I made it right this time):
Version 4
SHEET 1 1320 1148
WIRE -880 48 -976 48
WIRE -464 48 -880 48
WIRE 256 48 -464 48
WIRE 432 64 400 64
WIRE -880 80 -880 48
WIRE -608 96 -640 96
WIRE -464 96 -464 48
WIRE 256 96 256 48
WIRE -976 112 -976 48
WIRE -768 176 -832 176
WIRE -720 176 -720 96
WIRE -720 176 -768 176
WIRE -672 176 -720 176
WIRE -544 176 -544 96
WIRE -544 176 -592 176
WIRE -528 176 -544 176
WIRE 336 176 336 64
WIRE 336 176 320 176
WIRE 384 176 336 176
WIRE 512 176 512 64
WIRE 512 176 464 176
WIRE 624 176 512 176
WIRE 720 176 624 176
WIRE -880 192 -912 192
WIRE 816 192 768 192
WIRE -464 240 -464 192
WIRE -272 240 -272 208
WIRE -272 240 -464 240
WIRE -224 240 -272 240
WIRE -192 240 -224 240
WIRE -96 240 -112 240
WIRE -64 240 -96 240
WIRE 80 240 80 208
WIRE 80 240 16 240
WIRE 256 240 256 192
WIRE 256 240 80 240
WIRE -976 256 -976 192
WIRE -768 256 -832 256
WIRE -512 256 -512 208
WIRE -512 256 -768 256
WIRE 304 256 304 208
WIRE 624 256 304 256
WIRE 720 256 624 256
WIRE -608 304 -640 304
WIRE -464 304 -464 240
WIRE 256 304 256 240
WIRE 432 304 400 304
WIRE -224 336 -224 240
WIRE -192 336 -224 336
WIRE -96 336 -96 240
WIRE -96 336 -128 336
WIRE -768 384 -832 384
WIRE -720 384 -720 304
WIRE -720 384 -768 384
WIRE -672 384 -720 384
WIRE -544 384 -544 304
WIRE -544 384 -592 384
WIRE -528 384 -544 384
WIRE 336 384 336 304
WIRE 336 384 320 384
WIRE 400 384 336 384
WIRE 512 384 512 304
WIRE 512 384 480 384
WIRE 624 384 512 384
WIRE 720 384 624 384
WIRE -880 400 -912 400
WIRE 816 400 768 400
WIRE 304 464 304 416
WIRE 624 464 304 464
WIRE 720 464 624 464
WIRE -832 480 -832 464
WIRE -768 480 -768 464
WIRE -768 480 -832 480
WIRE -512 480 -512 416
WIRE -512 480 -768 480
WIRE -464 480 -464 400
WIRE 256 480 256 400
WIRE 0 560 -192 560
WIRE 96 560 64 560
WIRE 176 560 96 560
WIRE -752 592 -1120 592
WIRE -592 592 -688 592
WIRE -544 592 -592 592
WIRE -448 592 -544 592
WIRE -384 592 -448 592
WIRE -320 592 -384 592
WIRE -288 592 -320 592
WIRE -192 592 -192 560
WIRE -192 592 -224 592
WIRE -144 592 -192 592
WIRE 0 592 -80 592
WIRE 96 592 96 560
WIRE 176 592 96 592
WIRE -752 624 -944 624
WIRE -544 624 -544 592
WIRE -448 624 -448 592
WIRE -384 624 -384 592
WIRE -48 624 -80 624
WIRE -592 640 -592 592
WIRE -944 656 -944 624
WIRE -320 656 -320 592
WIRE -288 656 -320 656
WIRE -192 656 -224 656
WIRE -48 656 -48 624
WIRE 0 656 -48 656
WIRE 96 656 64 656
WIRE 176 656 96 656
WIRE -1120 688 -1120 672
WIRE -192 688 -192 656
WIRE 0 688 -192 688
WIRE 96 688 96 656
WIRE 176 688 96 688
WIRE -944 768 -944 736
WIRE -592 768 -592 688
WIRE -544 768 -544 704
WIRE -448 768 -448 704
WIRE -384 768 -384 688
FLAG -880 80 UE
FLAG -1120 688 0
FLAG -272 208 UA
FLAG 80 208 UB
FLAG -1120 592 Vref
FLAG 256 480 0
FLAG -464 480 0
FLAG 176 560 S4
FLAG 176 592 S1
FLAG 176 656 S2
FLAG 176 688 S3
FLAG -976 256 0
FLAG 768 240 0
FLAG 768 448 0
FLAG -880 240 0
FLAG -880 448 0
FLAG -912 192 S1
FLAG -912 400 S2
FLAG 816 192 S3
FLAG 816 400 S4
FLAG -416 128 0
FLAG -416 336 0
FLAG 208 128 0
FLAG 208 336 0
FLAG -944 768 0
FLAG -592 768 0
FLAG -544 768 0
FLAG -448 768 0
FLAG -384 768 0
SYMBOL voltage -976 96 R0
WINDOW 3 -38 26 VLeft 2
WINDOW 123 0 0 Left 2
SYMATTR Value 400
SYMATTR SpiceLine Rser=0.1 Cpar=1m
SYMATTR InstName V1
SYMBOL res -96 224 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R1
SYMATTR Value 40
SYMBOL ind -80 256 R270
WINDOW 0 32 56 VTop 2
WINDOW 3 5 56 VBottom 2
SYMATTR InstName L1
SYMATTR Value 300µ
SYMATTR SpiceLine Rser=10m Rpar=100k
SYMBOL Digital\\inv -288 592 R0
WINDOW 3 -27 113 Left 2
SYMATTR Value tau=5n
SYMATTR InstName A1
SYMBOL Digital\\buf1 -288 528 R0
WINDOW 0 8 31 Left 2
WINDOW 3 -18 4 Left 2
SYMATTR InstName A2
SYMATTR Value tau=5n
SYMBOL voltage -1120 576 R0
WINDOW 123 0 0 Left 2
WINDOW 39 0 0 Left 2
WINDOW 3 -81 156 Left 2
SYMATTR Value SINE(0.5 0.45 50)
SYMATTR InstName V2
SYMBOL res -576 160 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName RG1
SYMATTR Value 30
SYMBOL res -576 368 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName RG2
SYMATTR Value 30
SYMBOL res 480 160 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName RG3
SYMATTR Value 30
SYMBOL res 496 368 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName RG4
SYMATTR Value 30
SYMBOL Digital\\and -112 544 R0
WINDOW 3 -32 0 Left 2
SYMATTR Value td=50n
SYMATTR InstName A3
SYMBOL Digital\\and 32 512 R0
WINDOW 3 -40 4 Left 2
SYMATTR Value tripdt=5n
SYMATTR InstName A4
SYMBOL Digital\\and 32 608 R0
WINDOW 3 -34 111 Left 2
SYMATTR Value tripdt=5n
SYMATTR InstName A5
SYMBOL cap -128 320 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName C1
SYMATTR Value 100µ
SYMATTR SpiceLine Rser=10m
SYMBOL diode -544 80 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName D5
SYMATTR Value Dideal
SYMBOL diode -544 288 R90
WINDOW 0 0 32 VBottom 2
WINDOW 3 32 32 VTop 2
SYMATTR InstName D6
SYMATTR Value Dideal
SYMBOL diode 336 80 R270
WINDOW 0 32 32 VTop 2
WINDOW 3 0 32 VBottom 2
SYMATTR InstName D7
SYMATTR Value Dideal
SYMBOL diode 336 320 R270
WINDOW 0 32 32 VTop 2
WINDOW 3 0 32 VBottom 2
SYMATTR InstName D8
SYMATTR Value Dideal
SYMBOL res -624 80 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R2
SYMATTR Value 1
SYMBOL res -624 288 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R3
SYMATTR Value 1
SYMBOL res 528 48 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R4
SYMATTR Value 1
SYMBOL res 528 288 R90
WINDOW 0 0 56 VBottom 2
WINDOW 3 32 56 VTop 2
SYMATTR InstName R5
SYMATTR Value 1
SYMBOL g -832 160 R0
SYMATTR InstName G1
SYMATTR Value 1
SYMBOL g -832 368 R0
SYMATTR InstName G2
SYMATTR Value 1
SYMBOL g 720 160 M0
SYMATTR InstName G3
SYMATTR Value 1
SYMBOL g 720 368 M0
SYMATTR InstName G4
SYMATTR Value 1
SYMBOL res -784 160 R0
SYMATTR InstName R6
SYMATTR Value 6
SYMBOL res -784 368 R0
SYMATTR InstName R7
SYMATTR Value 6
SYMBOL res 608 160 R0
SYMATTR InstName R8
SYMATTR Value 6
SYMBOL res 608 368 R0
SYMATTR InstName R9
SYMATTR Value 6
SYMBOL GaN_LTspice_GS66516B_L3V4P1 -512 144 R0
WINDOW 3 281 -72 Center 2
SYMATTR InstName U1
SYMBOL GaN_LTspice_GS66516B_L3V4P1 -512 352 R0
WINDOW 3 252 87 Center 2
SYMATTR InstName U2
SYMBOL GaN_LTspice_GS66516B_L3V4P1 304 144 M0
WINDOW 3 297 -42 Center 2
SYMATTR InstName U3
SYMBOL GaN_LTspice_GS66516B_L3V4P1 304 352 M0
WINDOW 3 239 111 Center 2
SYMATTR InstName U4
SYMBOL voltage -944 640 R0
WINDOW 3 -78 188 Left 2
WINDOW 123 0 0 Left 2
WINDOW 39 0 0 Left 2
SYMATTR Value PULSE({Vlow} {Vhigh-Vlow} 0 {1/(2*f)} {1/(2*f)} {1/(100*f)} {1/f})
SYMATTR InstName V3
SYMBOL Digital\\diffschmitt -752 544 R0
WINDOW 3 -39 -19 Left 2
SYMATTR Value Vt=0.0001 Vh=0.0001 Td=5n
SYMATTR InstName A6
SYMBOL g -544 608 R0
SYMATTR InstName G5
SYMATTR Value 1
SYMBOL res -464 608 R0
SYMATTR InstName R10
SYMATTR Value 1
SYMBOL cap -400 624 R0
SYMATTR InstName C2
SYMATTR Value 1f
TEXT 112 968 Left 2 !.tran 0.03
TEXT 112 904 Left 2 !.param D_Vto=0\n.param D_ron=0.1m
TEXT 112 872 Left 2 !.model Dideal D(Vfwd={D_Vto} Ron={D_ron} Epsilon={10m} RevEpsilon={10m})
TEXT 512 528 Left 2 !.option ITL1=500\n.option ITL2=500\n.option ITL4=500\n.option RELTOL=0.01\n.option ABSTOL=1E-09\n.option CHGTOL=1E-12\n.option VNTOL=1E-6\n.option GMIN=1E-15\n.option TRTOL=1\n.option noopiter\n.option gminsteps=0\n.option topologycheck=0
TEXT -728 864 Left 2 !.param f=400k\n.param Vhigh=1\n.param Vlow=0

A: You could try some of these, for start:

*

*Avoid behavioural sources, just use VCVS (E) with 6 as gain. Better yet, use VCCS (G) with a unity gain and 6 Ohms terminating resistance, since voltage sources off the ground are not as convergence-friendly as their current counterparts.

*No need to ground unused A-devices pins, they are internally grounded if not used. It's also a possible cause for wrong results (see the manual at LTspice > Circuit Elements > A. Special Functions, among the first paragraphs).

*Add parasitics as helpers: to the main supply (e.g. Rser=0.1 Cpar=1m), capacitors (e.g. Rser=10m), inductors (e.g. Rser=10m Rpar=100k).

*If you're going to use the default, ideal diode, the biggest service you can do to yourself is to set epsilon (and revepsilon) to something in the range 10m...100m. Else, since you're already going through the trouble of simulating real-life elements, you may as well select a model from the database, or external sources.

*Not lastly, your copy-pasted code is useless because you pasted the netlist, as opposed to the schematic (the .asc file). Even then, without the custom library/-ies and symbols (which I can get from your link), it still could be useless -- but something to remember when sending schematics to others.


text:
Q: Custom bool parsing in PYYAML I need to parse booleans in PYYAML in a custom way and convert them into strings. For that purpose I tried to write a 'constructor' and registered it with yaml, but it didn't do anything. Booleans got parsed as normal. Is it a problem with the tag or do I have to handle this problem in a different way?
def bool_constructor(loader, node):
value = loader.construct_yaml_bool(node)
if value == False:
    return '$false'
else:
    return '$true'

enter code here`yaml.add_constructor('!!bool', bool_constructor)

I would appreciate your help, thank you.

A: After some try and error I found the answer myself. it seems, that I used the wrong tag. The correct python code looks like this:
def bool_constructor(self, node):
    value = self.construct_yaml_bool(node)
    if value == False:
        return '$false'
    else:
        return '$true'

yaml.Loader.add_constructor(u'tag:yaml.org,2002:bool', bool_constructor)
yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:bool', bool_constructor)


text:
Q: Screen socket not generating I'm making a python flask server to run and turn off multiple Minecraft servers, Im using screen to run the minecraft server however screen seems to ignore my command
@app.route('/startserver/<int:serverid>', methods=['PUT'])
def start(serverid):
    os.system(
        f'screen -dmS {serverid} java -Xmx1024M -Xms1024M -jar server.jar nogui')

    return("Server starting")

When I preform the screen -ls command it doesn't always show up.
I tried it without the python and just entered it in the terminal but it still didnt work.
Im running mac os and I intend to later move it to production on a linux server.

A: Elikill58 kindly suggested that the command that I started with might of failed. Which is what happened. When I ensured the java -Xmx1024M -Xms1024M -jar server.jar nogui worked properly the screen socket consistently generated.


text:
Q: Gnu make - how to handle sources from outside my project tree Using:

*

*Linux as build host (kubuntu 14.04)

*Gnu make 3.81

*Compiling some C/C++ projects

I have a directory tree like this:

*

*Repository/

*

*Framework/

*

*Source/

*

*Subdir1/

*Subdir2/

*

*Subdir3/

*et cetera

*something more

*Projects/

*

*Project1/

*

*Source/

*

*SubdirA/

*SubdirB/

*

*SubdirX/

*et cetera

*Out/            ← subdirs structure below Out/ is for example

*

*Source/

*

*SubdirA/

*SubdirB/

*

*SubdirX/

*Framework/

*

*Source/

*

*Subdir1/

*Subdir2/

*

*Subdir3/

*Makefile

*Project2/

*

*Source/

*

*...

*Out/

*

*...

*Makefile

*et cetera

The content of the Framework/Source directory is just a connection of some general purpose source files which will be used in a couple of projects. The Framework directory has no own makefile and e.g. won't build a lib. It's just, that the projects uses some of the sourcecode from the Framework directory.
When building Project1, I first cd into the related projects dir and then calling make, e.g.:
cd ~/Repository/Projects/Project1
make

And all build output has to be put into Project1/Out directory.
Below the Out directory, my makefile mirrors the directory hierarchy from the source tree(s).
Within my makefile, I do something like this:
SRCS += $(shell find Source -name "*.c")
SRCS += $(shell find ../../Framework/Source -name "*.c")
BUILDDIR := Out
OBJS = $(addprefix $(BUILDDIR)/, $(addsuffix .o, $(basename $(SRCS))))
$(BUILDDIR)/%.o : %.c
    $(CC) $(CFLAGS) -c $< -o $@

and this causes the problem that during the pattern rule and the ../.. part, some of the generated object files will be placed outside of my build output directory, e.g.:
gcc -c ../../Framework/Source/*.c -o Out/../../Framework/Source/*.o

My first approach was, to force all source filenames to absolute path names like this:
OBJS = $(addprefix $(BUILDDIR)/, $(addsuffix .o, $(basename $(abspath $(SRCS)))))

This works (even with realpath), but it makes my build output quite ugly because of the long path + filename outputs.
I have a second approach, were I just substitute all ../ parts of the .o files with something like up/ and it looks like this:
OBJS = $(addprefix $(BUILDDIR)/, $(addsuffix .o, $(subst ../,up/,$(basename $(SRCS)))))

but then it unfortunately seems. that I have to duplicate all my pattern rules like:
$(BUILDDIR)/%.o : %.c
    $(CC) $(CFLAGS) -c $< -o $@
$(BUILDDIR)/up/up/%.o : ../../%.c
    $(CC) $(CFLAGS) -c $< -o $@

So, I'm still looking for a slightly nicer solution for this problem.
For some reasons, I have the following restrictions:

*

*no symlinks

*no recursive make calls

*no use of vpath

*no libs

*no git submodules ...

Any suggestions for a bit more elegant approach?

A: Here is the solution:
COLLAPSED_SRC_PREFIXES_IN_BLD := ../../

SRCS += $(shell find Source -name "*.c")
SRCS += $(shell find ../../Framework/Source -name "*.c")

BUILDDIR := Out

.PRECIOUS: %/.
%/.:
    mkdir -p $@

define BLD_FROM_TO

$2/%.o: $1%.c Makefile | $$$$(@D)/.
    $(CC) $(CFLAGS) $$< $$@

endef

.SECONDEXPANSION:

$(foreach prefix, $(COLLAPSED_SRC_PREFIXES_IN_BLD), $(eval $(call BLD_FROM_TO,$(prefix), $(BUILDDIR))))
$(eval $(call BLD_FROM_TO,, $(BUILDDIR)))

A: My original answer is preserved below for reference, but the consensus of discussion seems to be that my answer is wrong.  When you have been around long enough, as I have, there is a certain "ring of truth" you can hear in certain criticism.  One just ignores criticism that lacks the ring of truth, but this criticism has that ring.
The odd thing is that I have been using recursive Make for years in my own work, in a properly refactored manner (so that I do not, in effect, keep multiple instances of more or less the same rule) with the help of include and symlinks to makefiles (and of course by letting my compiler automatically emit the header dependencies), and it all seems to work fine for me.  It is not easy to set up, and there is some hassle whenever I open a new source subdirectory; but then I had believed that Make with multiple source directories just wasn't going to be easy to set up, so there I am.
I do not know whether the OP has learned what he had sought to learn today, but I seem to have learned something.
I withdraw my answer.  Thank you for having read my answer and having commented on it.
ORIGINAL ANSWER
Makefiles always seem to be hard.  There is no definite, unalterable rule, but there are some practices that help.

*

*In general, a file is best made by a makefile, not in the directory of the file's prerequisites, but in the directory in which the file is to be made.  Thus, you can use several makefiles, one in each directory in which files are to be made.  In your example, for instance, you can put a makefile in the Out/ directory, then move the $(BUILDDIR)/%.o: rule over to that makefile.

*If you do not know it already, learn Make's -C option, and start using it extensively and consistently.  There is nothing wrong with your cd ~/Repository/Projects/Project1 before make, exactly, unless the reason for the cd is that you didn't think to use -C, instead.  Consistent use of -C, both on the command line and within makefile rules, eventually leads you to think in a more productive way about makefiles.  It gradually clarifies your perception in the matter, which is good.

*Also if you do not know it already, learn the use of Make's $(MAKE), for recursive invocation of Make.

*Use $(MAKE) and -C together in your rules.
How exactly you assemble these elements into a solution that works for you depends on the details of what you want to do, but the above advice will tend to keep you from fighting Make's design philosophy.  Not fighting will make things easier for you.  Since Make's manual explains features, but does not explain the design philosophy underlying the features very well, this is important.
One could write whole chapters in the matter, so I'll stop here; but if there is a specific point upon which you would like me to expand, feel free to let me know.


text:
Q: How to change the text color of a UIButton on iOS when selected and keep it selected I have a very minimal UIButton (no border, white text color on a clear background, its superView has a dark background). When a user taps the UIButton, I change the alpha channel of the white text color to give it that greyed out look and signal to the user they actually pressed it. Now how do I keep the button in a selected state after they have pressed the button?
The textColor almost instantaneously switches back from gray to white, and I want the color to stay gray, almost behave "stickily" so the user really sees it was selected. How do I achieve this? This is the code I have so far.
logInButton.setTitleColor(pwStyle.appThemeTextFontColor, for: .normal)
        logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .highlighted)
        logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .selected)

^^ Above pwStyle.appThemeTextFontColor just returns UIColor.white

A: You could add the "selected" color to the "disabled" button state:
logInButton.setTitleColor(pwStyle.appThemeTextFontColor.withAlphaComponent(0.3), for: .disabled)

and simply disable the button on press.. and re-enable it at some later point.

A: Make sure the button type is Custom instead of System so the title does not fade out and use this in your touch up inside.
   @IBAction func myButtonDidPress(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected

    }

Cheers


text:
Q: Can I make type redefinition more optimal? I have such code:
type Speed float64
type Distance float64
type Time float64

func speed(a Distance, b Time) Speed {
    return Speed(float64(a) / float64(b))
}

func main() {
    s := Distance(123.0)
    t := Time(300)
    fmt.Println(speed(s, t))
}

Can I make it more optimal by removing somehow casting to float64 in speed function?

A: No, you cannot avoid casting your distance and time back into floats because the division is not defined for those types. And as previously said, Go is strongly typed.
So, in your case you'd have to put casts everywhere (not a good idea). Type aliasing is good if you want to write custom methods for your types, but its purpose is not to solely hide the underlying type under a custom one.
However, not all type are working this way. If you make an alias of a map, then you can call the bracket operators without problem.
type Map map[string]string

func main() {
    m := Map(make(map[string]string))
    m["answer"] = "42"
    fmt.Printf("m's type is %T and answer is %s\n", m, m["answer"])
    //
    // m's type is main.Map and answer is 42
}

Also, when initializing your custom aliases, casting is unnecessary:
type Speed float64
type Distance float64

func main() {
    var s Distance = 123.0
    var t Time = 300

    // ...
}

This compiles and works perfectly. What happens behind the scene is that the literal 123.0 is considered as an untyped float and 300 is considered as an untyped int.
I know this sounds weird but basically those values are not typed so Go tries to fit them into the type at the left. This is why you can write var f float64 = 1 even though 1 is not a float. But you can't write var f float64 = int(1) because 1 becomes a typed int which cannot be translated in a float64.
This is why the following won't work:
func main() {
    var distance float64 = 123.0
    var time float64 = 300

    var s Distance = distance
    var t Time = time

    // ...
}

A: You can't make implicit casts between custom types-- Go is strongly typed.
I know this is just a small example, but maybe you really don't need those custom types?
package main

import "fmt"

func speed(distance float64, time float64) float64 {
    return distance / time
}

func main() {
    s := 123.0
    t := 300.0
    fmt.Println(speed(s, t))
}


text:
Q: VSTO Bug - GetVstoObject returning wrong worksheet I'm developing an application-level add-in for Excel using VSTO on VS2013. My code works for all my worksheets, except for one. I found out that the function GetVstoObject is returning a sheet different than the sheet given as parameter.
This is my Immediate Window RIGHT NOW:
?sheet.Name
"Sheet2"
?Globals.Factory.GetVstoObject(sheet).Name
"Sheet1"

Why is this happening? I read that this return is only calculated once and for the subsequent calls, the cached value is returned. There is some way to clear this cache?
EDIT:
On this workbook, I have two worksheets, the first named as "Sheet1" and the second named "Sheet2". I never renamed or copied one of these sheets, I just started a new workbook and created an additional worksheet.
This is my code for debugging:
Dim sheet1 As Microsoft.Office.Interop.Excel.Worksheet = formMapeamento.wb.Worksheets.Item(1)
Dim sheet2 As Microsoft.Office.Interop.Excel.Worksheet = formMapeamento.wb.Worksheets.Item(2)

Dim sheet1_vsto = Globals.Factory.GetVstoObject(sheet1)
Dim sheet2_vsto = Globals.Factory.GetVstoObject(sheet2)

Dim sheet1_vsto_inner = sheet1_vsto.InnerObject
Dim sheet2_vsto_inner = sheet2_vsto.InnerObject

And this is my immediate window right now, with more data.
'Checking "Sheet1". Everithing looks as expected
?sheet1.Name
"Sheet1"
?sheet1.Index
1
?sheet1.CodeName
"Sheet1"
?Globals.Factory.HasVstoObject(sheet1)
True
?sheet1_vsto.Name
"Sheet1"
?sheet1_vsto.Index
1
?sheet1_vsto.CodeName
"Sheet1"
?sheet1_vsto_inner.Name
"Sheet1"
?sheet1_vsto_inner.Index
1
?sheet1_vsto_inner.CodeName
"Sheet1"

'Checking "Sheet2". STRANGE VALUES
?sheet2.Name
"Sheet2"
?sheet2.Index
2
?sheet2.CodeName
"Sheet1"
?Globals.Factory.HasVstoObject(sheet2)
False
?sheet2_vsto.Name
"Sheet1"
?sheet2_vsto.Index
1
?sheet2_vsto.CodeName
"Sheet1"
?sheet2_vsto_inner.Name
"Sheet1"
?sheet2_vsto_inner.Index
1
?sheet2_vsto_inner.CodeName
"Sheet1"

This problem suddenly started happening. Before that, both sheets were returning correct values. After I run my code some times (the code iterates over some ranges, add and remove windows comboboxes on the worksheets, displays some forms and writes on CustomXMLParts) sheet2_vsto started responding as sheet1_vsto. I saved this workbook to study the problem,  to avoid this from happening with my users.
I couldn't reproduce the problem again. It's the first time that I see this strange behavior. I think the source of the problem is at the CodeName of sheet2.
Does anyone knows some workaround for this problem, or some reason for this to happen?


text:
Q: Troubleshooting Python YouTube-download script I have been using youtube-dl for a while now with no issues, but now I keep getting an error saying

ERROR: unable to download video (format may not be available) for all videos.

What may the issue be?

A: Works with the most current version of yt-dl, which can be found here:
http://rg3.github.com/youtube-dl/download.html

A: I have fixed this issue like the following and made it working.
Note: using the below mentioned command twice is mandatory, I think. I tried it once only, but it didn't work so after executing this command twice it really worked.
Simply type the following command twice in your terminal window with administrator permissions.
sudo youtube-dl -U

sudo youtube-dl -U

The first update fetches the GitHub version, while the second update retrieves the version 2011.03.29 which really worked for me.
The stuff provided here is not my own, but I found Youtube-dl - Download videos from youtube in Ubuntu from some other site, and I think this may also work for you.


text:
Q: How to check if at least one of three input fields is filled with content in Angular 7 I am developing a web client with angular 7 and bootstrap. On my start page I have a form group with three input fields and a submit button which shall be disabled until at least one of the three fields gets some input data from the user. How can I achieve that?

A: your html file.

    <input type="text" name="Aktenzeichen" [(ngModel)]="Aktenzeichen">
    <input type="number" name="Edvnumber" [(ngModel)]="Edvnumber">
    <input type="number" name="Dienstelle" [(ngModel)]="Dienstelle">
    <button type="button" *ngIf="Aktenzeichen ||  Edvnumber || Dienstelle"> Suche starten</button>
    <button type="button" *ngIf="Aktenzeichen ||  Edvnumber || Dienstelle"> Neue Suche</button>

your .ts file:
 import { Component, OnInit } from '@angular/core';

 @Component({
 selector: 'app-page',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
 })
 export class PageComponent implements OnInit {
 Aktenzeichen:string;
 Edvnumber:number;
 Edvnumber:any;
 constructor() { }

 ngOnInit() {
   }
 }

A: You can add custom validator to your FormGroup. Check is the form valid to toggle disabled property on your submit button.
  static groupAtLeastOneRequired(controlsNames: string[]): ValidatorFn {
    return (group: AbstractControl): ValidationErrors | null => {
      const controls: AbstractControl[] = controlsNames.map((controlName) => group.get(controlName));
      const values: (string | null)[] = controls.map((control) => control.value);

      const areAllEmpty = values.every((value) => value === null || value === '');

      if (areAllEmpty) {
        controls.forEach((control) => {
          control.addValidators(Validators.required);
          control.updateValueAndValidity({ onlySelf: true });
        });
      } else {
        controls.forEach((control) => {
          control.removeValidators(Validators.required);
          control.updateValueAndValidity({ onlySelf: true });
        });
      }

      return null;
    };
  }


text:
Q: How to add horizontal scroll bar in bootstrap table? I need to add horizontal scroll bar in bootstrap table. I already assigned class = table-responsive to the table but no scroll bar appears. And when I add new content to table, it appears under the existing content I add. I tried adding overflow-y:hidden; but it does not work.

.out_headings {
  border-left: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  border-top: 3px solid #0fc;
}
.out_headings h4 {
  font-family: myfont;
  font-weight: normal;
  font-size: 15px;
}
.out_headings strong {
  font-family: myfont;
  font-weight: normal;
  font-size: 17px;
}
.to {
  color: #888;
  font-weight: lighter;
  font-family: Tahoma, Geneva, sans-serif;
  font-size: 14px;
  position: relative;
  bottom: 1px;
  color: rgba(0, 0, 0, 0.5);
}
.early_late {
  background: #f2f2f2 !important;
  padding: 0px;
  line-height: 30px;
  border-left: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  margin-bottom: -3px;
}
.ticket_price {
  padding: 0px;
}
.early_late ul li a {
  font-weight: bold;
  font-size: 13px;
}
.span_left {
  font-size: 12px !important;
  top: 1px;
  color: #09C;
  left: 3px;
  padding-left: 3px;
}
.table-striped {
  border-top: 0px;
}
.ticket_price div {
  padding: 0px;
  text-align: center;
}
.ticket_price div button {
  padding: 0px;
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-left: 0px;
  background: #fafafa;
  padding-bottom: 5px;
}
button {
  border-left: 1px solid rgba(0, 0, 0, 0.3) !important;
}
.ticket_price div button {
  padding: 0px;
  width: 100%;
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-left: 0px;
  background: #fafafa;
  padding-bottom: 5px;
}
button {
  border-left: 1px solid rgba(0, 0, 0, 0.3) !important;
}
.ticket_price div button strong {
  font-family: myfont;
  font-weight: lighter;
  font-size: 16px;
}
.time_in_btn {
  color: #000;
  font-size: 18px;
}
.ticket_price div button .glyphicon {
  font-size: 8px;
  color: #48d5b5;
  position: relative;
  padding: 5px 0px;
}
.ticket_price div button span {
  font-size: 10px !important;
  left: -3px;
  color: #069;
  display: block;
}
.ticket_price div button span {
  font-size: 10px !important;
  left: -3px;
  color: #069;
  display: block;
}
.ticket_price div {
  padding: 0px;
  text-align: center;
}
.select_price {
  padding: 0px;
  border: 1px solid #ffc022;
  position: relative;
  margin-top: 30px;
}
.select_price strong {
  font-size: 12px;
  background: #ffc022;
  display: block;
  line-height: 20px;
}
.select_price p {
  font-weight: bold;
  font-size: 13px;
  margin-top: 5px;
}
.ticket_price div {
  padding: 0px;
  text-align: center;
}
.first_class_single {
  border: 1px solid #ddd;
  padding: 0px;
  padding-top: 10px;
}
th {
  padding: 0px !important;
}

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />

 OUT

      05/02/2016

Lahore  to Faisalabad

            Earlier

          Late

              <button type="button">
                LHR
                6:00

                SMD
                 9:30
                3h 30m
              </button>

                Cheapest
                <input type="radio" name="price" value="250" />

Rs 250

                <input type="radio" name="price" value="400" />

Rs 400

              <button type="button">
                LHR
                6:00

                SMD
                 9:30
                3h 30m
              </button>

                Cheapest
                <input type="radio" name="price" value="250" />

Rs 250

                <input type="radio" name="price" value="400" />

Rs 400

              <button type="button">
                LHR
                6:00

                SMD
                 9:30
                3h 30m
              </button>

                Cheapest
                <input type="radio" name="price" value="250" />

Rs 250

                <input type="radio" name="price" value="400" />

Rs 400

              <button type="button">
                LHR
                6:00

                SMD
                 9:30
                3h 30m
              </button>

                Cheapest
                <input type="radio" name="price" value="250" />

Rs 250

                <input type="radio" name="price" value="400" />

Rs 400

              <button type="button">
                LHR
                6:00

                SMD
                 9:30
                3h 30m
              </button>

                Cheapest
                <input type="radio" name="price" value="250" />

Rs 250

                <input type="radio" name="price" value="400" />

Rs 400

JS Fiddle

A:

  .out_headings {
    border-left: 1px solid rgba(0, 0, 0, 0.3);
    border-right: 1px solid rgba(0, 0, 0, 0.3);
    border-top: 3px solid #0fc;
}
.out_headings h4 {
    font-family: myfont;
    font-weight: normal;
    font-size: 15px;
}
.out_headings strong {
    font-family: myfont;
    font-weight: normal;
    font-size: 17px;
}
.to {
    color: #888;
    font-weight: lighter;
    font-family: Tahoma, Geneva, sans-serif;
    font-size: 14px;
    position: relative;
    bottom: 1px;
    color: rgba(0, 0, 0, 0.5);
}
.early_late {
    background: #f2f2f2 !important;
    padding: 0px;
    line-height: 30px;
    border-left: 1px solid rgba(0, 0, 0, 0.3);
    border-right: 1px solid rgba(0, 0, 0, 0.3);
    margin-bottom: -3px;
}
.ticket_price {
    padding: 0px;
}
.early_late ul li a {
    font-weight: bold;
    font-size: 13px;
}
.span_left {
    font-size: 12px !important;
    top: 1px;
    color: #09C;
    left: 3px;
    padding-left: 3px;
}
.table-striped {
    border-top: 0px;
}
.ticket_price div {
    padding: 0px;
    text-align: center;
}
.ticket_price div button {
    padding: 0px;
    width: 100%;
    border: 1px solid rgba(0, 0, 0, 0.3);
    border-left: 0px;
    background: #fafafa;
    padding-bottom: 5px;
}
button {
    border-left: 1px solid rgba(0, 0, 0, 0.3) !important;
}
.ticket_price div button {
    padding: 0px;
    width: 100%;
    border: 1px solid rgba(0, 0, 0, 0.3);
    border-left: 0px;
    background: #fafafa;
    padding-bottom: 5px;
}
button {
    border-left: 1px solid rgba(0, 0, 0, 0.3) !important;
}
.ticket_price div button strong {
    font-family: myfont;
    font-weight: lighter;
    font-size: 16px;
}
.time_in_btn {
    color: #000;
    font-size: 18px;
}
.ticket_price div button .glyphicon {
    font-size: 8px;
    color: #48d5b5;
    position: relative;
    padding: 5px 0px;
}
.ticket_price div button span {
    font-size: 10px !important;
    left: -3px;
    color: #069;
    display: block;
}
.ticket_price div button span {
    font-size: 10px !important;
    left: -3px;
    color: #069;
    display: block;
}
.ticket_price div {
    padding: 0px;
    text-align: center;
}
.select_price {
    padding: 0px;
    border: 1px solid #ffc022;
    position: relative;
    margin-top: 30px;
}
.select_price strong {
    font-size: 12px;
    background: #ffc022;
    display: block;
    line-height: 20px;
}
.select_price p {
    font-weight: bold;
    font-size: 13px;
    margin-top: 5px;
}
.ticket_price div {
    padding: 0px;
    text-align: center;
}
.first_class_single {
    border: 1px solid #ddd;
    padding: 0px;
    padding-top: 10px;
}
th{padding:0px !important;}

td{
    min-width:155px; /* force table to be oversize */
    padding:0px !important;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

 OUT

          05/02/2016

Lahore  to Faisalabad

                Earlier

              Late

                    <button type="button">
                      LHR
                      6:00

                      SMD
                       9:30
                      3h 30m
                    </button>

                    <button type="button">
                      LHR
                      6:00

                      SMD
                       9:30
                      3h 30m
                    </button>

                    <button type="button">
                      LHR
                      6:00

                      SMD
                       9:30
                      3h 30m
                    </button>

                    <button type="button">
                      LHR
                      6:00

                      SMD
                       9:30
                      3h 30m
                    </button>

                    <button type="button">
                      LHR
                      6:00

                      SMD
                       9:30
                      3h 30m
                    </button>

                  Cheapest
                  <input type="radio" name="price" value="250" />

Rs 250

                  Cheapest
                  <input type="radio" name="price" value="250" />

Rs 250

                  Cheapest
                  <input type="radio" name="price" value="250" />

Rs 250

                  Cheapest
                  <input type="radio" name="price" value="250" />

Rs 250

                  Cheapest
                  <input type="radio" name="price" value="250" />

Rs 250

                  <input type="radio" name="price" value="400" />

Rs 400

                  <input type="radio" name="price" value="400" />

Rs 400

                  <input type="radio" name="price" value="400" />

Rs 400

                  <input type="radio" name="price" value="400" />

Rs 400

                  <input type="radio" name="price" value="400" />

Rs 400

You can adjust

td{
    min-width:155px; /* force table to be oversize */
}

to the minimum width you like.
JS Fiddle
The HTML
 is as given in here


text:
Q: How do I set content negotiation for .jsonld files and .html? I'm developing a Linked Data application and I need to use 303 URIs for my dataset. Currently, I have a dataset of 22500 .jsonld files with URIs as follows:
http://example.com/project/resource/file.jsonld

And I want to redirect browsers looking for text/html content to:
http://example.com/project/page/file.html

Which are not semantic files, so they are more readable.
Does anyone know how can I do this with Apache 2.4.10? I've been considering the type-map files, but I was wondering if there are another more efficient solutions than creating 22500 .var files.

A: Look at W3C: Best Practice Recipes for Publishing RDF Vocabularies. Although it is about publishing vocabularies, it lists a number of recipes for configuring content negotiation on Apache that apply equally to datasets.
The other key documentation for doing this is Apache Module mod_rewrite.


text:
Q: Highcharts date misunderstood I use highcharts from a long time until this January, that date is misunderstood with September.
I read a CSV file like this:
09.01.21 00:40:01;331.000;100.000
09.01.21 00:45:01;331.000;100.000
09.01.21 00:50:01;331.000;100.000
09.01.21 00:55:01;331.000;100.000

That is dd.mm.YY HH:MM:SS, 9 of January 2021, But on Highcharts I see 1 of Setember.
I tried to format date with dateFormat: 'dd/mm/YY' but don't work https://api.highcharts.com/highcharts/data.dateFormat
Here the code:
Highcharts.chart('container', {
        title: { text: 'Log' },
        data: { csv: document.getElementById('csv').innerHTML, itemDelimiter: ';',
        lineDelimiter: '\n', decimalPoint: '.' ,dateFormat: 'dd/mm/YY'},
        plotOptions: {   series:  {     visible: false,    marker: {    enabled: false  }    }  },
        series: [{},{visible: true}] });

How I can solve?

A: Your dates are not valid with the 'dd/mm/YY' format, please check this example with valid dates: https://jsfiddle.net/BlackLabel/jgyu6q9h/
You can use the parseDate function to convert your dates to timestamps:
    data: {
        ...,
        parseDate: function(date) {
            var parts = date.split(' '),
                dateParts = parts[0].split('.'),
                convertedDate = '20' + dateParts[2] + '-' + dateParts[1] + '-' + dateParts[0] + 'T' + parts[1];

            return new Date(convertedDate).getTime();
        }
    }

Live demo: https://jsfiddle.net/BlackLabel/edx3cvno/
API Reference:
https://api.highcharts.com/highcharts/data.parseDate
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date


text:
Q: How to dynamically ensure that a function in an object is called only with the params that it accepts? Consider the following,
interface ITemplateA {
    name: string;
}
const templateA = ({ name }: ITemplateA) => `Hello, I am ${name}`

interface ITemplateB {
    age: number;
}
const templateB = ({ age }: ITemplateB) => `I am, ${age} years old`;

const templates = {
    templateA,
    templateB
}

interface IGenerateText {
    template: keyof typeof templates;
    params: any;
}
const generateText = ({ template, params }: IGenerateText) => templates[template](params);

How can I refactor the part with params: any, so that typescript would pick up the following:
generateText({ template: 'templateA', params: { name: 'michael' } }); // no error
generateText({ template: 'templateA', params: { age: 5 } }); // error
generateText({ template: 'templateB', params: { age: 5 } }); // no error

A: This seems to do the trick. I think you could get rid of the as any inside the function with some cleverness too...
const templateA = ({ name }: { name: string }) => `Hello, I am ${name}`;

const templateB = ({ age }: { age: number }) => `I am, ${age} years old`;

const templates = {
  templateA,
  templateB,
};
type TemplateName = keyof typeof templates;

interface IGenerateText<T extends TemplateName> {
  template: T;
  params: Parameters<typeof templates[T]>[0];
}

function generateText<T extends TemplateName>({ template, params }: IGenerateText<T>) {
  return (templates[template] as any)(params);
}

generateText({ template: "templateA", params: { name: "michael" } }); // no error
generateText({ template: "templateA", params: { age: 5 } }); // error
generateText({ template: "templateB", params: { age: 5 } }); // no error

A: Externally (i.e. when calling the function), it is enough to have a mapped type (like typeof templates in your case, templates being a map/dictionary) and an inferred generic type argument selecting a key of the mapped type, to express the correlation between some of the function parameters, as done in @AKX's answer.
But internally (i.e. within the function body), this mapped type is not enough: TypeScript static analysis has no way to know that only 1 key type is used (it can still be a union of keys), hence it falls back to keeping the union of all types.
The only way to tell TS that only 1 key value is present, is to use some type narrowing. And to have TS narrow the types of correlated parameters along with it, they must be part of a discriminated union. Unfortunately, in your case this may lead to some repetitive code, which cannot be avoided currently to keep full safety:
type Template = keyof typeof templates;

// Build a discrimated union from the templates map:
type DiscriminatedUnionTemplates = {
    //^? { template: "templateA"; params: ITemplateA; } | { template: "templateB"; params: ITemplateB; }
    // Use a mapped type:
    [T in Template]: {
        template: T;
        params: Parameters<typeof templates[T]>[0]
    }
}[Template] // Use indexed access to convert the mapped type into a union

const generateText = <T extends DiscriminatedUnionTemplates>({ template, params }: T) => {
    // Narrow the type within the union,
    // based on the `template` discriminant key
    switch (template) {
        case 'templateA': return templates[template](params); // Okay
        case 'templateB': return templates[template](params); // Okay, repetitive but currently only way to keep full safety
    }
};

generateText({ template: 'templateA', params: { name: 'michael' } }); // Okay
generateText({ template: 'templateA', params: { age: 5 } }); // Error: Object literal may only specify known properties, and 'age' does not exist in type 'ITemplateA'.
generateText({ template: 'templateB', params: { age: 5 } }); // Okay

Playground Link
In your case, it is obvious what the function does internally, and we may accept the type assertion to avoid the repetitive code.


text:
Q: How to get sum of groups within another groups using pandas GroupBy? I have this MultiIndexed DataFrame:
-                             metric_1
cat_A   date         cat_B
foo     2019-03-18   blue             1
                     yellow           2
                     red              3
        2019-03-19   blue             5
                     red             10
                     green            5
bar     2019-03-18   yellow           2
                     black            2
                     red              2
        2019-03-19   red              1
                     blue             8
                     black            1
I want to create a metric_2 that takes metric_1 alone and divides by the total sum of metric_1 for all cat_B within a specific date AND within the respective cat_A.
Example of output:
-                             metric_1   metric_2
cat_A   date         cat_B
foo     2019-03-18   blue             1      0.166
                     yellow           2      0.333
                     red              3      0.500
        2019-03-19   blue             5      0.250
                     red             10      0.500
                     green            5      0.250
bar     2019-03-18   yellow           2      0.333
                     black            2      0.333
                     red              2      0.333
        2019-03-19   red              1      0.100
                     blue             8      0.800
                     black            1      0.100
I'm trying to sum the levels using sum(level = 0), sum(level = 1) and so on, but it takes only the sum of the whole level and I guess I'm missing something.
Thanks in advance!

A: Using reindex
df['New']=df['metric_1']/df['metric_1'].sum(level=[0,1],axis=0).reindex(df.index)


text:
Q: Electrostatic adhesion instead of glue. Is it possible? I am thinking about the way to attach the printed photographs to the wall but not using the frame.
And the most interesting idea for me is the use of electrostatics.
In addition I have found the following video that shows this process in action:
http://youtu.be/r0u85k5EpcE
Also I think that something like this is used in some kinds of wall-climbing robots.
So does somebody know how it works?  I suppose that the materials of the objects are very important here. Probably it works because the wall and photo are made of paper, and plastic between them gets charged and consequently attracts paper. What other materials or combinations of materials can provide this effect?
And how is the electrostatic charge transferred to the material (plastic foil and paper)? I know only about objects gaining electrostatic charge after rubbing them. But in the stick from this video it must be done by some simple electric circuit...

A: I've never done the experiment with the plastic film, but as child I remember that if I rubbed a balloon on my pullover it would stick to the wall. The reason is the one you suggest. When you run the balloon on your pullover you charge it. When you bring the balloon close to the wall the charge on the ballon polarises the surface of the wall, i.e. it repels like charges and attracts unlike charges, so the surface of the wall acquires a charge opposite to the balloon. The opposite charges on the ballon and the surface of the wall attract, so the balloon sticks to the wall.
The problem with using this to fix pictures to the wall is that the charge gradually leaks away so the balloon/picture will fall off. My recollection is that the balloon would stay stuck to the wall for about an hour.
As you say, objects may be charged by rubbing them and this is called triboelectricity. Alternatively you can charge objects by touching them with something else that is charged. Because like charges repel, if you touch a charged object to an uncharged object there will be a tendancy for the charge to spread over both objects. To what extent this happens depends on the conductivity of the objects. I imagine the plastic film is a poor conductor and this is why you have to rub the Fun-Fly-Stick all over it.
I had never heard of the Fun-Fly-Stick but a quick Google suggests it's a type of Van de Graaff generator.


text:
Q: Как сделать структуру блоков как на картинке? Нужно таблицу из блоков как на картинке

Есть какие нибудь идеи?
Вот через флекс пробовал, не работает как хотелось бы

.parent {
  border: 1px solid #333;
  max-width: 490px;
  margin: 20px;
}
.wrap {
  margin: 0 -3%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.wrap::after {
  content: '';
  flex: auto;
}

.item {
  height: 85px;
  width: 85px;
  background: #aaa;
  margin: 0 3% 50px;
  display: inline-block;
}

A: Допустим... ) Принцип понятен?

* {
  padding: 0;
  margin: 0;
}

.wrapper {}

.item {
  width: 85px;
  height: 85px;
  background-color: rgba(0, 0, 0, .2);
  float: left;
  margin-right: calc((100% - 4 * 85px) / 3);
  margin-bottom: calc((100% - 4 * 85px) / 3);
}

.item:nth-child(4n) {
  margin-right: 0;
}

@media (max-width: 400px) {
  .item {
    margin-right: calc((100% - 3 * 85px) / 2);
    margin-bottom: calc((100% - 3 * 85px) / 2);
  }
  .item:nth-child(4n) {
    margin-right: calc((100% - 3 * 85px) / 2);
  }
  .item:nth-child(3n) {
    margin-right: 0;
  }
}


text:
Q: d3 force layout nodes are pinning on dblick but appearance does not modify Using and playing around with the Les Miserables Json data, I coded from modifications in d3.   I was able to code everything except highlighting/marking a node if it is in the "fixed" state (vs the force graph layout).  When you double click a node, it will freeze, a drag and move will pin it somewhere while all the other nodes (by default) in the force layout.  When you double click the node again, the node is unpinned, and floating in the force layout as usual.  The second thing I wanted to do is that if the node is in a "pinned" state, the node should be a different color, or highlighted somehow.  I tried a few ways within the method chaining, checking with conditional statements for the node state to modify the node features, but they are not working.  I also separated out the dblclick handler as an outside function (which is my current version.
I put my code here of the original attempt within the method chains:
http://pastebin.com/SqrqgVET
I also tried another way, using a variable "pinned" to determine the state of the node, within the double-click, to modify the nodes border, and change the state accordingly but that is not changing the node's appearance either. There is a console.log() statement, and the function is going into the if else portions accordingly.
http://pastebin.com/dzEw42mQ
Below is the current version.
Any feedback would be great.  Thanks!
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
  cursor: move;
  stroke: #fff;
  stroke-width: 1.5px;
}
.node.fixed {
    fill: #f00;
}

   .link {
  stroke: #999;
  stroke-opacity: .6;
}

</style>

<head>
<title>Victor Hugo Had No Internet</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://d3js.org/colorbrewer.v1.min.js"></script>
</head>

<body>
<script type="text/javascript">

//Size of region to render on
var width = 960,
    height = 500;

var color = d3.scale.ordinal()
    .domain([1, 10])
    .range(colorbrewer.BrBG[9]);

//D3 force directed layout
//Try playing with the charge and link distance
var force = d3.layout.force()
    .charge(-100)
    .linkDistance(40)
    //.on("tick", tick) //event ADDED
    .size([width, height]);

//Add our canvas
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

//Select the miserables data ;)
d3.json("miserables.json", function(error, graph) {
  force
      .nodes(graph.nodes)
      .links(graph.links)
      .start();

//Add the links
  var link = svg.selectAll(".link")
      .data(graph.links)
      .enter().append("line")
      .attr("class", "link")
      .style("stroke-width", function(d) { return Math.sqrt(d.value); });

//Add the nodes
  var node = svg.selectAll(".node")
      .data(graph.nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", function(d){ return Math.sqrt(d.coolness);})
      .attr("stroke", "#ffffff")
      .on("dblclick", dblclick)
      .call(force.drag)
        .style("fill", function(d) {return color(d.group);}); //});
        //.style("border", 5);//function(d) {
             //if (d.fixed==false) {return 4}; });

// node.append("text") //label
 //       .attr("dx", 6)
 //       .attr("dy", ".10em")
 //       .text(function(d) { return d.name; });

 //add labels
  var labels = svg.selectAll("text")
        .data(graph.nodes)
        .enter()
        .append("text")
        .attr({"x":function(d){return d.x;},
              "y":function(d){return d.y;}})
        .text(function(d) {
              if (d.coolness>25 && d.name.length > 6) {return d.name.substring(0,6)+'...'}
              if (d.coolness>25 && d.name.length < 6) {return d.name}
              else    { return null } ;})
        .call(force.drag);

//Update stuff for animation:
//   This takes the physics simulation for the force directed graph and
//   sets the location of the nodes and edges to the new positions
  force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    labels.attr("x", function(d) { return d.x; })
           .attr("y", function(d) { return d.y; });

  });

    // action to take on mouse double click

function dblclick(d) {  //color, stroke not working.
        //var pinned  = d3.select(this).attr("stroke");
        console.log("dblclick")
        if (d.fixed == true) { //pinned state
        console.log("pinned")
        d3.select(this)
        .attr("stroke", "#ffffff")
        .attr("stroke-width", 1.5)
        .classed("fixed", d.fixed = false);//now unpin
        } else { //else not pinned state
        console.log("not pinned")
        d3.select(this)
        .attr("stroke", "#000000")
        .attr("stroke-width", 4)
        .classed("fixed", d.fixed = true);
        }

        }//end dbl click

});

</script>`

Here is the output of the console log (where I added console.log(this) to check the right element is being passed to the dblclick function and if parameters are being set accordingly:
[Log] dblclick (miserables_graph.html, line 131)
[Log] <circle class="node fixed" r="9.1104335791443" stroke="#000000" style="fill: #f6e8c3;" cx="630.38114584665" cy="98.39845698676822" stroke-width="4"></circle> (miserables_graph.html, line 132)

[Log] not pinned (miserables_graph.html, line 140)
[Log] dblclick (miserables_graph.html, line 131)
[Log] <circle class="node" r="9.1104335791443" stroke="#ffffff" style="fill: #f6e8c3;" cx="630.38114584665" cy="98.39845698676822" stroke-width="1.5"></circle> (miserables_graph.html, line 132)

[Log] pinned (miserables_graph.html, line 134)