text:
Q: Performance gain issue in multicore application I have a serial(nonparallel) application written in C. I have modified and re-written it using Intel Threading Building Blocks. When I run this parallel version on an AMD Phenom II machine which is a quad-core machine, I get a performance gain of more than 4X which conflicts with the Amdahl's law. Can anyone give me a reason why this is happening?
Thanks,
Rakesh.

A: If you rewrite the program, you could make it more efficient.  Amdahl's law only limits the amount of speedup due to parallelism, not how much faster you can make your code by improving it.
You could be realizing the effects of having 4x the cache, since now you can use all four procs.  Or maybe having less contention with other processes running on your machine.  Or you accidentally fixed a mispredicted branch.
TL/DR: it happens.

A: It's known as "super linear speedup", and can occur for a variety of reasons, though the most common root cause is probably cache behaviour.  Usually when superlinear speedup occurs, it's a clue that you could make the sequential version more efficient.
For example, suppose you have a processor where some of the cores share an L2 cache (a common architecture these days), and suppose your algorithm makes multiple traversals of a large data structure.  If you perform the traversals in sequence, then each traversal will have to pull the data into the L2 cache afresh, whereas if you perform the traversals in parallel then you may well avoid a large number of those misses, as long as the traversals run in step (getting out of step is a good source of unpredictable performance here).  To make the sequential verison more efficient you could interleave the traversals, thereby improving locality.

A:
Can anyone give me a reason why this is happening?

In a word, caches.
Each core has its own L1 cache and, therefore, simply by using more cores you have increased the amount of cache in-play which has, in turn, brought more of your data closer to where it will be processed. That alone can improve performance significantly (as if you had a bigger cache on a single core). When combined with near linear speedup from effective parallelization, you can see superlinear performance improvements overall.


text:
Q: Loading data to Remote SQL Server Database I need some suggestions about a problem in hand. I receive some report  containing some financial transactions in Excel files. The Excel data needs to be loaded to a SQLServer Database running  behind fire wall. The file is transmitted to a Windows machine which does not have access to the SQL Server over port 1433.
So is there any other option to load the Excel content (we can convert it to XML if need be) other than web services.
Is it possible to use XMLBulk load under such circumstances?
In case web services is the only option what is the best practice for bulk loading data through web services.
Thanks for sparing you time.

A: You can use SSIS in order to convert data of your excel file to SQL Server.
SSIS run on the server and must be access to your excel file from network.
In this method windows firewall not effect to your process.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing Material Table with api call Angular I have been developing an application with Angular 2 and it has admittedly been a struggle doing so as a new developer.  I've managed quite a bit so far but I do need some assistance.  I'm including a plunkr that I'm using for reference to get a Material Table with pagination, filter and sort, but this example, as well as all of the other examples on material.angular.io show an example with a database that's essentially hardcoded/generated in the component class.  I have a service that calls the api for an SQL query and I'd like to populate the table in the example with that, however my attempts so far have been miserable failures and I think I've overwhelmed myself in the process.
By request I can post my component code, but I fear that I've gutted/revised it beyond the point of any use.  But until then below is the plunkr with what I want to implement, and the service class I'd like to use to populate the data table in place of the plunkr's database and data source.
Please let me know if you can help, you'd be saving me a huge headache.
https://plnkr.co/edit/EU3BBlViWpPf2NJW4PXx?p=preview
My service
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RcgqueueService {

  constructor(private http: Http) { }

  populateRCGQueue() {
    return this.http.get('/api/rcgqueue').map(res => res.json());
  }
}

And my current pathetic attempt at the component code
import { Component, ElementRef, ViewChild, OnInit, forwardRef } from '@angular/core';
import { DataSource, SelectionModel } from '@angular/cdk/collections';
import { MatPaginator, MatSort, MatTable } from '@angular/material';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/debounceTime';
import { RcgqueueService } from './rcgqueue.service';

@Component({
  selector: 'app-rcgqueue',
  templateUrl: './rcgqueue.component.html',
  styleUrls: ['./rcgqueue.component.css']
})
export class RcgqueueComponent implements OnInit {
  isDataAvailable = false;
  displayedColumns = ['changeId', 'changeTitle', 'dateSubmitted', 'changeSponsor', 'changeDescription'];
  dataChange: BehaviorSubject<ChangeData[]> = new BehaviorSubject<ChangeData[]>([]);
  get data(): ChangeData[] { return this.dataChange.value; }
  dataSource: ExampleDataSource | null;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(forwardRef(() => MatSort)) sort: MatSort;
  @ViewChild('filter') filter: ElementRef;

  constructor(private rcgservice: RcgqueueService) {
  }
  populateRCGQueue() {
    this.rcgservice.populateRCGQueue().subscribe(rcgitems => {
      this.dataChange = rcgitems;
      this.isDataAvailable = true;
    })
  }

  ngOnInit() {
    this.populateRCGQueue();
    this.dataSource = new ExampleDataSource(this, this.paginator, this.sort);
    Observable.fromEvent(this.filter.nativeElement, 'keyup')
      .debounceTime(150)
      .distinctUntilChanged()
      .subscribe(() => {
        if (!this.dataSource) { return; }
        this.dataSource.filter = this.filter.nativeElement.value;
      });
  }
}

export interface ChangeData {
  ChangeId: string;
  ChangeTitle: string;
  DateSubmitted: string;
  ChangeSponsor: string;
  ChangeDescription: string;
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  _filterChange = new BehaviorSubject('');
  get filter(): string { return this._filterChange.value; }
  set filter(filter: string) { this._filterChange.next(filter); }

  dataChange: BehaviorSubject<ChangeData[]> = new BehaviorSubject<ChangeData[]>([]);
  get data(): ChangeData[] { return this.dataChange.value; }

  filteredData: ChangeData[] = [];
  renderedData: ChangeData[] = [];

  constructor(private rcgcomponent: RcgqueueComponent,
    private _paginator: MatPaginator,
    private _sort: MatSort) {
    super();

    this._filterChange.subscribe(() => this._paginator.pageIndex = 0);
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<ChangeData[]> {
    // Listen for any changes in the base data, sorting, filtering, or pagination
    const displayDataChanges = [
      this.rcgcomponent.dataChange,
      this._sort.sortChange,
      this._filterChange,
      this._paginator.page,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      // Filter data
      this.filteredData = this.rcgcomponent.data.slice().filter((item: ChangeData) => {
        const searchStr = (item.ChangeDescription + item.ChangeSponsor).toLowerCase();
        return searchStr.indexOf(this.filter.toLowerCase()) !== -1;
      });

      // Sort filtered data
      const sortedData = this.sortData(this.filteredData.slice());

      // Grab the page's slice of the filtered sorted data.
      const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
      this.renderedData = sortedData.splice(startIndex, this._paginator.pageSize);
      return this.renderedData;
    });
  }

  disconnect() { }

  /** Returns a sorted copy of the database data. */
  sortData(data: ChangeData[]): ChangeData[] {
    if (!this._sort.active || this._sort.direction === '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number | string = '';
      let propertyB: number | string = '';

      switch (this._sort.active) {
        case 'changeId': [propertyA, propertyB] = [a.ChangeId, b.ChangeId]; break;
        case 'changeTitle': [propertyA, propertyB] = [a.ChangeTitle, b.ChangeTitle]; break;
        case 'dateSubmitted': [propertyA, propertyB] = [a.DateSubmitted, b.DateSubmitted]; break;
        case 'changeSponsor': [propertyA, propertyB] = [a.ChangeSponsor, b.ChangeSponsor]; break;
        case 'changeDescription': [propertyA, propertyB] = [a.ChangeDescription, b.ChangeDescription]; break;
      }

      const valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      const valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction === 'asc' ? 1 : -1);
    });
  }
}

I've removed anything having to do with selection from the table from the plunkr code, what is left here is where I am currently.  I'm very sorry if this ends up more hindering than helpful.
Oh and this may be helpful, my api.js on the server side with the query I'm using. (The only one so far)
const express = require('express');
const async = require('async');
const jwt = require('jsonwebtoken');
const shape = require('shape-json');
const router = express.Router();

var sql = require('mssql/msnodesqlv8');
var config = {
    driver: 'msnodesqlv8',
    connectionString: 'Driver=SQL Server Native Client 11.0;Server=localhost;Database=Change;Trusted_Connection=yes;',
}

var conn = new sql.ConnectionPool(config);
conn.connect().then(function() {
     log("Change Governance Database Connection opened");
}).catch(function (err) {
    console.error(new Date() + " - Issue connecting to the MS SQL database.", err);
});

router.get('/', (req, res) => {
    res.send('api works');
});

router.get('/rcgqueue', (req, res) => {
    new sql.Request(conn)
    .query('SELECT ChangeId, ChangeTitle, DateSubmitted, ChangeSponsor, ChangeDescription FROM dbo.ChangeEvaluationForm;')
    .then(function(recordset) {
        log("Successful query request for RCG Records.");
        res.send(recordset.recordset);
    }).catch(function(err) {
        log(err);
        res.send("Issue querying database!");
    });
});

/********************************/
/*          Functions           */
/********************************/
// Log lines with date/time for server
function log(msg) {
    console.log(new Date() + " - " + msg);
};

module.exports = router;

EDIT: Adding template and errors.
Template

      <md-input-container floatPlaceholder="never">
        <input mdInput #filter placeholder="Filter">
      </md-input-container>

    <md-table #table [dataSource]="dataSource" mdSort>

      <ng-container cdkColumnDef="changeId">
        <md-header-cell *cdkHeaderCellDef md-sort-header> ChangeId </md-header-cell>
        <md-cell *cdkCellDef="let row"> {{row.ChangeId}} </md-cell>
      </ng-container>

      <ng-container cdkColumnDef="changeTitle">
        <md-header-cell *cdkHeaderCellDef md-sort-header> Change Title </md-header-cell>
        <md-cell *cdkCellDef="let row"> {{row.ChangeTitle}}% </md-cell>
      </ng-container>

      <ng-container cdkColumnDef="dateSubmitted">
        <md-header-cell *cdkHeaderCellDef md-sort-header> Date Submitted </md-header-cell>
        <md-cell *cdkCellDef="let row"> {{row.DateSubmitted}} </md-cell>
      </ng-container>

      <ng-container cdkColumnDef="changeSponsor">
        <md-header-cell *cdkHeaderCellDef md-sort-header> Change Sponsor </md-header-cell>
        <md-cell *cdkCellDef="let row"> {{row.ChangeSponsor}} </md-cell>
      </ng-container>

      <ng-container cdkColumnDef="changeDescription">
        <md-header-cell *cdkHeaderCellDef md-sort-header> Change Description </md-header-cell>
        <md-cell *cdkCellDef="let row"> {{row.ChangeDescription}} </md-cell>
      </ng-container>

      <md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
      <md-row *cdkRowDef="let row; columns: displayedColumns;">
      </md-row>
    </md-table>

      No changes found matching filter.

    <md-paginator #paginator [length]="dataSource.filteredData.length" [pageIndex]="0" [pageSize]="25" [pageSizeOptions]="[5, 10, 25, 100]">
    </md-paginator>

And finally a screenshot of my errors

A: The reason why you are getting

Cannot set property pageIndex of undefined

is that you wrap table in *ngIf and by the time you pass @ViewChilds to DataSource class they are not initialized yet.
I solved it by calling initialization after getting data:
this.rcgservice.populateRCGQueue().subscribe(rcgitems => {
  this.dataChange.next(rcgitems);
  this.isDataAvailable = true;
  this.cdRef.detectChanges(); // make sure that all ViewChilds were initialized
  this.initSource();

Another mistake is that you assign data to BehaviourSubject
this.rcgservice.populateRCGQueue().subscribe(rcgitems => {
   this.dataChange = rcgitems;

it should be:
this.dataChange.next(rcgitems);

I also added some safe navigation operators to your template:
[length]="dataSource?.filteredData.length"

and
[style.display]="dataSource?.renderedData.length == 0 ? '' : 'none'"

Plunker Example
If we don't use ngIf then we do not need ChangeDetectorRef anymore
Plunker Example


text:
Q: GCalendar: Fee / Busy-Setting per Script which command is responsible for the fee/busy-Setting in GCalendar?

Thanks

A: https://developers.google.com/apps-script/reference/calendar/ has all of the enumerated properties, busy/free doesn't seem to be one you can get at from calendar service. I personally put in "interrupt ok" to a bunch of my block names.


text:
Q: DropDownListFor value empty after Postback to Controller I develop a web application below ASP.NET MVC 4 with Razor Views.
I noticed now that SomethingID is empty in the ViewModel after Postback (to the Controller)if I only add the disabled HTML attribute to DropDownListFor:
// SomethingID becomes 0:
@Html.DropDownListFor(m => m.SomethingID, Model.SomethingList, new { @disabled = "disabled" })

It doesn't happen if I remove the disabled Attribute, SomethingID has the proper value then:
// SomethingID keeps its value (greater than 0):
@Html.DropDownListFor(m => m.SomethingID, Model.SomethingList)

Has someone experienced that problem already?
At the moment, I try to solve the problem with jQuery, by storing the value in a HiddenFor field.
But my question would be: Is there a better solution? Is it intended behaviour from Microsoft that Dropdownlists shall forget everything as soon as they are disabled? Do I do a mistake? Is it a bug?
Remark: I have 5 Dropdownlists in my View, all 5 show the same behaviour.
Many thanks in advance!!!

A: Quite simply the reason you are seeing this is because elements that have the disabled attribute do not have their values posted to the server. See this SO post for more detail.


text:
Q: How append classes dynamically in jquery in one of my variable i have something like
var x='.myclass'.
Now I want to append this var x while traversing the dom in jQuery.What should be the exact format for that.
Lets say I want to write
$("div.myclass a").someoperation();

now this .myclass has to dynamic, so I am trying something like
$("div"+x+"a").someoperation()

but this is not working, any clue.

A: I think you missed a space here:
$("div"+x+" a").someoperation()

A: $("div"+x+" a").someoperation();

Just missing a space?

A: var x = '.myclass';
$('div' + x + ' a').someoperation();

is equivalent to:
$('div.myclass a').someoperation();

so if the first doesn't work as the second it is because the value of x is not .myclass.

A: Here is another alternative
where x is ".myclass"
$('div').find(x).find('a')

A: x='.'+var_className
$("div"+x+" a").someoperation();


text:
Q: 500 Internal Server Error on POST call to /index.html in Angular application I'm working on an angular application. I'm facing this issue, and I need some help solve it.
When I perform a GET operation on http://<myapp>/index.html, it works fine.
When I perform a POST operation on http://<myapp>/index.html, it returns 500 Internal Server Error with no content in the response body or header.
I looked into RouterModule.forRoot in app.module.ts but couldn't find any option to filter out POST call alone.
This is an Asp.Net Core MVC application that I'm running.
I'm new to angular. I'm not sure which path to follow. Any help would be appreciated.
Thanks.

A: I recently got into the same issue and from my investigation the code is behaving differently depending on the environment (Development vs Production )
On the development if you do a POST to /index.html you get 404, on production you get 500. I also raised a GitHub issue: https://github.com/dotnet/aspnetcore/issues/34420
My temporary solution was to add a middleware and catch the exception coming from UseSpa middleware
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ......
    app.Use(async (context, next) =>
    {
        //Redirect to root request to /index.html ( except the GET request )
        //Do not generate logs for requests originating from automated tools: POST /Index.html, OPTIONS /index.html, DEBUG /index.htm, etc..
        if (!HttpMethods.IsGet(context.Request?.Method)
            && context.Request?.Path.Value.ToLower() == "/index.html")
        {
            context.Response.Redirect("/");
            return;
        }

        try
        {
            await next();
        }
        catch (InvalidOperationException spaException)
        {
            if (spaException.Message.StartsWith("The SPA default page middleware could not return the default page"))
            {
                context.Response.StatusCode = StatusCodes.Status404NotFound;
                return;
            }
            throw;
        }
    });

    app.UseSpa(...);
    .....
}


text:
Q: Capturing windows keyboard strokes while script isn't current used process I am trying to make an application that redoes my exact movements on keyboard on a certain process, so I am attempting to register my keyboard strokes time-stamped, I tried to do it using msvcrt or pygame, however they both require keys to be entered to the command prompt itself, else it wont detect it.
Is it possible to create a time-stamped "keylogger" using PYTHON
P.S: I just want to learn more about python scripting.
this is the code i tried:
import msvcrt
import time
import datetime
while True:
    char = msvcrt.getch()
    print char
    print datetime.datetime.now().time()

A: What you've written is a program that captures inputs to itself.  What you need, at least for Windows, are global input hooks.  This will allow your application to capture all input to the machine.
Take a look at the following resources:
Windows Hooks Overview
Python for Windows Extensions
PyHook, a Python wrapper for global input hooks


text:
Q: My WordPress theme style.css override admin theme I create a new WordPress theme in WordPress latest version 4.5.1. and some theme css override in admin theme. How can I block this css for admin area?

A: Use wp_enqueue_style to add css/js to front end.
add_action('wp_enqueue_style', 'some_hook_function'):

Use admin_enqueue_scripts to add css/js to back end.
add_action('admin_enqueue_scripts', 'some_hook_function'):


text:
Q: Dynamically Generate Form Row With Select Populated From Database Here's my dilema. In Laravel, I'm passing inspections to the view like so:
$inspections = Inspection::where("status", "!=", "started")->get();
return View::make('process')->with("inspections", $inspections);

Inspections contains a list of all the Inspections that are passed the started stage. In the view, I'm creating a form to process these Inspections like so:

    <select class="form-control input-sm" name="inspection[0]">
      <option value=""></option>
      @foreach($inspections AS $inspection)
      <option value="{{ $inspection->id }}">{{ $inspection->submission_number }} - {{ $inspection->policy_number }} - {{ $inspection->location_address }}</option>
      @endforeach
    </select>

  <input type="radio" name="received[0]" value="yes" >Yes<input type="radio" name="received[0]" value="no" >No
  <input id="i_on_0" type="radio" name="invoiced[0]" value="yes" onclick="toggleInvoice(this);" data-row="0"/>Yes<input id="i_off_0" type="radio" name="invoiced[0]" value="no" onclick="toggleInvoice(this);" data-row="0"/>No
  <input type="hidden" id="in_0" name="invoice_number[0]" disabled/>
  <input type="text" id="ia_0" name="invoice_amount[0]" class="form-control input-sm" disabled/>
  <input type="radio" id="p_on_0" name="paid[0]" value="yes" disabled/>Yes<input type="radio" id="p_off_0" name="paid[0]" value="no" disabled/>No

Which creates the following:

This is fine and dandy, but I have no idea how to append another row to this table and still display the value of each option. Right now, I have my + button call the following function in Javascript:
function appendProcessingRow(){
  var current_row = $("#processing_table tr:last").attr("data-row");
  var content = '
<input type="text" name="policy_number[' + (parseInt(current_row) + 1) + ']" class="form-control input-sm"/>	<input type="radio" name="received[' + (parseInt(current_row) + 1) + ']" value="yes">Yes<input type="radio" name="received[' + (parseInt(current_row) + 1) + ']" value="no"> No	<input type="radio" name="invoiced[' + (parseInt(current_row) + 1) + ']" value="yes" onclick="toggleInvoice(this);" data-row="' + (parseInt(current_row) + 1) + '"/> Yes<input type="radio" name="invoiced[' + (parseInt(current_row) + 1) + ']" value="no" onclick="toggleInvoice(this);" data-row="' + (parseInt(current_row) + 1) + '"/> No	<input type="hidden" id="in_' + (parseInt(current_row) + 1) + '" name="invoice_number[' + (parseInt(current_row) + 1) + ']" disabled/>><input type="text" id="ia_' + (parseInt(current_row) + 1) + '" name="invoice_amount[' + (parseInt(current_row) + 1) + ']" class="form-control input-sm" disabled/>	<input type="radio" id="p_on_' + (parseInt(current_row) + 1) + '" name="paid[' + (parseInt(current_row) + 1) + ']" value="yes" disabled/> Yes<input type="radio" id="p_off_' + (parseInt(current_row) + 1) + '" name="paid[' + (parseInt(current_row) + 1) + ']" value="no" disabled/> No
';
  $('#processing_table > tbody:last').append(content);
}

Which works, but creates an <input> tag instead of the select option. See the following:

My question, how would I got about creating the same row layout in Javascript, keeping in mind that the select is generated by @foreach in Laravel? Tried putting the:
<select class="form-control input-sm" name="inspection[0]">
  <option value=""></option>
  @foreach($inspections AS $inspection)
  <option value="{{ $inspection->id }}">{{ $inspection->submission_number }} - {{ $inspection->policy_number }} - {{ $inspection->location_address }}</option>
  @endforeach
</select>

Inside the Javascript appendProcessingRow() And it "worked" to an extent, but the values aren't there:

So, any help would be appreciated. Thanks in advance, sorry for the long post.

A: Without going "full ajax" to fetch the options from the server I think cloning the existing row is the easiest approach.
function appendProcessingRow(){
    var lastRow = $("#processing_table tr:last");
    var newRow = lastRow.clone();
    var newId = parseInt(lastRow.data('row'))+1;
    newRow.data('row', newId);
    newRow.prop('id', newId);
    newRow.find('select').prop('selectedIndex', 0);

    // reset other inputs in a similar fashion

    lastRow.after(newRow);
}

Also about your input names... You should be able to just leave them all like policy_number[] without an index. It will automatically put the values in an array (in the order they appear in the html)


text:
Q: Time threshold as where clause I've got this table:
+-----------------+------+----------------+------------+------------------+------+--------+
| date            | host | process        | text       | num1             | num2 | suffix |
+-----------------+------+----------------+------------+------------------+---       0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656871111 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656871111 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656871111 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656871111 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656871111 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | dn     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | dn     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | dn     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | dn     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656872222 |    0 | dn     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | mt     |
| Jul 23 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | mt     |
| Jul 29 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | dn     |
| Jul 29 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | dn     |
| Jul 29 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | dn     |
| Jul 29 09:24:16 | mmr  | mmr-core[1111] | Aweg3AOMTs | 1563866656877777 |    0 | dn     |
+-----------------+------+----------------+------------+------------------+------+--------+

From the table I need to find which num1 id has both suffix mt and dn. Which I with Gordon Linoff' help managed with this query:
SELECT num1
    -> from table4
    -> WHERE suffix IN ('mt', 'dn')
    -> GROUP BY num1
    -> HAVING COUNT(DISTINCT suffix) = 2;

Now the thing is that I need to find num1 which suffix 'dn' is arrived later than 72 hours or don't find the num1 if its dn didn't arrived until 72 hours...
Any help would be really appreciated!!

A: Just slight modification of the query
SELECT num1
FROM table4
WHERE suffix = 'mt' or (suffix = 'dn' and `date` > NOW() - INTERVAL 72 HOUR)
GROUP BY num1
HAVING COUNT(DISTINCT suffix) = 2;

A: You can use conditional aggregation on the date/time values:
SELECT num1
FROM table4
WHERE suffix IN ('mt', 'dn')
GROUP BY num1
HAVING MIN(CASE WHEN suffix = 'dn' THEN date END) < MAX(CASE WHEN suffix = 'mt' THEN date END) + INTERVAL 72 HOUR;

You have multiple rows for 'dn' and 'mt'.  It is not clear if you want the mins or the maxes.  But this comparison givens you an idea of how to proceed.


text:
Q: Passing flags to bash script with case statement - only first flag is set This might be an obvious error but I'm just not seeing it.
I have a case statement which is supposed to enable passing arguments to a script (ex: script.sh --verbose --all).
For some reason, this specific function does not work correctly - it only works on whichever flag I pass first:
#Pass arguments to the script
flags()
{
    while test $# -gt 0
    do
        case "$1" in
        (-v|--verbose)
            shift
            export VERBOSE="1"
            shift;;
        (-vv|--extra-verbose)
            shift
            export VERBOSE="1"
            export EXTRA_VERBOSE="1"
            shift;;
        (-a|--all)
            shift
            export ALL="1"
            shift;;
        (-h|--help)
            usage;;
        (*) usage;;
        esac
    done
}
flags "$@"
echo "Verbose: $VERBOSE, Extra Verbose: $EXTRA_VERBOSE, All: $ALL"

So in this case, if I pass -v -a, the script will only set the $VERBOSE variable. If I pass -a -v, the script will only set the $ALL variable.
I have quite a few scripts using this structure which do not exhibit this.
I'd really appreciate it if you could help me figure out what is it I'm missing.
Thanks!

A: You have too many shift.
It should be done just once, after you processed an argument, you shift to a next one.
#!/bin/sh
#Pass arguments to the script
flags()
{
    while test $# -gt 0
    do
        case "$1" in
        -v|--verbose)
            export VERBOSE="1"
            ;;
        -vv|--extra-verbose)
            export VERBOSE="1"
            export EXTRA_VERBOSE="1"
            ;;
        -a|--all)
            export ALL="1"
            ;;
        -h|--help)
            usage;;
        *) usage;;
        esac

        # and here we shift to the next argument
        shift
    done
}
flags "$@"
echo "Verbose: $VERBOSE, Extra Verbose: $EXTRA_VERBOSE, All: $ALL"


text:
Q: How to make an Android FCM notification service always running in background? I'm currently working on an App that works with topics to inform users about new changes. It actually works pretty good, but only if the app is currently running. If the app is in the background or closed no notification is getting pushed. And that's what I want to change. The app/Notificationservice should allways run in background.
I've allready found some solutions on SO, but wether they weren't Server-Client solutions (with FCM) or they didn't realy worked.
this is the FCM/Notification-Class running on my server:
public static void pushFCMNotification(String DeviceIdKey, String title, String content) throws Exception {

    String authKey = AUTH_KEY_FCM;
    String FMCurl = API_URL_FCM;

    URL url = new URL(FMCurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "key=" + authKey);
    conn.setRequestProperty("Content-Type", "application/json");

    JSONObject data = new JSONObject();
    data.put("to", DeviceIdKey.trim());
    JSONObject info = new JSONObject();
    info.put("title", title); // Notification title
    info.put("content-text", content); // Notification body
    info.put("click_action", ".MainActivity");
    data.put("data", info);

    System.out.println(data.toString());
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data.toString());
    wr.flush();
    wr.close();

    int responseCode = conn.getResponseCode();
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

}

//test method
public static void main(String[] args) throws Exception {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    FCMNotification.pushFCMNotification("/topics/general",   dateFormat.format(date), "dracky");
}
}

These are my FCM classes running on Android:
1. FCM_Instance_ID_Service.java
public class FCM_Instance_ID_Service extends FirebaseInstanceIdService {
    final String tokenPreferenceKey = "fcm_token";
final static String infoTopicName = "info";

private static final String REG_TOKEN = "REG_TOKEN";

@Override
public void onTokenRefresh() {

    super.onTokenRefresh();
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.edit().putString(tokenPreferenceKey, FirebaseInstanceId.getInstance().getToken()).apply();

    FirebaseMessaging.getInstance().subscribeToTopic(infoTopicName);

}
}

2. FCM_Messaging_Service.java
public class FCM_Messaging_Service extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    super.onMessageReceived(remoteMessage);

    if (remoteMessage.getFrom().equals("/topics/" + FCM_Instance_ID_Service.infoTopicName)) {
        displayNoification(remoteMessage.getData().get("title"), remoteMessage.getData().get("content-text"), this);

    } else {
        displayNoification(remoteMessage.getData().get("title"), remoteMessage.getData().get("content-text"), this);
    }

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    // Vibrate for 500 milliseconds
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
    } else {
        //deprecated in API 26
        v.vibrate(500);
    }

    //startAlarm(true, false);
    }

@SuppressLint("NewApi")
public void displayNoification(String title, String contentText, Context context) {
    Notification notification = null;

    notification = new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(contentText)
            .setSmallIcon(R.mipmap.ic_launcher_round)

            .setLights(Color.RED, 3000, 3000)
            .setSound(Uri.parse("android.resource://"
                    + context.getPackageName() + "/" + R.raw.alarm))
            .setLargeIcon(BitmapFactory.decodeResource(
                    getResources(), R.mipmap.ic_launcher))
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(14, notification);
}
}

This is my manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.ddns.kodiakscloud.fastalker">

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name=".MainActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <service android:name=".FCM_Messaging_Service">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".FCM_Instance_ID_Service">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <activity android:name=".BrowserActivity" />
        <activity android:name=".ReviewActivity" />
        <activity android:name=".WatchListActivity"></activity>
    </application>

</manifest>

Does anybody have an idea?

A: I think this is not a problem of FCM nor notification service. I think it's a problem of some devices. Check my answer in a similar post and maybe this helps you.
Notifications not received on Android


text:
Q: Extract and Search a Column I have a {{!COL4}} set previous in my script, but i need to make a validation if the specific value exists in the page.
I tried the following code but seems the format is wrong
SET !VAR4 EVAL("var q = '{{!EXTRACT}}'.match(/\\'{{!COL4}}'\\/ig); if (!q) MacroError(\"ERROR - NO RECORD FOUND\"); else 'FOUND';")

A: Ok i found the correct format, thanks anyway!
SET !VAR4 EVAL("var q = '{{!EXTRACT}}'.match('{{!COL4}}'); if (!q) MacroError(\"ERROR - NO RECORD FOUND IN FIND\"); else ('{{!COL4}}');")


text:
Q: How to input unicode character and get its numeric value I am trying to take a file and remove all characters that are not in the greek language. We found the unicode values for the alphabet, 880 - 1023, and were able to print out the correct characters with a simple print(unichr(880)) line. The problem is when running this code
greek ='ÏÎ'
for c in greek:
    if(unichr(c) >= 880 and unichr(c) <= 1023):
        print(c)

Is there a way to enter any letter or symbol that will return a unicode value. We have tested with values inside of the greek range and outside and still get the same error, UnicodeDecodeError: 'ascii' codec cannot decode byte 0xc3 in position 0: ordinal not in range(128)

A: unichr accepts an integer and returns a unicode character. My first suggestion is that you replace unichr with ord here, since you're passing in a string and want to get back an integer that represents a unicode code point.
Now for the Unicode decode errror—I suspect that it's occurring because print is implicitly trying to encode your unicode string, but doesn't know how to do so. You might have more luck if you explicitly encode your unicode string with utf-8. Try this:
greek = u'ÏÎ'
for c in greek:
    if(ord(c) >= 880 and ord(c) <= 1023):
        print(c.encode('utf-8'))

A: You definitely want to use ord, it is like the inverse function of chr or unichr:
>>> x = unichr(1000)
>>> ord(x)
1000
>>> y = unichr(880)
>>> y
u'\u0370'
>>> ord(y)
880
>>> help(ord)
Help on built-in function ord in module __builtin__:

ord(...)
    ord(c) -> integer

    Return the integer ordinal of a one-character string.

so you pass it a unicode character and it gives you the ordinal of the character.

A: You have several problems. Assuming this is python 2 (since there is no unichr in python 3 you'd get a different error) your first problem is that you didn't initialize a unicode string in the first place.
>>> greek ='ÏÎ'
>>> len(greek)
4

These aren't 2 unicode characters... they are 4 single byte characters that also happen to be the utf-8 encodings of the unicode characters. Instead do
greek =u'ÏÎ'

Next, these are not the droids, I mean greek characters, you think they are.
>>> ord(greek[0])
207

These are codepage characters in the 128-255 range and are outside of the range you are looking for. Did you want these instead?
>>> greek = u'Ϊΐ'
>>> ord(greek[0])
938

Finally, unichr goes the wrong way... it converts ordinals to characters but you wanted to go the other way. So,
>>> for c in greek:
...     if ord(c) >= 880 and ord(c) <= 1023:
...         print(c)
...
Ϊ
ΐ

A: You must make sure your editor saves your program in UTF-8 encoding. This depends on the text editor you use.  If you use IDLE, it will suggest to add the coding line when you save.
Also, no need to enclose conditions in parentheses, and you can use short .
This is for python 3
# -*- coding: utf-8 -*-
greek ='ÏÎ'
for c in greek:
  if 880 <= ord(c) <= 1023:
    print(c)

(In my screen, the two characters appear as capital I with tilde accent and capital I with circumflex accent--replace with appropriate characters).


text:
Q: Random process with very high rate of convergence Write down a sequence of random (positive, whole) numbers which are not very large (say within a factor of ten or so) compared to its length.  Start anywhere not very far from the end of the sequence (say within the first half or so). Walk as many numbers down the line as there are units contained in the number you are currently in. Do this repeatedly until you can no longer do so without extrapolating the sequence. I will then say you are at your final destination. Then, for almost all such sequences and almost all initial positions, the final destination is a constant which depends only on the sequence, but not on the initial position. (In a sense I cannot define precisely but if you do the experiment with concrete numbers, you will see that the probabilities are astoundingly high).
Does anyone know the name of this phenomenon?
Does anyone know an explanation for it?
Thank you for your answer(s).


text:
Q: nspasteboard readObjectsForClasses blows up I am trying to implement a simple drag and drop operation in a tableView. However, when I try to retrieve the data from the pasteboard using readObjectsForClasses, I get a runtime exception saying
"[__NSCFConstantString initWithBytes:length:encoding:]: unrecognized selector sent to instance  "
This is my acceptDrop method where the problem occurs. Can someone please help point out what I am doing wrong.
  (BOOL) tableView: (NSTableView *) view
    acceptDrop: (id ) info
           row: (NSInteger) row
 dropOperation: (NSTableViewDropOperation) op
   {

   NSArray *pBoardClasses = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:[NSStringPboardType class], [NSDragPboard class], nil]];
   NSPasteboard *board =[info draggingPasteboard];

   if(![board canReadObjectForClasses:pBoardClasses options:nil])
   {
    NSLog(@"No acceptable data format in pasteboard. Cannot perform this operation!");
    return NO;
   }

   NSArray * dFromPboard = [board readObjectsForClasses:pBoardClasses options:nil];

   }

A: use [NSString class] instead of [NSStringPboardType class]
also: [NSDragPboard class] looks like it's not right. Remove this and test if it works with [NSString class] only.
NSArray *stringObjects = [pboard readObjectsForClasses:@[ [NSString class], [NSAttributedString class] ] options:@{}];
    if(stringObjects.count > 0) {
        NSString *myStr = stringObjects[0];
        //…
    }
//…


text:
Q: Trimming of SQL Database values from my c# application Am trying to achieve trimming my comboBox whch is getting data from my SQL Server. Am aware that the Trim function should be used. I have applied it in various ways but seem to still be faced with white spaces from my database. How do I go about including the Trim function effectively?
void fill()//fill combobox with values
{
    try
    {
        string connectionString = "Data Source=cmcentraldb;Initial Catalog=CMLTD;Integrated Security=True";
        SqlConnection con2 = new SqlConnection(connectionString);
        con2.Open();
        string query = "SELECT DISTINCT ITEMDESC  FROM dbo.IV00101";
        //select Convert(nvarchar(50),Item_Description)+ ':' +Convert(nvarchar(50),Item#) as Combined from Carimed
        SqlCommand cmd2 = new SqlCommand(query, con2);

        SqlDataReader dr2 = cmd2.ExecuteReader();
        while (dr2.Read())
        {
            string cari_des = dr2.GetString(dr2.GetOrdinal("ITEMDESC"));
            suggestComboBox1.Items.Add(cari_des);
            suggestComboBox1.Text.Trim();
        }
        //con2.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

A: You need to trim the items that you Add to the combobox
suggestComboBox.Items.Add(cari_des.Trim());

you can delete the line, it does nothing:
suggestComboBox1.Text.Trim();     // delete this

A: You need to trim value before binding it to combobox. Do it like below:
void fill()//fill combobox with values
{
    try
    {
        string connectionString = "Data Source=cmcentraldb;Initial Catalog=CMLTD;Integrated Security=True";
        SqlConnection con2 = new SqlConnection(connectionString);
        con2.Open();
        string query = "SELECT DISTINCT ITEMDESC  FROM dbo.IV00101";
        //select Convert(nvarchar(50),Item_Description)+ ':' +Convert(nvarchar(50),Item#) as Combined from Carimed
        SqlCommand cmd2 = new SqlCommand(query, con2);

        SqlDataReader dr2 = cmd2.ExecuteReader();
        while (dr2.Read())
        {
            string cari_des = dr2.GetString(dr2.GetOrdinal("ITEMDESC"));
            suggestComboBox1.Items.Add(cari_des.Trim());
        }
        //con2.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

A:
How do I go about including the Trim function effectively

One thing I notice is you have SQL query prepared in application side.
For many reasons this is neither good practice nor advisable.
You should have created stored procedures which returns the needed data.
implementing "Trim" function should be on database side (inside the db procedure) rather on the application side unless you are sure that data returned from the database is never going to be in large amount.
declare @name varchar(5)='a   '
select @name,RTRIM(LTRIM(@name))

A: You can also use Replace
suggestComboBox1.Items.Add(cari_des.Replace(" ", ""));

Note: This will remove all the white spaces at start at end and in middle.


text:
Q: Storing XSLT in SQL Server 2005 with xml type? I have a lot of XSL files in my ASP.NET web app. A lot. I generate a bunch of AJAX HTML responses using this kind of generic transform method:
public void Transform(XmlDocument xml, string xslPath)
{
    ...
    XslTransform myXslTrans = new XslTransform();
    myXslTrans.Load(xslPath);
    myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
}

I'd like to move the XSL definitions into SQL Server, using a column of type xml.
I would store an entire XSL file in a single row in SQL, and each XSL is self-contained (no imports).  I would read out the XSL definition from SQL into my XslTransform object.
Something like this:
public void Transform(XmlDocument xml, string xslKey)
{
    ...

    SqlCommand cmd = new SqlCommand("GetXslDefinition");
    cmd.AddParameter("@xslKey", SqlDbType.VarChar).Value = xslKey;
    // where the result set has a single column of XSL: "<xslt:stylesheet>..."
    ...

    SqlDataReader dr = cmd.ExecuteReader();
    if(dr.Read()) {
        SqlXml xsl = dr.GetSqlXml(0);
        XslTransform myXslTrans = new XslTransform();
        myXslTrans.Load(xsl.CreateReader());
        myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
    }
}

It seems like a straightforward way to:

*

*add metadata to each XSL, like lastUsed, useCount, etc.

*bulk update/search capabilities

*prevent lots of disk access

*avoid referencing relative paths and organizing files

*allow XSL changes without redeploying (I could even write an admin page that selects/updates the XSL in the database)

Has anyone tried this before?  Are there any caveats?
EDIT
Caveats that responders have listed:

*

*disk access isn't guaranteed to diminish

*this will break xsl:includes

A: The two big issues I can see are:

*

*We use a lot of includes to ensure that we only do things once, storing the XSLT in the database would stop us from doing that.

*It makes updating XSLs more interesting - we've been quite happy to dump new .xsl files into deployed sites without doing a full update of the site. For that matter we've got bits of code that look for client specific xsl in a folder and those bits of code can reach back up to common code (templates) in the root - so I'm not sure about the redeploy thing at all, but this will depend very much on the particular use case, yours is certainly different to ours.

In terms of disk access, hmm... the db still has to go access the disk to pull the data and if you're talking about caching then the db isn't a requirement for enabling caching.
Have to agree about the update/search options - you can do stuff with Powershell but that needs to be run on the server and that's not always a good idea.
Technically I can see no reason why not (excepting the wish to do includes as above) but practically it seems to be fairly balanced with good arguments either way.

A: I store XSLTs in a database in my application dbscript. (However I keep them in an NVARCHAR column, since it also runs on SQL Server 2000)
Since users are able to edit their XSLTs, I needed to write a custom validator which loads the text of TextBox in a .Net XslCompiledTransform object like this:
    args.IsValid = true;

    if (args.Value.Trim() == "")
        return;

    try
    {
        System.IO.TextReader rd = new System.IO.StringReader(args.Value);
        System.Xml.XmlReader xrd = System.Xml.XmlReader.Create(rd);
        System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
        System.Xml.Xsl.XsltSettings xslts = new System.Xml.Xsl.XsltSettings(false, false);
        xslt.Load(xrd, xslts, new System.Xml.XmlUrlResolver());
        xrd.Close();
    }
    catch (Exception ex)
    {
        this.ErrorMessage = (string.IsNullOrEmpty(sErrorMessage) ? "" : (sErrorMessage + "
") +
            ex.Message);
        if (ex.InnerException != null)
        {
            ex = ex.InnerException;
            this.ErrorMessage += "
" + ex.Message;
        }
        args.IsValid = false;
    }

As for your points:

*

*file I/O will be replaced by database-generated disk I/O, so no gains there

*deployment changes to providing an INSERT/UPDATE script containing the new data


text:
Q: What is the most simple way to sent HTTP Post request to server I want write simple code in JAVA that will allow to me send HTTP POST request to server
1)The request will contain the next JSON
{
    "Key": "asd",
    "dId": 123456,
    "SomeData": {
        "id": 12345,
        "name": "abcd"
    },
    "Url": "https://google.com/",
    "tdId": 1,
    "wdId": 0
}
2)display the JSON answer from the server
have seen lots of tutorial videos on YouTube but no one explain it in simple way step by step

A: If you don't want to fight with the JRE internal HttpURLConnection then you should have a look at the HttpClient from Apache Commons:
org.apache.commons.httpclient

final HttpClient httpClient = new HttpClient();

String url; // your URL
String body; // your JSON
final int contentLength = body.length();

PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Accept", "application/json");
postMethod.setRequestHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setRequestHeader("Content-Length", String.valueOf(contentLength));
postMethod.setRequestEntity(new StringRequestEntity(body, "application/json", "utf-8"));

final int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != 200)
    throw new java.io.IOException(statusCode + ": " + HttpStatus.getStatusText(statusCode));

java.io.InputStream responseBodyAsStream = postMethod.getResponseBodyAsStream();
java.io.StringWriter writer=new StringWriter();
org.apache.commons.io.IOUtils.copy(responseBodyAsStream,writer,java.nio.charset.StandardCharsets.UTF_8);

String responseJSON=writer.toString();

A: Since JDK 9, there is HttpClient class. In JDK 9 and JDK 10, it was in incubator status. Since JDK 11 it is no longer incubator. I did not see any mention in your post as to which JDK version you are using. Did I miss something? Here is link to javadoc for JDK 11...
java.net.http.HttpClient
In my opinion, the advantage of using JDK's HttpClient class means no third-party dependency.


text:
Q: Webforms vs Razor vs MVC and Industry Uses I'm pretty familiar with C# and web development, so I've decided to delve back into the world of developing aspx sites - after working in lamp for a few years now. Since I'm really only familiar with classic asp-era in MS terms, I have a few questions in terms of when to use which approach - and also some more insight on which might be favored in the industry.
I've seen these types of questions asked a few times, but couldn't find anything as specific as what I am looking for:

*

*I realize ASP MVC is the major approach to developing robust web
applications, but is this the correct approach even for simple,
client websites that don't require much other than a clean and/or
responsive design? If not, are web forms what I should be looking
at?

*Outside of focusing on a few sites I have to do (that I plan to do via ASPX),
what should I be focusing on to gain a more practical approach to showcase
my abilities with C#/ASP in order to obtain a junior/mid developer role working
with C#/.NET, etc.
*3. Almost forgot, any possible suggestions on some good books that apply to real-world scenarios using C# MVC, WPF, WCF, Razor, etc. would be helpful

A: In theory, ASP.NET Web Forms should be more suitable for rapid prototyping ie. quickly throwing somethnig together without really focusing on scalability and things like separation of concerns etcetera.
ASP.NET MVC on the other hand makes a better separation between the views and the logic and should be the way to go when you want to build large applications where separation of concerns and scalability is important.
That being said, personally I would never choose ASP.NET Web Forms, not even for a small project. I find that ASP.NET MVC is a much cleaner approach. To me Web Forms is just trying to force a desktop development model over HTTP, which is just a leaky abstraction as you will soon be trying to circumvent this model because it just doesn't fit. As for rapid prototyping, it's true that MVC doesn't have the quick Grid Views and elaborate controls, but personally I think you'll gain much more speed from having things well structured and separated not to mention a real HTTP-model.
As for other things you should focus on, I think apart from the server-side, client-side development is increasingly important. Apart from just plain JavaScript, jQuery is almost a must-have and lately SPA-frameworks such as AngularJS and Durandal are gaining a lot of traction.
On the other side of the spectrum, there's the whole cloud idea which in certain cases requires specific knowledge. If you will be focusing on c#/.NET, I'd say take a look at Azure (you can get a free 90-day trial).
In between all of that there's a whole spectrum of different technologies that are worth knowing, but I would say start with what you need, invest time in some technologies and try to follow up on new technologies.
Just make sure you don't let yourself guided by buzzwords and focus on those technologies that actually help you solve a problem.

A: Only my Opinion but,

*

*MVC is fine for small, clean sites. On a like for like basis its typiucally cleaner than the ASPX equivalent (as it carries less state around and page sizes tend to be smaller). Being responsive is really down to the CSS and JS that you include.

*Firstly, focus on what you really enjoy, but take a look at some of the thinks like Angular JS or KnockoutJS and back end at things like IoC, Dependency Injection, Test Driven Development, Entity Framework and Azure.

*Just go through the various Getting Started and MVC Content, examples and dev blogs on ASP.Net there is a mine of useful information there.

A: MVC is more suitable for maintaining complex web application . if it is a simple web site i would not over kill it with IoC , Mocking , Web forms is more suitable for quick prototyping and RAD.


text:
Q: Clarification of the relationship between similarity and linear transformations Consider the map $f: \mathbb{R}^2 \rightarrow \mathbb{R^2}$ given by $f(x,y)=(3x,2y)$. This map scales the plane horizontally by a factor of $3$ and vertically by a factor of $2$.
For the function given by $g(x)=x^2$, the image of its graph under $f$ has the equation $y=2g(\frac{1}{3}x)$.
It happens that, under a dilation centered at the origin by a factor of $\frac{9}{2}$, the graph of $g$ has the same image. That is, $2g(\frac{1}{3}x)=\frac{9}{2}g(\frac{2}{9}x)$. However, this is not true for the function given by $h(x)=\sin x$. Clearly, in general, $(3x,2y) \not = (\frac{9}{2}x,\frac{9}{2}y)$
My specific question is if $f$ is not equivalent to a dilation of the plane in general, why does it "seem" to be for $g$?
My general question is about vocabulary. When two figures can be mapped to each other by a sequence of reflections, rotations, and dilations, they are "similar." Is there a word for two figures that can be mapped to each other by a general linear transformation?


text:
Q: Save Dark mode to local storage in JavaScript I've added dark mode to my website and it works perfectly
But just after I refresh my page the default view that is Day Mode is shown.
so, is there any way to save this preferences?
HTML

JavaScript
    function myFunction() {
    var element = document.getElementById("main-page");
    var icon = document.getElementById("darkIcon");
    element.classList.toggle("active-dark");

    if (element.className == ["main-page active-dark"]){
        if (icon.className == "fa fa-moon"){
            icon.classList.toggle("fa-sun");
        }else {
            icon.classList.toggle("fa-moon");

        }

    }
    if (element.className == "main-page"){
        if (icon.className == "fa fa-sun"){
            icon.classList.toggle("fa-moon");
        }else {
            icon.classList.toggle("fa-sun");

        }

    }
}

NOTE :
To activate dark mode i just add "active-dark" after "main-page" class and to disable dark mode i just remove the class

A: In your myFunction function save state of darkmode in localStorage
function myFunction() {
     localStorage.setItem('isDarkMode', true);

And in your JS add following line
Just make sure DOM is loaded before execution of this line
if (localStorage.getItem('isDarkMode') === 'true') {
    document.getElementById('main-page').classList.add('active-dark');
}

A: This depends on where you render (generate the html) your page.
If you render it on the client (browser) you can save it in the session storage:
sessionStorage.setItem("darkmode", true)

and then get it when loading your page via:
sessionStorage.getItem("darkmode")

If you render it on the server you can save it in a session variable. This depends however heavily on your server side library / language which you use to implement this. You would then make a request to the server in order to set this variable.
An alternative is to use a cookie. You can read this on the server and on the client.
You can set it like this.
document.cookie = "darkmode=true"

EDIT:
You should use the local storage since it will outlive the session.
localStorage.setItem("darkmode", true)

and
localStorage.getItem("darkmode")

A: Here is the full code to auto-detect user dark mode and save it to local storage for keeping the current mode throughout the session.
The below code will run when the user clicks the dark mode toggle button. Make sure you create the CSS class for .dark-mode with the required CSS code.
$(document).ready(function () {

   $("#dark-mode").click(function () {
      $("body").toggleClass("dark-mode");
      if (localStorage.hasOwnProperty('isDarkMode')) {
         if (localStorage.getItem('isDarkMode') === 'true') {
            localStorage.setItem('isDarkMode', 'false');
         }
         else if (localStorage.getItem('isDarkMode') === 'false') {
            localStorage.setItem('isDarkMode', 'true');
         }
      }
   })

   if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").addClass("dark-mode");
         localStorage.setItem('isDarkMode', true);
      }
   }
   else {
      if (!(localStorage.hasOwnProperty('isDarkMode'))) {
         $("body").removeClass("dark-mode");
         localStorage.setItem('isDarkMode', false);
      }
   }

   if (localStorage.hasOwnProperty('isDarkMode')) {

      if (localStorage.getItem('isDarkMode') === 'true') {
         $("body").addClass("dark-mode");
      }
      else if (localStorage.getItem('isDarkMode') === 'false') {
         $("body").removeClass("dark-mode");
      }
   }
})

A: My take:

                        <button class="btn btn-light btn-sm" onclick="myFunction()">Toggle dark mode</button>


text:
Q: Worklight: How to get current device ID for Push subscription I want to get the currently subscribed device ID ? how i can get it on the client side or on the server side?
I know the subscription table, but i donn't want to get from it.
Secondly, if one user has already subscribed two devices and now he/she is subscribing third device, i want to capture the third (current) device ID.
Later, I have to save that third device Id in my another table.
If there is no way to identify the currently subscribed device , then if i go to subscription table, then how i get know that "this device ID is the newly registered device ID ? "
Hope it would be clear.
Thanks

A: *

*When registering event source in adapter you can specify onUserSubscribe callback. This callback will be invoked once user subscribes to push notifications. Once invoked this callback will receive user subscription object as a parameter. This object contains both userId and deviceId.

*WL.Server.getUserNotificationSubscription("event-source","userId") will return user subscription object with an array of device subscriptions. Each device subscription object will have deviceId.

*On a client side deviceId is a userId of device authentication realm. E.g. in case you use no provisioning you can get deviceId by using WL.Client.getUserInfo("wl_deviceNoProvisioningRealm", "userId");

*Server side doesn't know your "current" device. You can use onUserSubscribe callback to mark specific device as latest.

*user subscription object can have custom properties, you can use them to maintain subscription state.


text:
Q: what's the size and type for facebook profile picture? I tried to upload a 512x512 PNG image for the profile picture of a page that we own on Facebook, but it failed w/o showing the image after I uploaded the image file. Could there be something wrong with the PNG image or the size of the image?

A: 180 x 540 in jpg
is what I use for mine
There is a tutorial with sizes etc here :
http://www.clear-river.com/weblog/comments/making_the_most_of_your_facebook_page_profile_picture/
I think 512PX wide is way too wide, as the logo is only a thin strip.


text:
Q: Combining multiple pandas read_csv and/or file.readline() I am trying to read a text-data file, that it is composed of many consecutive and alternating blocks of data, and each block is either with N rows and X columns or N+1 rows and Y columns.
My idea was to use pd.read_csv with two consecutive calls, the first using the option nrow=N, the second with nrow=N+1, but I have found this problem that I don't understand.
Let's consider this minimal example:
#header first line
#header second line
-2.000000000000e+00 7.853981633974e-03
-1.998000000000e+00 7.853981633974e-03
-1.999000000000e+00 1.570796326795e-05 8.214081241617e-13 8.222110115758e-18 6.069302089412e+00 3.450000000000e+07 3.077971152413e+03 0.000000000000e+00 0.000000000000e+00 -6.315974034994e+02 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 -1.000000000000e+00 8.526515773580e+06 2.736441000000e+03

This is the code that I am using to read the data:
import pandas as pd
fp=open('test.txt')
fp.readline()#let's skip first and second line
fp.readline()
q=pd.io.parsers.read_csv(fp,nrows=2,header=None,sep=' ',names=['x_ar','a_ar'])

Now, I was expecting that the result of a further:
In [4]: fp.readline()

would be the last line, but, I got an empty string.
Out[4]: ''

What's going on? How can I solve this problem?
PS. I know I could just iterate with fp.readline, but I am interested in a pandas solution.

A: *

*About the null string in the last fp.readline():

When you open a file with open(filepath) a file handle iterator is
  returned. An iterator is good for one pass through its contents. So
  pd.io.parsers.read_csv(fp,nrows=2,header=None,sep='
  ',names=['x_ar','a_ar']) reads the contents and exhausts the
  iterator. Subsequent calls to pd.read_csv thinks the iterator is
  empty.
Answer adapted from this
  question.

*To handle comments that you have at the top of the file, you could pass, comments='#' like this:

fp=open('../test.txt')
pd.io.parsers.read_csv(fp,nrows=2,header=None,sep=' ',names=['x_ar','a_ar'], comment='#')

Your output then would be:
     x_ar   a_ar
0   -2.000  0.007854
1   -1.998  0.007854


text:
Q: Can I import OneSignal tokens to FCM? I have several thousand OneSignal web push notification tokens I want to import to FCM. Is there a way to do this?
I see this endpoint which requires the https://fcm.googleapis.com/fcm/send/...key... endpoint that OneSignal gives me, but I don't know what to put in for auth and p256dh.
https://developers.google.com/instance-id/reference/server#create_registration_tokens_for_apns_tokens

A: So yes this can be done. First you will need to contact OneSignal support and get the public and private VAPID keys for your app. Each app in your dashboard will have a different set.
Next you will need to make an API call to OneSignal in order to export the users in a CSV file.
You can find the API url in the docs and use curl or use your favorite language. I used Node + Axios to make my calls. The API call will supply you with a link to download the CSV.
Here is the documentation https://documentation.onesignal.com/reference#csv-export
You want to make sure you add the "extra_fields" parameter to your request with the "web_auth" and "web_p256" fields added. The CSV will provide you with the other piece of the puzzle which is the endpoint url in their identifier column.
Once you have all this information you can now send pushes using a library such as web-push for Node
https://github.com/web-push-libs/web-push
Hope that helps!
EDIT
As Cedric stated the actual push payload is a little bit more complicated because you need to comply with the OneSignal Service worker data handling.
You can see the formatting starting at line 313 here
If you are using a library like web-push for Node to send your push payloads your payload would be formatted something like this for a standard push to a OneSignal service worker.
const uuidv1 = require('uuid/v1')
const webpush = require('web-push')

let subscription = {
    endpoint: 'USER ENDPOINT URL',
    keys: {
        auth: 'USER AUTH KEY',
        p256dh: 'USER P256 KEY'
    }
}

let vapid = { private: 'VAPID PRIVATE KEY', public: 'VAPID PUBLIC KEY' }

// Format Message for OneSignal Service Worker
let notification = JSON.stringify({
    custom: {
        i: uuidv1(), //Generate UUID for the OneSignal Service worker to consume
        u: 'CLICK URL'
    },
    title: 'TOP TITLE',
    alert: 'MESSAGE BODY',
    icon: 'ICON IMAGE URL'
})

webpush.setVapidDetails('mailto: sendError@YourEmail.com', vapid.public, vapid.private)
webpush.sendNotification(subscription, notification)

A: It's much more complex than Dan's answer. If your users don't subscribe to your own service worker, it won't work. OS will send its default notification when an 'unknown' error occurs, which it will send "You have new updates" as a notification to the user even though you passed different payload. You also need to pass: "custom": { "i": uuidv1() } to your payload for it to work. (don't forget to install uuid first through npm and call it). Check out this link and you'll figure out what other payload props you need to pass.


text:
Q: Consuming Yellow Pages.com using FSharp Type Providers I signed up for the yellow pages.com API program found here: https://publisher.yp.com/home.
I went to make a call like this and I am getting back JSON in the browser:
http://pubapi.atti.com/search-api/search/devapi/search?term=Jumbo+China+5&searchloc=6108+Falls+Of+Neuse+Rd+27609&format=json&key=ZZZZZZZZ
When I take the json results and put it into Json2CSharp, it renders fine.  When I try  and load it into a type provider:
type RestaurantListingJson = JsonProvider< @"http://pubapi.atti.com/search-api/search/devapi/search?term=Jumbo+China+5&searchloc=6108+Falls+Of+Neuse+Rd+27609&format=json&key=ZZZZZZZ">
I get a 400
Looking at fiddler, I see
"User agent is a required field"
Has anyone run into this before?  How do I add a user agent to a type provider?
Thanks in advance

A: I have not created an account, so I could not try this - but if the error message says "user agent is a required field", then I guess that the service requires setting the User-Agent header of the HTTP request.
This is not supported in static parameters of the JsonProvider, so the best way to get this to work would be to download the sample JSON, save it to a local file (say yp.json) and then use that to create the type provider:
type Yp = JsonProvider<"yp.json">

To actually download some data (when you want to make a request), you can use Http.RequestString which takes headers - there you can specify any required headers including User-Agent:
let response =
  Http.RequestString("http://httpbin.org/user-agent", headers=["user-agent", "test"])

Then you can load the data using Yp.Parse(response) (rather than using the Load method directly to request a URL which would not let you specify the header).

A: The latest version of F# Data now always sends user agent and accept headers, so this should now work directly:
type RestaurantListingJson = JsonProvider<"http://pubapi.atti.com/search-api/search/devapi/search?term=Jumbo+China+5&searchloc=6108+Falls+Of+Neuse+Rd+27609&format=json&key=ZZZZZZZ">


text:
Q: How to convert curl "--user" command to Restsharp? My curl is
curl -X POST -d "email=jeff@example.com" -d "password=*******"
         --user admin@example.com:password https://example.com/admin/web/users/add

what I have so far is
var client = new RestClient("https://example/admin/web/users/add");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("accept", "application/json");
request.AddParameter("application/x-www-form-urlencoded", "email=jeff@example.com" + "password=********", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Console.WriteLine(response.Content);

what i dont understand is where do I put
--user admin@example.com:password

A: Unless specified otherwise, curl uses HTTP Basic authentication when making HTTP(S) requests.
In RestSharp, HTTP Basic auth is provided via the RestSharp.Authenticators.HttpBasicAuthenticator type:
var client = new RestClient("https://example/admin/web/users/add");
client.Authenticator = new HttpBasicAuthenticator("admin@example.com", "password");
...


text:
Q: LaTeX allows line break between concluding em-dash and comma before a new sub clause begins I am surprised by LaTeX putting a comma which follows an em-dash on a new line when the previous line is flushed. My intuition and sense of style tells me that they should never be separated. For example:
\documentclass[a4paper]{book}
\usepackage[top=35mm, bottom=38mm, inner=40mm, outer=24mm]{geometry}
\usepackage[UKenglish]{babel}

\begin{document}

Foo bar. The erosion responsible for 'residuals' is less related to the material process of
creation---e.g., rewriting in the sense of Mondrian or blurring the edges in the sense of
Rothko---, but to the double nature of time\ldots

\end{document}

Why isn't the second line ending with em-dash and comma? Is this the correct way you would break lines in (British) English?

A: You're being very unlucky, since a comma is really a thin character. You'll probably avoid all those cases by loading microtype.
However, if you want to be on the safe side, type \textemdash, which will not add a discretionary break, as explained in answers to Hyphenation problem with --- versus \textemdash
The output with microtype, with no change in the input, is the same as with \textemdash,; of course, microtype has other benefits.


text:
Q: What does the code img src="'.$target.'" mean?  <?php
    define('upload', 'images/');

    if (isset($_POST['submit'])) {

         $name=$_POST['name'];
         $score=$_POST['score'];
         $screenshoot=$_FILES['screenshoot']['name'];
         $target=upload.$screenshoot;
         move_uploaded_file($_FILES['screenshoot']['tmp_name'], $target);
         if(!empty($name)&&!empty($score)){
          $dbc=mysqli_connect('localhost','root','57317019','guitar_game');
          $query="INSERT INTO guitargame(id,date,name,score,screenshoot".
          "values(0,NOW(),'$name','$score','$screenshoot')";
          $result= mysqli_query($dbc,$query);

          mysqli_close($dbc);
            }
         else{
            echo "Please fill out all the blanks";
             }

          }

         echo "
Thanks for adding your new high score!
";
         echo "
Name:"."$name
";
         echo "
Score:"."$score
";
         echo '';
         echo '
Back to high scores
';
       ?>

l wanna asked what does the img src="'.$target.'" means? Why not use img src="$target" instead? Thanks in advance! I am new to php.

A: The difference between
echo '';

and
echo "";

is that in the former strings are concatenated whereas in the latter the double quotes need to be escaped inside the string to use double quotes which are required to process the variable inside the string. Using just img src="$target" would not work in the echo in either case.

A: Short answer:
echo '';

gives an equal result to
echo "";

Longer answer: the PHP parser looks inside the "..."-style tags for any variables to replace. It doesn't look inside the '...'-style tags. So the latter is a bit faster. You will only notice a difference when this is inside a loop that is executed hundreds of times.


text:
Q: Soma da multiplicação da quantidade por valor do produto em vendas diarias Tenho uma página de pedidos, vamos tomar como base um mercantil, onde a pessoa compra 3 refrigerantes cada um com o valor de R$6,00 e 2 biscoitos no valor de R$2,00 cada.
Primeiro preciso realizar a multiplicação desses valores (3 * 6) e (2 * 2) e depois somar seus resultados, o que daria um valor total da compra de R$22,00 bem como trazer o nome do cliente que fez a compra.
Estou usando o Eloquent do Laravel, mas venho encontrando algumas dificuldades na elaboração da query, se puderem me ajudar, segue o código e a imagem do relacionamento
$vendas = Venda::where('data', date('Y-d-m'))
        ->join('clientes', 'vendas.cliente_id', '=', 'clientes.id')
        ->join('produtos_venda', 'vendas.id', '=', 'produtos_venda.venda_id')
        ->select('vendas.*', 'clientes.nome as nome_cliente', 'produtos_venda.quantidade', 'produtos_venda.valor')
        ->sum('produtos_venda.valor * produtos_venda.quantidade as valor_total')->get();

A: A maneira correta seria:
$select = "sum(produtos_venda.valor*produtos_venda.quantidade) as total,";
$select .= "vendas.cliente_id, clientes.nome, vendas.data";

$vendas = Venda::where('data', date('Y-d-m'))
        ->join('clientes', 'vendas.cliente_id', '=', 'clientes.id')
        ->join('produtos_venda', 'vendas.id', '=', 'produtos_venda.venda_id')
        ->groupBy('vendas.cliente_id', 'clientes.nome', 'vendas.data')
        ->select(\DB::raw($select))
        ->get();

Observações:

*

*Na tabela produto, mudo o tipo do campo preco para decimal(10,2)

*Na tabela vendas, mudo o tipo do campo data pra date

*Na tabela de produtos_vendas mudo o tipo do campo valor para decimal(10,2)

*Se por ventura achar que decimal(10,2), seja insuficiente aumente o número 10 para 12

Essas observações podem e devem ser seguidas, se tem o tipo correspondente porque utilizar um tipo que pode atrapalhar inclusive nas operações de soma, multiplicação, etc e filtros com datas, então, sempre coloque os tipos correspondentes.
Referencias:

*

*Laravel - queries#selects

*Laravel - Ordering, Grouping, Limit, & Offset


text:
Q: Check All not working //toggle check all

$("#bill-all").click(function(){

    if( $(this).is(":checked") ){

        $('.bill_fillter').prop('checked', true);

    } else {

        $('.bill_fillter').prop('checked', false);

    }

});

Html:Code
If i check here.
<input type="checkbox" name="all" id="bill-all" />

Check All is not working, nothing gonna checked if i checked
<input type="checkbox" name="bill_<?php echo($i);?>" report_date="<?php echo $a1[1]; ?>" value="<?php echo($unit_id);?>" class="bill_fillter" id="bill-all"/>

A: $("#bill-all").click(function(){

   if( $(this).is(":checked") )
     $(".bill_filter").prop('checked', true);
   else
     $(".bill_filter").prop('checked', false);

});

A: Remove id form -
<input type="checkbox" name="bill_<?php echo($i);?>" report_date="<?php echo $a1[1]; ?>" value="<?php echo($unit_id);?>" class="bill_fillter" id="bill-all"/>

Try with -
<input type="checkbox" name="bill_<?php echo($i);?>" report_date="<?php echo $a1[1]; ?>" value="<?php echo($unit_id);?>" class="bill_fillter"/>

Sample -
   <input type="checkbox" name="bill"   class="bill_fillter" />
   <input type="checkbox" name="bill"   class="bill_fillter" />
   <input type="checkbox" name="bill"   class="bill_fillter" />

   <input type="checkbox" name="all" id="bill-all" />

Script -
$(document).ready(function() {
    $("#bill-all").click(function(){

    if( $(this).is(":checked") ){

        $('.bill_fillter').prop('checked', true);

    } else {

        $('.bill_fillter').prop('checked', false);

    }

});

A: I suspect your not binding the click event on document ready.
Given the HTML as an example
<input type="checkbox" id="bill-all" />

<input type="checkbox" class="bill_filter" />

<input type="checkbox" class="bill_filter" />

<input type="checkbox" class="bill_filter" />

The javascript code needs to be executed when the DOM (document) is ready, e.g. all HTML elements are available.
  $(function() {
    $('#bill-all').click(function() {
      $('.bill_filter').prop("checked", $(this).is(':checked'));
    });
  });


text:
Q: Is there a way to use UIAutomator to enter cyrillic letters? I'm trying to test my company's browser's auto suggest functionality for the Russian language with UIAutomator and am hitting a snag:
There are no KeyEvent.KeyCode_* code for Russian letters and UiDevice.pressKeyCode(KeyEvent.KEYCODE_LANGUAGE_SWITCH) doesn't appear to help. What documentation I found inside the KeyEvent class seems to suggest that I just need to use the same KeyCodes as the english letters but magically they would be mapped across to the letters of of the other languages. That does not appear to actually happen however as I'm still seeing the English letter show up when I try that.
Normally with Russian I just use UiObject2.setText(...) but that method does not trigger auto suggestions.
I've tried delving into what UiDevice.pressKeyCode is doing and attempting a couple workarounds such as:
KeyEvent eventsб2 = new KeyEvent(SystemClock.currentThreadTimeMillis(), "б", KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
Instrumentation.sendKeySync(eventsб2);

or
KeyEvent[] eventsа = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD).getEvents(new char[] {'a'});
Instrumentation.sendKeySync(eventsа[0]);

But they either don't enter the letter or throw a permission exception regarding needing the INJECT_EVENTS permission. Overall I'm feeling like I'm stumbling in the dark and would love some advice on how to proceed.

A: I tried this and worked.
/**
 * @@Test comment here@@
 *
 * @throws Exception
 */
@Test
public void culebraGeneratedTest_CyrillicKeyBoardAndSelectSuggestion() throws Exception {
    mDevice.pressHome();
    mDevice.findObject(By.res("com.android.quicksearchbox:id/search_widget_text").clazz("android.widget.TextView").text(Pattern.compile("")).pkg("com.android.quicksearchbox")).clickAndWait(Until.newWindow(), DEFAULT_TIMEOUT);
    mDevice.findObject(By.desc("й").clazz("com.android.inputmethod.keyboard.Key").text(Pattern.compile("")).pkg("com.android.inputmethod.latin")).clickAndWait(Until.newWindow(), DEFAULT_TIMEOUT);
    (new UiScrollable(new UiSelector().resourceId("com.android.quicksearchbox:id/suggestions").index(1).packageName("com.android.quicksearchbox"))).getChildByText(new UiSelector().className("android.widget.RelativeLayout").packageName("com.android.quicksearchbox"), "йемен", true).click();
}

I have to admit that I don't know Russian or what I was selecting on the Cyrillic keyboard, so bear with me.
To generate this test I used CulebraTester as it seems to be an interesting use case for the tool.

The steps were:

*

*start recording the test (generating Java UiAutomator, can also generate python and other languages)

*press Home

*select the Quick Search Box

*Press the key

*Select one of the suggestions

You will be able to create a similar test using AndroidViewClient/culebra in python but because this tool is based on the information obtained from uiautomator dump it won't be able to detect the letters on the keyboard, but you can also touch them using DIPs
vc.dump(window=-1)
vc.findViewByIdOrRaise("com.android.quicksearchbox:id/search_widget_text").touch()
vc.sleep(_s)
vc.dump(window=-1)
device.touchDip(15.33, 393.33, 0)

but this is not as device independent as the first solution.
Hope this helps you.


text:
Q: How should I invoke an asynchronous action in OpenWhisk using API Manager from IBM Bluemix? I have created a small OpenWhisk action written in Node.js. This action makes a call to a backend system. The function implementing the action follows (I have removed the part of code which is not related with this problem).
/**
  *
  * main() will be invoked when you Run This Action.
  *
  */

function main() {

    var request = require("request");

    var data = {
    };

    var options = {
        method: "POST",
        url: "https://whatever.it.is",
        body: data,
        json: true
    };

    request.post(options, function(error,response,body) {
        var data = [];
        return whisk.done({"msg":data});
    });

    return whisk.async();
}

Then I have tried to define an API call in Bluemix API Manager.The call is done. But I receive as a result the Id for the activity and not the contents I returned using whisk.done().
Any ideas?. Thanks in advance.

A: Tldr: Append blocking=true to the query of your URL to return the result of the activation in the same HTTP request.

Speaking of action invocations in OpenWhisk there are two different modes you can choose from. blocking or non-blocking.
Non-blocking invocations are the default, where you POST your payload against the OpenWhisk backend and get back an activation id, under which the results of your invocation (aka activation) will be stored. You can get those results at a later point in time (hence non-blocking) via the Activations API.
Blocking invocations will wait until your activation is finished and return the results in the same HTTP request. Blocking requests are made via the same API but with the query parameter blocking=true appended.
Your issue sounds like you most likely want a blocking invocation. Variations of query parameters can be found at the OpenWhisk REST API Reference.


text:
Q: how stage3d uv mapping work? I am new to 3d programming. Recently I found uv mapping is confusing to me.
using
tex ft0, v1, fs0 <2d,repeat,nomip>
mov oc, ft0

I gives v1 as uv coordinate and fs0 for texture bitmap, this worked as it is. Textures wrapped the 3D objects.
But I only copied ft0 to oc once with one coordinate v1, how the system knows what to fill the else area ?
and I didn't provide the vertex coordinate either, did fragment program get call every pixel or every vertex render?

A: Well, first you're getting 'v1':(Varying register 1) from the vertex shader: By setting it from one of your (Vertex attributes) 'vaX', usually: mov vX, vaX or other operations.
What a varying register does (ie 'v1') is interpolate the values of uv (ie 'vaX') for the three vertices which make up the triangle.
Note:Varying registers are the only way you can communicate between vertex and fragment shaders.
For each pixel, the 'tex' function will sample an area 'v1' (rasterise) from the texture sampler 'fs0' with the rules between the brackets (ie <2d,repeat,nomip>).
Think of the first line as ft0 = fs0.getPixel(v1), with v1 running from say va1(1)[x, y, z, w] to va1(2)[x, y, z, w] (z can be used for lighting and other effects), you are then outputting this one pixel/fragment to 'oc' (Output color).
Fragment shader are also called Pixel shaders -> get called once for every pixel.
On the other hand Pixel Shaders are called once for every vertex.
There is a third type of shaders called Geometry shaders, but aren't available in Stage3D/AGAL.

A: Just to clarify - YOU don't need to sort out calling the shaders for every pixel. Provided you're giving the vertex and fragment shaders the correct textures and constants, it's enough to have the program3Ds uploaded (with both vertex and fragment shaders). The GPU will sort out the rendering when you call context3D.drawTriangles(...) and then context3D.present.


text:
Q: How does AWS inform API users of changes? I'm working on a project centered around API Change Management. I'm curious as to how AWS informs developers of changes to its APIs. Is it through the document history (https://docs.aws.amazon.com/apigateway/latest/developerguide/history.html)? Or do they send out emails to developers?
Regarding emails, are emails sent to all developers using the API (ex. API Gateway) or just developers using a particular endpoint and will be affected by the change? What is the frequency of notifications - breaking changes, minor changes, etc.
Thanks so much for your help!

A: For non-breaking changes, you can learn about them on the Developer Guide as you pointed out. Some of these changes are also announced on their What's New page (RSS feed). You can also follow the SDK releases which are updated often (e.g. by using the RSS feed for aws-sdk-go releases). I believe that most of the SDKs are using code generation to generate a lot of the API functionality. They push updates to these files in the SDK git repositories (ruby example, go example), but it is not clear if there is another place to find these files. It doesn't seem like they want us to consume these directly (see this developer forum thread from 2015). There's also awsapichanges.info, which appears to be built by AWS themselves.
AWS very rarely makes breaking changes to their API. Even SimpleDB, which is a very old AWS product, still works.
Having said that, they do make breaking changes from time to time, but they try to announce them well ahead of time. The biggest breaking change that they are trying to complete is probably their attempt to deprecate S3 path-style access. This was first quietly announced in their AWS Developer Forums, which caused a lot panic especially since the timeline was incredibly short. Based on the panic, AWS quickly backtracked and revised the plan, more publicly this time.
They have done some other S3 breaking changes in other ways. For example, S3 buckets must now have DNS-compliant names. This was only recently (March 1, 2018) enforced on new buckets in us-east-1, but for most other regions this was enforced from the start when the regions were made available. Old S3 buckets in us-east-1 may still have names that are not DNS-compliant.
Lambda is removing old runtimes once the version of the programming language stops being maintained (such as Python 2.7). This should be a known expectation for anyone who starts using the service, and there is always a new version that you can migrate to. AWS sends you email reminders if you still have Lambda functions that is using the old runtime, when the deadline nears.
Here is a GitHub repository where people try to track breaking changes: https://github.com/SummitRoute/aws_breaking_changes. You can see that the list is not that long.


text:
Q: Why does the error 'invalid or unsupported image format' appear? I've been working on CS50's pset3 and have been stuck on this one problem for awhile now. I copy most of my code from copy.c and referred to the walkthroughs to design my code as similar as possible but I can't seem to get the enlarged image to show. The code compiles fine and doesn't seem to have any problems when I run debug50 so I'm not quite sure how to go about doing this.
// Copies a BMP file
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>

    #include "bmp.h"

    int main(int argc, char *argv[])
    {

        // ensure proper usage
        if (argc != 4)
        {
            printf("Usage: ./resize n infile outfile");
            return 1;
        }

        // remember filenames
        int n = atoi(argv[1]);
        char *infile = argv[2];
        char *outfile = argv[3];

        if (n < 0 || n > 100)
        {
            printf("Usage: ./resize n infile outfile");
            return 1;
        }

        // open input file
        FILE *inptr = fopen(infile, "r");
        if (inptr == NULL)
        {
            printf("Could not open %s.\n", infile);
            return 2;
        }

        // open output file
        FILE *outptr = fopen(outfile, "w");
        if (outptr == NULL)
        {
            fclose(inptr);
            printf("Could not create %s.\n", outfile);
            return 3;
        }

        // read infile's BITMAPFILEHEADER
        BITMAPFILEHEADER bf, bf_new;
        fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

        // read infile's BITMAPINFOHEADER
        BITMAPINFOHEADER bi, bi_new;
        fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

        // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
        if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
            bi.biBitCount != 24 || bi.biCompression != 0)
        {
            fclose(outptr);
            fclose(inptr);
            printf("Unsupported file format.\n");
            return 4;
        }

        bi_new = bi;
        //increase the size of biWidth for outfile
        bi_new.biWidth = bi.biWidth * n;
        //increase the size of biHeight for outfile
        bi_new.biHeight = bi.biHeight * n;
        // determine padding for scanlines
        int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
        int newpadding = (4 - (bi_new.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

        bi_new.biSizeImage = (bi_new.biWidth * sizeof(RGBTRIPLE) + newpadding) * abs(bi_new.biHeight);
        // write outfile's BITMAPINFOHEADER
        fwrite(&bi_new, sizeof(BITMAPINFOHEADER), 1, outptr);

        bf_new = bf;
        bf_new.bfSize = bi_new.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
        // write outfile's BITMAPFILEHEADER
        fwrite(&bf_new, sizeof(BITMAPFILEHEADER), 1, outptr);

        // iterate over infile's scanlines
        for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
        {
            //multiply each scanline by n
            for (int j = 1; j <= n; j++)
            {
                // iterate over pixels in scanline
                for (int k = 0; k < bi.biWidth; k++)
                {
                    //multiply each pixel in the width by n times
                    for (int l = 0; l < n; l++)
                    {
                        // temporary storage
                        RGBTRIPLE triple;

                        // read RGB triple from infile
                        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

                        // write RGB triple to outfile
                        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
                    }

                }
                // skip over padding, if any
                fseek(inptr, padding, SEEK_CUR);

                //add padding to the outfile's scanline
                for (int m = 0; m < newpadding; m++)
                    {
                        fputc(0x00, outptr);
                    }
            }
        }

        // close infile
        fclose(inptr);

        // close outfile
        fclose(outptr);

        // success
        return 0;
    }

A: Your way of enlarging the image is wrong. You now read pixels in the inner most loop. That won't work.
You must read a whole scanline, enlarge its pixels n times into a new scanline and then write that scanline n times.
I leave to you to change your code accordingly.

A: your question:
Why does the error 'invalid or unsupported image format' appear
It appears because when you try to display the image, the OS recognizes that the image file is not properly formatted.
bmp image format


text:
Q: MonthCalendar in WPF? Is there a free class library that offers a MonthCalendar control for WPF? And is the MonthCalendar equal to if not better than the Winforms MonthCalendar.

A: I think there is one included in VS 2010, but there is not one built in for sure in VS 2008.
You can use the WPF toolkit, it has a nice month calendar control that should fit your needs.

A: Download the WPF Toolkit... it includes a Calendar, DatePicker, and DataGrid.  Once you add the toolkit dll to your project, you can implement the calendar like so:
<Window x:Class="WPF_Playground.Window4"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" >

    <Grid>
        <toolkit:Calendar/>
    </Grid>
</Window>


text:
Q: Wordpress suppressing php error through htaccess throwing 500 error I am suppressing PHP errors from the front-end through .htaccess in WordPress. I want to hide the errors thrown by WordPress if we are trying to access a file through folder structure:
eg: www.my_site/wp-content/themes/twentyeleven/sidebar-page.php
.htaccess snippet:
php_flag display_errors off

But, it is showing a 500 internal server error. I've tried
error_reporting(0);
ini_set('display_errors', 0);

in the header.php file, no change.
Is there any way to redirect to the homepage if a 500 error occurs?

A: Try:
ErrorDocument 500 /index.php

That should cause any 500 error to redirect to the home page. The header will still have a 500 status, so it would be interesting to see how WordPress handles that.


text:
Q: finite generation of a certain type of subring Let $k$ be a field, and let $R$ be a finitely generated $k$-algebra.  (If it helps, you may assume $R$ is an integral domain.)  Let $I$ be an ideal of finite colength.  Note that $A:=k+I$ is a subring of $R$.  Indeed, it is the pullback of the diagram $k \hookrightarrow R/I \twoheadleftarrow R$.  Here's my question: $$\text{Is }A \text{ finitely generated as a } k\text{-algebra?}$$
By the Eakin-Nagata theorem, I know that $A$ is Noetherian, since the Noetherian ring $R$ is module-finite over it (as it is module-generated over $A$ by any lifting of any $k$-basis of $R/I$).  Also, without the condition on colength or something like it, this tends to be false (and maybe always is).  Witness that when $R=k[x,y]$ and $I=(x)$, $k+I \cong k[x,xy,xy^2,xy^3,\ldots]$ is not even Noetherian.

A: Yes. Both $R$ and $A=k+I$ are filtered by powers of $I$ and we may look at the associated graded rings.
Now $I/I^2$ is a finitely generated $R/I$ module and $R/I$ is a finitely generated vector space, by Zariski's lemma
on finitely generated $k$ algebras that are fields. So $I/I^2$ is a finitely generated vector space and the associated
graded of $A=k+I$ is a finitely generated $k$ algebra. But that is not enough. It only shows that the hypotheses are reasonable.
Choose $v_1$, $\dots$, $v_m$ in $R$ so that their images together with $1$ form a basis of the vector space $R/I$.
Then $R$ is generated as an $A$-module by $1$, $v_1,\dots,v_m$. So $A$ is a finitely generated $k$-algebra by the
Artin-Tate lemma in wikipedia.
One may argue more directly. Every $r\in R$ may be written as a $k$ linear combination of $1$, $v_1,\dots,v_m$ plus an element, say $f(r)$, in $I$.
Now take a generating set $y_1,\dots,y_m$ of the $k$-algebra $R$ and choose $x_1$, $\dots$, $x_n$ in $I$ so that the $f(y_i)$ and the $f(v_iv_j)$
are amongst the $x_j$.
We claim that every element of $R$ can be written as a
$k$ linear combination of the generators $1$, $v_1$, $\dots$, $v_m$  plus a polynomial in the $x_j$, $v_ix_j$.
Indeed it is easy to check that the set of elements that can be written this way is invariant under multiplication by the $v_i$ and the $x_j$, hence also
by the $y_j$.
If an element of $A$ is written as a $k$ linear combination of the generators $1$, $v_1$, $\dots$, $v_m$  plus a polynomial in the $x_j$, $v_ix_j$,
then it must be a polynomial in the $x_j$, $v_ix_j$.
So the $x_j$ together with the $v_ix_j$ generate the $k$ algebra $A=1+I$.