text:
Q: Place second bookmark on next line within a word document table cell? I place a bookmark within a word document table cell at the curser location.  Now I want to move down one line after the bookmark, within the same table cell, and place another bookmark.  I tried adding a carriage return after the bookmark, but the curser remains on the first line within the bookmark.
ActiveDocument.Bookmarks.Add Name:=bmItemNo, Range:=BMRange
'Adds carriage return after bookmark
BMRange.InsertAfter (Chr(13))

I also tried moving my curser to the end of the line and down 1 line, but it jumps out of the table cell:
ActiveDocument.Bookmarks.Add Name:=bmItemNo, Range:=BMRange
'Adds carriage return after bookmark
BMRange.InsertAfter (Chr(13))
Selection.EndKey unit:=wdLine, Extend:=wdMove
Selection.MoveDown unit:=wdLine, Count:=1, Extend:=wdMove

My bookmark can also word wrap with multiple lines.
How do I move my curser to the next line after a bookmark?

A: Your code almost works. You don't define or tell us what BMRange is, so I made some assumptions. Always use 'Option Explicit' for that reason. You want to explicitly define all variables. Also, inserting text and the cursor are not related. Get into the practice of thinking with Ranges to build within a document, not the insertion point. Although my code example is not the best for that, it does illustrate your question.
I can't get your results but it's what I think you wanted. Is that right?
Option Explicit
Public Sub Test()
    Dim BMRange As Range
    Set BMRange = Selection.Range

    ActiveDocument.Bookmarks.Add Name:="One", Range:=BMRange

    'Adds carriage return after bookmark
    BMRange.InsertAfter (Chr(13))

    Selection.EndKey unit:=wdLine, Extend:=wdMove
    Selection.MoveDown unit:=wdLine, Count:=1, Extend:=wdMove

    Set BMRange = Selection.Range
    ActiveDocument.Bookmarks.Add Name:="Two", Range:=BMRange
End Sub


text:
Q: Passing Data with Subjects and Proxies Is it possible to have a 2 way data flow using Subjects in a service? Suppose for example that I want some component to retrieve information and then post it through the service Subject for other another component to consume.
The consuming component then makes some changes to this information and then re-posts it so that the original component can retrieve changes.
Is this possible using the Observer pattern?
Also, if I wanted to watch this data for changes (let's say that the data came in through an array), would I have to use a proxy to accomplish this?

A: When passing data between components, I find the RxJS BehaviorSubject very useful.
You can also use a regular RxJS Subject for sharing data via a service, but here's why I prefer a BehaviorSubject.

*

*It will always return the current value on subscription - there is no need to call onNext().

*It has a getValue() function to extract the last value as raw data.

*It ensures that the component always receives the most recent data.

*you can get an observable from behavior subject using the asObservable()
     method on behavior subject.

*Refer this for more
Example
In a service, we will create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable to handle this data stream as an observable that will be used by other components. Lastly, we create the function that calls next on the BehaviorSubject to change its value.
The parent, child, and sibling components all receive the same treatment. We inject the DataService in the components, then subscribe to the currentMessage observable and set its value equal to the message variable.
Now if we create a function in any one of these components that changes the value of the message. The updated value is automatically broadcasted to all other components.
shared.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class SharedService {

  private messageSource = new BehaviorSubject<string>("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

parent.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
     {{message}}
   `,
   styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  message: string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }
}

sibling.component.ts
import { Component, OnInit } from '@angular/core';
import { SharedService } from "../shared.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message: string;

  constructor(private service: SharedService) { }

  ngOnInit() {
  }

  newMessage() {
    this.service.changeMessage("Hello from Sibling");
  }

}

A: Thats totally possible:

*

*Figure out what type of subject you need, normal subject, Behaviour Subject or Replay subject. Each has its own use case, I'd recommend taking a look at this question for a clear and concise explanation: Angular 2 special Observables (Subject / Behaviour subject / ReplaySubject).

*Declare your subject in a service.

*Call a next() value in your main component which your second component will listen to.

*You can then subscribe to that subject from your secondary component and modify it.

*From here you can either call the next() value on the same subject using the modified data or create a separate subject in your service and use that to pass your modified data into. Either case you can subscribe in your main component to get that data. I'd recommend the later option though as I'm assuming if you modify the data you'll change the object and it's good to strictly type your subjects to catch errors.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have these dictionaries. What command should I put to print the "d" key from the second one? There is a trick
*

*So, the first requirement was to print the key 'a' from d1, which was very simple.

*The second one was to get the key 'c' from d1, which doesn't exist. And if doesn't exist return
the 0. This one I solved with get.
d1 = {'a': 1, 'b': 2, 'd': 5}
d2 = {'a': 1, 'b': 2, 'c': {'d': 4}}
print(d2.get('a', 0))

*The third requirement was to print the value assigned to 'd' from d2.

As you can see, 'c':{'d':4}. C contains a little dict merged in the main one. Or something like that.
Is there a possibility to print the key value of 'd'?

A: Well "akchually", there is no "d" key in d2.
However if you type:
print(d2['c']['d'])

you will get what you want.

A: The .get() method for dictionaries has a optional parameter for a default value if the key is not found: dictionary.get(key, default)
Since a value could technically be 0, even though the default value is 0, you could test the type of the result in a if/else.
Using a loop and default values you can return whatever data you want, such as this:
d1 = {'a': 1, 'b': 2, 'd': 5}
d2 = {'a': 1, 'b': 2, 'c': {'d': 4}}

for item in [d1,d2]:
    print(item)
    print("value of 'a':", item.get('a', 0))
    c_value = item.get('c', 0)
    if type(c_value) == dict:
        print("value of dictionary in 'c':", item['c'].get('d'))
    else:
        print("value of 'c':", c_value)
    print("value of 'd':", item.get('d', 0))
    print()

Resulting in:
{'a': 1, 'b': 2, 'd': 5}
value of 'a': 1
value of 'c': 0
value of 'd': 5

{'a': 1, 'b': 2, 'c': {'d': 4}}
value of 'a': 1
value of dictionary in 'c': 4
value of 'd': 0


text:
Q: CSS popup jumps back to top of page when closed Can anyone tell me a solution to make the page not jump back to the top when this CSS driven popup box closes?
At the moment the popup opens in the correct place but when you close it, the page jumps back to the top.

body {
  font-family: Arial, sans-serif;
  background-color:#721213;
  background-size: cover;
}

h1 {
  text-align: center;
  font-family: Tahoma, Arial, sans-serif;
  color: orange;
  margin: 100px 0;
}

.box {
  width: 20%;
  margin: 0 auto;
  background: rgba(255,255,255,0.2);
  padding: 35px;
  border: 2px solid #fff;
  border-radius: 20px/50px;
  background-clip: padding-box;
  text-align: center;
}

.button {
  font-size: 1em;
  padding: 10px;
  color: #fff;
  border: 2px solid orange;
  border-radius: 20px/50px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s ease-out;
}
.button:hover {
  background: orange;
}

.overlay {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  transition: opacity 500ms;
  visibility: hidden;
  opacity: 0;
}
.overlay:target {
  visibility: visible;
  opacity: 1;
}

.popup {
  margin: 70px auto;
  padding: 20px;
  background: #fff;
  border-radius: 5px;
  width: 40%;
  position: relative;
  transition: all 5s ease-in-out;
  min-height:500px;
}

.popup h2 {
  margin-top: 0;
  color: #333;
  font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
  position: absolute;
  top: 20px;
  right: 30px;
  transition: all 200ms;
  font-size: 30px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}
.popup .close:hover {
  color: orange;
}
.popup .content {
  max-height: 30%;
  overflow: auto;
}

.iframe {
 width:95%;
 display:block;
 margin:0px auto 0px auto;
 height:500px;
}

Let me Pop up

Here i am

  ×

A: Weave: http://kodeweave.sourceforge.net/editor/#3cfa8a8181c0ffdc30103eb2bc19d9b3
Weave: (properly use a hash on an href)
http://kodeweave.sourceforge.net/editor/#3a84a44278b04eea7b5d0f067ba22427
Stop using href="#" and start using href="javascript:void(0)" instead.
The reason it jumps to the top is because when you use a hash in a href attribute it directs to an ID if none is specified it goes to the top by default. Unless you use e.preventDefault() using a click event in JS.
Because you're using :target This can easily be fixed by targeting a new ID.
So change this...
Let me Pop up
×

to this...
Let me Pop up
×

and it's fixed!
NOTE: You can do the same effect using a input[type=checkbox] instead of :target: http://kodeweave.sourceforge.net/editor/#8d7733f82faf240e0edcb6739c5d1a1a
A few key notes:
margin:0px auto 0px auto;

Values of 0 shouldn't have units specified.

Also it's bad practice to add CSS to your HTML element

Here is an example of one way on how to properly use a hash tag on a href attribute.

body {
  padding: 1em;
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

.left {
  text-align: left;
}

    Lorem.

    Ispum!

    Dolor!

    Sit!

    Amet!

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste distinctio omnis a nihil, quisquam nisi similique facere, reprehenderit sint nostrum. Ipsa quibusdam, adipisci laudantium nam voluptatum quasi animi placeat eveniet.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel tempora quasi, maiores debitis cupiditate laboriosam alias placeat temporibus veritatis. Quisquam, debitis dolorem saepe enim maiores, ex numquam corporis atque magnam.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione architecto quia officiis, amet. Eaque, et quia ducimus possimus rem suscipit, maxime, porro mollitia, corporis sequi magnam debitis. Expedita iure, maiores.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ipsum vitae quasi, id reiciendis iure qui veritatis voluptatibus omnis libero ea, labore voluptate maxime, ducimus tenetur, deleniti. Rem, consequatur, accusantium.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum maiores saepe sunt commodi soluta minus ad. Facilis magnam, distinctio voluptatibus ratione iste, laboriosam hic perspiciatis molestiae repellat accusamus tempora cumque!

Go to top

A: it happens because your button for closing is a element and href="#" change it to div element instead of a
EDIT :
i dont know why i got arrow down/point down but
i will explain it easier for you
Your CODE :

Here i am

        ×

The what i suggest :

Here i am

X

we added id="popup" to (div.popup) element, then we replaced " element" close button with


text:
Q: Scripts result to a other script on a other pc (python) So Im a beginner in coding and I was wondering if there is away to send script results to a other script on a other pc and how to let the second script (the script thats recieving the results) WAIT until it gets result so yea thats my first question since I couldnt find any answers on yt or on stackoverflow or google

A: It is a really interesting problem you are trying to tackle, and something that is still actively being developed solutions for (e.g. cloud computing).
First of all, you need a way of transferring data between the two computers in order to automatically start a script on a computer when a result has been generated on another computer.
You could utilize a ssh connection if both computers have an internet connection.
Alternatively, you use an USB drive to store the result on, and manually insert it into the second computer with a program able to recognize that the USB drive has become available.
In regards to coding this, I believe what you are looking for what is called a listener. You can find some solutions to this here.


text:
Q: WordPress hide dropdown when clicked anywhere I created a multiselect dropdown with jQuery. There is a problem. When I click on drop menu it open, but when click outside the box it doesn't hide.

    ژانر فیلم

<input name="product_cat" value="action" type="checkbox">action

<input name="product_cat" value="animation" type="checkbox">animation

<input name="product_cat" value="history" type="checkbox">history

<input name="product_cat" value="horror" type="checkbox">horror

jquery for this is:
$(".dropdown dt li").on('click', function() {
    $(".dropdown dd ul").slideToggle('fast');
});

$(".dropdown dd ul li a").on('click', function() {
    $(".dropdown dd ul").hide();
});

function getSelectedValue(id) {
    return $("#" + id).find("dt a span.value").html();
}

$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
});

$('.mutliSelect input[type="select"]').on('click', function() {

    var title = $(this).closest('.mutliSelect').find('input[type="option"]').val(),
        title = $(this).val() + ",";

    if ($(this).is(':checked')) {
        var html = '' + title + '';
        $('.multiSel').append(html);
        $(".hida").hide();
    } else {
        $('span[title="' + title + '"]').remove();
        var ret = $(".hida");
        $('.dropdown dt a').append(ret);
    }

});

What in the world should I do to fix my dropdown?

A: Try this

$(".dropdown dt li").on('click', function() {
    $(".dropdown dd ul").slideToggle('fast');
});

$(".dropdown dd ul li a").on('click', function() {
    $(".dropdown dd ul").hide();
});

function getSelectedValue(id) {
    return $("#" + id).find("dt a span.value").html();
}

$(document).on('click', function(e) {
    var $clicked = $(e.target);
    if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
});

$('.mutliSelect input[type="select"]').on('click', function() {

    var title = $(this).closest('.mutliSelect').find('input[type="option"]').val(),
        title = $(this).val() + ",";

    if ($(this).is(':checked')) {
        var html = '' + title + '';
        $('.multiSel').append(html);
        $(".hida").hide();
    } else {
        $('span[title="' + title + '"]').remove();
        var ret = $(".hida");
        $('.dropdown dt a').append(ret);
    }

});

$(document).mouseup(function (e)
                    {
  var container = $(".hida");

  if (!container.is(e.target)
      && container.has(e.target).length === 0)
  {
    $(".dropdown dd ul").hide();
  }
});

    ژانر فیلم

<input name="product_cat" value="action" type="checkbox">action

<input name="product_cat" value="animation" type="checkbox">animation

<input name="product_cat" value="history" type="checkbox">history

<input name="product_cat" value="horror" type="checkbox">horror

A: $(document).click(function() {
    $(".dropdownc dd ul").hide();
});


text:
Q: Print screen with cursor in Windows 7 I'm trying to capture some screenshots for a tutorial. When I press Print Screen (or PrtSc) on my keyboard, and paste into an image editor, the cursor's gone. The "tooltips" (if any) do print, but I need the cursor to show users where to click.

* There is supposed to be a cursor over the photo icon here.
Is there any way to keep the cursor and print the screen?
I'd like to avoid installing even more third party software on my computer, if possible, for this small feature (browser addons I'm happy to install), and I'm really only interested in what's in the browser's viewport. I have the Screengrab Firefox add-on installed, but that doesn't help. I also tried one or two random key combos in Windows, but they didn't do it either.
Is there any way to keep the cursor and print the screen?

A: I'm sorry, but, I don't know a way to do this without third party software.
Faststone Screen Capture has an option that you can turn on to do this.

A: IrfanView is free, and ad-free, and has a nice screencap feature that includes the mouse pointer.

A: Semi-related: you can also use LICEcap to have animated screenshots (GIF recordings) that contain the cursor

LICEcap is interesting because it lets you manually create a transparent frame over the portion of the screen to precisely choose what portion of the screen will be captured.

A: You might want to try Problem Step Recorder. It can be accessed in Windows 7 by entering psr into the search field in the start menu. It's primary use is to record what happens when someone is having a problem by taking screenshots and putting them in an HTML file (hence the name). But you can take use the pictures or edit the html file. Here is a link that gives a little insight into the Problem Step Recorder: http://windows.microsoft.com/en-US/windows7/How-do-I-use-Problem-Steps-Recorder

A: *

*Use PSR tool from Windows and record the steps.
(Win+R ->> PSR)

*Then open .mht file in browser.

*So either copy images from browser or take screen shot of that page.

A: If you want to include the cursor, you'll need to use some third-party screen capture software like ShareX.

A: Using the above link goto Control Panel --> Mouse --> Pointers tab..create a print screen image of any cursor that you desire from the "Preview" in that tab.
Paste it in the desired place in your actual screenshot and goto "Select" menu --> Transparent Selection.
For more, check here. http://www.tomcomknowshow.com/how-to-add-a-cursor-mouse-pointer-to-a-print-screen-image.html

A: When I am setting up tutorials for users and it includes screen shots in which I need to show them where to click I simply paste the screen shot into MS Paint, add graphics (arrows, circles, etc.) showing them where to click, and then copy that altered screen shot into the tutorial. This may be your best option if you do not want to use freeware or purchase software. Thanks!

A: Big fan of http://getgreenshot.org - free, open source, sits in sys tray, hooks up to Print Screen, outputs to file/clipboard etc, has a useful little image editor built in.


text:
Q: Multiple Grids using ngIf and ngRepeat will not update pagination controls and footer from server side paging We have an issue we are facing where we have tabs of grids and different gridOptions per grid. When tabbing from grid to grid, the data updates correctly, but the footer does not update the total items properly. We have the ui-grid directive wrapped in our own custom directive so that we can pass different options to each of the tabs, although I've removed some of that code for the purpose of reporting here.
The first tab always works just fine with everything. But none of the other tabs do. Once going to the tab, clicking on a different tab, and back again, the footer seems to update just fine on the second time around... I thought it might have something to do with onRegisterApi not being set correctly on the 2 - x tabs because I did notice some weirdness there and that's why even after my extend of the default options, I have the line scope.gridOptions.onRegisterApi = setGridApi; just to make sure that gets run. If I don't add this line, then the other tabs do not call this method.
I've even tried not using ngIf and ngRepeat and just using a watch on the gridOptions to update a single grid with different data, but still had the same issue. ngShow works great, except that it loads all of the grids all at once on first page load and I can't have that.
Am I doing something wrong or is this an issue I've found? (I know pagination is still in "Alpha")
I've searched stack overflow as well as ui-grid's github issues and have found some similar issues regarding the footer, but nothing that has really been relevant. Most of the issues I found were about the grid not being drawn correctly until the browser is resized, and this is not that issue. I've also posted this same issue on their github: https://github.com/angular-ui/ui-grid/issues/4364
I'm using Angular 1.4.4 and angular-ui-grid 3.0.4 (tried 3.0.6 as well, but same issue)
Here's a plnkr: http://plnkr.co/edit/4XWarYb9xlDnadpTC0kG?p=preview
subTab.html:

      {{tab.heading}}

subTab Directive (slightly edited for privacy):
...
function csSubTab($resource, $stateParams, $state) {
    var directive = {
      restrict: 'A',
      scope: {},
      templateUrl: 'subTab.html',
      link: link
    };

    function link(scope) {
      scope.activeTab;

      scope.tabs = getModuleSubTabs($stateParams.module);

      select(scope.tabs[0]);

      scope.select = select;
      scope.isActiveTab = isActiveTab;
      scope.getTabClasses = getTabClasses;

      function select(tab) {
        scope.activeTab = tab.heading;
      }

      function isActiveTab(tab) {
        return tab.heading === scope.activeTab;
      }

      function getTabClasses(tab) {
        var classes = '';
        if (isActiveTab(tab)) {
          classes += 'active';
        }
        return classes;
      }

      function getModuleSubTabs(moduleName) {
        var tabs = [];
        var tabList = ['Tab 1', 'Tab 2', 'Tab 3', 'Tab 4', 'Tab 5'];
        for (var i = 0, len = tabList.length; i < len; i++) {
          tabs.push({
            heading: tabList[i],
            gridOptions: getSubTabGridOptions(tabList[i].toLowerCase().replace(/ /g, ''))
          });
        }
        return tabs;
      }

      function getSubTabGridOptions(subTabName) {
        return {
          useExternalPagination: true,
          paginationPageSizes: [10],
          paginationPageSize: 10,
          enableFiltering: false,
          enableGridMenu: true,
          exporterMenuPdf: false,
          enableRowSelection: true,
          selectWithCheckboxOnly: true,
          showSelectionCheckbox: true,
          rowHeight: 22,
          columnsResource: $resource('app/modules/data/subTabs/' + subTabName + 'Columns.json'),
          dataResource: $resource('api/3/' + subTabName)
        };
      }
    }

    return directive;
  }

grid.html:

grid Directive (slightly edited for privacy):
...
function csGrid($resource) {
    var directive = {
      restrict: 'A',
      scope: {
        gridOptions: '='
      },
      templateUrl: 'grid.html',
      link: link
    };

    function link(scope) {
      var defaultGridOptions = {
        useExternalPagination: true,
        paginationPageSizes: [10],
        paginationPageSize: 10,
        onRegisterApi: setGridApi,
        enableFiltering: false,
        enableGridMenu: true,
        exporterMenuPdf: false,
        enableRowSelection: true,
        selectWithCheckboxOnly: true,
        showSelectionCheckbox: true,
        rowHeight: 22
      };

      scope.gridOptions = angular.extend({}, defaultGridOptions, scope.gridOptions);
      scope.gridOptions.onRegisterApi = setGridApi;

      scope.gridOptions.columnsResource.get({}, setColumns);
      getPage(1);

      function setColumns(data) {
        scope.gridOptions.columnDefs = data.columns;
      }

      function setData(data) {
        if (data['@type'] && data['@type'] !== 'Error') {
          scope.gridOptions.totalItems = data['hydra:totalItems'];
          scope.gridOptions.data = data['hydra:member'];
          if (data['hydra:member'].length === 0) {
            alert('No Results');
          }
        } else {
          alert(data['hydra:title'] + ':\n\t' + data['hydra:description']);
        }
      }

      function dataError(e) {
        alert('error retrieving data:\n\t' + e);
      }

      function setGridApi(gridApi) {
        scope.gridApi = gridApi;
        scope.gridApi.pagination.on.paginationChanged(scope, getPage);
      }

      function getPage(pageNum){
        scope.gridOptions.dataResource.get({page: pageNum}, setData, dataError);
      }
    }

    return directive;
  }


text:
Q: Catching POST data in php with variable ID I'm creating a form from a database and the input id's could be 1-9, 1,2,5,8, etc. IE with the way it is now, I cannot determine what the number will be unless I were to iterate from number 1 to the final number of menu items in the database... which I imagine is not optimal from a coding perspective.
I have two files. File1 will get list number of menu items from a database and create a list. The condensed version of my code is as follows, please keep in mind i have condensed a lot of useless stuff;
File1.php

    $menuArray = openMenu(1);
    $return = "
<form method='post' action='file2.php'><input type='submit' name='submit' value='Commit Order' />
";
    $i=1;
    foreach($menuArray as $recordNum => $record)
    {
            if ($record['available'] > 0)
            {
                    $thisClass='available';
            } else{
                    $thisClass='unavailable';
            }

            $return.="

                            $record[itemid]
                            $record[name]
                            <button type='button' id='itemid-$record[itemid]' class='subtract'>-</button><input class='itemadder' id='itemid-$record[itemid]' type='number' min='0' value='0' /><button id='itemid-$record[itemid]' class='addition' type='button'>+</button>

";
    }
    $return.="
</form>
";

    return $return;

File2.php
    I don't know how to code this :(
Is anyone able to shed some light on the best way to do this?
I just need a way to be able to see what id's have a value when posted.
I am using jQuery at the moment; would this be something best done using jquery?

A: The script File1.php rendering the inputs above does know about what has rendered out. So what, if it also puts a list of rendered form element names in to the session for later use in file2.php:
In the beginning:
 $_SESSION['formids'] = array();

in the loop:
 ....
 $_SESSION['formids'][] = "itemid-" . $record[itemid];

and in file2.php:
 $sendItems = $_SESSION['formids'];
 ...

 foreach ( $sendItems as $itemId )
 {
      $val = empty($_POST[$itemId]) ? null : $_POST[$itemId];

      if ( isset($val) )
 ...

A: Assuming I understand you correctly the best way to do this would be to have an array of inputs.
Code you should try to achieve for your HTML output would need to be something like this:
<input type="text" name="number[1]" value="" />
<input type="text" name="number[3]" value="" />
<input type="text" name="number[5]" value="" />

Now you know after your form submission in PHP:
foreach($_POST['number'] as $id => $value){
    echo 'The value for ID #' . $id . ' is ' . $value;
}


text:
Q: '0xEF' is an invalid escapable character within a JSON string I got this strange message when parsing a json configuration file:

"JsonReaderException: '0xEF' is an invalid escapable character within
a JSON string. The string should be correctly escaped. LineNumber: 3 |
BytePositionInLine: 11."

The content of the json file is:
{
  "books": {
    "Content": [
      "運作"
    ]
  }
}

There is no such char '0xEF' in the configuration file, and nothing to escape.
The C# code as following:
using Microsoft.Extensions.Configuration;

// ...

config = new ConfigurationBuilder()
  .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "config.json"))
  .Build();

Any help would be appreciated.
Note:

*

*as I memtioned above, "there is no such char '0xEF' in the configuration file", but the message is showing "'0xEF' is an invalid escapable character within a JSON string". Where does it come from?

*The configuration file is the right file, all information posted above are double confirmed.

*The byte representaion of the word 運作 is: byte[] { 0xff 0xfe 0x4b 0x90 0x5c 0x4f }.

*The issue is created by the word "運", all other words are working fine. Is there certain words are not allowed as string in json file?

A: It seems that the file at initialization encoding is ANSI. Change encoding json file to UTF-8 BOM.

A: (") aka the Fullwidth Quotation Mark (FWQM) is not (") aka the Quotation Mark (QM).
FWQM (") is a character which has for UTF-8 encoding EF BC 82. Hence the origin of the 0xEF byte.
There is probably a FWQM (") instead of a QM (") somewhere in the JSon file.


text:
Q: use jquery/ajax for Getting ALL Youtube Video ID's for a given user I'm having a problem in getting all Youtube Video id's.
I'm trying to get all video id's from from Youtube for a given Youtube username, but the problem is that youtube allows only 50 results at a time . What is the best way to get all Youtube id.
this is the code I have now:

A: Assuming you can get the count of videos, you can do something like this:
int currentIndex = 1
int count = GET_COUNT_SOMEHOW;
while (currentIndex < count) {
           $.getJSON('http://gdata.youtube.com/feeds/users/Revision3/uploads?alt=json-in-script&callback=?&start-index=' + currentIndex + '&max-results=49',
           function(data){
               $.each(data.feed.entry, function(i, item){
                   var id = item['id']['$t'];
                   id = id.replace("http://gdata.youtube.com/feeds/videos/","");
                   $("#video").append('
 ['+id+'] ['+i+'] ');
                   $("#video").append('
');
       });
   });
    currentIndex += 50;
}

A: You can call it recursively until there are no more results:
function getYouTubeAllInfo(perpage, page, recursive) {
   // $("#video").append('
 http://gdata.youtube.com/feeds/users/Revision3/uploads?alt=json-in-script&callback=?&start-index='+(((page-1)*perpage)+1)+'&max-results='+perpage+'
');  //debug
   $.getJSON('http://gdata.youtube.com/feeds/users/Revision3/uploads?alt=json-in-script&callback=?&start-index='+(((page-1)*perpage)+1)+'&max-results='+perpage,
   function(data){
       $.each(data.feed.entry, function(i, item){
           var id = item['id']['$t'];
           id = id.replace("http://gdata.youtube.com/feeds/videos/","");
           $("#video").append('
 ['+id+'] ['+i+']
');
           //alert(page+perpage-2);
           if(i == perpage-2 && recursive){
               getYouTubeAllInfo(perpage, page+1, recursive);
           }
       });
   });
}

       getYouTubeAllInfo(49, 1, true);

You can test it here:  http://jsfiddle.net/Xemgz/8/
It's a slow process, this user has many videos.


text:
Q: iOS: Reading NSDictionary crashes app I have a dictionary which I am storing in another dictionary, which itself gets stored in an array, like so:
NSMutableDictionary* sectionHeights = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
                [NSString stringWithFormat:@"%f", section1Height], @"Section 1 Height",
                [NSString stringWithFormat:@"%f", section2Height], @"Section 2 Height",
        nil];

        [sectionObjects addObject:
         [[NSMutableDictionary alloc] initWithObjectsAndKeys:
          @"Site Inspection Report", @"Form Name",
          @"2", @"Section Count",
          sectionHeights, @"Section Heights",
          nil]
         ];

I pass the array to a property value of another class. When I try to read back sectionHeights, like so, the app crashes:
//get the subSectionData
    NSDictionary* subSectionData = [sectionObjects objectAtIndex:sectionObjects.count-1];
    NSDictionary* sectionHeights = [subSectionData objectForKey:@"Section Heights"];
    for(id obj in sectionHeights) {
        NSLog(@"%@", obj);
    }

in this case sectionHeights has 2 objects, NSStrings which will get converted to floats, but looking at the console output it seems as if the app is trying to output 3 objects:
2012-11-01 10:59:26.338 OAI_Accordion[2402:c07] Section 1 Height
2012-11-01 10:59:26.339 OAI_Accordion[2402:c07] Section 2 Height
2012-11-01 10:59:26.340 OAI_Accordion[2402:c07] -[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x9088
2012-11-01 10:59:26.341 OAI_Accordion[2402:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x9088'
*** First throw call stack:
(0x1c95012 0x10d2e7e 0x1d204bd 0x1c84bbc 0x1c8494e 0x46e8 0x2c84 0xfb817 0xfb882 0x4aa25 0x4adbf 0x4af55 0x53f67 0x225b 0x177b7 0x17da7 0x18fab 0x2a315 0x2b24b 0x1ccf8 0x1bf0df9 0x1bf0ad0 0x1c0abf5 0x1c0a962 0x1c3bbb6 0x1c3af44 0x1c3ae1b 0x187da 0x1a65c 0x1e9d 0x1dc5 0x1)
libc++abi.dylib: terminate called throwing an exception

I can't see where I am setting it up wrong so I was hoping extra sets of eyes on it might help.

A: It looks like your application is crashing because of the loop:
for(id obj in sectionHeights) {
    NSLog(@"%@", obj);
}

Which is most likely why you're getting the error countByEnumeratingWithState:objects:count: as you're trying to loop through a dictionary of values incorrectly.
You could loop through your dictionary using enumeration via a block as such:
[sectionHeights enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
{
    //
    NSLog(@"key: %@ -> value: %@", key, obj);
}];

This gives you access to the dictionary keys and values side by side. Your previous implementation crashes as the compiler doesn't know what to do with a dictionary in the context you have provided.
If you prefer the syntax of fast enumeration, you should loop through the array of dictionary values (or keys if you need them instead) by changing your code to:
for(id obj in [sectionHeights allValues]) {
    NSLog(@"%@", obj);
}

You can also use [sectionHeights allKeys] if you need the dictionary keys instead.

A: Please, try this:
NSDictionary* subSectionData = [sectionObjects objectAtIndex:sectionObjects.count-1];
NSDictionary* sectionHeights = [subSectionData objectForKey:@"Section Heights"];

for(id obj in [sectionHeights allValues]) {
    NSLog(@"%@", obj);
}


text:
Q: Android Pexels Api integration error using retrofit. Getting 404 error I am trying to integrate my application with Pexels API by using Retrofit and GSON but without success. I keep getting 404 error and therefore I am getting a null pointer exception on the console.
This is the working api:
https://api.pexels.com/v1/curated?page=1&per_page=14
public class ApiClient {

    public static final String API_KEY = "xxxxxxxxxx";
    public static final String BASE_URL = "https://api.pexels.com/v1/";
    public static Retrofit retrofit = null;

    public static Retrofit getClient(){
        if(retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

public interface ApiInterface {

    @Headers({"Authorization: " + ApiClient.API_KEY})
    @GET("/curated")
    Call<ExplorePageModelResponse>getExplorePagePhotos(
            @Query("page") int page,
            @Query("per_page") int per_page
    );

}

This is the service class that communicates with the pexels api. The response body is empty...

public class ExplorePageService implements ItemListContract.Model<ExplorePageModelPhotos> {

    private final String TAG = "ExplorePageService";
    private int pageNo = 1;
    private final int PER_PAGE = 14;

    @Override
    public void getExploreItemList(OnFinishedListener<ExplorePageModelPhotos> onFinishedListener, int pageNo) {

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<ExplorePageModelResponse> call = apiService.getExplorePagePhotos(1, PER_PAGE);

        call.enqueue(new Callback<ExplorePageModelResponse>() {
            @Override
            public void onResponse(Call<ExplorePageModelResponse> call, Response<ExplorePageModelResponse> response) {

                List<ExplorePageModelPhotos> list = response.body().getExplorePageModelPhotos();

                onFinishedListener.onFinished(list);

            }

            @Override
            public void onFailure(Call<ExplorePageModelResponse> call, Throwable t) {
                Log.e(TAG, t.toString());
                onFinishedListener.onFailure(t);

            }
        });

    }

}

This is the api response:
Response{protocol=h2, code=404, message=, url=https://api.pexels.com/curated?page=1&per_page=14}
I must be doing something wrong in the ApiInterface part since it's all working on the postman side but couldn't figure out. Thanks.


text:
Q: Electronic signature on a pdf file HTML5 I've been given a task where I must generate a PDF file, then the customer performs an electronic signature in a certain area on the document.
It will be used on a tablet (I don't know much about it). It must be also be a part of web application, and I've been told that HTML5 can handle this nicely.
Could anyone give me a tip how to start working on this? I have hardly any experience with HTML5.

A: Sorry for the "very" late reply but I got the same work recently
I am using sencha 2 touch, in which am using a PDF viewer in js Itself try this
https://github.com/SunboX/st2_pdf_panel
For the signature part try using this
https://github.com/SimFla/SimFla-signaturePad
mind you signature pad needed a lot of changes.
else another solution would be using Mozilla's pdf.js, display that on the canvas and use the same canvas to draw on the signature.
Thanks. Do share if you have already solved this.

A: There are also commercial solutions, with an API that allows integration into your environments. Check out Namirial.com (former xyzmo), on www.xyzmo.com or www.significant.com


text:
Q: Nested class of class template can be "incomplete" I'm at a loss as to how to explain why it is valid to create the member inner in the class template OuterTempl<T> whereas it is illegal to do so in the untemplated class Outer.
// Non-template version
struct Outer
{
    struct Inner;
    Inner inner;   // incomplete type (I get this)
};

struct Outer::Inner
{
};

// Template version
template<typename T>
struct OuterTempl
{
    struct InnerTempl;
    InnerTempl inner; // OK ... Huh!?
};

template<typename T>
struct OuterTempl<T>::InnerTempl
{
};

int main()
{
}

See also ideone.

A: The member types need to be defined when the class is defined. However, a class template doesn't get defined until it gets instantiated. Any kind of dependent types can change till then. The definition of members is only needed when the class gets instantiated.
On the other hand the definition of a non-template class is a definition which needs to know the size of its member at that point.

A: Yes - consider [temp.mem.class]/1:

A member class of a class template may be defined outside the class
  template definition in which it is declared.   [ Note: The member
  class must be defined before its first use that requires an
  instantiation (14.7.1). For example,
template<class T> struct A {
    class B;
};

A<int>::B* b1;  // OK: requires A to be defined but not A::B

template<class T> class A<T>::B { };

A<int>::B b2;   // OK: requires A::B to be defined

— end note ]

It is also important to mention that the definition of inner, which constitutes the use of Inner the above note describes, is only instantiated once it is required:

Unless a member […] has been explicitly instantiated or explicitly specialized, the specialization
  of the member is implicitly instantiated when the specialization is
  referenced in a context that requires the member definition to exist;

Since no instantiation of OuterTempl is present in your code, the definition of inner is never instantiated, and an instantiation of Inner is never necessitated. The completeness of the nested class type for such a declaration is thus only required at the point of instantiation. You don't instantiate OuterTempl here, but if you would do that before the definition of Inner, the code would be ill-formed.
That is,
template<typename T>
struct OuterTempl
{
    struct InnerTempl;
    InnerTempl inner;
};

template struct OuterTempl<int>; // Bad - Ill-formed (NDR?)

template<typename T>
struct OuterTempl<T>::InnerTempl {};

template struct OuterTempl<int>; // Fine

Demo.


text:
Q: How to select all child from document.queryselectorall() over eventlistener const modalTriggers = document.querySelectorAll(".modal-trigger");
modalTriggers.forEach((modalTrigger) => {
    modalTrigger.addEventListener("click", (clickEvent) => {
        const trigger = clickEvent.target;
        const modalId = trigger.getAttribute("data-modal-id");
        openModal(modalId);
    });
});

<button class="modal-trigger bg-brandPrimary-500 rounded-full p-8 shadow-custom text-white" data-modal-id="openFilterDialog"></button>

When I click over the #span #i it won't trigger the data-modal-id but when I click over the #button it triggers the data-modal-id. What is the possible way to trigger data-modal-id if we click over either button span or I? Can anyone help me on this?

A: Just use your already existing modalTrigger variable instead of looking at the target.
const modalTriggers = document.querySelectorAll(".modal-trigger");
modalTriggers.forEach((modalTrigger) => {
    modalTrigger.addEventListener("click", () => {
        const modalId = modalTrigger.getAttribute("data-modal-id");
        openModal(modalId);
    });
});

Another solution is to disable the click events on the child elements with CSS pointer-events:
.modal-trigger * {
  pointer-events: none;
}

A: i'm not entirely sure the .parent() will select the right element when clicked on the i but the .children() onclick is the correct thing to detect the right click event on the child elements

$(".modal-trigger").children().on('click', function(){
$(this).parent().click();
});

<button class="modal-trigger bg-brandPrimary-500 rounded-full p-8 shadow-custom text-white" data-modal-id="openFilterDialog">dddd</button>


text:
Q: Create macro to output and update file after merging several excel files I am a novice at VBA. I am using Excel 2013 for this task. I have several Excel files I am combining into a single file with multiple sheets using the macro below.
Sub Merge2MultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Application.ScreenUpdating = False
    MyPath = "H:\Survey Research\ECAS\Reports\2015\Tracks"
    Set wbDst = Workbooks.Add(xlWBATWorksheet)
    strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

    Do Until strFilename = ""

        Set wbSrc = Workbooks.Open(FileName:=MyPath & "\" & strFilename)

        Set wsSrc = wbSrc.Worksheets(1)

        wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)

        wbSrc.Close False

    strFilename = Dir()

Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

I want each sheet in the new file to take the name of its original file. I tried to edit the code below and include in the macro above, but while I didn't get an error message, it did not accomplish the task.
Do While fileName <> ""
Workbooks.Open (directory & fileName)
WrdArray() = Split(fileName, ".")
For Each sheet In Workbooks(fileName).Worksheets
Workbooks(fileName).ActiveSheet.Name = WrdArray(0)
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy after:=Workbooks("import-   sheets.xlsm").Worksheets(total)

Once the files have been merged and the sheets named, I want to output the new file and to easily update it if the data in my original files change.
Is it possible to achieve all of this with one macro? If so, could anyone  suggest a way to write a Macro in Excel to automatically name the sheets, output the file and update it if changes are made to the data in the original files?

A: For the first part I think you only need to add one line:
Do Until strFilename = ""

        Set wbSrc = Workbooks.Open(FileName:=MyPath & "\" & strFilename)

        Set wsSrc = wbSrc.Worksheets(1)
        'name the tab according to the file name
        wsSrc.Name = Replace(strFilename,".xls","")

        wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)

        wbSrc.Close False

    strFilename = Dir()

Loop

The last part about updating the workbook if the source files change is potentially much more complex: the easiest approach would be to re-run the consolidation code.  If that doesn't work for you then you'd need to add more details on that.


text:
Q: ¿Como definir un arreglo de un tipo de datos en una propiedad en un objeto JSON? tengo esl siguente obj
nuevoEvento : {
    infoBasica : {
        nombre: String,
        escenario:String,
        valor: [{
            titulo: String,
            valor: String
        }],
        lugar:{
            escenario: String,
            direccion: String,
            barrio: String,
            ciudad: String,
        },
        genero: String,
        modalidad: String,
        edad: [{
            titulo: String,
            rango: String
        }],
        fechas:{
            inicio: {
                fecha: Date,
                hora: TimeRanges
            },
            limite: {
                fecha: Date,
                hora: TimeRanges
            }
        },
        tipoCompetencia: "Individual" | "Equipos",
    },
    infoAvanzada : {
        cupos: Number,
        inscriptos: String,
        premios: Array<Premio>

    }
}

Mi inquietud es mas exactamente en la propiedad premio, quiero que solo me reciba un arraglo de datos de tipo Premio
export class Premio {
    titulo: String
    valor: String
    constructor(titulo, valor) {
        this.titulo = titulo
        this.valor = valor
    }
}

¿Eso estaría correcto?

A: Si quieres que sea un arreglo del tipo Premio, deberías ponerlo:
premios: [Premio]

A: Realmente no puedes definir tipos en Javascript, o al menos no desde el enfoque que necesitas. En casos como estos, la opción adecuada, si quieres seguir usando la sintaxis de Javascript, es programar en TypeScript.


text:
Q: Yii2 Login authentication issue I am having trouble in Authtenticating password for Yii2 in advance fronend. I get following error
"Incorrect username or password."
I know yii2 uses hash authentication. I am providing correct password that I remember from time of signup.
My Password field in database is always blank, there is nothing there, but there are bunch of characters in my password_hash and auth_key.
Is it normal for password field to be blank? or is this a bug in signup process?
Here is my User model code
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
      public static function tableName()
{
    return '{{%user}}';
}

A: While storing the password you can use the following function in your User model before saving the details of the user
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);

Now when the user inputs password you can validate it by using the following code
if (Yii::$app->getSecurity()->validatePassword($password, $user->password) == true) {
    /* Password is valid */
} else {
    /* Invalid password */
}

Regarding the blank password, it is acceptable by the Yii2 while converting the blank password to hash but is a bad practice for allowing the user to input blank password. You must add the validaiton rule in your  model to avoid blank password input.


text:
Q: Which is correct, "he was already dead" or "he already was dead"? How should I say, "he was already dead" or "he already was dead"?
The second way does not sound entirely correct to me, but I couldn't find a rule stating that it is wrong.

A: This link offers some useful guidelines on adverb positioning.
Other possibilities exist, but you might strain to justify using them.
It has two suggestions for already. These are (in no particular order):

he was dead already - at the end of the clause or sentence
He was already dead - between a 'be' word and the main verb

A: Both are grammatically correct. However their common usage differs.
For example if you're telling a story about someone who was walking up to a body hoping to revive him, you'd say "he was already dead".
The other expression is used to emphasize "already". Imagine one doctor saying to another "you only do that if they're dead!" and another replying "but he already was dead."

A: For this discussion "already" is superfluous.  Write or read the two sentences without it.  He is dead.  He was dead.
You can only use the second sentence if the person is no longer dead.  Therefore, unless they have risen from the dead, he already was dead is grammatically incorrect. He is already dead means he is still dead.


text:
Q: Is Netbeans handling indexing on C code better than Eclipse's CDT? I am using CDT 8 with indigo. Basically I am quite happy with it except one thing, which is the indexer is too slow and freezes my machine after I edited some files. The code base of the project is quite large, around 2G , but I tried with CScope, it actually indexes pretty fast, ~0.5 hour compared to ~3 hours on eclipse.
I am wondering if netbeans handles indexing better ? of course with an okay code assistant.

A: Not having used the NetBeans C editor much I can't say what the state of the code completion is. In recent versions of NetBeans (7 onwards) they have started using native file system listeners to detect code changes. I don't think the work is completed yet, however what it should mean is that indexing will become faster with each successive version.


text:
Q: Need help writing trigger to only allow certain users to update/delete based on JOINED tables I have two tables, let's just call them A & B, which can be joined together via a foreign key. There is a BIT field on Table A (and only on Table A), and once set to TRUE, I want ONLY users of a certain group membership to able to update/delete the record.
For just Table A, I used the following:
CREATE trigger [trigger_TableA] on [TableA] after update, delete
as
begin
set nocount on
 if exists (select 1 from deleted d where d.[BitFlag] = 1)
     and exists (select 1 from inserted i where i.[BitFlag] = 1)
     and 1 != isnull(IS_MEMBER('GROUP_NAME'), 0)
 begin
     RAISERROR('Only members of GROUP_NAME are allowed to update or delete.', 16, 1)
     ROLLBACK TRAN
  RETURN
 end
end

How would I modify the above for table to be a Trigger for Table B that involves checking the BitFlag on Table A?
Thanks!

A:  if exists (select 1 from deleted d INNER JOIN tableA a on d.? = a.? where a.[BitFlag] = 1)
     and exists (select 1 from inserted i INNER JOIN tableA a on i.? = a.? where a.[BitFlag] = 1)

Of course you will have to replace the ?s with whatever field you need to join on.


text:
Q: Is it possible to separate the table based on year in mysql using php I have a simple column which output years. But the outputs are in a single table. Is it possible to separate the table automatically based on a different year.
<?php
if(mysqli_num_rows($result) > 0){ ?>

            Year

            <?php
                while($row = mysqli_fetch_assoc($result)){
                    $year = $row['year'];
                ?>

                    <?php echo $year; ?>

                <?php
                    } ?>

<?php } ?>

This outputs this
+------+
| year |
+------+
| 2017 |
| 2017 |
| 2018 |
+------+

I am looking for this
+------+
| year |
+------+
| 2018 |
+------+

+------+
| year |
+------+
| 2017 |
| 2017 |
+------+

A: Your loop just needs to check internally if the "year" has changed in the results, and output the HTML table footer/header to start a new table.  Consider the following pseudo-code logic:
results = query(); // assume ordered by year
year = 0;
first_row = true;
output_HTML_table_header();
while (row = results.next()) {
    if (year != row["year"] && !first_row) {
        output_HTML_table_footer();
        output_HTML_table_header();
    }
    year = row["year"];
    first_row = false;
    output_HTML_table_row(row);
}
output_HTML_table_footer();

Supposing your data is this:
2016
2017
2017
2018
2019

The output operations this produces would be:
HTML table header
  2016 row
HTML table footer
HTML table header
  2017 row
  2017 row
HTML table footer
HTML table header
  2018 row
HTML table footer
HTML table header
  2019 row
HTML table footer

The "HTML table header" output is simply:

        Year

The row is:

    <?php echo $year; ?>

and the footer is:

You just need to alternate/repeat them in the nested logic.

A: If the $result sql is order by year you can use this.
<?php
$year='';
if(mysqli_num_rows($result) > 0){
  echo'

Year

';
  while($row = mysqli_fetch_assoc($result)){
    //if a new year create new table
    if($year!=$row['year']&&$year)echo'

Year

';
    echo'
'.$row['year'].'
';
    //remeber the last year
    $year=$row['year'];
  }
  echo'

';
}
?>


text:
Q: mysql drop multiple table using where or is not like condition? anyone can suggest me the query to delete multiple tables from database.?? like.......

Drop table is not like 'prefix%';

please suggest me the right query to do that ??

A: You cannot do it with just a single MySQL command, however you can use MySQL to construct the statement for you:
In the MySQL shell or through PHPMyAdmin, use the following query
SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' )
AS statement FROM information_schema.tables
WHERE table_name LIKE 'myprefix_%';

This will generate a DROP statement which you can than copy and execute to drop the tables.
EDIT: A disclaimer here - the statement generated above will drop all tables in all databases with that prefix. If you want to limit it to a specific database, modify the query to look like this and replace database_name with your own database_name:
SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' )
AS statement FROM information_schema.tables
WHERE table_schema = 'database_name' AND table_name LIKE 'myprefix_%';


text:
Q: Compare two classes and seeing if they are equal considering primitive and its wrapper class In the end, I want to have something that does something similar to this, which I will use to search correct constructor for reflection.
public static boolean equalWithPrimitive(Class<?> from, Class<?> target){
    if(from == target){
        return true;
    }else if((from == Byte.class || from == byte.class) && (target == Byte.class || target == byte.class)){
        return true;
    }else if((from == Short.class || from == short.class) && (target == Short.class || target == short.class)){
        return true;
    }else if((from == Integer.class || from == int.class) && (target == Integer.class || target == int.class)){
        return true;
    }else if((from == Long.class || from == long.class) && (target == Long.class || target == long.class)){
        return true;
    }else if((from == Float.class || from == float.class) && (target == Float.class || target == float.class)){
        return true;
    }else if((from == Double.class || from == double.class) && (target == Double.class || target == double.class)){
        return true;
    }else if((from == Boolean.class || from == boolean.class) && (target == Boolean.class || target == boolean.class)){
        return true;
    }else if((from == Character.class || from == char.class) && (target == Character.class || target == char.class)){
        return true;
    }
    return false;
}

Is there a shorter and an accurate way to achieve this thought?

A: The most fool-proof way is to keep a Map of primitive->boxed type and use that for conversion before doing the check:
private static final Map<Class, Class> primitiveWrapperMap = new HashMap();
static {
     primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
     primitiveWrapperMap.put(Byte.TYPE, Byte.class);
     primitiveWrapperMap.put(Character.TYPE, Character.class);
     primitiveWrapperMap.put(Short.TYPE, Short.class);
     primitiveWrapperMap.put(Integer.TYPE, Integer.class);
     primitiveWrapperMap.put(Long.TYPE, Long.class);
     primitiveWrapperMap.put(Double.TYPE, Double.class);
     primitiveWrapperMap.put(Float.TYPE, Float.class);
     primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}

public static Class primitiveToWrapper(Class cls) {
    Class convertedClass = cls;
    if (cls != null && cls.isPrimitive()) {
        convertedClass = (Class) primitiveWrapperMap.get(cls);
    }
    return convertedClass;
}

public static boolean equalWithPrimitive(Class<?> from, Class<?> target) {
    return primitiveToWrapper(from) == primitiveToWrapper(to);
}

This is also how the apache commons ClassUtils library does it.

A: It might be little dirty but -
Get the name of the both classes convert those to lower case / upper case and equals them

Ex -
from.getName().toLowerCase().equals(target.getName().toLowerCase())
public static boolean equalWithPrimitive(Class<?> from, Class<?> target){
    if(from == target){
        return true;
    }
    return from.getName().toLowerCase().equals(target.getName().toLowerCase());
}


text:
Q: R: Group data frame by attaching columns I want to group rows of my data frame. But the columns should not be summarized, I want to attach them.
I tried the tidyverse package and came to a close (wrong) solution.
This is my df:
  `Order ID` Quantity `Sub-Category 1` `Sub-Category 2` `Sub-Category 3` `Sub-Category 4` `Sub-Category 5` `Sub-Category 6`
  <chr>         <dbl> <chr>            <chr>            <chr>            <chr>            <chr>            <chr>
1   22              2 Bookcases        Bookcases        NA               NA               NA               NA
2   33              3 Chairs           Chairs           Chairs           NA               NA               NA
3   22              2 Labels           Labels           NA               NA               NA               NA
4   33              5 Tables           Tables           Tables           Tables           Tables           NA

The number of columns represent the Quantity, so Quantity column not longer needed.
I want to group them and attach the same Order ID rows, to get this solution:
  `Order ID` Quantity `Sub-Category 1` `Sub-Category 2` `Sub-Category 3` `Sub-Category 4` `Sub-Category 5` `Sub-Category 6`
  <chr>         <dbl> <chr>            <chr>            <chr>            <chr>            <chr>            <chr>
1   22              2 Bookcases        Bookcases        Labels               Labels               NA               NA
2   33              3 Chairs           Chairs           Chairs           Tables               Tables               Tables               Tables               Tables

Thank you very much, appreciate your help.

A: Using the tidyr package's spread and gather functions, maybe try:
library(tidyverse)

df <- data %>%
  select(-Quantity) %>%
  gather(key = "col", value = "val", -`Order ID`) %>%
  group_by(`Order ID`, col) %>%
  mutate(val = max(val, na.rm = T)) %>%
  slice(1) %>%
  ungroup() %>%
  spread(key = "col", value = "val")


text:
Q: Select from mysql by day with different timezones (php) I'm storing leads in a database, and each lead has a datetime field with a PST timezone based date & time.
I want my user to be able to display all leads from a certain date (e.g. today, yesterday), and choose the timezone.
E.g. if I want to see all leads that were generated yesterday in EST timezone, I need to first convert (or read) all the datetime values to EST, and then only select those who are in the target range (yesterday).
What would be the best way to do that?

A: You can use MySQL's Convert_TZ(dt, from_tz, to_tz) function.
E.g.
SELECT CONVERT_TZ('2010-03-20 12:00:00', 'EST', 'PST8PDT')

returns 2010-03-20 10:00:00
edit: TO select all records that are "today in EST" you can use something like
SELECT
  x,y,z
FROM
  foo
WHERE
  dt >= CONVERT_TZ(CURDATE(), 'EST', 'PST8PDT')
  AND dt < CONVERT_TZ(CURDATE(), 'EST', 'PST8PDT')+Interval 1 day


text:
Q: Merge - Orcle error While executing below code, getting  error "Missing ON keyword"  but  I have already written ON clause. Please assist on cause.
merge into emp_temp s

using (select p.employee_id, p.salary, p.last_name,p.email, p.Hire_date,
p.job_id from employees p
minus
   select s.employee_id, s.salary, s.last_name,s.email, s.Hire_date,
s.job_id from emp_temp s
) EMPLOYEES p

ON (s.employee_id = p.employee_id)

when matched then
 update set s.salary = p.salary

when not matched then
insert
(s.employee_id , s.salary,s.last_name,s.email,s.Hire_date, s.job_id)
values
    (p.employee_id, p.salary, p.last_name,p.email, p.Hire_date, p.job_id);

A: It's coming from this line:
) EMPLOYEES p

You're setting the using clause's alias as EMPLOYEE, but that you're trying to re-alias that as just p. The error doesn't mean that you don't have an ON clause at all, just that it isn't where the parser is expecting to see it.
Since you refer to p later, you just want that single alias:
...
minus
   select s.employee_id, s.salary, s.last_name,s.email, s.Hire_date,
s.job_id from emp_temp s
) p

ON (s.employee_id = p.employee_id)
...


text:
Q: codeigniter: out of memory this is the print screen of my error, please click..
I'm using codeigniter here,
this is my controller...

class Copy extends CI_Controller {

public function index()
{
    redirect('home');
    ini_set("memory_limit", "4096M");
}

public function getFile($file = '')
{
    $this->load->model('home_model');
    $files = $this->home_model->getFile($file);
    $this->load->library('zip');
    $this->load->helper('download');

    if($files !== FALSE)
    {
        foreach ($files->result() as $row)
        {

            $data = file_get_contents(base_url().$row->File_Path); // Read the file's contents

            $name = substr($row->File_Path, 26);
            $name2 = str_replace("_", " ", $name);

            force_download($name2, $data);
        }
    }

}

}
I'm using codeigniter helper DOWNLOAD, to download file in the server...
I already, update memory_limit in php.ini 2048M TO 4096M, it seems nothings happen, and I tried to put ini_set('memory_limit','4096M'); in my code, and it didn't work also...
can someone tell me how to fix this... THANK YOU


text:
Q: Trouble running all migration files. What else can one do? I have a very large amount of migration files that need to run and some of them apparently are outdated. For example:
This fails:
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      ...

With this error:
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition

I assume because Devise was updated at the time of writing this.
What else can I do?
It turns out there's a schema file. Here's part of it:
ActiveRecord::Schema.define(version: 20160221211458) do

  create_table "activities", force: true do |t|
    t.integer  "user_id",                  null: false
    t.string   "target_type", default: "", null: false
    t.integer  "target_id",                null: false
    t.string   "action",      default: "", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "activities", ["target_id"], name: "index_activities_on_target_id_and_target_type", using: :btree
  add_index "activities", ["user_id"], name: "index_activities_on_user_id", using: :btree

  create_table "addresses", force: true do |t|
  ...

What's the difference between doing bundle exec rake db:schema:load vs trying to run the migrations. Is there a difference between the two?
Also, this database is a mysql database:
# SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
  adapter: mysql2
  database: arthouse_development
  username: root
  password:
  host: localhost
  port: 3306
  #socket: /tmp/mysql.sock

How do I see this database after running bundle exec rake db:schema:load

A:
This fails:

def self.up
 create_table(:users) do |t|
 t.database_authenticatable :null => false

I assume because Devise was updated at the time of writing this.

I need to know the error messages you get

It turns out there's a schema file:

In your schema I see that you have not users table, I think that you need to check your db mysql2 and see if you have something there.

What's the difference between doing bundle exec rake db:schema:load vs trying to run the migrations. Is there a difference between the two?

let's say I fork a github project and the schema file is already populated. With that command I load the schema so I do not run every migration but just create the tables like in the schema.
Migrations use scripts to populated the database, this scripts have function like add_column that modify the schema.rb file.
Every function from ActiveRecord:Migrations will modify the schema, this means maybe adding a column and later deleting. This conflict in migrations are cause by the incompatibility in this migrations, for example you add a column, then you need to reverse it, but later you add an index to that column, so the migration fails. More info at the following link

Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
You can think of each migration as being a new 'version' of the database. A schema starts off with nothing in it, and each migration modifies it to add or remove tables, columns, or entries. Active Record knows how to update your schema along this timeline, bringing it from whatever point it is in the history to the latest version. Active Record will also update your db/schema.rb file to match the up-to-date structure of your database.

Solution
Your error
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition

Given your problem, you should find the solution hear
undefined method `database_authenticatable' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x9dee690>

A: I also ran into this issue on my existing app as I tried to deploy to a new staging server.
Ended up being that the Devise gem had been updated to 2.1 and I hadn't fixed the migration to work correctly with the new version.
Be sure to read through their migration to 2.1 doc on their wiki -- https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.1
Also, be sure to read through the doc for how to correctly adjust existing migrations -- https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0-migration-schema-style


text:
Q: app crash on Android 5.0.x i'm having an issue of application crashing on android versions 5.0.X.
No error available, just this warning:
06-19 11:50:22.900: W/google-breakpad(24934):
Chrome build fingerprint:
1.4.4
11
5c230f07-455f-4c1f-91eb-9c44019cd813
### ### ### ### ### ### ### ### ### ### ### ### ###
Tombstones are disabled on JB MR2+ user builds.
### ### ### ### ### ### ### ### ### ### ### ### ###

Sometimes it crashes even without clicking anything.
version 5.1 and version below 5 do work normally.
ANy idea what might be wrong?
Found similar issue here but Xamarin is used there.

A: I had exactly the same error in Xamarin.Android and was able to solve the problem with this fix. Just add this to the Fragment which holds the WebView:
public override void OnDetach()
    {
        base.OnDetach();
        DestroyWebView();
    }

    public void DestroyWebView()
    {
        var webView = Activity.FindViewById<WebView>(Resource.Id.webView);
        if(webView != null)
        {
            webView.ClearHistory();
            webView.ClearCache(true);
            webView.LoadUrl("about:blank");
            #pragma warning disable 618, 414
            webView.FreeMemory();
            #pragma warning restore 618, 414
        }
    }


text:
Q: Net name requirement for PCB design on upverter I am using Upverter to do my PCB design. Whenever I have 3 or more connections on a net, it shows me a warning saying that I need to explicitly name it.

I would like to know if this is just a quirk of Upverter or it is some industry standard to name nets with 3 or more connections. In addition to that, is there an industry convention on how to name nets?

A: That naming  requirement must be a quirk of Upverter.  I haven't seen such a requirement in the CAD systems I've used (Protel, Altium, KiCAD), or seen any mention it in other systems.


text:
Q: Grails: Clear errors when passing object to view I am checking if my user has entered the same password twice in controller:
if(params.password1 != "" || params.password2 != "") {
    // change password
    if(params.password1 != params.password2) {
        user.errors.rejectValue('password', 'noMatch')
    }

    user.password = params.password1
}

if (user.errors.errorCount > 0 || !user.save()) {

    println user.errors.errorCount
    render(view: "edituser", model: [userInstance: user])
    return
}

I get the correct user error count displayed in console so my if-clause works and Grails does not re-validate the object by using double pipe.
When I have a look into my GSP I get the following message:

grails.validation.ValidationErrors: 0 errors

It seams like Grails clears all errors or uses an other object. It's curious, because my custom validator in my domain class works fine...


text:
Q: Firefox marketplace: manifest file validation I am trying to submit an app as packaged app to the firefox marketplace. The code is hosted on github at the address https://github.com/dacapito/ebac/ .
When running the manifest validator I get the following errors

Your app failed validation with 2 errors.

*

*JSON Parse Error
   *  Manifests must be served with the HTTP header "Content-Type: application/x-web-app-manifest+json".
and looking to the error details:

*

*Error: The webapp extension could not be parsed due to a syntax error
in the JSON
No JSON object could be decoded: line 2 column 1 (char 1)

I have tested my manifest file with a json validator and it gave no problems. And moreover the very same app was submitted to the marketplace as a packaged app and the validator gave no problems at all..
Could it be a server trouble (not serving the file with the correct content) or what else ?
regards

A: Remove this part
 <meta http-equiv="Content-Type" content="application/x-web-app-manifest+json; charset=UTF-8">

and retire  manifest="manifest.appcache" because is for hosted apps
 <html manifest="manifest.appcache">  for
 <html>

A: If I understood correctly, you want to create a hosted app, not a packaged app isnt?
In that case you can serve your app from github, but you need to follow github rules to create the project github pages, more information here.
Fortunately, git pages recognise the extension .webapp and will server with the correct content type.
You have a whole article by Margaret Leibovic on how to use github pages for your FirefoxOS application here.


text:
Q: Many-to-many withouth relations (Laravel) I have two application, in two different server.
In the first Laravel application I have my User model, and in the secound application I have my Blog model.
There is a many-to-many relationship between them, a user can have multiple blogs, and one blog can belongs to many user.
They have two different database, but everything is built like its only one app in one server.
They have a REST API, and its communicating between them. The problem is, I cant set up real relations between them (like belongsToMany in the Eloquent Model), and I can't list User's blogs.
Is there a way to copy the "User::blogs()" relation function, with some query work on Blog:: class? For e.g. select all blogs where user_id is equal to 1 in the pivot table?

A: <?php
class User extends Model{
  protected $connection = 'Your Connection';

  public function blogs(){

    return $this->belongsToMany(Blog::class);
  }

}

Blog.php
class Blog extends Model{

  protected $connection = 'Your other connection';

public function users(){

    return $this->belongsToMany(User::class);
  }

}

You can set the multiple connections in your database.php and assign each model a different connection.
I am assuming that you have a user_blogs  table. some where
hope this helps.

A: I found it, like this:
Blog::join('blog_user', 'blogs.id','=','blog_user.blog_id')->where('blog_user.user_id', '=', $this->userId)->get();


text:
Q: Elasticsearch Python Django: How to limit the output text content and highlight the input keyword This is my search function in views.py
def search(request, pk, slug):
    es = Elasticsearch()
    es_client = Elasticsearch(['http://127.0.0.1:9200'])
    print('called search')
    search_text = request.GET.get('qq')
    print('Search text: {}'.format(search_text))
    print('cluster id/ ealstic search index: {}'.format(pk))
    s = None
    count = 0

    try:
        if search_text:
            s = Search(index=str(pk)).using(es_client).query("match", content=search_text)
            response = s.execute()
            count = 0
            for hit in s:
                count += 1
                print(str(count) + ' - ' + str(hit.currnet_url))
                #print(hit.content)
            else:
                print('nothing more found')
        else:
            print('No text to search')

    except Exception as e:
        count = 0
        print('Exception caught')
        msg = 'Cluster is not ready to be searched'
        return render(request, 'base_app/cluster_search.html', {'warning':msg, 'count':count})

    return render(request, 'base_app/cluster_search.html', {'cluster':slug, 'hits':s, 'count':count})

This is how I am indexing data to Elasticsearch.
def elastic_indexer(text, depth, url, clusrer_id):

    es_client = Elasticsearch(['http://127.0.0.1:9200'])
    doc = {
        "date": time.strftime("%Y-%m-%d"),
        "currnet_url": url,
        "depth": depth,
        "content": text
    }
    res = es_client.index(index= str(clusrer_id), doc_type="_doc", body=doc)
    print(res["result"])

This is the frontend template where the users input a text to search.
{% extends "account/base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}

{% block head_title %}{% trans "Search" %}{% endblock %}

{% block content %}
Go Back

You are searching in {{cluster.title}}

<form method="GET" action="">
    {% csrf_token %}
    <button class="btn btn-primary" action="">Search</button>
    <input id="q" name="qq" type="text" placeholder="enter search text here" style="width: 500px;">
</form>

{% if hits %}

        {% for hit in hits %}

            Hit: {{hit.currnet_url}}

            Content: {{hit.content}}

        {% empty %}

 No search result found

        {% endfor %}

{% endif %}

        {% if page_obj.has_previous %}
            « first
            previous
        {% endif %}

            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.

        {% if page_obj.has_next %}
            next
            last »
        {% endif %}

{% endblock %}

This is returning everything, all the text stored in "content", how do I limit this to only the user's input text and only show limited characters before and after the input text? and including highlighting the input text? Please help me out
Example:
What it shows:
*User inputs text, assuming it's "django"*
hits: https://www.djangoproject.com/
Content: all of the scraped text stored in "content"

What I want it to show:
User inputs text, assuming it's "django"
hits: https://www.djangoproject.com/
Content: 10 words before "django" and 10 words after "django"


text:
Q: Cancel Previous request(if there are any) before making another while using debouncing in react Sample react code what I am currently using...
I want to abort the request as soon as I make another request using debouncing.
Right now it cancels the very request it is making even for the first time.

import "./App.css";
import React, { useCallback, useState } from "react";

function App() {
  const [mesg, setMesg] = useState(0);
  const [pin, setPin] = useState("");
  const abortCon = new AbortController();
  const signal = abortCon.signal;
  const debounce = (fn, timer) => {
    let time;
    return function () {
      let arg = arguments;
      let context = this;
      if (time) clearTimeout(time);
      time = setTimeout(() => {
        fn.apply(context, arg);
        time = null;
      }, timer);
    };
  };

  const onChangeHandler = (val) => {
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    console.log(val);
    if (abortCon) abortCon.abort();
    fetch(url, { signal })
      .then((result) => {
        return result.json();
      })
      .then((res) => {
        // const result = await res.json();
        console.log(res.title);
        setPin(val);
        setMesg((prev) => prev + 1);
      })
      .catch((e) => console.log(e));
  };
  // const newHandler = debounce(onChangeHandler, 400);
  const newHandler = useCallback(debounce(onChangeHandler, 200), []);

  return (

{mesg}

      <input
        type="text"
        placeholder="PIN code"
        value={pin}
        onChange={(e) => {
          setPin(e.target.value);
          newHandler(e.target.value);
        }}
      />

  );
}

export default App;

I want to abort the request as soon as I make another request using debouncing.
Right now it cancels the very request it is making even for the first time.

A: The problem is that you are not making a new Abort Controller for each request.
So instead we save a ref to the AbortController using useRef(). Then create a new AbotrController and assign it to the ref at the start of each request.
Please see the updated code below:
import "./App.css";
import React, { useCallback, useRef, useState } from "react";

function App() {
  const [mesg, setMesg] = useState(0);
  const [pin, setPin] = useState("");
  const abortConRef = useRef();
  const debounce = (fn, timer) => {
    let time;
    return function () {
      let arg = arguments;
      let context = this;
      if (time) clearTimeout(time);
      time = setTimeout(() => {
        fn.apply(context, arg);
        time = null;
      }, timer);
    };
  };

  const onChangeHandler = (val) => {
    const url = "https://jsonplaceholder.typicode.com/todos/1";
    console.log(val);
    if (abortConRef.current) abortConRef.current.abort();
    abortConRef.current = new AbortController();
    fetch(url, { signal: abortConRef.current.signal })
      .then((result) => {
        return result.json();
      })
      .then((res) => {
        // const result = await res.json();
        console.log(res.title);
        // setPin(val);
        setMesg((prev) => prev + 1);
      })
      .catch((e) => console.log(e));
  };
  // const newHandler = debounce(onChangeHandler, 400);
  const newHandler = useCallback(debounce(onChangeHandler, 200), []);

  return (

{mesg}

      <input
        type="text"
        placeholder="PIN code"
        value={pin}
        onChange={(e) => {
          setPin(e.target.value);
          newHandler(e.target.value);
        }}
      />

  );
}

export default App;

https://codesandbox.io/s/serene-wright-f85hy?file=/src/App.js
Edit: I also commented out the setPin in the response callback. It was making the input buggy.


text:
Q: Excel Chart not showing SOME X-axis labels I have a chart that refreshes after a dataload, and it seems like when there are more than 25 labels on the x-axis, the 26th and on do not show, though all preceding values do.  Also, the datapoints for those values show in the chart.  In the chart data window, the labels are blank.

Any ideas?

A: I had a similar problem I think it's somewhat related to what was brought up in this thread, although I didn't really follow. What I did to make it work was the following:

*

*On the legend entries (series) section I clicked edit for each series and confirmed they were the right series.

*I think clicked "edit" on the Horizontal (category) Axis labels and confirmed it was the correct selection (in my case I had to extend the range to incorporate added data)

*Once this was complete the values showed up in the horizontal (category) Axis labels and when I selected them it populated my chart.
I recognize this is only a work around so if anyone knows the root cause and how to prevent it that would be great.

A: Mine disappeard because the Column with the data was hidden.  Unhiding the column fixed it.  Not sure why this is related.

A: I right-clicked on the x-axis and then played around with the 'major units' field, until all the labels I required showed.

A: In Excel 2013, select the bar graph or line chart whose axis you're trying to fix. Right click on the chart, select "Format Chart Area..." from the pop up menu. A sidebar will appear on the right side of the screen. On the sidebar, click on "CHART OPTIONS" and select "Horizontal (Category) Axis" from the drop down menu. Four icons will appear below the menu bar. The right most icon looks like a bar graph. Click that. A navigation bar with several twistys will appear below the icon ribbon. Click on the "LABELS" twisty. You can play with the options under here to get your X axis looking how you want.

A: I was having a similar problem and it was only due to what excel can fit in the chart. Click the chart, and then drag one of the sizing handles to enlarge the chart. By default, the fonts in the chart scale proportionally as you resize the chart. Once you make your chart big enough, your labels should show.

A: i had the same problem. I found that excel had trouble picking up the values from cells which had been merged. Once i de-merged the values appeared in my chart.
Good luck!

A: Had the same issue. Finally was able to select data manually for the "chart data range." The blank x-axis categories were not being pulled in, though the numerical data was. It was bizarre and annoying but I was eventually able to get the darn labels to show.

A: Right clicked on the horizontal axis and selected Format Axis.  Changed axis type from automatic to text and the missing labels appeared.

A: In my case the issue was on Format Axis | Axis Options, Bounds had a custom value for Maximum; I hit the Reset button to switch back to Auto, and all the missing values were displayed.

A: What worked for me was to right click on the chart, go to the "Select Data" option. In the box, check each Legend Entry and ensure the corresponding Horizontal Labels are fully filled in. I found for me only one Legend had the full X-axis list, but there was one that didn't and this meant half of my X-axis labels were blank.


text:
Q: A Simple Join and In Clause taking too long I am attempting to get results from the combined table using the SQL below for the inventory status information. But the problem came when I am using about 36,000 variant IDs to the IN clause parameter and got a timeout on the website due to protection against timeout activity. So most likely the query took longer than 3 min max.
SELECT vid.`variant_id`, name, iq.`quantity`
FROM products vid
JOIN inventoryQuantity iq USING(inventory_item_id)
JOIN vendor v ON iq.`location_id` = v.`shopify_location_id`
WHERE vid.`variant_id` IN (123456,98764,..)

Here are three tables:
products
id | variant_id | sku | inventory_item_id
-----------------------------------------
1         123456 12-S            40005212
2         123457 13-M            40058213

inventoryQuantity
id | inventory_item_id | location_id | quantity
-----------------------------------------------
1              40005212         0001        50
2              40058213.        0004         5

vendor
company_id | name | shopify_location_id | logicbroker_id | mage_vendor_id | enable
----------------------------------------------------------------------------------
1000         Kroll                 0001            12574     MagVendID_12       1
1001         Luxo.                 0004            12574     MagVendID_13       0

And here is EXPLAIN SELECT result using about 500 variant IDs: screenshot
id|select_type|table|partitions|type|possible_keys|key|key-len| ref |  rows  |filtered| Extra
1   SIMPLE         v    NULL     ALL    NULL       NULL NULL    NULL    9       100.00  NULL
1   SIMPLE         iq   NULL     ALL    NULL       NULL NULL    NULL    49907   10.00   Using where; Using join buffer (Block Nested Loop)
1   SIMPLE         vid  NULL     ALL    NULL       NULL NULL    NULL    34422   5.00    Using where; Using join buffer (Block Nested Loop)

So, how do I optimize this query to be faster in less than 3 min (around 1 sec or less is better)?

A: You seem to have no keys in your tables.  You probably want primary keys, but you can just create indexes:
create index idx_product_variant on product(variant_id);
create index idx_inventoryQuantity_3 on inventoryQuantity(inventory_item_id, location_id, quantity);
create index idx_vendor_2 on vendor(shopify_location_id, name);


text:
Q: Log into Windows/Mac OS X authorised against users on a Linux server We have a Linux server, and about 10 Mac OS X (10.5 Leopard and 10.6 Snow Leopard) workstations and 5 Windows (mostly 7, some XP) workstations and are looking at expanding.
Is it possible to log into the work stations with user accounts that are centralised on the Linux server?
So for example I could log into any of workstations using my username/password with out setting up a local accounts.
We don't need to store user profiles/files on the server though. (although it would be nice if we could)
The Linux server is Debian and we are also using Samba and ACL's to share files.
Is this possible, and what software should I use to implement this?

A: I have no experience with it myself but you could try OpenLDAP. Your Mac OS clients will let you authenticate against this natively, and there is a client for the Windows workstations.

A: The windows side is easy: Just setup Debian to use OpenLDAP for authentication, configure Samba as a domain controller, put the Windows boxes into the domain and you are done. This is pretty standard stuff and you will find plenty of tutorials on how it's done.
The Mac side is more complicated. Generally, you can authenticate against any LDAP server, but for this to work nicely out of the box, the LDAP server has to be OpenDirectory (MacOS Server) or Active Directory, as these are best supported by Apple. For OpenLDAP to fully work, you will need to add a plethora of custom configuration to your LDAP server and your Mac boxes, but I guess it will be significantly easier if you don't need roaming profiles.


text:
Q: Remove values from array inside a hash I have a hash %m_h with a couple of different data types inside. I want to remove the item 'q20_bases' from the array in $VAR4 but can't figure out how.
Data Structure (From print Dumper %m_h)
$VAR1 = 'run_m';
$VAR2 = [
          'run_id',
          'machine',
          'raw_clusters',
          'passed_filter_reads',
          'yield'
        ];
$VAR3 = 'ln_m';
$VAR4 = [
          'run_id',
          'lane_number',
          'read_number',
          'length',
          'passed_filter_reads',
          'percent_passed_filter_clusters',
          'q20_bases',
          'q30_bases',
          'yield',
          'raw_clusters',
          'raw_clusters_sd',
          'passed_filter_clusters_per_tile',
          'passed_filter_clusters_per_tile_sd',
          'percent_align',
          'percent_align_sd'
        ];

I tried delete $m_h{'q20_bases'}; though it did nothing and I'm not sure what direction to head in.

A: delete removes a key and the associated value from a hash, not an element from an array.
You can use grep to select the elements of the array that are different to q20_bases.
$m_h{ln_m} = [grep $_ ne 'q20_bases', @{ $m_h{ln_m} }];

or
@{ $m_h{ln_m} } = grep $_ ne 'q20_bases', @{ $m_h{ln_m} };

You can also use splice to remove an element from an array, but you need to know its index:
my ($i) = grep $m_h{ln_m}[$_] eq 'q20_bases', 0 .. $#{ $m_h{ln_m} };
splice @{ $m_h{ln_m} }, $i, 1;

You can see that you always need to dereference the value with @{...} to get the array from the array reference. Recent Perls also provide an alternative syntax for it:
$m_h{ln_m}->@*


text:
Q: pandas with Sumo traci: error raise valueError: Shape of passed values is (7, 1), indices imply (7, 7) hello I'm working with Traci libary in Sumo in python as i'm trying to get all trace information and put it in excel file
and i get this error when i pass the data to dataframe can anyone help me where is it wrong and how to fix it??
Traceback (most recent call last):
dataset = pd.DataFrame(parkingList,  index=None ,columns=columnnames)
_check_values_indices_shape_match(values, index, columns)
raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
ValueError: Shape of passed values is (7, 1), indices imply (7, 7)
here is my code :
   import traci
   import time
   import traci.constants as tc
   import pytz
   import datetime
   from random import randrange
   import pandas as pd

   def getdatetime():
    utc_now = pytz.utc.localize(datetime.datetime.utcnow())
    currentDT = utc_now.astimezone(pytz.timezone("Asia/Riyadh"))
    DATIME = currentDT.strftime("%Y-%m-%d %H:%M:%S")
    return DATIME

   sumoCmd = ["sumo", "-c", "cologne6to8.sumocfg"]
   traci.start(sumoCmd)

while traci.simulation.getMinExpectedNumber() > 0:

    traci.simulationStep();

 ParkingAreas = traci.parkingarea.getIDList();

    for i in range(0,len(ParkingAreas)):

      paid = ParkingAreas[i]
      lane = traci.parkingarea.getLaneID(ParkingAreas[i])
      startpos = traci.parkingarea.getStartPos(ParkingAreas[i])
      endpos =  traci.parkingarea.getEndPos(ParkingAreas[i])
      vehCount = traci.parkingarea.getVehicleCount(ParkingAreas[i])
       vehid = traci.parkingarea.getVehicleIDs(ParkingAreas[i])

  parkingList = [getdatetime(), paid, lane, startpos, endpos, vehCount, vehid]

   traci.close()

    #Generate Excel file
columnnames = ['dateandtime', 'parkingAreaID', 'Lane', 'start pos', 'end pos',
 'numVehStops', 'vehIDsAtStop']

dataset = pd.DataFrame(parkingList,  index=None ,columns=columnnames)

dataset.to_excel("outputparking.xlsx", index=False)
time.sleep(5)

A: when collecting the data you probably want to do something like
parkingList.append((getdatetime(), paid, lane, startpos, endpos, vehCount, vehid))

to add another row to your data collection. This also means you will need to initialize the parkingList as an empty list in the beginning


text:
Q: Correct multithreaded lemmatization using spaCy I'm trying to multithread the lemmatization of my corpus using spaCy. Following the documentation, this is currently my approach:
import spacy
nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner', 'tagger'])

def lemmatize():
    for doc in nlp.pipe(corpus, batch_size=2, n_threads=10):
        yield ' '.join([token.lemma_ for token in doc])

new_corpus = list(lemmatize())

However, this takes the same amount of time regardless when using 10 or 1 thread (I use it on 100.000 documents), suggesting that it is not multithreaded.
Is my implementation wrong?

A: The n_threads argument has been deprecated in newer versions of spacy and doesn't do anything. See the note here: https://spacy.io/api/language#pipe
Here's their example code for doing this with multi-processing instead:
https://spacy.io/usage/examples#multi-processing


text:
Q: max and min of $f(x,y)=\log(1-{x \over 2}-{y \over 4})$ in $D$ I have $D=\{(x,y) \in R^2: x^2+y^2\le 1\}$. In $D$ there aren't stationary points because gradient isn't null. On the boundary?

A: Use Lagrange multiplier
$$F(x,y,k)=k \left(x^2+y^2-1\right)+\log \left(-\frac{x}{2}-\frac{y}{4}+1\right)$$
Set equal to zero all partial derivatives
$
\left\{
\begin{array}{l}
 2 k x-\dfrac{1}{2 \left(-\frac{x}{2}-\frac{y}{4}+1\right)}=0 \\
 2 k y-\dfrac{1}{4 \left(-\frac{x}{2}-\frac{y}{4}+1\right)}=0 \\
 x^2+y^2-1=0 \\
\end{array}
\right.
$
Which gives $\left(x=-\dfrac{2}{\sqrt{5}},y= -\dfrac{1}{\sqrt{5}}\right);\;\left(x=\dfrac{2}{\sqrt{5}},y= \dfrac{1}{\sqrt{5}}\right)$
See the max and min on the circumference $x^2+y^2=1$ which is represented as a cylinder in the picture. Max and min are along the intersection between the surface $f(x,y)$ and the cylinder
Hope this helps
$$...$$


text:
Q: Construct a correlation matrix based on pairwise correlation coefficients For the purpose of simulation, I would like to construct such a correlation matrix that would respect to some extend the given set of preferable/desirable correlation coefficients for each pair of variables.
I tried filling in a matrix with the given coefficients and then enforcing the sum of absolute values of off-diagonal entries in each row/column to be smaller than one. It works, but it considerable weakens the given correlations, which I would like to avoid (as much as possible).
I would appreciate any suggestions. Thank you!
Regards,
Ivan

A: Arranging the correlations into a matrix: Let $\rho_{ij}$ be the correlation between variables $i$ and $j$. Place $\rho_{ij}$ into positions $(i,j)$ and $(j,i)$ of the correlation matrix. Note that $\rho_{ii}=1$, so place $1$'s down the diagonal. If the set of correlations is consistent, the matrix you have is a proper correlation matrix.
Sometimes (depending on how they were obtained), it turns out that the set of correlations doesn't form a proper correlation matrix. One way to check whether you do is to take the singular value decomposition and check all the singular values are non-negative.
[Such problems with a matrix that is "put together" are common. For example, pairwise correlation coefficients may have been generated from sets of observations where - due to partially missing observations, for example - different observation-pairs are available between different pairs of variables. If pairwise correlations are computed on all available data, sometimes the resulting correlation matrix is not positive semi-definite.]
If the constructed correlation matrix is not positive semi-definite, one simple approach to finding a valid correlation matrix near to the constructed one is to compute a singular-value decomposition and then set all negative singular values to zero, at which point you have the SVD of a correlation matrix which is often fairly close to the original. (There are alternatives, such as described at the link I gave in comments.)


text:
Q: Sending information an email using the On Insert macro I am pretty new to using MS Access and Sharepoint etc, so your help is greatly appreciated.
I have setup a basic system on Access that allows you to log a technical support ticket on Sharepoint Web App.
When a new ticket is added to the system I have it setup to send an email. However I would like the body of email to contain the Ticket Number, which is Field Name 'ID'.
For example:

To: My email address
Cc:
Bcc:
Subject: Ticket Number: [ID] has been added to the system.
Body: Please review ticket Number: [ID]

I have searched the net and found lots of information about using SetLocalVar etc but I am struggling to understand it.

A: I have got this working now after setting the LocalVar
SetLocalVar
Name: varTicketID
Expression: = [ID]
for Ticket Number and using the following Syntax in the Subject:
=Concat("Ticket Number ",[varTicketID],"has been added to the system") –


text:
Q: Multiple function invocations in javascript ie combine(foo)(bar) I have seen in the past that you can do something like this:
function combine(arg1){
   return function(arg2){
      return (arg1 + arg2);
   };
}
combine("foo")("bar");

And the result will be "foobar".
You can of course do something like:
(function(x){
    return function(y){
       return x+y;
    };
})(2)(3);

With the result of 5.
I am simply wondering what this is called. I think I saw a small video of Crockford that I can't seem to find, I am sure it was on the Good Parts, that briefly talked about this. I also have the book and I can't see it in there.
It seems like just another way to invoke a function and control the scope of the variables.

A: I believe you are looking for the word Currying

A: Rchristiani, the video where Crockford references a function that adds from two invocations can be found on YouTube. It's part of a FrontEndMasters.com workshop series.
Test Your Knowledge of Function Scope with Douglas Crockford: http://youtu.be/hRJrp17WnOE
Crockford's site contains a copy of an excellent, and mind-blowing, breakdown of Currying. (I'm not sure who the original author is.) It shows examples of multiple invocations.
http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html

A: If you are referring to the ability of the inner function to access the variables from the outer function, this is called a closure.
You can read up closures here:
How do JavaScript closures work?

A: What are you looking for is the Currying, or Partial (it depends if the functions takes more than two arguments or not).
You can actually do that also with bind, from ES5 specs. For instance:
function sum(a, b) {
    return a + b;
}

var sum5 = sum.bind(null, 5);

console.log(sum5(10)); // 15