text:
Q: Is there a non-reference-counted base class like TInterfacedObject? I need a base class like TInterfacedObject but without reference counting (so a kind of TNonRefCountedInterfacedObject).
This actually is the nth time I need such a class and somehow I always end up writing (read: copy and pasting) my own again and again. I cannot believe that there is no "official" base class I can use.
Is there a base class somewhere in the RTL implementing IInterface but without reference counting which I can derive my classes from?

A: I did this. It can be used in place of TInterfacedObject with or without reference counting. It also has a name property - very useful when debugging.
// TArtInterfacedObject
// =============================================================================

// An object that supports interfaces, allowing naming and optional reference counting
type
  TArtInterfacedObject = class( TInterfacedObject )
    constructor Create( AReferenceCounted : boolean = True);
  PRIVATE
    FName             : string;
    FReferenceCounted : boolean;
  PROTECTED
    procedure SetName( const AName : string ); virtual;
  PUBLIC

    property Name : string
               read FName
               write SetName;

    function QueryInterface(const AGUID : TGUID; out Obj): HResult; stdcall;
    function SupportsInterface( const AGUID : TGUID ) : boolean;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;

  end;

// =============================================================================

{ TArtInterfacedObject }

constructor TArtInterfacedObject.Create( AReferenceCounted : boolean = True);
begin
  inherited Create;

  FName := '';

  FReferenceCounted := AReferenceCounted;
end;

function TArtInterfacedObject.QueryInterface(const AGUID: TGUID; out Obj): HResult;
const
  E_NOINTERFACE = HResult($80004002);
begin
  If FReferenceCounted then
    Result := inherited QueryInterface( AGUID, Obj )
   else
    if GetInterface(AGUID, Obj) then Result := 0 else Result := E_NOINTERFACE;
end;

procedure TArtInterfacedObject.SetName(const AName: string);
begin
  FName := AName;
end;

function TArtInterfacedObject.SupportsInterface(
  const AGUID: TGUID): boolean;
var
  P : TObject;
begin
  Result := QueryInterface( AGUID, P ) = S_OK;
end;

function TArtInterfacedObject._AddRef: Integer;
begin
  If FReferenceCounted then
    Result := inherited _AddRef
   else
    Result := -1   // -1 indicates no reference counting is taking place
end;

function TArtInterfacedObject._Release: Integer;
begin
  If FReferenceCounted then
    Result := inherited _Release
   else
    Result := -1   // -1 indicates no reference counting is taking place
end;

// =============================================================================

A: You might consider TInterfacedPersistent. If you don't override GetOwner it does no ref-counting.

A: In the unit Generics.Defaults there is a class TSingletonImplementation defined. Available in Delphi 2009 and above.
  // A non-reference-counted IInterface implementation.
  TSingletonImplementation = class(TObject, IInterface)
  protected
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;

A: I don't know of any out-of-the-box base class, so I wrote my own (like you). Just put it in a common utils unit and you are done.
type
  TPureInterfacedObject = class(TObject, IInterface)
  protected
    { IInterface }
    function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
  end;

{ TPureInterfacedObject }

function TPureInterfacedObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  Result := E_NOINTERFACE;
end;

function TPureInterfacedObject._AddRef: Integer;
begin
  Result := -1;
end;

function TPureInterfacedObject._Release: Integer;
begin
  Result := -1;
end;

A: There is no such class, but you can easily write your own, as others have shown. I do, however, wonder why you would need it. In my experience, there is seldom a real need for such a class, even if you want to mix object and interface references.
Also note that when you use such a class, you'll still have to take care of setting any interface references you have to such an object to nil before they leave scope and before you free the object. Otherwise you might get the situation the runtime tries to call _Release on a freed object, and that tends to cause an invalid pointer exception.
IOW, I would advise against using such a class at all.

A: As of Delphi 11 Embarcadero added TNoRefCountObject to the System unit.  Here's the note from the release notes:

The new class System.TNoRefCountObject is a non-reference-counted
IInterface implementation (replacing the old and oddly named
TSingletonObject)


text:
Q: tmap view mode covers half screen Why tmap view mode only covers half of my screen? is there an argument for that?
library(tmap)

data(World)

tmap_mode("view")

tm_shape(World) +
  tm_polygons(c("HPI", "economy")) +
  tm_facets(ncol = 2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: WCF jquery parsererror unterminated string constant response For my recent project, I created a Web service that returns an array of custom type to jquery client-side code. WCF is called by $.ajax command and is in the same domain.
When I run my web applicaiton on localhost (which is IIS run on local machine), everything works fine. When I deploy it to our integration server, suddenly ajax call to WCF ends with an error: "parsererror - unterminated string constant" and status of 200. Returned message is however something like "[{\"Text\":\"Test dodatnih naslov", which of course is not a correct json format.
Correct response should have been: "[{"Text":"Test dodatnih naslovov","Value":"100"},{"Text":"Test dodatnih naslovov - ISO2","Value":"101"},{"Text":"UPDATE","Value":"102"}]"
I have traced WCf service for malfuncitons, but it does not seem to be crashing. I also tried and set timeout to ajax call, but to no avail. Some help would be much appreciated.
My IIS is IIS7, where integration runs IIS6 on Windows Server 2008.
js file
function InsuranceClientContact_ItemsRequesting(o, e) {
    var $ = $telerik.$;
    var urlSvc = ServiceBaseUrl + '/GetContacts'
    $.ajax({
        type: "POST",
        url: urlSvc,
        data: '{"ixClient": ' + selectedItemId + '}', //selectedItemId is a positive number
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            // do something
        },
        error: function (result) {
            var msg = result.status + " - " + result.statusText;
            setTimeout(function () { throw new Error(msg) }, 0);
        }
    });

wcf interface
namespace Sid.Skode.Web.Services.Populate {
    [ServiceContract]
    public interface IInsuranceClientContactService {
        [OperationContract]
        [WebInvoke(Method="POST",
            BodyStyle=WebMessageBodyStyle.WrappedRequest,
            ResponseFormat=WebMessageFormat.Json)]
        Contact[] GetContacts(long ixClient);
    }

    [DataContract]
    public class Contact {
        [DataMember]
        public string Text;
        [DataMember]
        public string Value;
    }

}

wcf service implementation
namespace Sid.Skode.Web.Services.Populate {
    [AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed )]
    public class InsuranceClientContactService : IInsuranceClientContactService {

        public Contact[] GetContacts( long ixClient ) {
            return GetContactsFromDatabase( ixClient );
        }

        #region Private methods

        private Contact[] GetContactsFromDatabase( long ixClient ) {
            DataTable dt = GetDataFromDataBaseById( ixClient );
            return ConvertDataTableToContactArray( dt );
        }

        private DataTable GetDataFromDataBaseById( long ixClient ) {
            AutoCompleteBLL model = new AutoCompleteBLL();
            return model.SearchContactsByPartner( ixClient );
        }

        private Contact[] ConvertDataTableToContactArray( DataTable dt ) {
            Contact[] rgContact = new Contact[dt.Rows.Count];
            int cnContact = 0;
            foreach (DataRow dr in dt.Rows) {
                if (!dr.IsNull( "NAZIV" )) {
                    Contact contact = new Contact();
                    contact.Text = dr["NAZIV"].ToString();
                    contact.Value = dr["ID_DODATEN_KONTAKT"].ToString();
                    rgContact[cnContact++] = contact;
                }
            }
            return rgContact;
        }

        #endregion

    }
}

web.config wcf part
<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="httpServiceBehavior">
          <serviceMetadata httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="httpEndpointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithTransportWindowsSecurity">
          <security mode="Transport">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="false" aspNetCompatibilityEnabled="true" />
    <services>
      <service name="Sid.Skode.Web.Services.Populate.InsuranceClientContactService" behaviorConfiguration="httpServiceBehavior">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithTransportWindowsSecurity"
                  contract="Sid.Skode.Web.Services.Populate.IInsuranceClientContactService"
                  behaviorConfiguration="httpEndpointBehavior">
        </endpoint>
        <endpoint
          address="mex"
          binding="mexHttpsBinding"
          bindingConfiguration=""
          contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>

A: As described here, you need remove all instances of RadCompression http module from web config. Then, it works.


text:
Q: WPF/ How can I IValueConverter Update Force I write code for multilanguage using IValueConverter.
Text will be change dynamically and so many texts has. So I cannot be make using Resource file.
I decided to make using IValueConverter. And First time it displayed well.
But change language runtime, it will not work I expected.
IValueConverter will return a value by current language type.
And language type is change in runtime by user.
This is my simplified code:
internal class MessageConverter : IValueConverter, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string? valueOrigin = parameter == null ? ":" : parameter.ToString();
        string[] values = valueOrigin == null ? new string[2] : valueOrigin.Split(':');
        if (values.Length == 0)
        {
            values = new string[] { string.Empty, string.Empty };
        }
        else if (values.Length == 1 && false == values[0].StartsWith("@"))
        {
            values = new string[] { string.Empty, values[0] };
        }

        if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
        {
            return values[1];
        }

        MessageHelper.GetInstance().LanguageChanged += MessageConverter_langchanged;

        return MessageHelper.GetMessage(values[0]);
    }

    private void MessageConverter_langchanged(object? sender, EventArgs e)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("")); // ???
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public class MessageHelper
{
    private static object lockObject = new object();
    private static MessageHelper? instance = null;

    private Dictionary<string, string> ko = new Dictionary<string, string>();
    private Dictionary<string, string> en = new Dictionary<string, string>();
    private Dictionary<string, string> jp = new Dictionary<string, string>();

    private MessageHelper()
    {
        // smaple
        ko.Add("@MSG_0001", "시작");
        en.Add("@MSG_0001", "Start");
    }

    public static MessageHelper GetInstance()
    {
        lock (lockObject)
        {
            if (instance == null)
                instance = new MessageHelper();
            return instance;
        }
    }

    private string language = "KO";

    public static string GetLanguage(string language)
    {
        return language;
    }

    public static void SetLanguage(string language)
    {
        MessageHelper.GetInstance().language = language;
        GetInstance().LanguageChanged?.Invoke(GetInstance(), EventArgs.Empty);
    }

    public event EventHandler? LanguageChanged;

    public static string GetMessage(string messageCode)
    {
        var dic = MessageHelper.GetInstance().language == "en" ? MessageHelper.GetInstance().en : MessageHelper.GetInstance().ko;
        if (dic.ContainsKey(messageCode))
            return dic[messageCode];
        return messageCode;
    }
}

<Button Style="{StaticResource BoldButtonFontStyle}"
        Content="{Binding Converter={StaticResource MessageConverter}, ConverterParameter=@MSG_0001:시작하기, UpdateSourceTrigger=PropertyChanged}"
        Command="{Binding CommonCommand}"
        CommandParameter="SaleStart" />

<Button Style="{StaticResource BoldButtonFontStyle}"
    Content="한국어"
    Command="{Binding CommonCommand}"
    CommandParameter="Language_Korean" />
<Button Style="{StaticResource BoldButtonFontStyle}"
    Content="English"
    Command="{Binding CommonCommand}"
    CommandParameter="Language_English" />

private void CommonCommandProc(string param)
{
    if (param == "Language_Korean")
    {
        MessageHelper.SetLanguage("ko");
    }
    else if (param == "Language_English")
    {
        MessageHelper.SetLanguage("en");
    }
}

A: I code using inherit 'MarkupExtension'.
It works fine.
Thank you every one.


text:
Q: Creating Multiplie Pie Charts in a same page using d3 with JSON data <!DOCTYPE html>

<meta charset="utf-8">

Adult_Mortality_rate of Whole Population

100

<form>

   <input type="radio" name="dataset" value="country" > country
  <input type="radio" name="dataset" value="value" checked> values
</form>

This is my JSON file:
[{"country":"Singapore","gender": "Male", "Overall":"1234", "Under70": "1224"},
 {"country":"Singapore","gender": "Female", "Overall":"4567","Under70": "5678"}]

A: To have multiple diagrams on the same page the easiest way is to create different svgs in your page within your script and then point the pie charts to the different svgs.


text:
Q: Understanding about Pagination Hi Can someone explain to me what this means?
{#274 ▼
  +"pagelen": 10
  +"next": "https://bitbucket.org/!api/2.0/repositories/spycetek?page=2"
  +"values": array:10 [▶]
  +"page": 1
  +"size": 59
}

what does pagelen means?
and the size?
I just need to fully understand this. thanks

A: {#274 ▼
  +"pagelen": 10  // no of data on one page
  +"next": "https://bitbucket.org/!api/2.0/repositories/spycetek?page=2"  // next page link
  +"values": array:10 [▶]  contents of the page
  +"page": 1  // current page number
  +"size": 59  // i think total number of pages
}

you can always refer to laravel documentations.


text:
Q: Create IOS Background service and Call by Another Application I am new to ios, I wanted to create an iPhone background service with listening to some parameters and those parameters are passed from another application
OR
Create a rest API App that we call from outside of the application or another application
Please help me out with this or please provide me sample code
Thanks
Swapnil


text:
Q: How to calculate subtotals on grouped rows using Knockout in Javascript? I am trying to calculate sub totals for grouped row for selected rows, I am able to calculate but on every change total calculating by looping through all the elements. Can anybody suggest how to add or subtract row value from grouped row. If we have huge number of rows and select all is taking more time. here is sample code of mine http://jsfiddle.net/Srinivasa/PAtSd/2/

A: Your approach looks good to me. If you have performance problems with it you must have really big number of rows, in which case you really want to rethink the UI. That said, you could actually try optimizing calculations by subscribing to qty and selected observables and changing your totals based on old and new values for one book. The code below illustrates the idea but is not a complete solution. Also, standard knockoutjs observable doesn't have lastValue attribute, so you would have to implement it by yourself (here is an example of how you would do it).
function book(...){
    var self = this;
    ...
    self.qty.subscribe(function(newValue){
        if(self.selected()){
            //grandTotal is regular observable, not a computed one
            var grandTotal = rootViewModel.grandTotal();
            grandTotal = grandTotal - self.qty.lastValue() + newValue;
            rootViewModel(grandTotal);
        }
    }
}

For student level subtotals you will need to pass student viewmodel as a parameter to book constructor:
function book(student, name, qty){
    var self = this;
    ...
    self.qty.subscribe(function(newValue){
        if(self.selected()){
            //student.noOfBooks is regular observable, not a computed one
            var noOfBooks = student.noOfBooks();
            noOfBooks = noOfBooks - self.qty.lastValue() + newValue;
            student.noOfBooks(noOfBooks);
        }
    }
}

You will probably need to change student constructor to something like this:
function student(name, books /*array of plain object, not view models*/){
    var self = this;
    self.name = name;
    self.noOfBooks = ko.observable()
    self.books = ko.utils.arrayMap(books, function(b){
        return new book(self, b.name, b.qty);
    });
}


text:
Q: Python: How to read multiple Excel sheets into a list? From Excel, how can I parse 'Sheet1' and 'Sheet2' in to a list? I'm currently using xlrd, as shown in the code below.
Sheet1:

Sheet2:

My code:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
import xlrd
import sys

loc = 'excel.xlsx'
wb = xlrd.open_workbook(loc, encoding_override="iso-8859-5, cyrillic")
wb_name = wb.sheet_names()
count = len(wb_name)
data = []
column_excel =('Name', 'Course', 'Cost', 'level')
count_column = len(column_excel)
for i in range(count):
    ow = xlrd.open_workbook('excel.xlsx').sheet_by_index(i)
    for x in range (0, 100):
        for i in range(2):
            try:
                if ow.cell_value(0, x) == column_excel[i]:
                    ips = ow.col_values(x, 1)
                    data.append(ips)
                    break
            except IndexError:
                continue
print(data)

My results:
[['Andre'], [1], [200], [5],
['Sam'], [2], [100], [8],
[7], ['Antony'], [4], [150],
[9], ['Ben'], [3], [500]]

Expected output:
[['Andre'], [1], [200], [5],
['Sam'], [2], [100], [8],
['Antony'], [4], [7], [150],
['Ben'], [3], [9], [500]]

A: If you'd like to use pandas to read the XLSX file, rather than xlrd, things become much simpler, from a coding perspective. Additionally, as the .append() function is quite clever in its design, the columns are auto-aligned (providing the column name is the same) - which can be helpful since the sheets have different column order.
The official pandas read_excel docs can be found here.
Sample code:
When calling the .read_excel() using multiple sheets, a dict of DataFrames (df_) is returned.  The second line of code is used to combine the DataFrames.
import pandas as pd

df_ = pd.read_excel('courses.xlsx', sheet_name=['Sheet1', 'Sheet2'])
df = pd.DataFrame().append([df_[i] for i in df_]).reset_index(drop=True)

Output (as a DataFrame):
      Name  Course  Cost  level
0    Andre       1   200      5
1      Sam       2   100      8
2  Anthony       4   150      7
3      Ben       3   500      9

Output (as a list):
>>> df.to_numpy().tolist()

[['Andre', 1, 200, 5],
 ['Sam', 2, 100, 8],
 ['Anthony', 4, 150, 7],
 ['Ben', 3, 500, 9]]

Acknowledgement:
This list output is not identical (in format) to the expected output in the question. I presume this is a design flaw, as a the output of this answer provides a list of records rather than a list of individual fields - which may later become difficult to manage.


text:
Q: Custom UICollectionViewLayout header and storyboard I've created a UICollectionViewController in storyboard along with a header for the collection view.
I'm using a third party UICollectionViewLayout called CHTCollectionViewWaterfallLayout. When collectionView(_:viewForSupplementaryElementOfKind:atIndexPath:) is called for a header, kind is CHTCollectionElementKindSectionHeader instead of UICollectionElementKindSectionHeader and the program crashes and tells me I didn't register a class for CHTCollectionElementKindSectionHeader. Makes sense. But if I programmatically register a class for CHTCollectionElementKindSectionHeader, I don't get the benefit of my work with storyboard because the program would call initWithFrame: when initializing the header instead of initWithCoder.
Is there any way to get around this issue where I can somehow use what I've created in storyboard for CHTCollectionElementKindSectionHeader?

A: I was having a very similar issue today and found out that I had to change my header cell registration from:
collectionView.registerClass(
    UICollectionReusableView.self,
    forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,
    withReuseIdentifier: headerId
)

to
collectionView.registerClass(
    UICollectionReusableView.self,
    forSupplementaryViewOfKind: layout.CHTCollectionElementKindSectionHeader,
    withReuseIdentifier: headerId
)

Hope this is helpful, I have been hitting my head against a wall for a couple of hours, and I only found your question when search for help myself.
Note: layout was defined above like this let layout = CHTCollectionViewWaterfallLayout()


text:
Q: GUID foldername on Windows Server 2008 R2 Recently I'm seeing GUID folder names pop up on the system drive of my Server 2008 R2 machine (example below). Does anyone have any idea as to what might be causing these? If you open the folder there's nothing only an empty amd64 folder within.
.
I think it might be WSUS unpacking patches and failing to clean up properly after itself
EDIT 2014-11-24 Added screenshot of permissions

A: You're close--close enough that the folders might have been created as part of the Windows Update process.  But Windows update itself didn't unpack the patches there--it always downloads to %windir%\SoftwareDistribution\Download.
These folders were created by Windows Installer.  To quote from this MSDN article:

The ROOTDRIVE property specifies the default drive for the destination
  directory of the installation. If the Directory column of the
  Directory table indicates the root destination directory by a property
  name that is undefined, the installer uses the value of the ROOTDRIVE
  property to resolve the path to the destination directory.
If ROOTDRIVE is not set at a command line or authored into the
  Property table, the installer sets this property. During an
  administrative installation the installer sets ROOTDRIVE to the first
  connected network drive it finds that can be written to. If it is not
  an administrative installation, or if the installer can find no
  network drives, the installer sets ROOTDRIVE to the local drive that
  can be written to having the most free space.


text:
Q: Why Docker compose link does not work in react app? I've two application as a docker container. ReactJS as frontend and springboot application as backend.
When I up both of applications on windows docker desktop toolbox, I cant login from frontend because of backend api not accessible. All my containers use default network.
in react app I use this link for access to backend  API_URL: 'http://backend:8080/api/'
docker-compose.yml is here.
backend:
container_name: backend
image: backend:2.0.1b4
command: sh -c "/wait && catalina.sh run"
ports:
  - 8080:8080
environment:
  - ROTATOR_CLIENT=agent_url:9091
  - MAST_CLIENT=agent_url:9092
  - working-environment=RLAS
  - DB_URL=jdbc:postgresql://postgres_url:5432/postgres?schema=public
  - DB_USER=postgres
  - DB_PASSWORD=postgres
  - WAIT_HOSTS=postgres_url:5432
  - WAIT_SLEEP_INTERVAL=5
external_links:
  - database:postgres_url
  - agent:agent_url
restart: always

frontend:
    container_name: frontend
    image: frontend:2.0.1b4
    ports:
      - 3000:3000
    environment:
      - base_url=backend_url:9090
    external_links:
      - backend:backend_url
    restart: always

error is that:

A: As you figured out, you'll have to use http://localhost:8080 instead of http://backend:8080 as the URL.
This is because client-side fetching data with JavaScript occurs in your browser, and not inside the container. This therefore happens outside of the docker network.

A: I just changed my API_URL: 'http://backend:8080/api/' to API_URL: 'http://localhost:8080/api/'
now works fine! I don't know how it works!


text:
Q: jQuery: How to select elements of form whose corresponding button has been clicked? I have a jsfiddle here - http://jsfiddle.net/9kKXX/20/
My jQuery function
$(function() {
    $('form input[type="text"]').live('keyup', function() {
        var val = $.trim(this.value);
        $('form .create-playlist-button').prop('disabled', val.length == 0).click(function(){
            alert('ALERT TITLE HERE');
          });
    });
});

Requirement

*

*Click on dropdown -> enter text -> hit create
I would like to select the corresponding form elements like title, views etc. This is not happening right now

*When I click on create, it keeps on alerting again and again, how can I avoid that?
I am very new to jQuery and read couple of places but did not find the solution to it
Thank you
UPDATE
------------
Answer by Jeff works in fiddle, but when I put that on my code, it does nothing on click. I put the entire code sample in this fiddle - http://jsfiddle.net/rDe9V/  , please help me understand what shall have been wrong here

A: There's a few things going on here. Here is the final fiddle.
First, You are binding the click event every time the key up event is fired. That means the alert will fire at least once for every character in the playlist title. You need to bind the click even on document ready.
$(function() {
    $('form input[type="text"]').live('keyup', function() {
        var val = $.trim(this.value);
        $('form .create-playlist-button').prop('disabled', val.length == 0)
    });
    $('form .create-playlist-button').click(function(){
        alert('ALERT TITLE HERE');
    });
});

Second, You are using duplicate ids. There are many elements on the page with

IDs must be unique. You should change these to classes instead.

Third, you can access the title by traversing up the DOM tree to a common ancestor between the clicked button and the title the traverse back down to the title. Assuming you change the IDs to classes, that would look like this:
$('form .create-playlist-button').click(function(e){
    var title = $(e.target).closest('.video-detail').find('.title').text();
    alert(title);
});

You can go to my fiddle to see the final product.

A: I cannot post a comment because of my reputation, but the new problem is that you are searching for a class instead of an id.
Your code:
$('.item').live('click', function(){
    // alert(this.id);
    var url = $('#video-frame').attr('src');
    var new_url = url.replace(/embed\/[\w -]*/g, 'embed/' + this.id);
    $('#video-frame').attr('src', new_url);
});

The correct code (first line):
$('#item').live('click', function(){
    // alert(this.id);
    var url = $('#video-frame').attr('src');
    var new_url = url.replace(/embed\/[\w -]*/g, 'embed/' + this.id);
    $('#video-frame').attr('src', new_url);
});


text:
Q: Export animation sequence from Flash as JPEGs I'm wondering if it's possible at all to sort of record/capture the state of an swf movie over a period of time and save it all down as jpgs to the server?
AS3 has the new com.adobe.images.JPGEncoder class that seems to do the job, but can I capture a sequence? The hope would be that I could put it back together as a video or animation.
Is there other ways to encode swf to video programmatically?

A: I have done a "screen capture" before using the JPGEncoder, so I think you should be able to capture the screen on the ENTER_FRAME event.  This may not work as JPG encoding isn't super fast.
That is how I would go about doing it.  For your reference, here's some code that does this(for a single screenshot):
var fileReference:FileReference = new FileReference();

// Capture the BitmapData of the stage for example
var captureMovieClip:DisplayObjectContainer = stage;

var stage_snapshot:BitmapData = new BitmapData(captureMovieClip.width, captureMovieClip.height);
stage_snapshot.draw(captureMovieClip);

// Setup the JPGEncoder, run the algorithm on the BitmapData, and retrieve the ByteArray
var encoded_jpg:JPGEncoder = new JPGEncoder(100);
var jpg_binary:ByteArray = encoded_jpg.encode(stage_snapshot);

// save
fileReference.save(jpg_binary, "screenshot.jpg");

You can probably extend this to be called in your ENTER_FRAME event handler, and then save the file to different filenames.  Also instead of the stage, you can use a different display object.
I don't know how fast this will run, you may need to lower the frame rate so the ENTER_FRAME isn't called so much, but you'll lose some quality in your JPG renderings.
Also turning down the quality in the line: new JPGEncoder(100)
from 100 to a lower value may help with file sizes of the jpegs(but may or may not incur more overhead with compression).


text:
Q: Find a probability given specific cdf values Given $X$ is uniform random variable, $P\{X>1\} = 0.6$ and $F(2) = 0.5$.
Find $P\{-1\leq X < 3\}$.
My solution is: $P\{X>1\} = F(\infty) - F(1) = 0.6$. So $F(1) = 0.4$
And now I assume that F grows linearly. I need to find $F(3) - F(-1)$. Using fact of linearity I can say that $F(3) - F(-1) = 4 * [F(2) - F(1)]$.
My answer is $4\times(0.5 - 0.4) = 0.4$.
Am I right?

A: If $X$ is uniform on some support $a \le X \le b$, then the density is $$f_X(x) = \begin{cases} \frac{1}{b-a}, & a \le x \le b, \\ 0, & \text{otherwise}. \end{cases}$$ The CDF is then $$F_X(x) = \begin{cases} 0, & x < a \\ \frac{x-a}{b-a}, & a \le x \le b \\ 1, & b < x. \end{cases}$$  We are given $$F_X(1) = 1 - \Pr[X > 1] = 1 - 0.6 = 0.4,$$ and $$F_X(2) = 0.5.$$  From these, we determine $$\frac{1 - a}{b-a} = 0.4, \\ \frac{2 - a}{b-a} = 0.5.$$  Hence $$\frac{0.4}{0.5} = \frac{1-a}{2-a},$$ so $a = -3$; we then substitute back to obtain $b = 7$, and $$\Pr[-1 \le X < 3] = F_X(3) - F_X(-1) = \frac{3-(-3)}{7-(-3)} - \frac{-1-(-3)}{7-(-3)} = \frac{2}{5}.$$

The reason why your solution works is that it so happens that the given probabilities result in the support $[a,b]$ to be "large enough" to contain the desired outcome $-3 \le X < 1$.  For example, now that we know $[a,b] = [-3,7]$, if I asked you for $\Pr[-5 < X < 0]$, you could neither say this is $1$ nor $0.5$.  The answer is $0.3$ because $\Pr[-5 < X < 0] = \Pr[-3 < X < 0]$, since the intersection $$(-5,0) \cap [-3,7] = [-3, 0).$$  So you need an extra step to justify that the "shortcut" you used is valid.


text:
Q: Angular JS: IE Error: 10 $digest() iterations reached. Aborting I'm new to Angular and I'm stuck with a issue relating IE.
Here is the IE Error that I'm getting.
Webpage error details

User Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Timestamp: Thu, 13 Dec 2012 04:00:46 UTC

Message: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: function $locationWatch() {\n      var oldUrl = $browser.url();\n\n      if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t  if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t      defaultPrevented) {\n\t    $location.$$parse(oldUrl);\n\t  } else {\n\t    $browser.url($location.absUrl(), $location.$$replace);\n\t    $location.$$replace = false;\n\t    afterLocationChange(oldUrl);\n\t  }\n\t});\n      }\n\n      return changeCounter;\n    }; newVal: 7; oldVal: 6"],["fn: function $locationWatch() {\n      var oldUrl = $browser.url();\n\n      if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t  if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t      defaultPrevented) {\n\t    $location.$$parse(oldUrl);\n\t  } else {\n\t    $browser.url($location.absUrl(), $location.$$replace);\n\t    $location.$$replace = false;\n\t    afterLocationChange(oldUrl);\n\t  }\n\t});\n      }\n\n      return changeCounter;\n    }; newVal: 8; oldVal: 7"],["fn: function $locationWatch() {\n      var oldUrl = $browser.url();\n\n      if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t  if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t      defaultPrevented) {\n\t    $location.$$parse(oldUrl);\n\t  } else {\n\t    $browser.url($location.absUrl(), $location.$$replace);\n\t    $location.$$replace = false;\n\t    afterLocationChange(oldUrl);\n\t  }\n\t});\n      }\n\n      return changeCounter;\n    }; newVal: 9; oldVal: 8"],["fn: function $locationWatch() {\n      var oldUrl = $browser.url();\n\n      if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t  if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t      defaultPrevented) {\n\t    $location.$$parse(oldUrl);\n\t  } else {\n\t    $browser.url($location.absUrl(), $location.$$replace);\n\t    $location.$$replace = false;\n\t    afterLocationChange(oldUrl);\n\t  }\n\t});\n      }\n\n      return changeCounter;\n    }; newVal: 10; oldVal: 9"],["fn: function $locationWatch() {\n      var oldUrl = $browser.url();\n\n      if (!changeCounter || oldUrl != $location.absUrl()) {\n\tchangeCounter++;\n\t$rootScope.$evalAsync(function() {\n\t  if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).\n\t      defaultPrevented) {\n\t    $location.$$parse(oldUrl);\n\t  } else {\n\t    $browser.url($location.absUrl(), $location.$$replace);\n\t    $location.$$replace = false;\n\t    afterLocationChange(oldUrl);\n\t  }\n\t});\n      }\n\n      return changeCounter;\n    }; newVal: 11; oldVal: 10"]]
Line: 7859
Char: 6
Code: 0
URI: http://localhost:8080/__assets__/lib/angular/angular.js

This is not happening in any other browser but IE 8 and IE 9.
I have a watch looking at a content filtering object which includes a location filter.
My question with this is why doesn't it happen on any other browser but IE and what should I do to get rid of this. Thanks in advance.

A: I can tell from your error report you have a $watch for a changeCounter variable, and this watcher function:
function $locationWatch() {
    var oldUrl = $browser.url();
    if (!changeCounter || oldUrl != $location.absUrl()) {
        changeCounter++;
        $rootScope.$evalAsync(function () {
            if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl)
                .defaultPrevented) {
                $location.$$parse(oldUrl);
            } else {
                $browser.url($location.absUrl(), $location.$$replace);
                $location.$$replace = false;
                afterLocationChange(oldUrl);
            }
        });
    }
    return changeCounter;
};

And the changeCounter gets it's value incremented if $browser.url() doesn't equal $location.absUrl(). As the $watch function can only do 10 loops of change/reaction, it will err after those 10 iterations. As you are changing the value you are watching, it eventually breaks.
I would log those values - $location.absUrl() and $browser.url(), and see why the match in other browsers, but not in ie.

A: Tiago Roldão is definitely right. I had exact the same issue. After debug, I realized in my code I have
location.hash = "#/app/" + id;

which causes the infinitely loop issue. After some research, I found this
$location.path("/apps/" + id);

which solves my issue perfectly.

A: I was facing issue in IE 10.
I was using
window.location.href = '#/';

for changing the route.
Replacing it with
 below code
$location.path('/');

resolved the issue

A: I had the same issue with error which looked the same. Chrome\FF worked fine, but IE failed. I've clicked on some links in my app and sometimes got this error and sometimes not.
1) In my view I had few links which looked like this:
Add some IP

2) Click handler for those links added new object into IpRanges collection like this:
$scope.IpRanges.push(ip);

3) Collection itself was binded on view by ng-repeat, and I thought that somehow IE could not handle this situation well - probably order of binding\adding\applying events wasn't incorrect or else... Also after click on links I had # symbol added to url, and sometimes it blinked, and then I've got an error. So I removed href attribute and everything worked fine:
Add as allowed IP

Probably it's better to use spans or divs for similar situations.

A: TLDR
If you are using ui-router then you can also use
$state.go('details', {id:item.ID});

Background
I was using the following function to navigate from a list view to a details view so that you can click anything with ng-click="details(item)", in my case tr's in the list:
$scope.details = function (item) {
    $window.location.href = "#/details/" + item.ID;
}

But I was getting the dreaded 10 $digest() iterations reached in IE.
FYI
I placed a breakpoint in AngularJS v1.2.0rc1 angular.js line 7650 following Tiago's answer.
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
  var oldUrl = $browser.url();
  var currentReplace = $location.$$replace;

  if (!changeCounter || oldUrl != $location.absUrl()) {
    changeCounter++; /* <-- breakpoint here, line 7650 */
    $rootScope.$evalAsync(function() {
      if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
          defaultPrevented) {
        $location.$$parse(oldUrl);
      } else {
        $browser.url($location.absUrl(), currentReplace);
        afterLocationChange(oldUrl);
      }
    });
  }
  $location.$$replace = false;

  return changeCounter;
});

Results
Output from Chrome

*

*The breakpoint was only hit once the details page was loading and once only.

*oldUrl (i.e. $browser.url() was reporting the old url (i.e. the list one)

*$location.absUrl() was reporting the details url.

Output from IE7,8

*

*The breakpoint was hit continuously.

*oldUrl (i.e. $browser.url() was reporting the new url (i.e. the details one)

*$location.absUrl() was still reporting the list url.

A: I had the same issue using AngularJS v1.2.13 in IE9, IE10, when calling $window.history.back() (especially in Windows Phone).
It seems the root cause is that $window.history.back() in IE changes the href right before the $locationWatch() is fired hence oldUrl would contain the new Url and that throws off the angular into an infinite $digest.
The immediate work around is to replace the calls to $window.history.back() with the following:
setTimeout(function ()
{
    $window.history.back();
}, 0);

A: I had this problem when trying to redirect to other page as
$window.location.href = '#/path/'

solved by changing to:
$location.path('/path/');


text:
Q: HTML/CSS multiple columns I am trying to figure out the best way to create this:

The black square represents small icons, and there is heading and paragraph of that certain section. The icons should be aligned to the heading. The paragraph should be just underneath the heading.

A: I would use absolute positioned icons with a negative margin and float for the 3 columns with a width of 33.33%.
HTML:

Heading

Paragraph

Heading

Paragraph

Heading

Paragraph

CSS:
* {box-sizing: border-box;}
.row {overflow: auto;}
.col {width: 33.33%; float: left; padding-left: 100px;}
.col img {position: absolute; width: 80px; margin-left: -100px;}

@media (max-width: 991px) {.col {width: 100%;}}

Here a working demo: http://codepen.io/anon/pen/bqBNeL

A: If you're just displaying icons, I would not use an image tag at all as they are not "content" per-se. I'd be using background images.

ul {
  list-style: none;
  padding: 0;
}

li {
  background-repeat: no-repeat;
  float: left;

  /*Adjust the below lines based on your icon size*/
  padding-left: 55px;
  width: calc(33% - 55px);

}

h2 {
  /*Adjust the below lines based on your icon size and aligning requirements*/
  margin-top: 12px;
  margin-bottom: 25px;
}

.bill {
  background-image: url(http://fillmurray.com/50/50);
}

.city {
  background-image: url(http://lorempixel.com/output/city-q-c-50-50-7.jpg);
}

.cat {
  background-image: url(http://lorempixel.com/output/cats-q-c-50-50-7.jpg);
}

.food {
  background-image: url(http://lorempixel.com/output/food-q-c-50-50-7.jpg);
}

.sports {
  background-image: url(http://lorempixel.com/output/sports-q-c-50-50-7.jpg);
}

Bill Murray

Some Para

City

Some Para

Cat

Some Para

F00d

Some Para

Sports

Some Para

Bill Murray

Some Para

Cat

Some Para


text:
Q: Load issue with .tmx file I've got an issue when I try to load a .tmx file in a CCTileMap CocosSharp object.
Here is the code :
                layer2 = new CCLayer();
                CCTileMap tileMap;
                tileMap = new CCTileMap("TestCCS.Droid.Assets/TileMaps/TestTile2.tmx");

                layer2.AddChild(tileMap);
                this.AddChild(layer2);

I tried :
                tileMap = new CCTileMap("TestCCS.Droid.Assets.TileMaps.TestTile2.tmx");

or :
                tileMap = new CCTileMap("Assets.TileMaps.TestTile2.tmx");

The TestTile2.tmx file build Action is set to "Embedded resource"
And this my solution explorer :

Thank you for your help.

A: Found a way to load the TileMap file.
The solution I found :

*

*save the TileMap file in .xml format in Tiled software.

*save the .tsx file in .xml format.

*I use this code to load the tile map file :
            layer2 = new CCLayer();
            CCTileMap tileMap;

            CCTileMapInfo mi = new CCTileMapInfo("TestTile2.xml");
            tileMap = new CCTileMap(mi);

            layer2.AddChild(tileMap);
            this.AddChild(layer2);

Where "TestTile2.xml" is an android asset.

*

*every tile of layers must have an Id.
I had tiles without "gid", I had to set them to a transparent gid.

Hope this will help others !


text:
Q: How to send some data from Windows to browser? How can I send some data like a number from an application ran in my Windows to browser(Chrome) Window Object?
I am a web developer and I don't know anything about another languages like C, C++, C#, Python and etc.
Please help me.
Thanks.

A: If you are trying to manipulate the browser from a native windows app have a look at either Selenium Webdriver or the Chromium command line switches


text:
Q: Jekyll Blog don't load css in github pages I've try to create a Jekyll blog using a template Jekyll ready but when I try to load to the branch gh-pages it don't load any resource. I've already checked the base url but nothing, someone can help me?
Link:https://bestbug456.github.io/danilogiordani.info/

A: In _config.yml, add :
baseurl: "/danilogiordani.info"

Call your ressources like this :
<link rel="stylesheet" href="{{ site.baseurl }}/style.css">

<script src="{{ site.baseurl }}/js/jquery-1.11.0.js"></script>

or
<img class="img-responsive" src="{{ site.baseurl }}/img/profile.png" alt="">


text:
Q: How to create a custom streaming data source? I have a custom reader for Spark Streaming that reads data from WebSocket. I'm going to try Spark Structured Streaming.
How to create a streaming data source in Spark Structured Streaming?

A: As Spark 3.0 introduced some major changes to the data source API, here is an updated version:
A class named DefaultSource extending TableProvider is the entry-point for the API. The getTable method returns a table class extending SupportsRead. This class has to provide a ScanBuilder as well as define the sources capabilities, in this case TableCapability.MICRO_BATCH_READ.
The ScanBuilder creates a class extending Scan that has to implement the toMicroBatchStream method (for a non-streaming use case we would implement the toBatch method instead). toMicroBatchStream now returns as class extending MicroBatchStream which implements the logic of what data is available and how to partition it (docs).
Now the only thing left is a PartitionReaderFactory that creates a PartitionReader responsible for actually reading a partition of the data with get returning the rows one by one. You can use InternalRow.fromSeq(List(1,2,3)) to convert the data to an InternalRow.
I created a minimal example project: here

A: Also Here is a sample implementation for a custom WebSocket Stream Reader/Writer which implements Offset, MicroBatchReader, DataReader<Row>, and DataReaderFactory<Row>

A: As Spark is moving to the V2 API, you now have to implement DataSourceV2, MicroBatchReadSupport, and DataSourceRegister.
This will involve creating your own implementation of Offset, MicroBatchReader, DataReader<Row>, and DataReaderFactory<Row>.
There are some examples of custom structured streaming examples online (in Scala) which were helpful to me in writing mine.
Once you've implemented your custom source, you can follow Jacek Laskowski's answer in registering the source.
Also, depending on the encoding of messages you'll receive from the socket, you may be able to just use the default socket source and use a custom map function to parse the information into whatever Beans you'll be using. Although do note that Spark says that the default socket streaming source shouldn't be used in production!
Hope this helps!

A: A streaming data source implements org.apache.spark.sql.execution.streaming.Source.
The scaladoc of org.apache.spark.sql.execution.streaming.Source should give you enough information to get started (just follow the types to develop a compilable Scala type).
Once you have the Source you have to register it so you can use it in format of a DataStreamReader. The trick to make the streaming source available so you can use it for format is to register it by creating the DataSourceRegister for the streaming source. You can find examples in META-INF/services/org.apache.spark.sql.sources.DataSourceRegister:
org.apache.spark.sql.execution.datasources.csv.CSVFileFormat
org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider
org.apache.spark.sql.execution.datasources.json.JsonFileFormat
org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
org.apache.spark.sql.execution.datasources.text.TextFileFormat
org.apache.spark.sql.execution.streaming.ConsoleSinkProvider
org.apache.spark.sql.execution.streaming.TextSocketSourceProvider
org.apache.spark.sql.execution.streaming.RateSourceProvider

That's the file that links the short name in format to the implementation.
What I usually recommend people doing during my Spark workshops is to start development from both sides:

*

*Write the streaming query (with format), e.g.
val input = spark
  .readStream
  .format("yourCustomSource") // <-- your custom source here
  .load

*Implement the streaming Source and a corresponding DataSourceRegister (it could be the same class)

*(optional) Register the DataSourceRegister by writing the fully-qualified class name, say com.mycompany.spark.MyDataSourceRegister, to META-INF/services/org.apache.spark.sql.sources.DataSourceRegister:
$ cat META-INF/services/org.apache.spark.sql.sources.DataSourceRegister
com.mycompany.spark.MyDataSourceRegister

The last step where you register the DataSourceRegister implementation for your custom Source is optional and is only to register the data source alias that your end users use in DataFrameReader.format method.

format(source: String): DataFrameReader
  Specifies the input data source format.

Review the code of org.apache.spark.sql.execution.streaming.RateSourceProvider for a good head start.


text:
Q: MySQLNonTransientConnectionException in JDBC program at run time I have a JDBC MySQL connection in Java. My program works fine for simple execution of query.
If I run the same program for more than 10 hours and execute a query then I receive the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Connection.close() has already been called. Invalid operation in
this state.
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(
  Native Method)
  com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
  No operations allowed after statement closed.
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(
  Native Method)

I have not used close() method anywhere. I created database connection and opened it forever and always executed query. There is no place where I explicitly mentioned timeout for connection. I am unable to identify the problem.
Here is the code I use for the database connection:
 String driver = PropertyReader.getDriver();
 String url = dbURLPath;
 Class.forName(driver);
 connectToServerDB = DriverManager.getConnection(url);
 connectToServerDB.setAutoCommit(false);

What causes that exception?

A: You have to make a change in the configuration file or increase the timeout period of your database. If database remains idle for more than 8 hours it is closed by default.
Thanks

A: MySQL terminates a connection after 8 hour timeout. You can modify the timeout by setting wait_timeout variable in MySQL.
Yet, generally it is not such a good idea for an application to hold a connection for such a long time. A better approach is to set up a connection pool using a pooling API such as Apache DBCP and retrieve connections from the pool rather than directly though a driver. A connection pool will also take care about re-establishing a pooled connection if it dies for some reason, including timeouts.

A: I faced the same problem too. It's because of connection timeout by mysql and generally its not a good practice to extent the timeout in mysql as it serves for many other applications. It's good to reconnect the database on timeouts (i.e when this exception occurs) or to use some open source libraries for connection pooling like Apache DBCP as @slava suggested. ORM Frameworks takes care of this by default. Cheers!!


text:
Q: Row of images appearing as column I'm just getting started with tailwind and I would like to grid essentially a row of images that fit the container.
Currently I am just stubbing in 2 photos for testing/getting to know tailwind purposes.

                    {{item.description}}

This code is causing the 2 images to essentially appear underneath each other as seen here
https://i.imgur.com/vhSBkc7.png
Thank you for any help.

A: Your class should me grid-cols-2 and the img tag should have col-span-1. Checkout Grid Columns

  // grid-cols-2
      // col-span-1


text:
Q: smoothing irregularly sampled time data Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:
6   0.738158581
21  0.801697222
39  1.797224596
49  2.77920469
54  2.839757536
79  3.832232283
91  4.676794376
97  5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157 7.331607129
176 7.637492223
202 7.848079136
223 7.989456499
251 8.76853608
278 9.092367123
    ...

As you see, the measurements are sampled at irregular time points. I need to smooth the data by averaging the reading up to 100 seconds prior each measurement (in Python). Since the data table is huge, an iterator-based method is really preferred.
Unfortunately, after two hours of coding I can't figure out efficient and elegant solution.
Can anyone help me?
EDITs

*

*I want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds. (John, you are right)

*Huge ~ 1e6 - 10e6 lines + need to work with tight RAM

*The data is approximately random walk

*The data is sorted
RESOLUTION
I have tested solutions proposed by J Machin and yairchu. They both gave the same results, however, on my data set, J Machin's version performs exponentially, while that of yairchu is linear. Following are execution times as measured by IPython's %timeit (in microseconds):
data size   J Machin    yairchu
10        90.2        55.6
50          930         258
100         3080        514
500         64700       2660
1000        253000      5390
2000        952000      11500

Thank you all for the help.

A: I'm using a sum result to which I'm adding the new members and subtracting the old ones. However in this way one may suffer accumulating floating point inaccuracies.
Therefore I implement a "Deque" with a list. And whenever my Deque reallocates to a smaller size. I recalculate the sum at the same occasion.
I'm also calculating the average up to point x including point x so there's at least one sample point to average.
def getAvgValues(data, avgSampleTime):
  lastTime = 0
  prevValsBuf = []
  prevValsStart = 0
  tot = 0
  for t, v in data:
    avgStart = t - avgSampleTime
    # remove too old values
    while prevValsStart < len(prevValsBuf):
      pt, pv = prevValsBuf[prevValsStart]
      if pt > avgStart:
        break
      tot -= pv
      prevValsStart += 1
    # add new item
    tot += v
    prevValsBuf.append((t, v))
    # yield result
    numItems = len(prevValsBuf) - prevValsStart
    yield (t, tot / numItems)
    # clean prevVals if it's time
    if prevValsStart * 2 > len(prevValsBuf):
      prevValsBuf = prevValsBuf[prevValsStart:]
      prevValsStart = 0
      # recalculate tot for not accumulating float precision error
      tot = sum(v for (t, v) in prevValsBuf)

A: You haven't said exactly when you want output. I'm assuming that you want one smoothed reading for each raw reading, and the smoothed reading is to be the arithmetic mean of the raw reading and any others in the previous 100 (delta) seconds.
Short answer: use a collections.deque ... it will never hold more than "delta" seconds of readings. The way I've set it up you can treat the deque just like a list, and easily calculate the mean or some fancy gizmoid that gives more weight to recent readings.
Long answer:
>>> the_data = [tuple(map(float, x.split())) for x in """\
... 6       0.738158581
... 21      0.801697222
[snip]
... 251     8.76853608
... 278     9.092367123""".splitlines()]
>>> import collections
>>> delta = 100.0
>>> q = collections.deque()
>>> for t, v in the_data:
...     while q and q[0][0] <= t - delta:
...         # jettison outdated readings
...         _unused = q.popleft()
...     q.append((t, v))
...     count = len(q)
...     print t, sum(item[1] for item in q) / count, count
...
...
6.0 0.738158581 1
21.0 0.7699279015 2
39.0 1.112360133 3
49.0 1.52907127225 4
54.0 1.791208525 5
79.0 2.13137915133 6
91.0 2.49500989771 7
97.0 2.8309395405 8
100.0 3.12993279856 9
118.0 3.74976297144 9
131.0 4.41385300278 9
147.0 4.99420529389 9
157.0 5.8325615685 8
176.0 6.033109419 9
202.0 7.15545189083 6
223.0 7.4342562845 6
251.0 7.9150342134 5
278.0 8.4246097095 4
>>>

Edit
One-stop shop: get your fancy gizmoid here. Here's the code:
numerator = sum(item[1] * upsilon ** (t - item[0]) for item in q)
denominator = sum(upsilon ** (t - item[0]) for item in q)
gizmoid = numerator / denominator

where upsilon should be a little less than 1.0 (<= zero is illegal, just above zero does little smoothing, one gets you the arithmetic mean plus wasted CPU time, and greater than one gives the inverse of your purpose).

A: Your data seems to be roughly linear:
Plot of your data http://rix0r.nl/~rix0r/share/shot-20090621.144851.gif
What kind of smoothing are you looking for? A least squares fit of a line to this data set? Some sort of low-pass filter? Or something else?
Please tell us the application so we can advise you a bit better.
EDIT: For example, depending on the application, interpolating a line between the first and last point may be good enough for your purposes.

A: This one makes it linear:
def process_data(datafile):
    previous_n = 0
    previous_t = 0
    for line in datafile:
        t, number = line.strip().split()
        t = int(t)
        number = float(number)
        delta_n = number - previous_n
        delta_t = t - previous_t
        n_per_t = delta_n / delta_t
        for t0 in xrange(delta_t):
            yield previous_t + t0, previous_n + (n_per_t * t0)
        previous_n = n
        previous_t = t

f = open('datafile.dat')

for sample in process_data(f):
    print sample

A: O(1) memory in case you can iterate the input more than once - you can use one iterator for the "left" and one for the "right".
def getAvgValues(makeIter, avgSampleTime):
  leftIter = makeIter()
  leftT, leftV = leftIter.next()
  tot = 0
  count = 0
  for rightT, rightV in makeIter():
    tot += rightV
    count += 1
    while leftT <= rightT - avgSampleTime:
      tot -= leftV
      count -= 1
      leftT, leftV = leftIter.next()
    yield rightT, tot / count

A: While it gives an exponentially decaying average, rather than a total average, I think you may want what I called an exponential moving average with varying alpha, which is really a single-pole low-pass filter. There's now a solution to that question, and it runs in time linear to the number of data points. See if it works for you.

A: Sounds like you need a simple rounding formula. To round any number to an arbitrary interval:
round(num/interval)*interval
You can substitute round with floor or ceiling for "leading up to" or "since" affects. It can work in any language, including SQL.

A: what about something like this, keep storing values till time difference with last time is > 100, average and yield such values
e.g.
def getAvgValues(data):
    lastTime = 0
    prevValues = []
    avgSampleTime=100

    for t, v in data:
        if t - lastTime < avgSampleTime:
            prevValues.append(v)
        else:
            avgV = sum(prevValues)/len(prevValues)
            lastTime = t
            prevValues = [v]
            yield (t,avgV)

for v in getAvgValues(data):
    print v


text:
Q: How can low latency not = high throughput?
The graph above shows the latency of read and update operations while the column shows the throughput(operations/second) I am unsure how MyISAM can perform operations with such low latency but still be level with InnoDB in terms of throughput? MongoDB also dominates in terms of throughput but has a higher latency than MyISAM.
How do these results make sense?

A: Well, say you have a formula 1 car and a bus. The formula 1 will quickly carry a single pasenger while the slow bus can cary say 40 passengers at a slower pace. The bus will certainly achieve a higher throughput but with a higher latency. Note however, that the bus will lose its advantage in throughput if it is used to carry one passenger at a time.

A: No doubt, the confusing graph you provided comes from a single benchmark.  One of the beauties of benchmarking is that you can devise on to say whatever you what.
Now to shoot a few holes in the "conclusions":
MyISAM, if there is contention from multiple threads, can have bad, even terrible, latency and throughput.  This is due to table-level locking.  (It sounds like the benchmark had only a single thread operating.)
Update latency varies differently dramatically by engine -- depending on whether there is a single thread or multiple threads.  And whether they are competing for the same tables.  Or for the same rows.
The 'throughput' aspect of the benchmark was presumably aimed away from complex queries and toward simpler NoSQL queries.


text:
Q: Developing user interface to replace windows UI I would like to develop an application similar to Thinix touch
What tools would I need? Would visual basic 6 or Visual C++ be sufficient? I do know that some functions can be done using shell commands.

A: For touch based windows programming I highly recommend WPF.

Touch
Heres a short sample of why : http://www.wpftutorial.net/Multitouch2.html

Another cool sample (in silverlight) : http://www.davidezordan.net/blog/?p=1136

Heres a microsoft provided walkthrough : http://msdn.microsoft.com/en-us/library/ee649090.aspx

PS: all standard controls offer touch out of the box (just like any windows application in any windows language)

Rich User Interface composition
 WPF was designed for enabling next generation great interfaces. Check out the samples :  https://stackoverflow.com/questions/928128/wpf-any-cool-ui-ideas-i-can-look-at


text:
Q: comparing two different gridview's selected value Hello I have threegrid views with the select row enabled. The user will select an item from each grid view then on selected index change the values will be compared to the other two gridviews to see if they are equal. While debugging I can see that they are the same so I'm not sure why the if statement is always passing as true. Is it possibly comparing the indexes? Thanks for the help!
If gvCustomer.SelectedValue IsNot gvSiteAddress.SelectedValue Then
            dataSourceGVCust.SelectCommand = ConfigurationManager.AppSettings("SelectCustomer") & " WHERE CUST_NO LIKE '%" & gvSiteAddress.SelectedValue.ToString & "%' ORDER BY CUST_NAME"
        End If
If gvJobNumber.SelectedValue IsNot gvSiteAddress.SelectedValue Then
     dataSourceGVJobNumber.SelectCommand = ConfigurationManager.AppSettings("SelectJobNumber") & " WHERE CUST_NO LIKE '%" & gvSiteAddress.SelectedValue.ToString & "%' ORDER BY JOB_NO"
End If

A: You're misusing the IsNot operator.  See http://msdn.microsoft.com/en-us/library/t3bat82c.aspx
IsNot does a reference equals.  That is, are the two objects PHYSICALLY pointing to the same instance of an object -- not just do they have the same value.
Change IsNot to <> and you should be back in action.
EDIT: A cast to the proper type is likely required.  For example, if your values are a numeric ID then something like:
If CType(gvJobNumber.SelectedValue, Integer) <> CType(gvSiteAddress.SelectedValue, Integer) Then

Or if String then substitute String where you see Integer above.


text:
Q: Eclipse Helios 3.6.0 hangs while installing Egit I am trying to install Egit on my eclipse using market place.
The problem i am facing is that the installation gets stuck at 49%. I waited for almost 2 hours yesterday but still the installation did not happen. Has anyone faced any such problems before?
Is there a manual way i can install Egit. i.e. by downloading a package and then installing. I am using windows 7 machine.
Can anyone please guide me on this issue?
P.s: I have gone through the previous asked questions, and i do not have many other sites being used as download pages.(So it is not slow due to loading of many sites)

A: What has worked for me is the following:

*

*Find a mirror in your country, in my case was http://eclipse.tsl.gr/egit/updates-1.3/

*Go to install software and paste the mirror url in the work with box and select the packages you wish to install

*This is the solver: un check "Contact all update sites during install to find required software"
I am not sure whether it helped but I also updated Java to latest version while trying to install EGit on Helios.

A: Have you tried installing EGit from the following update site?
http://download.eclipse.org/egit/updates
You can use this update site by going to:
Help > Install New Software...
and enter the URL in the Work with: text box

A: I had the same problem as the OP with all marketplace plugins. My downloads of plugins consistently got stuck on 48% or 49% and would eventually time out.
In my case, I solved the problem by turning off my antivirus and then downloading plugins.
While my antivirus was turned off, I did not browse the web. I also ran antivirus and anti malware scans afterwards.


text:
Q: Activemq embedded broker Error when trying to start ERROR org.apache.activemq.broker.BrokerService - Failed to start Apache ActiveMQ ([localhost, null], java.io.IOException: org/apache/activemq/store/NoLocalSubscriptionAware)

INFO  org.apache.activemq.broker.BrokerService - Apache ActiveMQ 5.9.1 (localhost, null) is shutting down

INFO  org.apache.activemq.broker.TransportConnector - Connector tcp://localhost:61616 stopped

WARN  org.apache.activemq.broker.jmx.ManagementContext - Failed to start JMX connector Cannot bind to URL [rmi://localhost:1099/jmxrmi]: javax.naming.NameAlreadyBoundException: jmxrmi [Root exception is java.rmi.AlreadyBoundException: jmxrmi]. Will restart management to re-create JMX connector, trying to remedy this issue.

The code I am trying to use is
BrokerService broker = new BrokerService();
TransportConnector connector = new TransportConnector();
connector.setUri(new URI("tcp://localhost:61616"));
broker.addConnector(connector);
broker.start();

I am getting exception at start() method. I am deploying this on server not in my computer.

A: It's quite hard to say what is wrong given the limited information but one thing I'd check is that there isn't already a broker running on that server as it looks like something is at least sitting on the JMX port already.  You could check in the broker log to see if the broker logs any additional information on the error.


text:
Q: OSSEC active response host deny configuration I'm trying to configure OSSEC Active-response for having the host-deny command to block IP's within a timeframe of 600 s alert level or above.
  <active-response>
    <command>host-deny</command>
    <location>local, server</location>
    <level>10</level>
    <timeout>3600</timeout>

  </active-response>

Can I add the timeframe to the following code with at least 3 alerts within 600s or above within x number of seconds, but unblock after a period of y seconds if no more activity.
Also, is it possible to whitelist some IP's in the a local configuration on the server, not in the global configuration?


text:
Q: df.loc to remove whole row based on condition Quick question,
How would I adapt
df2.loc[df2['A'] ==0, 'B'] = np.NaN

To change to the whole row, aka B,C etc become np.Nan
Without a for loop as this would take too long
Many thanks

A: If you want every column including 'A':
df.loc[df['A'] == 0, :] = np.NaN

If you want every column from 'B' onwards,
df.loc[df['A'] == 0, 'B':] = np.NaN

More generally, if 'A' isn't the first column:
df.loc[df['A'] == 0, df.columns.drop('A')] = np.NaN


text:
Q: Generate new nested list Let's say I have a list of date object. I would like to separate them into a new list by month, and this list will add into another list. Which eventually become a List<List<DateTime>>.
{
[2020-12-25],
[2020-12-25],
[2020-11-24],
[2020-10-23]
}
to
[
[2020-12-25,2020-12-25],
[2020-11-24],
[2020-10-23]
]

What I have tried in sandbox
void test(List<DateTime> datelist) {
List<List<DateTime> mainList = [];
   datelist.forEach((date){
     if(mainlist.isEmpty == true) {
        List<DateTime> temp = [];
        temp.add(date);
        mainList.add(temp);
     } else {
        mainList.forEach((monthList) {
            if(monthList.first.month == date.month) {
               monthList.add(date);
            } else {
               List<DateTime> temp = [];
               temp.add(date);
               mainList.add(temp);
            }
        });
     }
   });
}

But hit error: Uncaught Error: concurrent modification during iteration: Instance of 'JSArray<List<DateTime>>.

A: Something like this should work:
void main() async {
  var dates = <DateTime>[
    DateTime(2020, 12, 25),
    DateTime(2020, 12, 25),
    DateTime(2020, 11, 24),
    DateTime(2020, 10, 23)];

  var monthMap = Map<int, List<DateTime>>();

  for (final date in dates) {
    var list = monthMap[date.month];
    if (list == null) {
      list = [date];
      monthMap[date.month] = list;
    } else {
      list.add(date);
    }
  }

  List<List<DateTime>> mainList = monthMap.values.toList();

  print("[" + mainList.map((e) {
    return "[${e.map((d) => "${d.year}-${d.month}-${d.day}").join(", ")}]";
  }).join(", ") + "]");

}


text:
Q: Come and see us / Come to see us
Come and see us again.
Come to see us again.

What's the difference in their meaning? My translator see no difference. Are they completely the same in their meaning and usage?

A: The following is the short answer and simple answer to what I think the question is.

Come and see us again.
Come to see us again.

These phrases generally mean the same thing, but the first is more informal and the second is what is appropriate for formal usage.  If this answers your question, don't bother to read the rest of this long explanation.
The longer and more complex answer to the question is that there are actually at least five different expressions at issue with different nuances that sometimes overlap.

*

*The first use of "come to" you should understand is that it can express a result that happens to a person.  An example is: "When you live in that city long enough, you will come to see the advantages of urban living."  In this usage, you must use the preposition.  The meaning of "come to" is close to "eventually and naturally," as in "you will eventually and naturally see the advantages."  It emphasizes that you think the result will inevitably happen.

*The next usage to understand would be to use two verbs in separate sentences or clauses, as in "You will come to our city and will see us again."  Here the relationship between "coming" and "seeing" is left open to context and the imagination.  It could just be a prediction that one event will happen completely independently of the other, on the same occasion or maybe even separate occasions.  This meaning can still posssibly be the same if you omit some of the words and just say "You will come and see us again"; however, note the next usage.

*The next usage is "You will come and see us again."  This seems identical to the last, but has no extra words.  The relationship between seeing and coming is technically left open, but leaving out additional words between the two verbs usually strongly implies that they are inseparable parts of a single event with whatever relation between the parts that is natural to assume.  Saying "come and see" with so few extra words almost always means that you are telling the person to come for that purpose.
In this third structure, the implication is that the purpose of coming will lead to seeing the person again without stating that this is necessarily the purpose.  It would be quite natural to use this structure if the purpose in coming included other goals and "seeing us again" was only an additional benefit.  For instance, if you say: "I'm going to go to the store and buy some milk."  You assert that at least one reason for your trip is to buy milk, but you may intend to buy other things as well.  Since this structure has some vagueness associated with it, it is less usual in formal writing.  Also, since this structure doesn't exist in French and Latin, traditional grammarians and those who follow their views look upon it with disfavor as a supposed illogical equivalent of the following more precise expression.

*The next usage is: "Come to see us again."  This expressly links the "seeing" as the purpose of the "coming."  Any other possible purpose or result is irrelevant to the expression.  If there are other possible purposes, they are secondary to this main purpose.  Because this statement is quite precise, speakers often prefer to use the slightly vaguer expression "Come and see us again" described in my point 3 above.  The structure in point 3 is a little softer, since the result of "seeing" can now be just an incidental "result" of coming.  In formal writing, precision is usually valued  and so this fourth structure should be used where possible.

Historically, English usage favored paratactic structures with sentence elements used side by side and joined by coordinating conjunctions (e.g., "come and see").  Under the influence of French and Latin, English now has many hypotactic constructions where sentence elements are embedded in each other or made subordinate to each other (e.g., "come to see").  "Clear" and "direct" writing in English tends to favor the former approach.  "Technical" and "sophisticated" writing tends to favor the latter approach.

*The last structure to consider is "Come in order to see us."  This structure even more explicitly expresses purpose, but is usually felt to be unnecessarily wordy if "come to see" expresses the same meaning.  Editors would usually delete "in order" if the bare infinitive is sufficient in the sentence to express purpose.


text:
Q: A calculation of relative homology. Assume $M$ is a closed manifold, x is a point, x $\in$ $M$, how to calculate $H_n(M, M − x)$?

A: Let $M$ be a $n$-dimensional manifold. As Aaron suggests, by excision $M$ can be assumed to be the $n$-ball $D^n$, with $x=0$. Now, there is a homology long exact sequence
$$H_i(D^n\setminus\{0\})\to H_i(D^n)\to H_i(D^n,D^n\setminus\{0\})\to H_{i-1}(D^n\setminus\{0\})\to\cdots$$
Now $D^n$ is nullhomotopic so only has homology in degree $0$, and $D^n\setminus\{0\}\simeq S^{n-1}$ only has homology in degrees $0$ and $n-1$.


text:
Q: An Algorithm For Finding Modular Square Roots I've been working on this algorithm for awhile, and have made some progress, but have hit a stumbling block. For the cases I'm working on, square roots are guaranteed to exist (atleast trivial ones), so that's not an issue. No assumptions are made about prime/composite modulus. Since roots come in even and odd pairs, I try to find both.
If the number is an actual square, that can be returned immediately, at any point of the algorithm, though I'm debating finding the non-trivial square roots in those cases as well, it just hasn't been necessary yet. For the even side of the algorithm, even numbers have the form $4*n^2$, so I calculate $4^{-1} \pmod n$ and multiply, then try to find the even and odd roots of that number, returning both multiplied by $2$, no issues there.
On the odd side, it's a bit more complicated. Odd square numbers have the form $8*\frac{k*(k+1)}{2}+1$, where $n = 2*k+1$. By subtracting $1$ and multiplying by $4^{-1}$, we isolate $k*(k+1)$. For some numbers, it suffices to just calculate non-modular $(k*(k+1))^{1/2}$ and take the floor, but this only works if the value of $k$ is less than $n^{1/2}$. If $k$ is greater, you can add multiples of $n$ and take the non-modular square root of that number and keep testing if you found the correct $k$, but this takes the algorithm to a much higher complexity than I want to allow.
I'm trying a find a way to transform $k*(k+1)$ into a problem I can solve for $k$ efficiently, I just haven't had much luck. An algorithm to determine the multiple of $n$ that's needed to find the proper value of $k$ would also work if it's fast (logarithmic), but I haven't had luck with that either. Is there some obvious steps I could try that I'm missing here? An example number where this is actually important is trying to find $72^{1/2} \pmod{287}$, which has trivial roots of $143$ and $144$, but also has at least one non-trivial roots $102$ and $185$. To solve it, I have to find the odd square root of $18$, but $k*(k+1) = 76 \pmod{287}$, with actual value of $k = 25$ and square root therefore $51$.
I'm not very worried about finding all of the roots, so much as finding at least one non-trivial root if it exists. The specific numbers I'm finding non-trivial roots of are $4^{-1}$ for odd numbers (all odd numbers have trivial roots $\frac{n+/-1}{2}$, only composite odd numbers with multiple prime factors have non-trivial roots), since this can be used to find values for which $a^2 \equiv a \pmod{n}$, which gives us values for extended euclidean algorithm to find factors of $n$.
EDIT: So to follow up on this, I've solved the problems with the original algorithm. essentially what we're looking at are the different partitions of residues mod n. If we can find one non-trivial square root of any residue in the partition, we can find all of the rest using 2^t*root mod n, where t is the distance between the residues in the chain. The length of these chains is always a factor of totient n, which can sometimes be much smaller than totient n, not allowing enough numbers to check to find an 'easy' non-trivial root. Also, we can't usually just stop when finding a perfect square because it may still yield a trivial root after 2^t multiplication.
The next step if there simply isn't an easy non-trivial root is to go to the next odd square (1 being the 1st), and finding a non-trivial square of one of the numbers in that chain, so that you have the root of 4 times an odd square and multiply by the inverse of the odd square. This obviously means the inverse must exist, but if you can't find an inverse, you already know that it shares a factor with n and can reduce n to get a number which works. The first 4 numbers for which a non-trivial root cannot be found in the first chain are 205, 217, 511, and 513. Because the lengths of the chains are factors of totient n (actually Carmichael function of n), prime numbers will have a very long running time to actually prove them prime, essentially n/2, since that's how many quadratic residues there are mod n.
But in practice for composite numbers, you don't actually need to go through every quadratic residue, since there are atleast sqrt(n) numbers which will yield a non-trivial root. And there may be a cutoff point where a number can be said to be deterministically prime/prime power (or atleast with a high degree of confidence) without having to perform every single iteration of modular multiplication. I'm trying to find hard numbers for the probability that a given chain contains or does not contain a non-trivial root, since the complexity rises to sqrt(n)*log(n)^c in the worst case (prime/prime power) but the average case is usually log(n)^c (actually substantially less than this).


text:
Q: Apply a function to each row in a data.frame and append the result to the data.frame in R It seems like I should either know how to do this or at least find the answer here or elsewhere. Unfortunately neither is working.
I have a data frame of customers where one column is their id and another column is their full address. I want to add 3 columns for each row with the lat, long and county code from a geocode lookup.
That data frame looks like
customer_id       fulladdress
     1            123 Main St., Anywhere, FL
     2            321 Oak St., Thisplace, CA

I created a geocode function that takes the full address and returns a data frame with lat, long and county columns.
How can I apply my geocode function to each row of the data frame and append the results as 3 columns into the existing data frame so that it looks like this:
customer_id       fulladdress                      lat        long     county
     1            123 Main St., Anywhere, FL     33.2345    -92.3333   43754
     2            321 Oak St., Thisplace, CA     25.3333    -120.333   32960

I've tried playing with apply and ddply, but I can't seem to figure out what either one is doing. I tried this with ddply but all it does is give me back the original data frame.
ddply(customers[1:3,], .(fulladdress), function(x) { geocode(x$fulladdress)})

Thanks for the help.

A: Thanks for putting me on the right track. Here is what finally worked:
cbind(customers, t(sapply(customers$fulladdress,geocode, USE.NAMES=F)))


text:
Q: Hybrid application development (PhoneGap, Cordova, Ionic) under the hood I am trying to understand how everything works, but have some questions about this topic.
I will explain how I understand this stuff.
First of all lets start from Cordova this is platform that translates JS,CSS,HTML files into native app. But stop this is not exactly the true.
Really it just puts all html, css files into asset folder only thing that such platform does is creates custom WebView specific for the platform, configures it, binds all required plugins to it and sets default page to open.
Everything else is just web development except hook methods provided by platform plugins which help to access native features like GPS,Camera through java calls from WebView.
So all other stuff is up to specific native web-core to handle and support features like HTML5, CSS3 ... If for example WebKit implementation of specific android version doesn't support such features, you cannot do something to get it working rather than update low level core of Android.
So I have following questions.

*

*What are platforms like Onsen UI, Ionics, Sencha ... Official websites say HTML5 Hybrid Mobile App Framework and UI Components for PhoneGap & Cordova. Why keyword HTML5 is used everywhere, this is just feature of native browser core nothing more, if browser doesn't support all these platfroms and frameworks are useless.

*What do special these platform provide to be Mobile-hybrid specific. I understand that PhoneGAp and Cordova provides plugins and some proxies for communicating with native API, but in case of UI frameworks this is just css,js, html files ? Why I can't use them in default PC browser ?

*What is the purpose of installing such platform and frameworks for example through npm for instance npm install onsenui, why I can't just simple copy js files to my project directory ? I understand that some platforms use css-preprocessors to compile pseudo-css files into css files, but in case of absence of such tools.
Please tell me where I am wrong and answer my questions. I would be grateful for any help

A: 1) All of the libraries / frameworks you mentioned in your first question are a little different.

*

*Ionic provides a UI framework (i.e. controls) to be used in hybrid apps as well as angular services to interact with the UI controls provided. It essentially gives you an entire stack on which to build you hybrid app.

*Onsen UI is another UI framework smaller and slightly more library agnostic than Ionic. Onsen does provide Angular bindings and services for their UI, but also works with plain old vanilla JS or jQuery. The upcoming version also supports React bindings.

*I cannot say too much about Sencha (I have not used it), but it is as well UI framework. Snecha, however, uses their own JS framework called ExtJS.
The use of the keyword HTML5 is more likely to advertise that the UI framework is using modern web technologies (Flexbox, etc.). I (and please someone correct me if I'm wrong) believe that that may be just a marketing ploy.
2) Technically, none are Hybrid specific. You are correct in believing that they can be used in a desktop browser environment. That being said, the UI components are designed for mobile and would not look very appealing on desktop. They are best suited for Hybrid apps and mobile web apps. Ionic is even pushing for progressive web apps and plans on extending support for desktop (including electron).
3) Installing these frameworks via a package manager is a matter of convenience as well. You easily could copy the files over (Ionics's website explains that you can do this). and manually compile the styles, but it's more work to get things working correctly. Some, like Ionic have a CLI installed through NPM, but the framework is typically installed via bower. It also makes it easy to upgrade when a new version is released. Overall, you could ask, why use package managers for any language / platform, and it comes down to organization and conveniences.
I hope I answered all your questions, and if not please leave a comment.


text:
Q: Ошибка: Can't convert 'int' object to str implicitly Я новичок-программист и у меня возникла проблема. Создавал рандомайзер при помощи модуля PySide. Но как только я пытаюсь вывести на экран случайное число мне выкидывает вышеупомянутую ошибку.
Помогите пожалуйста.
v =ui.lineEdit_2.text()
b =ui.lineEdit_3.text()
def bp():
    for i in range(1):
        ui.lineEdit_4.setText(str(random.randint(v, b+1).encode("utf-8").decode("utf-8")))
        return self.randrange(v, b+1)

ui.pushButton.clicked.connect(bp)

Ошибка выглядит так: TypeError: Can't convert 'int' object to str implicitly


text:
Q: Задача "Выборы" На выборах в Государственную думу в избирательные бюллетени внесено N партий. Электронный сканер для считывания информации с бюллетеней передает информацию о каждом бюллетене в следующем формате: если в соответствующей клетке бюллетеня стоит пометка, то сканер передает + (плюс), в противном случае он передает - (минус). Таким образом, он передает последовательность из N символов - плюсов и минусов.
Бюллетень считается действительным, если пометка есть ровно в одной клетке. Недействительные бюллетени в подсчете результатов выборов не участвуют.
Партия проходит в Государственную Думу, только если она набирает не менее 7% от общего числа действительных бюллетеней.
Требуется вывести номера (в порядке их перечисления в бюллетене) всех партий, которые проходят в Государственную Думу.

Код не проходит 1 тест, но я не знаю, какой. Помогите, пожалуйста, с задчкой.
#include <iostream>
#include <string>
#include <vector>
typedef long long ll;
using namespace std;
bool trub(string s)
{
    int kol = 0;
    for (int i = 0; i < s.size(); i++)
        if (s[i] == '+')
            kol++;
    if (kol == 1)
        return true;
    else
        return false;
}
int main()
{
    ll n, m;
    cin >> n >> m;
    vector<string>a(m);
    vector<ll>b(n);
    long double kol1 = 0;
    for (int i = 0; i < m; i++)
    {
        cin >> a[i];
        if (trub(a[i]) == true)
        {
            kol1++;
        }
    }
    for (int i = 0; i < m; i++)
    {
        if (trub(a[i]) == true)
        {
            for (int j = 0; j < a[i].size(); j++)
            {
                if (a[i][j] == '+')
                    b[j]++;
            }
        }
    }
    kol1 = kol1 * 0.07;
    for (int i = 0; i < b.size(); i++)
    {
        if (b[i] >= kol1 && b[i] != 0)
            cout << i + 1 <<' ';
   }
   return 0;
}


text:
Q: Sending Email from asp classic page When @ is in the body of email of classic asp page , the server where my application is deployed is not sending email. When I remove @ from the body email are going . Please tell me what could be the issue.
Thanks
Irfan Shaikh

A: Without more information such as code examples and server stack etc, I would say maybe replace the character with & #64;


text: Q: Connect to WLAN swift ios Is it possible to connect to WLAN using swift, in case I receive WLAN SSID and password from API with my permissions, and before connection I also accept Terms & Conditions. So as a user I totally agree that to happen through a particular app. So I'll search for/or get my local area network by name/WLAN SSID, and connect to it by password but all should go through code. The point is that even though I've a secured wlan, everyone who comes to my store and has my app to be able to connect to wifi even though it's secured.


text:
Q: Uses of 'that' as Relative or Noun Clause in a sentence The kittens are so noisy that I can hardly hear what you are saying.
Is 'that' a relative pronoun in this sentence? or Noun Clause? Can you explain in detail for both cases? thanks

A:
The kittens are so noisy [that I can hardly hear what you are saying].

The bracketed element is a declarative content clause functioning as complement of "noisy", the head of the adjective phrase.
Although it's a complement of the head, it's actually licensed by the "so" that modifies "noisily". We know this because if the "so" is dropped the sentence becomes ungrammatical.
For this reason, it can be called an 'indirect complement'.
Note: I would advise you to drop the term 'noun clause'. The classification of finite subordinate clauses is based on their internal form rather than spurious analogies with the parts of speech.


text:
Q: MySQL - Show result of count I just trying to show a result of a consult in MySQL (PHP).
The code is:
$example = mysql_query("SELECT count(*) as text FROM table WHERE name = '$name'");
$qtd = mysql_num_rows($example);
while($data = mysql_fetch_array($qtd)){
$count = $data["text"];
}

echo "
($count)
";

Error: Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\Site\index.php on line 9

A: CHANGE THIS
 while($data = mysql_fetch_array($qtd)){
 $count = $data["text"];
 }

to
while($data = mysql_fetch_array($example)){
 $count = $data["text"];
  }

EDIT :
you dont need to do a while loop here.
you should just do like that
     $example = mysql_query("SELECT count(*) as text FROM table WHERE name = '$name'");
     $data = mysql_fetch_array($example) ;
     $count = $data["text"];
     echo "
".$count."
";

A: This should work, you don't need to use a while statement.
$query = mysql_query("SELECT * FROM table WHERE name = '$name'");
$count = mysql_num_rows($query);
echo $count;


text:
Q: XWayland applications with black flickering Currently on my computer I have ArchLinux with sway-nvidia + nvidia-lts. With 2 monitors (1080p 144hz and 1080p 60hz) The wayland applications work perfectly (Chrome, vkube, alacritty, etc) but the X11 ones I have a graphic problem (xeyes, gparted, vmware-workstation, gimp, etc).
I attach this folder where there are 2 videos where you can see these failures. https://drive.google.com/drive/folders/1ji9GX3T1l4upFsrn4ErI4LMMrOaqXNpc?usp=share_link
I have tried to look for information and solutions but nothing I have tried seems to work.
Change environment variables such as XDG_CURRENT_DESKTOP
Change xorg.conf configuration
Using a single monitor
Using sway-git and wlroots-git


text:
Q: $(1^n+2^n+3^n+4^n)\mod5$ and using euler totient function to solve this The problem gives us an integer $n$ which can be extremely large (can exceed any integer type of your programming language) and we need to calculate the value of the given expression .
$$(1^n+2^n+3^n+4^n)\mod5$$
I came across this solution but couldn't get any of its steps so , I understand
$a^{\phi(n)}=1 \mod n
$

at the end according to solution we just need to check
if( n%4==0 )
        printf("4");
    else
        printf("0");

A: The first point of confusion is that $n$ seems to be used for $2$ different things.  Those $\phi(n)$'s should be replaced by $\phi(5)$. As for why the exponents are simply $n\mod4$, we have
$$a^n=a^{4q+r}=(a^4)^qa^r$$
Since $a^4\equiv 1\pmod5$, we have $a^n\equiv a^r\pmod5$ where $n\equiv r\pmod4$.  All that remains are to check the four possible cases.  If $n$ is a multiple of $4$, each term is equivalent to $1$ for an answer of $4$. If $n$ is odd, $1^n+4^n\equiv1^n+(-1)^n\equiv 1^n-1^n\equiv0\pmod5$.  The last case to check is $n\equiv2\pmod4$.  Since all squares are equivalent to $\pm1\pmod5$, this is equivalent to $2(1)+2(-1)\equiv0\pmod5$.

A: $\phi(5)=4$ and $m^{4} \equiv 1 \pmod 5$ for $m \in \{1,2,3,4\}$
so $m^{4a+b} \equiv m^b \pmod 5$ for $m \in \{1,2,3,4\}$
so $1^{4a+b} +2^{4a+b} +3^{4a+b} +4^{4a+b} \equiv 1^{b} +2^{b} +3^{b} +4^{b} \pmod 5$
so you only need to check $1^{b} +2^{b} +3^{b} +4^{b} \pmod 5$ for small $b$, and this does indeed give $0,0,0,4,\ldots$ for $b=1,2,3,4,\ldots$ with the pattern repeating


text:
Q: service worker fail NTLM auth with 504 error Try to use Service worker in my Angular7 app. ServiceWorker compiled by ServiceWorkerModule.
This issue was reproduced only if I use a service worker.

I can not understand why SW initiate auth POST request without sending pre-flight OPTIONS req.
May be anybody can help with this issue?
requests without WS:


text:
Q: Three ways to print in Python -- when to use each? According to Tim Peters, "There should be one-- and preferably only one --obvious way to do it." In Python, there appears to be three ways to print information:
print('Hello World', end='')
sys.stdout.write('Hello World')
os.write(1, b'Hello World')

Question: Are there best-practice policies that state when each of these three different methods of printing should be used in a program?

A: Note that the statement of Tim is perfectly correct: there is only one obvious way to do it: print().
The other two possibilities that you mention have different goals.
If we want to summarize the goals of the three alternatives:

*

*print is the high-level function that allow you to write something to stdout(or an other file). It provides a simple and readable API, with some fancy options about how the single items are separated, or whether you want to add or not a terminator etc. This is what you want to do most of the time.

*sys.stdout.write is just a method of the file objects. So the real point of sys.stdout is that you can pass it around as if it were any other file. This is useful when you have to deal with a function that is expecting a file and you want it to print the text directly on stdout.
In other words you shouldn't use sys.stdout.write at all. You just pass around sys.stdout to code that expects a file.
Note: in python2 there were some situations where using the print statement produced worse code than calling sys.stdout.write. However the print function allows you to define the separator and terminator and thus avoids almost all these corner cases.

*os.write is a low-level call to write to a file. You must manually encode the contents and you also have to pass the file descriptor explicitly. This is meant to handle only low level code that, for some reason, cannot be implemented on top of the higher-level interfaces. You almost never want to call this directly, because it's not required and has a worse API than the rest.
Note that if you have code that should write down things on a file, it's better to do:
my_file.write(a)
# ...
my_file.write(b)
# ...
my_file.write(c)

Than:
print(a, file=my_file)
# ...
print(b, file=my_file)
# ...
print(c, file=my_file)

Because it's more DRY. Using print you have to repeat file= everytime. This is fine if you have to write only in one place of the code, but if you have 5/6 different writes is much easier to simply call the write method directly.

A: To me print is the right way to print to stdout, but :
There is a good reason why sys.stdout.write exists - Imagine a class which generates some text output, and you want to make it write to either stdout, and file on disk, or a string. Ideally the class really shouldn't care what output type it is writing to. The class can simple be given a file object, and so long as that object supports the write method, the class can use the write method to output the text.

A: Two of these methods require importing entire modules. Based on this alone, print() is the best standard use option.
sys.stdout is useful whenever stdout may change. This gives quite a bit of power for stream handling.
os.write is useful for os specific writing tasks (non blocking writes for instance)
This question has been asked a number of times on this site for sys.stdout vs. print:
Python - The difference between sys.stdout.write and print
print() vs sys.stdout.write(): which and why?
One example for using os.write (non blocking file writes demonstrated in the question below). The function may only be useful on some os's but it still must remain portable even when certain os's don't support different/special behaviors.
How to write to a file using non blocking IO?