text:
Q: jQuery AlphaNumericPlugin - Copy Paste Issue I am using the .alphanumeric plugin for jQuery which is certainly doing what I would expect as users type directly into the textbox.  But, if a user were to copy and paste a value into the text box, all bets are off.
$("#<%= txtNumber.ClientID %>").alphanumeric({allow:"-"});

I can certainly do this:
$(document).ready(function() {
    $("#<%= txtNumber.ClientID %>").blur(function() {
        $("#<%= txtNumber.ClientID %>").val(
            RemoveInvalidCharacters(
                $("#<%= txtNumber.ClientID %>").val()
            )
        );
    });
});

//FUNCTION REMOVES ANY ; IN TEXT TO PREVENT SQL INJECTION
function RemoveInvalidCharacters(text) {
     return text.replace(';', '');
}

But... I'd rather not have to kluge up my code even further with .blur() functions.  Are there any other ways around this?

A: Handling the paste event is fairly straightforward.  I'm using this technique in my masked input plugin with good results. Feel free to browse the source to see it in use.
Here is the relevant bits modified for your example above.
var pasteEventName = $.browser.msie ? 'paste' : 'input';
$("#<%= txtNumber.ClientID %>").bind(pasteEventName, function() {
   setTimeout(function() {
      RemoveInvalidCharacters(
         $("#<%= txtNumber.ClientID %>").val()
      );
   }, 0);
});

A: I found this solution here:
http://www.devcurry.com/2009/10/allow-only-alphanumeric-characters-in.html
<script type="text/javascript">
$(function() {
 $('input.alpha').keyup(function() {
  if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
   this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
  }
 });
});
</script>

<input type="text" name="test" value="" class="alpha">

A: I too was needing a solution to the paste problem, and I figured out something that will work for me. A person can still use the Edit > Paste in the browsers menu, but Ctrl-V, as well as right click paste is handled. Tested in FF,IE,Opera,Safari,Chrome:
<!DOCTYPE html>
<html>
<head>
    <title>Only Allow Certain Characters</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
    <br>
    <form id="myform" action="">
        <input id="element1" name="mytext1" type="text">
        <input id="element2" name="mytext2" type="text">
    </form>
<script>
    /* removes evil chars while typing */
    (function($){
        $.fn.disableChars = function(a) {

            a = $.extend({
                allow: ''
            }, a);

            b = a.allow.split('');
            for ( i=0; i<b.length; i++) b[i] = "\\" + b[i];
            a.allow = b.join('');

            var regex = new RegExp('[^a-z0-9' + a.allow + ']', 'ig');

            $(this)
            .bind('keyup blur', function() {
                if (this.value.search(regex) != '-1') {
                    this.value = this.value.replace(regex, '');
                }
            })
            .bind('contextmenu',function () {return false});

        }
    })(jQuery);

    $("#element1").disableChars();
    $("#element2").disableChars({allow:".,:-() "});
</script>
</body>
</html>

A: Copy and Paste is definitely a challenge for masked inputs.
Have you considered "encoding" special characters when the form is submitted as opposed to when the user enters values?  We do the same thing to allow users to enter the < and > characters in TextBoxes (we convert them to < and > via javascript and then back in to < and > in the code behind.

A: This way you will not prevent an SQL injection. I'm not required to use your form, I can make mine and POST it to your script. Even easier: I can disable javascript and go drop your database.
Instead, check the input validity on server side.
The easiest ways are escaping it or using parametrised queries.


text:
Q: You must be online once before you can use Boxfuse offline I'm following the boxfuse tutorial.
Everything seems to we working...
$ boxfuse -v
Boxfuse client v.1.23.0.1181
Copyright 2016 Boxfuse GmbH. All rights reserved.

VirtualBox : 5.0.26r108824
JVM        : 1.8.0_74 (Oracle Corporation)
Host IP    : 10.0.1.10 (24:a5:68:2d:5a:a1)
OS         : Mac OS X 10.11.6 x86_64

So I generate and attempt to run their sample app...
$ boxfuse run hello-1.0.war
Boxfuse client v.1.23.0.1181
Copyright 2016 Boxfuse GmbH. All rights reserved.

ERROR: You must be online once before you can use Boxfuse offline. Go online and try again

As you can see, the app failed.  I've no context to understand what is meant by online/offline in this error message.
What do I need to do?

A: That message indicates that there was some kind of connectivity issue between the machine where you ran the Boxfuse Client on and the Boxfuse Console.
Ensure internet connectivity is working and retry. Everything should then work as expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drawing a rectangle behind a button makes the button not work (CSS) I'm new to CSS and I'm having some problems with it. Right now I'm trying to draw a rectangle behind two buttons, and while I've had some success at drawing the rectangle that renders the buttons useless. Here's the code I've made for the nav in the html (where the buttons are located):

body {

    background-color:mediumspringgreen;

    display: grid;
    grid-template-columns: 100%;
    grid-template-rows: 30% 6% 60% 4%;
    grid-template-areas:    "header"
                            "nav"
                            "main"
                            "footer";

}

.rectangle{

    width: 100%;

    height: 4%;

    background: gold;

    position: absolute;

    display: flex;

    z-index: -1;

    align-items: center;
    justify-content: center;

}

.button1{

    background-color: green;

    color: gold;

    border: 3px solid mediumspringgreen;

    border-radius: 12px;

    display: inline-block;
    cursor: pointer;

}

nav{

    display: flex;
    width: 100%;
    align-items: center;
    justify-content: center;

}
<nav>
    <p class = "rectangle">
        <button class = "button1" onclick="location.href= 'pàgina%20productes.html'">Productes</button>
        <button class = "button1" onclick="location.href= 'pàgina%20contacte.html'">Contacte</button>
    </p>
</nav>

Does anyone know any solution to make the buttons clickable? If I remove the rectangle I can go to the button's link, it only happens when there's the rectangle behind them.
Thanks in advance!
EDIT: It seems to fail only when there are more tags than nav inside the body. Here's the JSFiddle: https://jsfiddle.net/h0uw36dk/

A: There's a problem with z-index. You don't need to add z-index property in rectangle.
.rectangle {
    width: 100%;
    height: 4%;
    background: gold;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
}


text:
Q: how to display axis on binary while having log scale and adding custom grid lines I gathered different pieces of code from here. My code looks as follows:
fig, ax = plt.subplots()
ax.set_yscale('log', base=2)
ax.yaxis.set_major_formatter(lambda x, pos: f"{int(x):12b}")
data = np.arange(100)
ticks = [2, 3, 4, 13]
plt.plot(data,data)
ax.set_yticks(ticks, minor=True)
ax.yaxis.grid(True, which='minor')
plt.show()

So, the goal is to plot in logarithmic scale, displaying the y axis in binary and adding custom ticks. The code works perfectly, except that the ticks are displayed in decimal. As shown in the picture below. I'd like them to be also in binary. I tried to fix it, but I really have no idea how. I tried setting ax.set_ticks([lambda x: f"{int(x):12b}"], minor=True) but that didn't work. I'd appreciate if someone can help me.

A: For the minor ticks you need ax.yaxis.set_minor_formatter(...). You'll notice that the major and minor ticks aren't aligned equally. This is due to the tick lengths, which can be forced equal via ax.tick_params(..., length=...).
from matplotlib import pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(15, 4))
for ax in (ax1, ax2):
    ax.set_yscale('log', base=2)
    ax.yaxis.set_major_formatter(lambda x, pos: f"{int(x):12b}")
    ax.yaxis.set_minor_formatter(lambda x, pos: f"{int(x):12b}")
    data = np.arange(100)
    ticks = [2, 3, 4, 13]
    ax.plot(data,data)
    ax.set_yticks(ticks, minor=True)
    ax.yaxis.grid(True, which='minor')
ax1.set_title('default tick lengths')
ax2.set_title('equal tick lengths')
ax2.tick_params(axis='y', which='both', length=2)
plt.show()

PS: Note that minor ticks are suppressed when their position is very close to the major ticks. Therefore, no grid lines are visible for 2 and 4. You can work around that by shifting them a bit. E.g.
ticks = [2.001, 3.001, 4.001, 13.001]

Or you could change the role of major and minor ticks, using the LogLocator for the minor ticks:
from matplotlib.ticker import LogLocator

ax.yaxis.set_minor_locator(LogLocator(base=2))
ax.set_yticks(ticks)
ax.yaxis.grid(True, which='major')


text:
Q: How to recover the partition table (Windows, Ubuntu) of an unallocated disc? The following screenshot shows the current state of my hard disc.

The unallocated part of the disc used to contain two operating systems:

*

*Windows and Ubuntu, in this order. Windows has been installed first. Ubuntu used Grub.

*I do not have information about specific partitioning.

*There was a home partition of Ubuntu was encrypted. I wrote down the passphrase.

The NTFS partition is not of interest for this question. I already managed to recover data stored there.
Do you know any tool for Linux or Windows which is capable of recovering the partitions? I assume that I lost the partition table or just Grub.

Interim results

Running testdisk
After running the Quick Search the following shows up:
Disk /dev/sdb - 500 GB / 465 GiB - CHS 969021 16 63

Warning: the current number of heads per cylinder is 16
but the correct value may be 255.
You can use the Geometry menu to change this value.
It's something to try if
- some partitions are not found by TestDisk
- or the partition table can not be written because partitions overlaps.

[Continue]

Then ...
Disk /dev/sdb - 500 GB / 465 GiB - CHS 969021 16 63
     Partition             Start        End    Size in sectors
 * HPFS - NTFS               2   0 33    205   3 19     204800
 P HPFS - NTFS             205   3 20 203174   9 41  204593152
 P Linux                203176  10 11 305359   3 51  103000064
 L Linux                313112   6  7 373707   2 50   61079552
   HPFS - NTFS          373707   2 51 969022  15 47  600078336
   HPFS - NTFS          373707   2 58 969020  15 63  600076329

Success story

Finally, I was able to recover the partition table. I cloned the drive using dd and had to change the geometry settings of the target drive. Then I was able to detect the Linux partitions on the cloned hard drive. Finally, I wrote the partition table via TestDisk to the clone hard drive. I did not want to alter the original drive to avoid total damage.
To actually mount and copy the data from the encrypted home partition I followed this post by rausch. Helpful background information can be read in: Unwrapping passphrase and inserting into the user session keyring failed.

A: Testdisk is your friend. A year ago, I fixed a broken MBR and faced exactly the same issue as yours (MBR's magic number got corrupted) with this tool. There are lots of live media containing it http://www.cgsecurity.org/wiki/TestDisk_Livecd.
Once you fix your issue, I suggest you backup your partition table with sfdisk. http://ubuntuwiki.net/index.php/Partition_tables,_managing_with_sfdisk
EDIT :Since I cant comment
Do a deeper search to see if everything is getting detected properly. It will take quite some time. If it doesn't, then you need to experiment with what the software suggests, at your own risk.
Be cautious when writing to partition table. If you have an external HDD, first boot with CloneZilla Live media on your computer, and make a bare-metal back up of your harddisk to the External disk before doing anything so that your internal hdd can be rolled back if you mess up.


text:
Q: paginate_links() on page (shortcode output) On a standard WordPress page, I have a WP Query that runs through a post type I created. Along with that query, I am using paginate_links() to generate pagination. While the standard (no permalinks) seems to work fine - when enabling any permalink combination, the subsequent pagination pages do not load. Here is what I have so far:
$post_args = array(
    'post_type' => 'galleries',
    'paged'     => get_query_var('paged'),
    'post_type' => 'galleries'
);

$posts_query = new WP_Query($post_args);
$i = 0; // count
$total_items = $posts_query->post_count; // total profiles
$number_columns = $galleries_options['columns']; // number of columns
if ($posts_query->have_posts() ) {
    echo '
';
    while ($posts_query->have_posts() && ($i < $total_items)) { ?>
        <?php $posts_query->the_post(); if ($i % $number_columns == 0) echo ($i > 0 ? '

' : '
'); ?>
        <div class="<?php echo 'width'.intval(100 / $number_columns); ?> <?php if ($i % $number_columns == 0) echo 'first-item'; ?>">
            <?php
                galleries_list(get_the_ID());
            ?>

    <?php $i++;
    }
    echo '
';
    echo '
';

    $total_pages = $posts_query->max_num_pages;
    $big = 999999999; // need an unlikely integer
    if ($total_pages > 1){
        $current_page = max(1, get_query_var('paged'));
        echo '';
        echo paginate_links(array(
            'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'    => '?paged=%#%',
            'current'   => $current_page,
            'total'     => $total_pages,
            'prev_text' => 'Prev',
            'next_text' => 'Next'
        ));
        echo '';
    }

}

The default URL is ?page_id=60&paged=2 which works/loads fine - yet galleries/page/2/ does not. Anyone have any suggestions? I'm using the exact same thing for taxonomy pagination... so I'm a bit confused on why this isn't working. Thanks!

A: The issue ended up being the page in which I was accessing the shortcode on was using the same slug - which WP was freaking out about. While I'll need to investigate why it would happen, was easy enough to fix.


text:
Q: How to install Parsing API in Netbeans? I am running the latest Netbeans (7.4 beta), and am trying to install the Scala plugins.
Unfortunately I am getting this error:

I have tried adding http://deadlock.netbeans.org/hudson/job/nbms-and-javadoc/lastStableBuild/artifact/nbbuild/nbms/updates.xml.gz to my plugin repo list, but nothing on the new plugin list it provides is relevant to Parsing API.
How do I rectify this Parsing API issue?

A: Question is answered here: Can't install nb-scala on NetBeans 7.4rc1
A working plugin for 7.4 can be downloaded here (nbscala-7.4_2.10.x-1.6.1.1.zip): http://sourceforge.net/projects/erlybird/files/nb-scala/7.x_2.10.x/


text:
Q: ReactNative - build failed : http://central.maven.org/maven2/com/facebook/react/react-native/maven-metadata.xml'. 501 HTTPS Required As of January 15, 2020 my react native build is failing with the error:

http://central.maven.org/maven2/com/facebook/react/react-native/maven-metadata.xml'.
  Received status code 501 from server: HTTPS Required

A: Solution:
Update build.gradle
from:

http://central.maven.org/maven2/

To:

https://repo1.maven.org/maven2/

see ref:
https://support.sonatype.com/hc/en-us/articles/360041287334


text:
Q: Traefik 2 parsing ENV directly into map in golang template? I want to load configurations in a dockerized traefik 2 using environment variables.
To achieve this I would like to use the golang template capabilities in traefiks dynamic file configuration.
I tried several approaches (I'm posting my json test here) but I can not seem to be able to parse the ENV into a map.
Is there any other way I could achieve this?
docker-compose.yml:
version: "2.4"
services:
  internal-gateway:
    image: my-internal-gateway
    environment:
      MY_MAPPINGS: >-
        {
          "microservice1": {"host": "service1:1234"},
          "microservice2": {"host": "service2:4321"}
        }

My dynamic-traefik-configuration.yml:
http:
  routers:
    {{range $k, $v := env "MY_MAPPINGS"}}
    router-{{ $k }}:
      rule: "PathPrefix(`/{{ $k }}`)"
      service: {{ $k }}
    {{end}}

  services:
    {{range $k, $v := env "MY_MAPPINGS"}}
    {{ $k }}:
      loadBalancer:
        servers:
          - url: "{{ $v.host }}"
    {{end}}


text:
Q: Compilation error - ICE80: The 64BitComponent ... uses 32BitDirectory The following line
<Component Guid='{THE_GUID}' Id='GlobalScopePackages' >

Generates the following error:
Error   4   ICE80: This 64BitComponent GlobalScopePackages uses 32BitDirectory blablabla    c:\development\...\file.wxs

Error is described on this page
http://msdn.microsoft.com/en-us/library/aa369034(VS.85).aspx
How do I fix this or suppress the warning?  Is it safe to simply supress the warning?

A: I want a 64-bit installer (as per my Release configuration), so I used <Directory Id="ProgramFiles64Folder"> instead of ProgramFilesFolder as part of the target installation  path.
This article provides more information: How to: Create the Windows Installer Package for 64-bit Client Computers

A: Safe to just suppress the warning.

A: I wanted to be able to build my installer both for x86 and x64 depending on the build arguments passed in. I was able to do it like this.
See this blog post by Alek Davis for more information.
Simple example, in the .wxs file
<?if $(var.Platform) = x64 ?>
    <?define Win64 = "yes" ?>
    <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
<?else ?>
    <?define Win64 = "no" ?>
    <?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
<?endif ?>

<Fragment>
    <Directory Id="TARGETDIR"
           Name="SourceDir">
        <Directory Id="$(var.PlatformProgramFilesFolder)">
            <Directory Id="INSTALLFOLDER"
               Name="X" />
        </Directory>
    </Directory>
</Fragment>

<Fragment>
    <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
        <!-- TODO: Remove the comments around this Component element and the ComponentRef below in order to add resources to this installer. -->
        <Component Id="ProductComponent"
             Win64="$(var.Win64)">

    <File Source="$(var.X.TargetPath)" />
    <!-- TODO: Insert files, registry keys, and other resources here. -->
        </Component>
    </ComponentGroup>
</Fragment>

A: If anyone trying to automate 'component' creating process using HEAT, there is no switch available (until V3.10) to include Win64=yes/no.
Use -arch x64 switch with Candle will resolve this issue.

A: You can also set Win64="no" in the <Component /> tag of the components which are not 64-bit.
But I can confirm you can ignore this.

A: I was getting this error today and found that the Installer project was set to build as x64. All the other projects were Any CPU. I only wanted an x86 installer so simply changing the Platform to x86 fixed this problem for me.
Obviously if you want an x64 based installer then one of the answers above will solve your problem.


text:
Q: Issue trying to complete Firebase Storage download before showing tableview I have a table view where depending on the cell class it will download an image from Firebase. I've noticed when using the app that cells with the same cell identifier will show the previous downloaded image before showing the new one. This is what I have before changing it.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableData[indexPath.row]["Image"] != nil {
        let cell = tableView.dequeueReusableCell(withIdentifier: "imageNotesData", for: indexPath) as! ImageNotesCell
        cell.notes.delegate = self
        cell.notes.tag = indexPath.row
        cell.notes.text = tableData[indexPath.row]["Notes"] as! String
        guard let imageFirebasePath = tableData[indexPath.row]["Image"] else {
            return cell }
        let pathReference = Storage.storage().reference(withPath: imageFirebasePath as! String)
        pathReference.getData(maxSize: 1 * 1614 * 1614) { data, error in
            if let error = error {
                print(error)
            } else {
                let image = UIImage(data: data!)
                cell.storedImage.image = image
            }
        }
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "notesData", for: indexPath) as! NotesCell
        //let noteString = tableData[indexPath.row]["Notes"] as! String
        cell.notes.text = tableData[indexPath.row]["Notes"] as! String
        cell.notes.delegate = self
        cell.notes.tag = indexPath.row
        return cell
    }
}

Knowing that this is not a good user experience and that it looks clunky, I tried to move the pathReference.getData to where I setup the data but the view appears before my images finish downloading. I have tried to use a completion handler but I'm still having issues.
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
            getSectionData(userID: userID, city: selectedCity, completion: {(sectionString) in
            self.setupTableCellView(userID: userID, city: selectedCity, section: sectionString) { (tableData) in
                DispatchQueue.main.async(execute:  {
                    self.cityName?.text = selectedCity
                    self.changeSections.setTitle(sectionString, for: .normal)
                    self.currentSectionString = sectionString
                    self.setupTableData(tableDataHolder: tableData)
                })
            }
        })
}

func setupTableCellView(userID: String, city: String, section: String, completion: @escaping ([[String:Any]]) -> () ) {
        let databaseRef = Database.database().reference().child("Users").child(userID).child("Cities").child(city).child(section)
        var indexData = [String:Any]()
        var indexDataArray = [[String:Any]]()
        databaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
            for dataSet in snapshot.children {
                let snap = dataSet as! DataSnapshot
                //let k = snap.key
                let v = snap.value
                indexData = [:]
                for (key, value) in v as! [String: Any] {
                    //indexData[key] = value
                    if key == "Image" {
                        //let pathReference = Storage.storage().reference(withPath: value as! String)
                        print("before getImageData call")
                        self.getImageData(pathRef: value as! String, completion: {(someData) in
                            print("before assigning indexData[key]")
                            indexData[key] = someData
                            print("after assigning indexData[key]")
                        })
                    } else {
                        indexData[key] = value
                    }
                }
                indexDataArray.append(indexData)
            }
            completion(indexDataArray)
        })
    }

func getImageData(pathRef: String, completion: @escaping(UIImage) -> ()) {
    let pathReference = Storage.storage().reference(withPath: pathRef as! String)
    pathReference.getData(maxSize: 1 * 1614 * 1614, completion: { (data, error) in
        if let error = error {
            print(error)
        } else {
            let image = UIImage(data:data!)
            print("called before completion handler w/ image")
            completion(image!)
        }
    })
}

I don't know if I am approaching this the right way but I think I am. I'm also guessing that the getData call is async and that is why it will always download after showing the table view.

A: You can't do this.
Make the request from Firebase.
Over time, you will get many replies - all the information and all the changing information.
When each new item arrives - and don't forget it may be either an addition or deletion - alter your table so that it displays all the current items.
That's OCC!
OCC is "occasionally connected computing".  A similar phrase is "offline first computing".  So, whenever you use any major service you use every day like Facebook, Snapchat, etc that is "OCC": everything stays in sync properly whether you do or don't have bandwidth. You know?  The current major paradigm of device-cloud computing.

A: Edit - See Fattie's comments about prepareForReuse()!
With reusable table cells, the cells will at first have the appearance they do by default / on the xib.  Once they're "used", they have whatever data they were set to.  This can result in some wonky behavior. I discovered an issue where in my "default" case from my data, I didn't do anything ecause it already matched the xib, but if the data's attributes were different, I updated the appearance. The result was that scrolling up and down really fast, some things that should have had the default appearance had the changed appearance.
One basic solution to just not show the previous image would be to show a place holder / empty image, then call your asynchronous fetch of the image. Not exactly what you want because the cell will still show up empty...
Make sure you have a local store for the images, otherwise you're going to be making a server request for images you already have as you scroll up and down!
I'd recommend in your viewDidLoad, call a method to fetch all of your images at once, then, once you have them all, in your success handler, call self.tableview.reloadData() to display it all.


text:
Q: Adding module "angular-hotkeys" to my mean.js app Just getting started with angular - so hoping I am not missing something absolutely obvious.  I am using mean.js (Mongo, Express, Angular, Node stack) and working on a simple to do app to get me started.  I am trying to add the angular-hotkeys module to my app.
I installed the module using sudo npm install -g angular-hotkeys --save
I then added ApplicationConfiguration.registerModule('cfp.hotkeys'); to my core.client.module.js file.
And in my config.js file, I added cfp.hotkeys as a dependency:
var ApplicationConfiguration = (function() {

 // Init module configuration options

 var applicationModuleName = 'taskmanager';

 var applicationModuleVendorDependencies = ['ngResource', 'ngCookies',  'ngAnimate',  'ngTouch',  'ngSanitize',  'ui.router', 'ui.bootstrap', 'ui.utils', 'cfp.hotkeys'];

Finally - I bound hotkeys to my controller:
// Lists controller
angular.module('lists').controller('ListsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Lists', 'SelectedList', 'hotkeys',
    function($scope, $stateParams, $location, Authentication, Lists, SelectedList, hotkeys ) {
        $scope.authentication = Authentication;

        console.log('hotkeys');

But every time I load the page I get the following error:
Error: [$injector:unpr] Unknown provider: hotkeysProvider <- hotkeys http://errors.angularjs.org/1.2.22/$injector/unpr?p0=hotkeysProvider%20%3C-%20hotkeys
    at http://localhost:3000/lib/angular/angular.js:78:12
    at http://localhost:3000/lib/angular/angular.js:3792:19
    at Object.getService [as get] (http://localhost:3000/lib/angular/angular.js:3920:39)
    at http://localhost:3000/lib/angular/angular.js:3797:45
    at getService (http://localhost:3000/lib/angular/angular.js:3920:39)
    at invoke (http://localhost:3000/lib/angular/angular.js:3947:13)
    at Object.instantiate (http://localhost:3000/lib/angular/angular.js:3967:23)
    at http://localhost:3000/lib/angular/angular.js:7260:28
    at http://localhost:3000/lib/angular/angular.js:6651:34
    at forEach (http://localhost:3000/lib/angular/angular.js:332:20) <section data-ui-view="" class="ng-scope">

I know I am probably doing something very simple wrong - but for the life of me I can't figure out what it is.

A: That might be because the module is called cfp.hotkeys not hotkeys, that mean's you're loading the wrong module name in your file.
See the name of module defined here
Update: Install the module using bower instead of using npm and also not globally.
bower install angular-hotkeys --save


text:
Q: WPF unit testing, UIElement.RaiseEvent, ArgumentException I am trying to build out a unit test and would like to fake out a DropEvent.
I get an error as it is attempting to raise the event. I can't create a DragEventArgs is it protection level is internal.
System.ArgumentException : Object of type 'System.Windows.RoutedEventArgs' cannot be converted to type 'System.Windows.DragEventArgs'

I have the following...
        [Test]
    public void Test()
    {
        DesignerMock view = new DesignerMock();
        _viewModel = (PanelDesignViewModel)view.DataContext;
        view.Show();

        Assert.IsNotNull(_viewModel);

        RoutedEventArgs args = new RoutedEventArgs(DesignerCanvas.DropEvent,view.DesignerCanvas) ;
        view.DesignerCanvas.RaiseEvent(args);

        view.Close();

    }

A: As ascalonx says, you shouldn't test your View, only your ViewModel. This means your ViewModel needs to be decoupled from the View.  Instead of an event handler, expose a simple public method on the ViewModel that will do the work you need, and simply call this in your test.  To make your View call this method, use an attached behavior. Caliburn has a nice "Actions" attached behavior to do just this.
You mention you also have some VisualTreeHelper stuff "going on".  This is a violation of the M-V-VM pattern, as it couples your VM to a specific V implementation.  What ever your doing there, abstract it out to a "service" interface and use IoC or Service Locator to provide this service to your VM.  I might suggest looking at Onyx for this (disclaimer: I'm the author of this library). It provides a flexible and easy to use mechanism for providing services to your VM.

A: If you're adamant that you want to test your code in this way, you could use reflections to create a DragEventArgs.  However, the real question, I think, is if you're going in the right direction with your unit testing. I usually avoid doing any testing directly on my Views and stick with testing the more easily testable viewmodels (if indeed you're using MVVM) because of exactly the issue you're having right now.


text:
Q: Using an Angular Directive to draw a Google Chart without manual bootstrapping I want to write a directive to draw a google chart but I want to do so with out using the Angular-Google-Charts library or manually bootstrapping angular. As this will sit on Google Apps Script and the chart is a much lesser element of the webpage, the chart takes much lower priority.
I was hoping that I could use the link function in the directive to load the google charts library and then draw the chart like so:
.directive('barChart', [function () {
  return {
    restrict: 'A',
    scope: {
        data: '=',
     },
     link: function(data, elm, attrs) {
        google.load('visualization', '1', {packages:['corechart']});
        google.setOnLoadCallback(drawChart);
        function drawChart() {
          var data = new google.visualization.DataTable();
          data.addColumn('string', 'Topping');
          data.addColumn('number', 'Slices');
          data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
          ]);
          var options = {'title':'How Much Pizza I Ate Last Night',
                         'width':400,
                         'height':300};
          var chart = new google.visualization.PieChart(elm[0]);
          chart.draw(data, options);
        }
     }
  };
}]);

Is making this approach work possible? If so, how?
Many thanks
Toby

A: There's a directive already made for this. https://github.com/angular-google-chart/angular-google-chart/
Make sure you use the master branch, gh-pages branch is development and slightly unstable at the moment.


text:
Q: Shortest distance and calculus of variation. Every answer to the question "show that the shortest path between two points on $\mathbb{R}^2$ is the line segment joining them", seems to rely on some version of calculus of variation.
My problem with that approach is that most of them make the assumption that the path is the graph of a smooth function, rather than a generic curve. Okay, we may exclude the possibility of self-intersection, but how can we eliminate the possiblity that the curve may not be the graph of a function or not (piecewise) smooth?

A: Not true. See: Wikipedia article: we normally define the length of a curve as a (potentially infinite) supremum of all the lengths (in the "standard" sense) of polygonal lines joining the beginning and the end of the curve and "inscribed" in the curve. We say that the curve is "rectifiable" if this supremum is finite.
With that definition, the fact that the straight line is the shortest follows pretty much immediately from the definition. Pretty much, the only slightly nontrivial bit is to prove that the length of the straight line (in this new sense) is the same as the length of the straight line (in the standard sense). This is true because, for every polygonal line "inscribed" in a straight line, the (standard) length of it is exactly the same as the (standard) length of the original straight line.

This consideration works in any $\mathbb R^n$. However, it does not scale well to other manifolds, because those may be locally homeomorphic with $\mathbb R^n$ but not locally isometric with $\mathbb R^n$. The common way of adding metric to manifolds (which is: adding a metric tensor) requires differentiability of the maps between charts in the atlas (i.e. the manifold must be differentiable), in order for the metric tensor to allow for a change in co-ordinates when switching from one chart to another. That approach scales a lot better, but requires differentiability, and in that approach, the length of the shortest path is calculated using calculus of variations. This is probably what you had in mind in your question.


text:
Q: sendEmptyMessageAtTime issue A handler that I defined doesn't get a message set with sendEmptyMessageAtTime. The time I get from updateTime.getTimeInMillis is valid. What am I missing here ?
@Override
protected void onResume() {
    super.onResume();
    mNavigationBarFragment.configureFor(0);
    Calendar updateTime = Calendar.getInstance();
    updateTime.set(Calendar.YEAR, 2012);
    updateTime.set(Calendar.HOUR_OF_DAY, 18);
    updateTime.set(Calendar.MINUTE, 40);
    updateTime.set(Calendar.SECOND, 0);
    if(mUpdateOnAirLabel.sendEmptyMessageAtTime(1, updateTime.getTimeInMillis())){
    // messages gets placed
    }
}

private Handler mUpdateOnAirLabel = new Handler() {
    public void dispatchMessage(android.os.Message msg) {
    // doesn't get triggered
}

public void handleMessage(android.os.Message msg) {
    // doesn't get triggered
}
};

UPD
The time I get from the calendar object is right:
<?php

echo date("r", 1348753200578 / 1000);

output: Thu, 27 Sep 2012 17:40:00 +0400
After that I've tried to offset from the current timestamp
Calendar now = Calendar.getInstance();
long nowt = now.getTimeInMillis();
if(mUpdateOnAirLabel.sendEmptyMessageAtTime(1, now.getTimeInMillis() + 5000)){
        ...
}

And it's not triggering either. What's wrong here ?

A: You didn't specify the day! put Calendar.DAY_OF_YEAR or something like that!


text:
Q: Using SNMP to monitor Qnap Volume Usage I would like to use SNMP to monitor drive usage on a NAS. It's a Qnap TS-859U+.
I'm not sure how to use the MIB to my advantage in recognizing the correct OID's to query the right object instance.
How would I get the correct OID to query, and how would I know what queries the device supports.
I downloaded a MIB browser, iReasoning, but not sure where to look in the MIB tree. I also have the Qnap MIB.
I just need to know from the 3 volumes, what's the Available space.

A: First you should look if Qnap supports the UCD MIBs, like dskTable. This is likely. If not, you should look into the Qnap MIB you downloaded in order to find something similar. Open it, it's a text file, and read it. If you'll find something that looks suitable, place the Qnap MIB to the place your snmpwalk recognizes, add this MIB to the snmpwalk configuration (usually the snmp.conf file) and then query Qnap for this oid. Upon success, you can also translate the oid to numeric form with snmptranslate and use it without actual MIB file.


text:
Q: Как установить pywin32 на PyPy? Пытался установить pywin32, выдало ошибку:
D:\Download>pypy -m pip install pywin32
ERROR: Could not find a version that satisfies the requirement pywin32 (from ver
sions: none)
ERROR: No matching distribution found for pywin32

Погуглил, нашел pypiwin32, но при установке тоже выдает ошибку:
Пробовал также установить так: pypy -m pip install pypiwin32 --pre (ошибка таже)
C:\Windows\system32>pypy -m pip install pypiwin32
Collecting pypiwin32
Using cached pypiwin32-223-py3-none-any.whl (1.7 kB)
Using cached pypiwin32-219.zip (4.8 MB)
Preparing metadata (setup.py) ... error
error: subprocess-exited-with-error

├Ч python setup.py egg_info did not run successfully.
тФВ exit code: 1
тХ░тФА> [7 lines of output]
Traceback (most recent call last):
File "<string>", line 36, in <module>
File "<pip-setuptools-caller>", line 34, in <module>
File "C:\Users\HOME\AppData\Local\Temp\pip-install-cupl1f0p\pypiwin32_22
fafcc1eadd4bc780247dab0c362b25\setup.py", line 121
print "Building pywin32", pywin32_version
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("B
uilding pywin32", pywin32_version)?
[end of output]

note: This error originates from a subprocess, and is likely not a problem wit
h pip.
error: metadata-generation-failed

├Ч Encountered error while generating package metadata.
тХ░тФА> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Попробовал поставить в ручную в виде пакетов .tar.gz и .whl, но нет, опять ошибка:
D:\Download>pypy -m pip install pypiwin32-223.tar.gz
Processing d:\download\pypiwin32-223.tar.gz
Preparing metadata (setup.py) ... done
ERROR: Could not find a version that satisfies the requirement pywin32>=223 (fro
m pypiwin32) (from versions: none)
ERROR: No matching distribution found for pywin32>=223

Версия моего pypy:
D:\Download>pypy -V
Python 3.8.15 (c20fe3f310f1d209d69a71d903dd17e5c3cf0de9, Dec 05 2022, 15:20:36)
[PyPy 7.3.10 with MSC v.1929 64 bit (AMD64)]

После первой ошибки сразу обновил pip
D:\Download>pypy -m pip install --upgrade pip
Requirement already satisfied: pip in c:\program files\pypy3.8\pypy3.8-v7.3.10-w
in64\lib\site-packages (22.3.1)

Пока ничего не помогло, никак не получается поставить pywin32, что я делаю не так? (На обычный python 3.8 поставилось без проблем)


text:
Q: PostgreSQL, checking date relative to "today" Was wondering if someone could assist with some Postgres. I have a table which has a column called mydate which is a postgres date type. I want to do something like:
SELECT * FROM MyTable WHERE mydate > [Today-1year]

I've never used Postgres before and I'm sure I just need to know the name of some functions- I'll gladly look up the reference myself. Can anyone point me in the right direction?
Thanks!

A: This should give you the current date minus 1 year:
select now() - interval '1 year';

A: I think this will do it:
SELECT * FROM MyTable WHERE mydate > now()::date - 365;

A: You could also check using the age() function
select * from mytable where age( mydate, now() ) > '1 year';
age() wil return an interval.
For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131
See postgresql documentation

A: select * from mytable where mydate > now() - interval '1 year';

If you only care about the date and not the time, substitute current_date for now()
select * from mytable where mydate > current_date - interval '1 year';


text:
Q: Letters inside "int(input(())" def multiply():                                                                                #starts sub program when 'multiply()' is called
num1 = random.randint(1,12)                                                                     #randomly generates a number between 1 and 12
num2 = random.randint(1,12)
while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
    ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))          #asks question and requires a user input
    correct = (ans == num1 * num2)
    if correct:
        print("You are correct! ")
        break                                                                                #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
    else:
        print("Wrong, please try again. ")
    loop == False                                                                               #if the answer is wrong, it loops back to when 'loop' was last 'True'

I am wondering if there is a way for me to include a line of code that allows me to display "That is not an option!" when a symbol other than a number is entered into the 5th line in the code.

A: Use an exception to catch unexpected inputs.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random

def multiply():

    # Randomly generates a number between 1 and 12
    num1 = random.randint(1,12)
    num2 = random.randint(1,12)

    while True:

        i = input("What is the answer to {} x {} ".format(
            str(num1), str(num2)))

        try:
            ans = int(i)
        except ValueError:
            print('That is not an option!')
            continue

        if ans == num1 * num2:
            print("You are correct!")
            break
        else:
            print("Wrong, please try again.")

if __name__ == "__main__":

    multiply()

A: When you convert to int there is the chance that they will enter a non-integer value so the conversion will fail, so you can use a try/except
def multiply():                                                                                #starts sub program when 'multiply()' is called
    num1 = random.randint(1,12)                                                                     #randomly generates a number between 1 and 12
    num2 = random.randint(1,12)
    while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
        try:
            ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))          #asks question and requires a user input
            correct = (ans == num1 * num2)
            if correct:
                print("You are correct! ")
                break                                                                                #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
            else:
                print("Wrong, please try again. ")
            loop == False
        except ValueError:
            print("That is not an option")

Note that your previous code is now nested in a try block. If the int() fails because they entered a bad input, it will throw a ValueError that you can catch and notify them.
As a side note, another way to format your question to them would be
'What is the answer to {} x {}?'.format(num1, num2)

This is a nice way to generate a string with injected variable values.


text:
Q: generate json array with two data values please advice me how to get the results of both values 'content' and 'categories' on below json array.. currently it give results only for 'content'
     $abc=$_GET["term"];

$query=mysql_query("
SELECT  b.title as category ,a.title as content
FROM  tb_content a, tb_categories b
WHERE ( b.title like '%".$abc."%'
OR a.title like '%".$abc."%')
AND a.categories_id=b.id
AND b.parent_id=81
");
$json=array();
    while($display=mysql_fetch_array($query)){
         $json[]=array(
                    'value'=> $display["content"],
                    'label'=>$display["content"],

                        );

A: Here you go:

*

*You always should escape variables before using them in a query.

*You are not closing your while loop.

*You are using the same key for value and label.

*Remove the last comma in the while loop.

*Follow my code:
 $abc = mysql_real_escape_string( $_GET["term"] );

 $query = mysql_query("
                 SELECT  b.title as category ,a.title as content
                 FROM  tb_content a, tb_categories b
                 WHERE ( b.title like '%".$abc."%'
                 OR a.title like '%".$abc."%')
                 AND a.categories_id=b.id
                 AND b.parent_id=81
                ");
  $json = array();

  while ( $display = mysql_fetch_array($query) )
  {
      $json[]=array(
            'value' => $display["content"],
            'label' => $display["category"]
      );
   }

 //output:

 print_r($json); //as an array

 echo json_encode($json); // as a json string


text:
Q: kdenlive won't see my external hard drive kdenlive won't see my external hard drive. I have heard that it's a common issue. ..is there a new fix yet ?

A: I have found out that there are two versions of Kdenlive. One version works great at the Ubuntu Store.


text:
Q: How to combine complex surveys from different populations? I have 4 national representative surveys (DHS) and let us assume one survey belong to one country (e.g. Lesotho, Namibia, South Africa, and Zimbabwe).
The sampling method used in these surveys is biased (two-stage sampling) and the DHS provides sampling weights calculated against PSU (primary sampling units) and STRATA.
Although, I know it is possible to combine multiple surveys from the same target population (US) through reweighting as pointed by CDC (e.g. NHANES). I wonder if it's possible to combine surveys from different populations? This will allow me to obtain one giant dataset for southern Africa that I can analysis in further multilevel approaches.
if yes, how the weights are recalculated.
My environment (R 3.6.4, survey, INLA).

A: in some circumstances, adding a country-sample-specific identifier to the psu and strata variables would be enough to maintain the svydesign calculations.  if you stacked the datasets from those four nations, would the sum of weights match their relative populations?  otherwise you might want to postStratify ?
set.seed(1999)

library(survey)

x <- data.frame( psu_variable = sample( 1:3 , 200 , replace = TRUE ) , strata_variable = sample( 1:10 , 200 , replace = TRUE ) , weight_variable = sample( 1:2 , 200 , replace = TRUE ) , some_variable = sample( 1:50 , 200 , replace = TRUE ) )

y <- data.frame( psu_variable = sample( 1:3 , 200 , replace = TRUE ) , strata_variable = sample( 1:10 , 200 , replace = TRUE ) , weight_variable = sample( 1:2 , 200 , replace = TRUE ) , some_variable = sample( 1:50 , 200 , replace = TRUE ) )

# first country
# x
x[ , 'country_name' ] <- 'first country'

# second country
# y
y[ , 'country_name' ] <- 'second country'

# possible design for first country
x_des <- svydesign( ~ psu_variable , strata = ~ strata_variable , data = x , weights = ~ weight_variable , nest = TRUE )

# possible design for second country
y_des <- svydesign( ~ psu_variable , strata = ~ strata_variable , data = y , weights = ~ weight_variable , nest = TRUE )

# add a unique country identifier to psu and strata variables
x[ , 'new_psu_variable' ] <- paste( "first country" , x[ , 'psu_variable' ] )
y[ , 'new_psu_variable' ] <- paste( "second country" , y[ , 'psu_variable' ] )
x[ , 'new_strata_variable' ] <- paste( "first country" , x[ , 'strata_variable' ] )
y[ , 'new_strata_variable' ] <- paste( "second country" , y[ , 'strata_variable' ] )

# stack and create possible design
needed_variables <- c( 'new_psu_variable' , 'new_strata_variable' , 'weight_variable' , 'country_name' , 'some_variable' )
z <- rbind( x[ needed_variables ] , y[ needed_variables ] )

# possible stacked design
z_des <- svydesign( ~ new_psu_variable , strata = ~ new_strata_variable , data = z , weights = ~ weight_variable , nest = TRUE )

# these statistics definitely need to line up
svymean( ~ some_variable , x_des )
svymean( ~ some_variable , y_des )
svyby( ~ some_variable , ~ country_name , z_des , svymean )

# combined result assumes x and y had appropriate weights
svymean( ~ some_variable , z_des )

# do the weights match the country populations?
sum( x[ , 'weight_variable' ] )
sum( y[ , 'weight_variable' ] )

# otherwise, post-stratify the design so it matches the relative population sizes
pop.types <- data.frame( country_name = c( 'first country'  , 'second country' ) , Freq = c( 250000 , 750000 ) )
z_des_p <- postStratify( z_des , ~ country_name , pop.types )

# within-country estimates do not change
svyby( ~ some_variable , ~ country_name , z_des , svymean )
svyby( ~ some_variable , ~ country_name , z_des_p , svymean )

# combined country estimates now reflect relative population sizes for the `z_des_p` survey design
svymean( ~ some_variable , z_des )
svymean( ~ some_variable , z_des_p )


text:
Q: C# Moving a cross into a picturebox based on the Thumbstick Position I want to draw a cross into a picturebox. In the next step I want to move the cross based on my Data.
Which is the Thumbsticks position. I want it to appear similar to the figure below.

Here is my Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SlimDX;
using SlimDX.XInput;

namespace Controller_Test
{
    public partial class Form1 : Form
    {
        GamepadState Controller = new GamepadState(UserIndex.One);
        Graphics drawArea;

        public Form1()
        {
            InitializeComponent();
            timer1.Enabled = true;
            drawArea = pictureBox1.CreateGraphics();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Controller.Update();
            var LeftStick = Controller.LeftStick;
            float LeftStickX = LeftStick.Position.X;
            float LeftStickY = LeftStick.Position.Y;

            Pen blackPen = new Pen(Color.Black);

            //  horizontal Line
            drawArea.DrawLine(blackPen, x1+LeftStickX, y1-LeftStickY,   x2+LeftStickX, y2-LeftStickY);
        // vertical Line
            drawArea.DrawLine(blackPen, x1+LeftStickX, y1-LeftStickY, x2+LeftStickX, y2-LeftStickY);
        }
    }
    public class GamepadState
    {Get Postiton......}
}

My problem now is, if I move the Thumbstick every time a new cross is drawn but the old one is still in the
Picturebox like in the figure below. If i use the pictureBox1.Invalidate():/pictureBox1.Refresh(); Funtcion
the cross becomes invisible and is not displayed anymore. The interval of the timer is on 1.

What could i change in order to get the code to work?


text:
Q: Redirection: How did the extra word get in the file? I was testing a script and wanted to create a small file with a bit of text in it so I typed the following and forgot to escape the space in the filename:
echo "bob">other name

When I did ls, it showed the file "other" and when I did cat other, it showed the contents as:
bob name

How did "name" get in the file? I believe I saw somewhere that you can put redirection anywhere in a command. In fact, I just tested this:
echo >other Some text in a file

and "Some text in a file" was the contents of "other".
What is the purpose of this feature?
Of course, originally, I should have typed:
echo "bob">other\ name

A: This is how bash redirection works.
Writing this:
echo "bob">other name

is equivalent to this:
echo "bob" name >other

redirection can appear anywhere on the line, the chevron (>) only applies to "other".
This allows people flexibility of how they wish to structure their commands. If it looks more clear doing something like this:
>file.txt echo "one" "two" "three"

then that is up to the person writing the script or command.


text:
Q: Why is esp8266 client not connected to server? I am new to Arduino and I am not so familiar with it. I am not sure why the client cannot connect to the server and I have been looking at it for hours. Any solution to this would be a great help.
So I successfully establish a server with the code below. But...
// server.ino
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "WifiName"; // Wifie name
const char* password = "WifiPassword"; // Wifi password
float sensor_value = 0.0;
String Website;

ESP8266WebServer server(80);

void setup(){
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);

  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while(WiFi.status()!=WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }
  Serial.println("Server started at port 80.");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.print("URL=http://");
  Serial.println(WiFi.localIP());

  server.on("/", handleIndex); //use the top root path report last sensor value
  server.on("/update",handleUpdate); // use this route to update sensor value
  server.begin();
}

void loop(){
  server.handleClient();
}

void handleIndex(){
    Website = "
"+ String(sensor_value) +"
";
    server.send(200," text/html",Website);
}

void handleUpdate(){
  sensor_value = server.arg("value").toFloat();
  Serial.println(sensor_value);
  server.send(200,"text/plain","Updated");
}

I try to connect a client to the server so it could send data to the server, but a connection between the client and the server cannot be established and I don't know why. I check the IP address and it is all correct I just don't get why the client fails to connect to the server
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <HX711.h>
#include "Wire.h"

#define DOUT D5
#define CLK D6
HX711 scale;

const char* ssid     = "WifiName";
const char* password = "Wifipassowrd";
float calibration_factor = 107095;
float val_Weight;

const char* host = "192.168.0.167"; // Server host IP.
const int port = 80;
WiFiClient client;

void setup() {
   Serial.begin(115200);       //set baud rate
   Serial.println("Connecting to ");
   Serial.println(ssid);

   WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED)
        {
          delay(500);//millisecond
          Serial.print(".");
          }
   Serial.println("");
   Serial.println("WiFi connected & connect to client");

}

void loop() {

  //connect to the server and send the data as URL parameter

  if(client.connect(host, port)){
    String url = "update?value=";
    url+=String(25.0);
    client.print(String("GET /") + url + "HTTP/1.1\r\n" + "Host: " + host + "\r\n" +
    "Connection: close\r\n\r\n");
    delay(10);

    Serial.println("Response: ");
    while(client.available()){
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }
  }else{
    Serial.println("fail");
  }

}

Any help would be great thanks!!!

A: Check the passwords, you have a typo.
const char* password = "Wifipassowrd";


text:
Q: Flow on a Torus is Transitive iff it is Incommensurate Consider the system
$$
\dot{\mathbf{x}}(t)=\mathbf{a}
$$
where $t\in\mathbb{R},\mathbf{x}\in\mathbb{R}^n,$ and $\mathbf{a}\in\mathbb{R}^n.$
It is well known that the flow on the n-torus $\mathbb{T}^n$ generated by
$$\varphi_t:\mathbb{T}^n\to\mathbb{T}^n
$$
given by
$$\varphi_t\left(\mathbf{x}_0\right):=t\mathbf{a}+\mathbf{x}_0
$$
is transitive if and only if it is incommensurate.
This paper
http://fe.math.kobe-u.ac.jp/FE/FE_pdf_with_bookmark/FE01-10-en_KML/fe07-091-102/fe07-091-102.pdf
references several papers early on as a proof of this. However, I'm looking for a direct proof that doesn't rely on any measure theoretic notions or ergodic theory for pedagogical purposes. I think I have a proof, yet I haven't been able find one anywhere else despite this being an important example in integrable dynamical systems. Has anyone come across a direct proof of this well-known result?


text:
Q: How to enable asp.net-mvc6 to return JSONP instead of JSON I've just started with the new asp.net-mvc6 and run into some problems.
The documentation is still not very helpfull and I hope some of you guys can help me.
I've build a small website with one single page and I use one Controller as webservice to feed an autocomplete textfield with jquery.
As it is on the same domain, everything works fine.
Now I want to reuse the webservice inside of a wordpress blog which is hosted on a different server.
I reused my jQuery code from some older projects to get an JSONP response from my webservice but it doesn't work.
It seems, that it doesn't generate the right callback function on the server and always only returns plain JSON.
Is there any point in some config file or something else, where I can tell my server to return JSONP instead of JSON?
Or do you have a working example code for an asp.net-mvc6 project with JSONP?
Big Thanks and regards
Gogglehead

A: Instead of using JSONP, you may want to consider Cross-Origin Resource Sharing (CORS) which is now supported by all major browsers: Can I Use Listing
This option is great because it allows the use of standard JSON and only requires an additional response header to work.  If you have a project that contains only web services that you don't mind being shared, you can enable it for the whole project via the web.config file.
    <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>

    <!-- Enable Cross-Origin Requests -->
    <httpProtocol>
      <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>

  </system.webServer>
</configuration>

If you only want this enabled for a specific controller action, that can be accomplished as well by modifying the headers collection:
    [HttpGet("{subject}/{number}")]
    public CourseList Get(string subject, int number)
    {
        Response.Headers.Add("Access-Control-Allow-Origin", new string[] { "*" });
        CourseList list = new CourseList();
        //Retrieve the data
        return list;
    }


text:
Q: Simulating a simple physics related scenario I am a total beginner in both simulations so this question might be silly. If so, please feel free to edit it. I am trying to simulate the following scenario in Python. I randomly place a few small particles in a 2D field with fixed dimentions. Each particle has a radius of effect r. If the first particle has the second one within its radius of effect, then a force has to be applied on both the particles (the effect that the first one has on the second and vice versa) and my force function is defined as:
f(i,j)_n = (r - |pi_n - pj_n|)((pj_n - pi_n)/|pi_n - pj_n|)
where n is the time step currently, pi_n represents the position of i at time step n and || represents magnitude calculation and (pj_n - pi_n) represents vector subtraction.
I was wondering if there are any libraries that simplify this stuff for me. All I need is basically the following:
time-step particle position(x,y)

Does anyone have some suggestions for me please?

A: Googling for python library vector 2d returned http://www.supereffective.org/pages/Vector-2d-Vector-Library as the top hit, which seems like a competent library (containing projection-and-perpendicularization, normalization, rotation, scaling, etc.)
As long as the number of particles isn't too large, this should work just fine in combination with an integration scheme. e.g. you keep track of each particle's (pos, vel) and perhaps also accel vectors, and use:
F = m a
-> F = m dv/dt
-> dv/dt = F/m
and thus
dv ~= dt*F/m
-> v' - v ~= dt*F/m
-> ball.vel += timeStep*sum(ball.force(n) for n in ball.neighbors())/ball.mass
This is Euler integration which has pretty bad properties, but is okay for a game.

A: I really like the pymunk physics library, a wrapper for the chipmunk physics library.
First of all, the library needs to be initialized:
import pymunk
pymunk.init_pymunk()
space = pymunk.Space()
space.gravity = (0.0, -100.0)

To achieve something the likes you have requested you have to create a Body and a Circle shape for each particle you wish to create.
mass = 1
radius = 14
inertia = pymunk.moment_for_circle(mass, 0, radius, (0,0))
body = pymunk.Body(mass, inertia)
x, y = random.randint(0, 200), random.randint(0, 200)
body.position = x, 550
shape = pymunk.Circle(body, radius, (0,0))
shape.sensor = True
space.add(body, shape)

The particles will not collide with each other, beacause the sensor flag is set to True. The radius is now somewhat of an area of influence.
Now, we create a callback function for particles which have an overlapping area of influence:
def near_callback(space, arbiter, *args, **kwargs):
    body_i = arbiter.shapes[0].body
    body_j = arbiter.shapes[1].body

    # calculate the forces force_i and force_j with your formula
    ...

    body_i.apply_force(force_i)
    body_j.apply_force(force_j)

The callback is set in the space:
space.set_default_collision_handler(near_callback, near_callback, None, None, None)

Of course, the space has to be "stepped" for each time-frame:
space.step(dt)

I hope this was somewhat understandable and helpful.


text:
Q: Why is this PHP page completely blank? I have a shopping cart and I want to send the purchase to my database. I am completely sure that the form part works fine, however the page where the purchase needs to be inserted into the database is wrong. However, I don't really know what's wrong and why it's giving me just a blank page (addorder.php, the processing page) while it's supposed to give me an error message on the previous page. This is the code for addorder.php:
<?php

class PurchaseOrder
{
    private $db_connection = null;

    public $errors = array();

    public $messages = array();

    public function __construct()
    {
        if (isset($_POST["purchase"])) {
            $this->addOrder();
        }
    }

    private function addOrder()
    {
        if (empty($_POST['order_firstname'])) {
            $this->errors[] = "Please fill in your first name.";
        } elseif (empty($_POST['order_lastname'])) {
            $this->errors[] = "Please fill in your last name.";
        } elseif (empty($_POST['order_phone'])) {
            $this->errors[] = "Please fill in your phone number.";
        } elseif (empty($_POST['order_address'])) {
            $this->errors[] = "Please fill in your address.";
        } elseif (empty($_POST['order_city'])) {
            $this->errors[] = "Please fill in your city.";
        } elseif (empty($_POST['order_postalcode'])) {
            $this->errors[] = "Please fill in your postal code.";
        } elseif (empty($_POST['order_deliverydate'])) {
            $this->errors[] = "Please fill in a delivery date you like.";
        } elseif (empty($_POST['order_country'])) {
            $this->errors[] = "Please choose your country.";

            $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

            if (!$this->db_connection->set_charset("utf8")) {
                $this->errors[] = $this->db_connection->error;
            }

            if (!$this->db_connection->connect_errno) {

                $lastorder= "SELECT orderNumber FROM orders ORDER BY orderNumber DESC LIMIT 1";
                $lastordernumber=mysql_query($lastorder);

                while ($row=mysql_fetch_array($lastordernumber)) {
                    $lastnumber = $row['orderNumber'];
                }

                $order_firstname = $_POST['order_firstname'];
                $order_lastname = $_POST['order_lastname'];
                $order_phone = $_POST['order_phone'];
                $order_address = $_POST['order_address'];
                $order_city = $_POST['order_city'];
                $order_postalcode = $_POST['order_postalcode'];
                $order_deliverydate = $_POST['order_deliverydate'];
                $order_country = $_POST['order_country'];
                $order_date = date("Y-m-d");

                $customernumber = $_SESSION['CustomerNumber'];

                    $sql = "INSERT INTO orders (orderNumber, orderDate, requiredDate, shippedDate, status, comments, customerNumber) VALUES('" . $lastnumber . "', '" . $order_date . "', null, null, null, null, '" . $customernumber . "');";

                    $query_new_order = $this->db_connection->query($sql);

                    if ($query_new_order) {
                        $this->messages[] = "Your profile has been updated succesfully!";
                    } else {
                        $this->errors[] = "Sorry, your registration failed. Please go back and try again.";
                    }
            } else {
                $this->errors[] = "Sorry, no database connection.";
            }
        } else {
            $this->errors[] = "An unknown error occurred.";
        }
    }
}

And this is a picture of the 'orders' table in my database:

Can you guys help me out, I debugged the code and there are no syntax errors. What can it be? I am pretty confused now...
EDIT: This is how messages and errors are displayed on the sendviaparcel.php page, which is also the page with the form on it:

<?php
if (isset($purchaseOrder)) {
    if ($purchaseOrder->errors) {
        foreach ($purchaseOrder->errors as $error) {
            echo '

 '.$error.'

';
        }
    }
    if ($purchaseOrder->messages) {
        foreach ($purchaseOrder->messages as $message) {
            echo '

 '.$message.'

';
        }
    }
}

 require("includes/connection.php");

?>

And this is the form on sendviaparcel.php:

<form method="post" action="addorder.php" name="orderform">

                        <---THIS IS MY TABLE CONTENT---/>

 Cancel
 <button type="submit" class="btn btn-login btn-signin" name="purchase">Confirm purchase </button>

</form>

I have already turned on error reporting, but it returns nothing.


text:
Q: How to retrieve data on server side with node.js sent by frontend ajax via post method? I recently started learning node.js with express framework and stumbled upon a problem.
I'm trying out a simple query search webapp and I want to pass a piece of data(a boolean called all)
from front-end plain javascript via ajax to the server side, but the current code
that I have written as of right now, it seems that my data was not passed to the server side,
the 3 console.log that I planted all return {}.
What concept am I missing here? What am I doing wrong?
If any additional info is needed, pls let me know, Thanks.
front end js
window.onload=function(){
console.log("window loaded");
const xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:3000/search", true);
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status==200){
        // code later to be implemented
    }
}
let searchConditions = new SearchConditions(true);
console.log('data='+JSON.stringify(searchConditions));
xhr.send('data='+JSON.stringify(searchConditions));
}

class SearchConditions{
    constructor(all) {
        this.all = all;
    }
}

backend node.js
// only partial code

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.post('/search', (req, res) => {
    console.log(req.body);
    console.log(req.query);
    console.log(req.params);
});

my browser log

my backendlog

A: Because you send invalid data:
xhr.send('data='+JSON.stringify(searchConditions));

JSON Objects do not have variable declarations. What your Server gets is:
'data = {"all": true }'

This is not even a valid variable declaration.
What your server should get is:
{"all": true}

Try to send the plain JSON Object without a variable declaration and set the "Content-Type"-header to json:
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(searchConditions));


text:
Q: Greenplum connector giving hostname resolution error in ibm Datas stage GreenPlum Connection error:
 Greenplum_Connector_1,0: The following SQL statement failed: INSERT INTO GPCC_ET_20200903233319813_84175_0 select * from table .
 The statement reported the following reason: [SQLCODE=HY000][Native=56,966,976] [IBM(DataDirect OEM)][ODBC Greenplum Wire Protocol driver][Greenplum]ERROR: could not translate host name "hostname_of_machine", port "8001" to address: Name or service not known (cdbutil.c:819)
(seg5 192.168.111.240:6005 pid=38339) (cdbdisp.c:254)(File cdbdisp.c; Line 254; Routine cdbdisp_finishCommand; )
(CC_GPCommon::checkThreadStatusThrow, file CC_GPCommon.cpp, line 808)

A: As Jon mentioned, "hostname_of_machine" needs to be updated to the real hostname


text:
Q: How to create new database on heroku server with postgres I want to create a PostgreSQL database on a Heroku server.
My database.yml is
production:
  adapter: postgresql

  encoding: utf8

  database: ddb
  username: postgres

  port: 5432
  password: admin

  host: localhost

When I run heroku rake db:create it gives me the error:
mydatabase already exists
    (in /disk1/home/slugs/181380_8d7032f_f439-4fe4f5a6-f181-4150-a968-fadcf45f0af5/mnt)

I have tried it for various different database names, but get the same message.
How can I resolve this error?

A: heroku autogenerates database.yml on the deploy. Reads like: it doesn't matter what you put in your database.yml, which to me is nice, as I can include it in git without worrying about production db passwords.
You may choose another database by setting the ENV['DATABASE_URL']  (use heroku config:add DATABASE_URL=....)
Check heroku documentation
https://devcenter.heroku.com/articles/ruby-support#build-behavior


text:
Q: Electron white screen after built with log error not allowed to load resources I am trying to package my Electron application by using electron-builder. But somehow after succesfully built, When run the application and it only showed the white blank scree. Then when check the console, there is an error like below, is it a problem cause by the build itself or come from the package.json, or from my directory. any hint ?  Thankyou

, Already tried many solution on the stack overflow and other place but not fixing the problem so I decided to add question.
I also attached my

package.json

 {
  "name": "cookbook-dekstop",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "homepage": "./",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --config webpack.common.js --watch",
    "start": "electron .",
    "build": "electron-builder"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@fortawesome/free-regular-svg-icons": "^6.2.0",
    "@fortawesome/free-solid-svg-icons": "^6.2.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "axios": "^0.27.2",
    "babel-preset-es2015": "^6.24.1",
    "downloadjs": "^1.4.7",
    "file-loader": "^6.2.0",
    "html-to-image": "^1.10.8",
    "html2canvas": "^1.4.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.3.0",
    "url-loader": "^4.1.1"
  },
  "devDependencies": {
    "@babel/core": "^7.18.13",
    "@babel/preset-env": "^7.18.10",
    "@babel/preset-react": "^7.18.6",
    "autoprefixer": "^10.4.8",
    "babel-loader": "^8.2.5",
    "css-loader": "^6.7.1",
    "electron": "^20.1.1",
    "electron-reload": "^2.0.0-alpha.1",
    "postcss": "^8.4.16",
    "sass": "^1.54.8",
    "sass-loader": "^13.0.2",
    "style-loader": "^3.3.1",
    "tailwindcss": "^3.1.8",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0"
  },
  "build": {
    "appId": "cookbook-dekstop",
    "icon": "src/assets/cb.ico",
    "directories": {
      "output": "dist"
    },
    "extraFiles": [
      "./dist/assets/**"
    ],
    "files": [
      "./dist/**/*",
      "main.js",
      "preload.js"
    ],
    "linux": {
      "target": [
        "deb"
      ]
    },
    "mac": {
      "target": [
        {
          "target": "dmg",
          "arch": [
            "x64"
          ]
        }
      ]
    },
    "win": {
      "target": [
        "portable"
      ]
    }
  }
}

main.js

 var win = new BrowserWindow({
    width: 600,
    height: 800,
    backgroundColor: "white",
    icon: "./src/assets/cb.ico",
    webPreferences: {
      nodeIntegration: false,
      worldSafeExecuteJavaScript: true,
      contextIsolation: true,
      preload: path.join(__dirname, "preload.js"),
    },
    resizable: false,
  });

  win.loadURL(`file://${__dirname}/dist/index.html`);

A: Try:
win.loadFile(path.join(__dirname,'dist/index.html'));

The problem is you are trying to load an "external" resource that is packaged within a asar archive...

A: I faced the same problem, the problem is after packing our app with electron builder, dist folder is missing inside app.asar file, so application cannot able to find the starting path. I found a way and that is actually working.
Step 1 : In your angular.json file change your output path to out/{your-app-name}
"outputPath": "out/{your-app-name}",

Step 2 : Change the path of loadUrl in main.js file as below
    win.loadURL(`file://${__dirname}/out/{your-app-name}/index.html`)

Step 3 : Now run this command ng build --prod && electron-builder -w , this will first build angular app and then it will pack using electron.
Hope this works, I faced this issue for 2 weeks, later I unzipped app.asar file and tried various things then found this working solution.


text:
Q: Pushing the footer at the bottom of my page with a margin at the top I often use the method of an empty div to make my footer stay at the bottom of my page. The code idea is following:

My website's content

    Here my footer

The css:
html, body {
    height: 100%;
    margin:auto;
}
#canevas {
    min-height: 100%;
    height: auto;
    margin-bottom: -33px;
}
#footer, #push {
    height: 33px;
}

Today I'm looking for how to add a margin-top on my #caneva div without breaking the footer. Do you have any idea?
Note that my page's content can have many different size (a lot less and a lot more than 100% of the screen height).
Here a fiddle with previous code.

A: If using padding-top is an option, you could use box-sizing: border-box to calculate the width and height of the box including padding and border, as follows:
#canevas {
    min-height: 100%;
    margin-bottom: -33px;

    padding-top: 50px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

WORKING DEMO.
Also it's worth noting that border-box value is supported on IE8+.
Alternatively, you could add another spacer element as the first child of the #canevas element to push down the content, as follows:
.spacer {
    height: 50px;
}

My website's content

    Here my footer

This will have a promising browser support :)
UPDATED DEMO.
For further info, you could refer my answer on a similar question on SO here:

*

*Position footer at bottom of page having fixed header

A: If what you mean is to keep the height of the page, then the answer is to also add margin-bottom: -63px; to your #caneva div. This way basically only the top of the '#caneva div' will change, the rest of the page will remain the same.
I created an updated fiddle here for you.


text:
Q: Semantic versioning issue and npm 5 or above Can you tell me why do we need NPM 5 or above to avoid semantic versioning problems? In other words, how can we avoid it using package-lock.json file? Can't we avoid this issue if we use the same package.json file on all the development machine for the same project? I'm a little bit confused here.Hope you'll give a feedback for this.

A: This can be avoided if your package.json file lists packages like:
"@angular/core": "4.2.6",
"@angular/forms": "4.2.6",
"@angular/http": "4.2.6",

instead of
"@angular/core": "^4.2.6",
"@angular/forms": "^4.2.6",
"@angular/http": "~4.2.6",

By removing the tilde or cap(~, ^) sign from package.json npm will install exact same version on all machines. But its safe to add tilde or cap sign, so you can install small version updates of your packages without updating the file. But sometime this can cause issues, when package developer packs a breaking change in small version.
package-lock.json will do the same, it removes the tilde or cap sign, and marks the concrete version of package to be installed. And will make lock file priority to get the package version information while installing the packages.
Edit: Nice explanation from Angular University on Youtube.


text:
Q: Global React component in InertiaJS's createInertiaApp method How do I go about adding a global component (e.g. <Link />) to InertiaJS's createInertiaApp() method in Laravel 9?
createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        return render(<App {...props} />, el);
    },
});

A: Here you have an example of a global component registration. In this case, I'm globally importing the Head component, from InertiaJS.
import { createInertiaApp, Head } from '@inertiajs/inertia-vue3';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
    setup({ el, App, props }) {
        return render(<App {...props} />, el).component('Head', Head);
    },
});

Source here.


text:
Q: Django lookup multiple models reusing querysets Let's say I want to get a list of houses where the owner's car has a seat that's red.
I could do it like this:
queryset.filter(owner__cars__seats__color='red')

However, I would like to reuse the filter of getting cars that have a red seat, so I have a custom Queryset on Cars.
class CarsQuerySet(models.QuerySet):
    def with_red_seats(self):
         return self.filter(seats__color='red')

Is there a way to do reuse the "with_red_seats" filter on the first query?
Something like this, which obiously doesn't work:
queryset.filter(owner__cars__with_red_seats)

A: If you are wanting to reuse:
red_seated_cars = Cars.objects.with_red_seats()
House.objects.filter(owner__cars__in = red_seated_cars)

might do the trick


text:
Q: Modify fixed Array of a Struct by function I want to create a struct that have an array and that struct should have a function to modify that array by some parameters.
Like I have a white paper and I want to draw a line in a specific direction over that paper, but after one call, I get the error:   value used here after move.
I understand what the problem is, but I don't understand why this is a problem and how to solve that generally. I think I have not understood that principle behind that compiler error.
My second question is, is there a faster way to change a set of values by index in the fixed size array? In numpy I would write arr[x1,0:y] = newVal.
Here is the not-working example:
const N: usize = 4;

fn main() {
    println!("Hello, world!");
    let bebalken = [[false; N]; N];
    let stuetzen = [[true; N]; N];

    let mut f = Feld {
        abst: [[0; N]; N],
        bebalken: &bebalken,
        stuetzen: &stuetzen,
        balken: [[0; N]; N],

    };

    f.balken_einfugen(0, 0, 1, 4, 1);
    f.balken_einfugen(1, 0, 1, 4, 1);
}

struct Feld<'a> {
    abst: [[u8; N]; N],
    bebalken: &'a [[bool; N]; N],
    stuetzen: &'a [[bool; N]; N],
    balken: [[u8; N]; N],

}

impl Feld<'_> {
    pub fn balken_einfugen<'a>(mut self, x: usize, y: usize, dir: u8, r: u8, connBar: u8) {
        let imax: usize = N;

        if dir == 1 {
            for i in 0..imax {
                self.balken[x + i][y] = connBar;
            }
        };
    }
}

And here the full compiler error:
error[E0382]: use of moved value: `f`
  --> src\main.rs:19:5
   |
10 |     let mut f = Feld {
   |         ----- move occurs because `f` has type `Feld<'_>`, which does not implement the `Copy` trait
...
18 |     f.balken_einfugen(0, 0, 1, 4, 1);
   |       ------------------------------ `f` moved due to this method call
19 |     f.balken_einfugen(1, 0, 1, 4, 1);
   |     ^ value used here after move
   |
note: this function consumes the receiver `self` by taking ownership of it, which moves `f`
  --> src\main.rs:35:36
   |
35 |     pub fn balken_einfugen<'a>(mut self, x: usize, y: usize, dir: u8, r: u8, connBar: u8)  {
   |                                    ^^^^

A: Methods which take self as an argument take ownership of the struct they're called on. This means you can only call the method once since it consumes the struct.
If you'd like maintain ownership of the struct, and call the method multiple times, you have to write the method so that it mutably borrows the struct instead of taking ownership, i.e. &mut self instead of mut self.
Once you make this change in your code it compiles:
const N: usize = 4;

fn main() {
    let bebalken = [[false; N]; N];
    let stuetzen = [[true; N]; N];

    let mut f = Feld {
        abst: [[0; N]; N],
        bebalken: &bebalken,
        stuetzen: &stuetzen,
        balken: [[0; N]; N],
    };

    f.balken_einfugen(0, 0, 1, 4, 1);
    f.balken_einfugen(1, 0, 1, 4, 1);
}

struct Feld<'a> {
    abst: [[u8; N]; N],
    bebalken: &'a [[bool; N]; N],
    stuetzen: &'a [[bool; N]; N],
    balken: [[u8; N]; N],
}

impl Feld<'_> {
    // `mut self` changed to `&mut self` here
    pub fn balken_einfugen<'a>(&mut self, x: usize, y: usize, dir: u8, r: u8, connBar: u8) {
        let imax: usize = N;

        if dir == 1 {
            for i in 0..imax {
                self.balken[x + i][y] = connBar;
            }
        };
    }
}

playground


text:
Q: Extract pair ( VERB-Noun) from list I want to extract pair (verb-noun) from each row i want to add other column and put all pair there im using Eron dataset i worked the first part preprocessing (remove number, punctuation...) and know i want to detect (verb-noun) any help please
import spacy
import numpy as np
nlp = spacy.load('en')

a=nlp(str(train['text_lemmatized'])
noun_adj_pairs=[]
for i,token in enumerate(a):
    if token.pos not in ('VERB','NOUN'):
        continue
    for j in range(i+1,len(a)):
        if a[j].pos_ == 'NOUN':
           noun_adj_pairs.append((token,a[j]))
        break

noun_adj_pairs


text:
Q: jquery or javascript how to find if an array contains an object and that object has a name with a specified value I am trying to build an array of objects to save a menu's state in a cookie but it is not updating because it is not finding the proper index containing the object I need to update visibility for. What am I doing wrong and/or can you point me in the right direction?
$(document).ready(function() {
    var menu = new Array();
    $("#vertical-nav .head").click(function() {
        var c = $(this).next().attr('name');
        $(this).next().slideToggle("slow", function() {
            if ( $(this).next().is(':visible') ) {
                menu.push({
                    name: c,
                    visible: true,
                });
            } else {
                var index = $.inArray(c, menu);
                console.log("INDEX: " + index);
                menu[index] = { name: c, visible:false };
            }
        });
        console.log(menu);
    });
});

This is what I ended up with:
$(document).ready(function() {
    var menu = new Array();
    if ( $.cookie('menu') ) {
        var items = JSON.parse($.cookie('menu'));
        for ( var item in items ) {
            if ( items[item].visible ) {
                $("div[name='" + items[item].name + "']").show();
            }
            menu.push(items[item]);
        }
    }

    $("#vertical-nav .head").click(function() {
        var c = $(this).next().attr('name');
        if ( $(this).next().is(":visible") ) {
            hide(this, c);
        } else {
            show(this, c);
        }
    });

    function show(obj, c) {
        $(obj).next().slideDown('slow', function() {
            var elementExists = false;
            if ( menu.length > 0 ) {
                for ( var item in menu ) {
                    if ( menu[item].name == c ) {
                        elementExists = true;
                        menu[item].visible = true;
                    }
                }
            }
            if ( !elementExists ) {
                menu.push({
                    name: c,
                    visible: true,
                });
            }
            $.cookie('menu', JSON.stringify(menu));
        });
    }

    function hide(obj, c) {
        $(obj).next().slideUp('slow', function() {
            if ( menu.length > 0 ) {
                for ( var item in menu ) {
                    if ( menu[item].name == c ) {
                        menu[item].visible = false;
                    }
                }
            }
            $.cookie('menu', JSON.stringify(menu));
        });
    }
});

A: You could easily do this:
if (menu.length > 0) {
    for (var item in menu) {
        if (menu[item].name=="some text") alert("Found it!");
    }
}

What I would consider is instead of [{name: "item"; visible: true}] is switch to a key/value pair.  You can then use {"item": true}, but this is limited to only storing the visible value and no extra info can be stored in the key.  To solve this, try {"item": {visible: true}}.  Here's an example of detection in JS using this approach:
if (menu.length > 0) {
    for (var item in menu) {
        var strVisible="hidden";
        if (menu[item].visible==true) strVisible="visible";
        alert(item+" is "+strVisible);
    }
}


text:
Q: TextField.getFieldLabel() not working var rows=[];
for(var i=0; i<5;i++)
{
    var row = Ext.create(Prototype.view.RowModel);
    var text = row.getComponent(0).getFieldLabel();
    var text2 = row.getComponent(0).getId();
    rows.push(row);
    console.log(text+text2);
}
this.add(rows);

row.GetComponent(0) is confirmed to be a textfield.
When I call getFieldLabel() it crashes with the following error
Uncaught TypeError: Object [object Object] has no method 'getFieldLabel'

But the ExtJs 4.2 documentation says otherwise...?
Whatever the technique I use to reach the "label". i always receive a object Object which has no getFieldLabel(). How do I convert? Or reach it directly?
can someone help?
code of the row model :
Ext.define('Prototype.view.RowModel', {
extend: 'Ext.Container',

config: {
    layout: {
        type: 'hbox'
    },
    items: [
        {
            xtype: 'textfield',
            itemId: 'rowLabel',
            width: 100,
            label: 'Vin',
            labelWidth: '100%',
            name: 'rowLabel1',
            readOnly: true
        },
        {
            xtype: 'numberfield',
            itemId: 'UserField',
            width: 100,
            labelWidth: '0%'
        },
        {
            xtype: 'numberfield',
            itemId: 'ObjectField',
            width: 100,
            labelWidth: '0%'
        },
        {
            xtype: 'textfield',
            itemId: 'UnitLabel',
            style: 'font-size:15px',
            width: 60,
            label: 'L/User',
            labelWidth: '100%',
            readOnly: true
        },
        {
            xtype: 'numberfield',
            itemId: 'FactorField',
            width: 100,
            labelWidth: '0%'
        },
        {
            xtype: 'spacer',
            maxWidth: 15
        },
        {
            xtype: 'button',
            handler: function(button, event) {
                alert('help');
                console.log('okay');
            },
            height: 47,
            itemId: 'mybutton',
            ui: 'plain',
            iconCls: 'info'
        }
    ]
}

});

A: You can find the textfield by itemId:
row.down('#rowLabel');


text:
Q: Convert date from excel file to pandas I'm importing excel file, where the 'Date' column has different ways of writing:
      Date
13/03/2017
13/03/2017
13/03/2017
13/03/2017
   10/3/17
   10/3/17
    9/3/17
    9/3/17
    9/3/17
    9/3/17

Importing to pandas:
df = pd.read_excel('data_excel.xls')
df.Date = pd.to_datetime(df.Date)

results in:
                     Date
               13/03/2017
64             13/03/2017
65             13/03/2017
66             13/03/2017
67    2017-10-03 00:00:00
68    2017-10-03 00:00:00
69    2017-09-03 00:00:00
70    2017-09-03 00:00:00
71    2017-09-03 00:00:00
72    2017-09-03 00:00:00

Which means, pandas did not parse properly date and time:
10/3/17 -> 2017-10-03

when I tried to specify the format:
df.Date = pd.to_datetime(df.Date, format='%d%m%Y')

got the error:
ValueError: time data u'13/03/2017' does not match format '%d%m%Y' (match)

Question:
How to import properly date and times from the excel file to pandas?

A: New answer:
Actually pd.to_datetime has a dayfirst keyword argument that is useful here:
df.Date = pd.to_datetime(df.Date,dayfirst=True)

Result:
>>> df.Date
0   2017-03-13
1   2017-03-13
2   2017-03-13
3   2017-03-13
4   2017-03-10
5   2017-03-10
6   2017-03-09
7   2017-03-09
8   2017-03-09
9   2017-03-09
Name: Date, dtype: datetime64[ns]

Old answer:
Use the third-party module dateutil which can handle these kinds of variations. It has a dayfirst keyword argument that is useful here:
import dateutil

df = pd.read_excel('data_excel.xls')
df.Date = df.Date.apply(lambda x: dateutil.parser.parse(x,dayfirst=True))

Result:
>>> df.Date
0   2017-03-13
1   2017-03-13
2   2017-03-13
3   2017-03-13
4   2017-03-10
5   2017-03-10
6   2017-03-09
7   2017-03-09
8   2017-03-09
9   2017-03-09
Name: Date, dtype: datetime64[ns]


text:
Q: Moving li to next column I've got a simple ul like so :

ul.target {
  font-family: calibri, verdana, arial;
  min-height: 500px;
  float: none;
  column-count: 4;
  column-width: 25%;
  column-gap: 1rem;
  column-rule: 1px solid gray;
  box-sizing: border-box;
}
ul {
  margin: auto;
  list-style: none;
}
ul > li > ul {
  break-after: column;
}

category 1

test 1

test 2

category 2

test 3

test 4

test 5

test 6

test 7

test 8

category 3

test 9

test 10

test 11

test 12

test 13

test 14

test 15

test 16

test 17

test 18

category 4

test 19

test 20

test 21

test 22

test 23

test 24

category 5

test 25

test 26

test 27

test 28

test 29

test 30

test 31

test 32

test 33

As you can see here, category 2 is at the very bottom and category 3 is in the middle. I want to be able to move them to the next column dynamically if they're at the very bottom. Knowing that the height might be larger and there could be a lot of other categories in each column, I want to push the LAST category of the column to the next column, thus modifying the rest of the columns accordingly. I don't have any idea on where to start...
EDIT, taken from comments :
To clarify somet hings :
My code is a small example of a larger code containing much more than that, so no the question is still about how can I move each category to the next column, trying to find another way of doing it won't work in my case as this is just a preview. I'm using JQuery in order to get the categories and the list of items, and then I don't know what to do to push the category to the next column using JS. It should just reposition to the next column if it's the last category of the current column.

A: You could apply the break-before property to the .categ class, but then you end up with three columns:

var item = $(".item")
var categ = $(".categ")
ul {
  font-family: calibri, verdana, arial;
  min-height: 500px;
  float: none;
  margin: auto;
  list-style: none;
  column-count: 4;
  column-width: 25%;
  column-gap: 1rem;
  column-rule: 1px solid gray;
  box-sizing: border-box;
}
.categ {
  break-before: column;
}

category 1

test 1

test 2

category 2

test 3

test 4

test 5

test 6

test 7

test 8

category 3

test 9

test 10

test 11

test 12

You have to alter the DOM in order to get this to work. In the following snippet I've made "sublists" out of the .categ list items and all their following .item siblings (using jQuery as you'd included it in your snippet). I've also added a class to the top-most ul so as to differentiate it for styling. You could also use a class on the uls for the "sublists" instead of using the child selector as I did.

$(".categ").each((idx, cat) => $(cat).nextUntil(".categ", ".item").addBack().wrapAll("

"));
ul.target {
  font-family: calibri, verdana, arial;
  min-height: 500px;
  float: none;
  column-count: 4;
  column-width: 25%;
  column-gap: 1rem;
  column-rule: 1px solid gray;
  box-sizing: border-box;
}
ul {
  margin: auto;
  list-style: none;
}
ul > li > ul {
  break-after: column;
}

category 1

test 1

test 2

category 2

test 3

test 4

test 5

test 6

test 7

test 8

category 3

test 9

test 10

test 11

test 12

A: Disclaimer, I'm a little unsure about what you're trying to do:
I think the problem is not the presentation rules (CSS) you apply to your data (HTML). I think the problem is dat your data does not provide enough context for you presentation rules to act upon.
What I think you're trying to do is to have 3 (or more) separate lists presented on something that looks like a footer. However your HTML structures does not seem to properly match this scheme.
Try to make your HTML more explicit. Why put everything in one list instead of one list per category? Then you could justify the categories the way you want by either floats or flex or even grid layouts. I don't see why you should need jQuery for this?
Or have I misinterpreted your question?


text:
Q: dash.Datatable values are resetted when table row number is changed I have a dropdown to select no. of rows displayed in dash.datatable (eg. 4 rows default)
But when changed row no. is changed in dropdown my table values are gone.
I want them unchanged when increase the row value. can someone help me on this.
Callback used to fetch the row in datatable is here
@app.callback(
    Output('data_table','data'), Input('dropdown','value'),
)
def table(rows):
    if rows is not None:
        return dbdata.head(rows).to_dict('records')

I don't want to include any button to add new row, just when the dropwdown is changed I want the table value to remain unchanged.


text:
Q: Remove first two characters and replace with a different string SQL Server From column Attachmentname I need to remove the first two characters and replace add a different string.
Select
    attachmentName
from
    docstatus
where
    salesorder =  '230162'

AttachmentName
-------------------------------
H:\Quality\4513014196_00040.pdf

I need to remove the H: and replace it with 'file://server/certs' so that the result is.
AttachmentName
-------------------------------------------------
file://server/certs/Quality/4513014196_00040.pdf

I can remove the first two characters but I don't know the string to add file://server/certs within the same string
right(AttachmentName, len(AttachmentName) - 2)

A: This doesn't quite do what you asked, but this is probably what you are looking for.  It replaces the H:\ in a filename with file://server/certs/ and reverses the \ to / anywhere else.  This makes the assumption that these are simple windows drive letter replacements attachment names, so H:\ can't really appear anywhere else other than at the beginning.
UPDATE docstatus
SET attachmentName = REPLACE(REPLACE(attachmentName, 'H:\', 'file://server/certs/'),'\','/')
WHERE salesorder = '230162'

another option that uses SUBSTR to remove the first 3 characters:
UPDATE docstatus
SET attachmentName = 'file://server/certs/' + REPLACE(SUBSTR(attachmentName, 4, LEN(attachmentName)),'\','/')
WHERE salesorder = '230162'
  AND attachmentName LIKE 'H:\%'

A third option, hinted at by Martin Smith:
UPDATE docstatus
SET attachmentName = REPLACE(STUFF(attachmentName, 1, 3, 'file://server/certs/'),'\','/')
WHERE salesorder = '230162'
  AND attachmentName LIKE '[A-Z]:\%'


text:
Q: What is causing this warning in symfit? Consider this simple optimization code:
from symfit import *

x1 = 1
x2 = 4
p1, p2 = parameters('p1, p2')
model = p1*p2
constraints = [
    Eq(x1*p1+(x2-x1)*p2, 1),
    Ge(p1, p2),
    Ge(p2, 0)
    ]

fit = Fit(- model, constraints=constraints)
fit_result = fit.execute()
print(fit_result)

This gives me the following warning:
/home/user/.local/lib/python3.5/site-packages/symfit/core/fit.py:1783: RuntimeWarning: invalid value encountered in double_scalars
  return 1 - SS_res/SS_tot

What is causing this?

A: This happens because symfit currently always tries to calculate the coefficient of determination (R^2) for the fit. In this case, since there is no data, both SS_res and SS_tot are zero, resulting in a 0/0 and hence the warning and the resulting nan in fit_results.
We are now adding extra intelligence to FitResults such that it won't be calculated in the first place, but it is safe to ignore this warning.