text:
Q: How to customize the LXTerminal console in Lubuntu 16.04? first say hello, I'm new to the site.
I just installed Ubuntu 16.04.4 LTS on my computer and I still have to familiarize myself with the OS.
One of the things I can not change is the appearance of LXTerminal, which comes from black background and white letters.
I just wanted to change, for example, the color of the place where I am.
Example: user @ user: ~ / Documents $
As I say, everything is blank. Only the directories that are blue change.
I have seen several articles, but in none I find the editing tools that this console has.
It shows me: Edit> Preferences> And there are only four tabs to choose from:
Style, Show, Advanced, Shortcuts
I can not find a way to give it a little appearance, I have seen that with commands it is also possible, but with what I saw so far I am not capable.
If you can give me some idea or where to look for information.
Thank you

A: If you want colours you have 2 easy options.

*

*Upgrade to 18.04,
the new terminal has a funky colour scheme.

*Go to software and download terminal.

System tools-> Software, then search terminal.
The store typically has pictures from which you can get a feel for its functionality.

A: First backup using cp ~/.bashrc ~/.bashrc-backup
Edit the file ~/.bashrc and replace these lines:
if [ "$color_prompt" = yes ]; then
    PS1='───────────────────────────────────────────────────────────────────────────────
${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='───────────────────────────────────────────────────────────────────────────────
${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

Save the file and reopen the terminal to see if you like it.
If you don't like it restore the backup with: cp ~/.bashrc-backup ~/.bashrc and reopen the terminal.
What it looks like

NOTES:

*

*You don't need 18.04. This works in Ubuntu 16.04 and Lubuntu 16.04 (but the background there is black and the fonts are as well defined)


text:
Q: Swift 2 - Search in string and sum the numbers My old code was:
let comps = split(str, { $0 == "-" || $0 == " " }, maxSplit: Int.max, allowEmptySlices: false)

after update of Swift 2 my XCode 7 fix it to:
let comps = split(str.characters, { $0 == "-" || $0 == " " }, maxSplit: Int.max, allowEmptySlices: false).map { String($0) }

but now I have an error: Cannot invoke 'map' with an argument list of type '((_) -> _)'
How to fix it.
Link to old answer on Swift

A: The order of arguments for split() function messed up for some reason.  It should be:
let comps = split(str.characters, maxSplit: Int.max, allowEmptySlices: false) {
    $0 == "-" || $0 == " "
}.map {
    String($0)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the first child id inside the div using JQuery How to get the first child id inside the div using JQuery.
Sample code:

I want to get the id a1.
I have tried $('#id1 a:first-child').html() to get the text. How to get the id?

A: If you want immediate first child you need
$(element).first();

If you want particular first element in the dom from your element then use below
var spanElement = $(elementId).find(".redClass :first");
$(spanElement).addClass("yourClassHere");

try out : http://jsfiddle.net/vgGbc/2/

A: $("#id1:first-child").attr("id")

A: Use this to get first element of id1 element:
    $("#id1").children(":first");

A: Below Answer Will Select First 'a' Element under element With ID - 'id1" ( As per Asked in Question )
$('#id1 a:first-child').attr('id')

Below Code will only Select First Div with ID - 'id1' So it will select that div not child element of div ( But its not as per asked by question in answer )
$('#id1:first-child').attr('id')

A: $('#id1:first-child').attr('id')

A: To make things super clear, this is what to do in order to find any element within a certain element you already can access, in this case that is the element with id='e1':

text

The following line get's you div e2:
var child2 = $('#e1').find(".c2");

The following lines both get you div e3:
var child3   = $('#e1').find(".c3");
var child3_1 = $('#e1').find(".c2 :first");

To change something about these, you have to use the objects like this:
$(child2).css('background-color','white');
$(child3).css('border','4px dotted pink');
$(child3_1).css('color','#ef2323');

I hope this is clear and helpful.
Edit: This comment should be removed because it provides no value.

A: $("#form .form-group").first();
May be helpful for someone.


text:
Q: gdb convenience variable strcat I want to use convenience variables to collect a list of things.  I couldn't find anything about string concactenation of convenience variables.  So I tried some things out.
check this out:
(gdb) set $foo="foo"
(gdb) p $foo
$45 = 0x84c7fd8 "foo"
(gdb) call strcat($foo,"bar")
$46 = 139231192
(gdb) p $foo
$47 = 0x84c7fd8 "foobar"

Ok so i tried harder to crash it:
(gdb) set $foo="foo"
(gdb) set $bar="blue"
(gdb) p $foo
$48 = 0x85d9100 "foo"
(gdb) p $bar
$49 = 0x83cd1e8 "blue"
(gdb) call memset($foo,' ',100000)
$50 = 140349696
(gdb) call strlen($foo)
$51 = 100001
(gdb) p $foo
$52 = 0x85d9100 ' ' <repeats 200 times>...
(gdb) p $bar
$53 = 0x83cd1e8 "blue"

I'm getting lucky.
Yep:
(gdb) call sprintf($foo, "%d %d %d\n", 1,2,3)
*** glibc detected *** /dev_tools/base/LOCAL-4.0.8_RHEL5.4/bin/sicstus: malloc(): memory corruption: 0x085e8790 ***
======= Backtrace: =========
/lib/libc.so.6[0x9da250]
/lib/libc.so.6(__libc_malloc+0x67)[0x9dbd87]
/lib/libc.so.6(__libc_memalign+0x12b)[0x9dc01b]
/lib/ld-linux.so.2(malloc+0x25)[0x966705]
/dev_tools/base/LOCAL-4.0.8_RHEL5.4/bin/sicstus[0x80486f0]
[0xa]
======= Memory map: ========
00952000-0096c000 r-xp 00000000 fd:00 34185                              /lib/ld-2.5.so
0096c000-0096d000 r--p 00019000 fd:00 34185                              /lib/ld-2.5.so
0096d000-0096e000 rw-p 0001a000 fd:00 34185                              /lib/ld-2.5.so
00970000-00aaf000 r-xp 00000000 fd:00 34194                              /lib/libc-2.5.so
00aaf000-00ab0000 ---p 0013f000 fd:00 34194                              /lib/libc-2.5.so

Maybe this is a better way to do it:
(gdb) set $foo=(char*)malloc(100000)
(gdb) p $foo
$83 = 0xf0d18bd0 ""
(gdb) call memset($foo,' ',100000)
$84 = -254702640
(gdb) set $foo[99999]=0
(gdb) call strlen($foo)
$85 = 99999
(gdb) set $foo[0]=0
(gdb) call strcat($foo,"12345")
$86 = -254702640
(gdb) call strcat($foo,"12345")
$87 = -254702640
(gdb) p $foo
$88 = 0xf0d18bd0 "1234512345"

Anyone got a better idea?
EDIT
Thanks to Employed Russian, this works:
2       breakpoint     keep y   0xf1b451ee in xxx at yyy.c:230
        breakpoint already hit 30 times
        silent
        set logging on
        p szFileName
        set logging off
        cont

EDIT 2
Here is some stuff that worked with malloc:
1       breakpoint     keep y   0xf1ac915f in xxx at yyy:346
        breakpoint already hit 334 times
        silent
        call sprintf($foo+strlen($foo),"%.3s %.4s %lf\n", s1, s2, (p->Amts[0].lfAmt > 0.01) ? p->Amts[0].lfAmt : p->Amts[1].lfAmt)
        cont

before a run, I would do this:
(gdb) set $foo=(char*)malloc(100000)
(gdb) set $foo[0]=0

A: This:
(gdb) set $foo="foo"

effectively executes $foo = strdup("foo") in the inferior (being debugged) process.
This:
(gdb) call strcat($foo,"bar")

corrupts heap in the inferior. It didn't crash by pure luck.

Anyone got a better idea?

There is no better idea.
Also, I've never needed to collect things in that fashion. It seems to me that you could achieve the same result in a much more flexible way by either running GDB in emacs, or just cut/pasting the values you need into an editor buffer.


text:
Q: Unzip binary email attachment I have a background job in a Rails app which generates a big CSV file and sends it as an attachment to an email message. To manage the size of the email, I'm zipping the CSV before it's attached. This works fine; we have Letter Opener in development and I can open the zipped attachment and read the data. I'm using the "rubyzip" gem to do the zipping.
The trick seems to be testing it. Using rspec, I can verify that the message has an attachment and that the type of the attachment is application/x-zip-encoded, which is all good. What I'd like to do is unzip the attachment and validate the data within the test, though, and that's proving more difficult. The attachment is an object of type Mail::Part. If I call the attachment part, I can get data from it using part.body.raw_source, part.body.encoded or part.decode_body. (The first and third are identical.) part.body.encoding tells me the body is binary. When I try to feed the data to a Zip::InputStream object (using Zip::InputStream.open(part.body.raw_source) or any of the other data methods) I get something like ArgumentError: string contains null byte.
How can I open this attachment and read its data within rspec? I have a hunch there's a decoding step I need to do in here somewhere.
The errors look a lot like this question, but there's no answer there either.

A: The solution here was a little less than ideal, but it works. I had to use the Mail library to write the attachment to a file, then use Zip::File to extract the original data and verify it.
it 'has a ZIP attachment' do
  additional_fields = ["student_identifiers"]

  expect(message.attachments.size).to eq(1)
  message.attachments.first.tap do |zip|
    expect(zip.content_type).to eq('application/x-zip-compressed')
    tmpfile_name = "tmp/#{zip.filename}"
    File.open(tmpfile_name, "w+b", 0644) { |f| f.write zip.decoded }
    csv = Zip::File.open(tmpfile_name) do |zip_file|
      entry = zip_file.glob('*.csv').first
      entry.get_input_stream.read
    end
    csv.split("\n").tap do |rows|
      expect(rows.size).to be(2)
      rows.each do |row|
        expect(CSV.parse_line(row).size).to eq(dimensions_count)
      end
    end
    File.delete(tmpfile_name)
  end
end


text:
Q: Matlab HRV frequency domain analysis using pburg and pwelch function i am doing HRV analysis and i've ran into a problem. I have sets of RR interval (about 100-160 in each) for example RR=[726 679 687 655 719 632 1071 978] etc, there are about 100-160 values in each RR. Now i need to do frequency analysis using function pburg and pwelch and then spliting the PSD from these functions into frequency bands (LF = 0.03 - 0.86 Hz; HF = 0.86 - 1.91 Hz). My sampling frequency is 2000.
So far that part of my code looks like this:
[Pxx1,w1]=pburg(RR,16,256,2000);
[Pxx2,w2]=pwelch(RR);

This function returns PSD on y-axis and frequency (0-1kHz) on x-axis. I just cant figure out how to evaulate PSD in these frequency bands (I need 0.03 - 0.86 Hz and x-axis is 0-1kHz, which seems extreme). After that i need probably itegrate the space under that curve somehow?
I i would figure pburg second thing is i dont know what input arguments should i input into pwelch.

A: If I am correctly getting you, you want to find the PSD within a specified frequency range.
If my assumption is correct, you can do the following.
%[Pxx,W] = PWELCH(double(data),window_length,overlap_size,[low_freq:high_freq], sampling_freq);

[Pxx,W] = PWELCH(double(RR), 512, 256, [30:860], 1000);

plot(W,(Pxx));

xlabel('Hz'); ylabel('Power');


text:
Q: Many-to-Many Nested Attributes in Rails 4 (with strong parameters) I have been trying to figure this one out for a few days now. I am using Rails 4 (with the updated mass assignment technique) and trying to use nested attributes with a many-to-many relationship. My record is saving to the DB but everything is nil and I'm getting an "Unpermitted parameters: school, alumnis, prospects" error in my logs.
Here's what I have:
referral.rb
class Referral < ActiveRecord::Base
 belongs_to :school
 belongs_to :alumni
 belongs_to :prospect
end

alumni.rb
class Alumni < ActiveRecord::Base
  has_many :referrals
  has_many :prospects, through: :referrals

  accepts_nested_attributes_for :referrals
end

school.rb
class School < ActiveRecord::Base
  has_many :referrals
  has_many :prospects, through: :referrals
  has_many :alumnis, through: :referrals

  accepts_nested_attributes_for :referrals
end

prospect.rb
class Prospect < ActiveRecord::Base
  has_many :referrals
  has_many :alumnis, through: :referrals

  accepts_nested_attributes_for :referrals
end

referrals_controller.rb
def create
  @referral = Referral.create(referral_params)

  respond_to do |format|
    if @referral.save
      # ReferralMailer.referrer_email(@referral).deliver
      # ReferralMailer.referral_email(@referral).deliver
      format.html { redirect_to @referral, notice: 'Referral was successfully created.' }
      format.json { render action: 'show', status: :created, location: @referral }
    else
      format.html { render action: 'new' }
      format.json { render json: @referral.errors, status: :unprocessable_entity }
    end
  end
end

private
  # Use callbacks to share common setup or constraints between actions.
  def set_referral
    @referral = Referral.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def referral_params
    params.require(:referral).permit(prospects_attributes: [:first_name, :last_name, :email], alumnis_attributes: [:first_name, :last_name, :email], schools_attributes: [:name])

  end

_form.html.erb
<%= form_for(@referral) do |f| %>
  <% if @referral.errors.any? %>

<%= pluralize(@referral.errors.count, "error") %> prohibited this referral from being saved:

      <% @referral.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

  <%= f.fields_for :school do |builder| %>
    <%= builder.label :name, "School Name" %>
    <%= builder.text_field :name %>
  <% end %>

  <%= f.fields_for :alumnis do |builder| %>
    <%= builder.label :first_name, "First Name" %>
    <%= builder.text_field :first_name %>

    <%= builder.label :last_name, "Last Name" %>
    <%= builder.text_field :last_name %>

    <%= builder.label :email, "Email" %>
    <%= builder.text_field :email %>
  <% end %>

  <%= f.fields_for :prospects do |builder| %>
    <%= builder.label :first_name, "First Name" %>
    <%= builder.text_field :first_name %>

    <%= builder.label :last_name, "Last Name" %>
    <%= builder.text_field :last_name %>

    <%= builder.label :email, "Email" %>
    <%= builder.text_field :email %>
  <% end %>

    <%= f.submit %>

<% end %>

server log output
Processing by ReferralsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ee+rREUU/0wGzNFTEaMxr8oRStaA53X9fmDrlVRyrD8=", "referral"=>{"school"=>{"name"=>"asdf"}, "alumnis"=>{"first_name"=>"asdf", "last_name"=>"asfd", "email"=>"asdf"}, "prospects"=>{"first_name"=>"asdf", "last_name"=>"asdf", "email"=>"asdf"}}, "commit"=>"Create Referral"}
Unpermitted parameters: school, alumnis, prospects
   (0.1ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "referrals" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Fri, 12 Jul 2013 03:49:06 UTC +00:00], ["updated_at", Fri, 12 Jul 2013 03:49:06 UTC +00:00]]
   (0.6ms)  commit transaction
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/referrals/68

Referral Record
=> #<Referral id: 68, created_at: "2013-07-12 03:49:06", updated_at: "2013-07-12 03:49:06", school_id: nil, alumni_id: nil, prospect_id: nil>

A: You should pass also 'id' in each of your nested model params try :
def referral_params
    params.require(:referral).permit(prospects_attributes: [:id,:first_name, :last_name, :email], alumnis_attributes: [:id,:first_name, :last_name, :email], schools_attributes: [:id,:name])
end

Have swing
Cheers

A: You parameters are not being past to the controller as strong parameters is expecting.
From you server log:
"referral" => {
  "school"  => {
     "name" => "asdf" },
  "alumnis" => {
    "first_name" => "asdf",
    "last_name"  => "asfd",
    "email"      => "asdf"
  },
  "prospects" => {
    "first_name" => "asdf",
    "last_name"  => "asdf",
    "email"      => "asdf"
  }
 }

Strong parameters is expecting prospects_attributes, alumnis_attributes and schools_attributes so prospects, alumnis and school are getting blocked and the objects are getting created without any attributes.


text:
Q: How to add new elements each loop in a set of tuples? I need help with converting a string of tuple into a set of tuples using comprehension and slicing preferably. I just cannot figure out how to add new elements each time.
Input: ('test', 'sample', 'check')
Expected: {('test',),('test','sample',),('test', 'sample', 'check')}
What's the best way to approach this problem?

A: Something like this could work:
x = ('test', 'sample', 'check')

set_of_tuples = {x[:i+1] for i in range(len(x))}

print(set_of_tuples)

Result is:
{('test',), ('test', 'sample'), ('test', 'sample', 'check')}

A: Using set comprehension:
{s[:i+1] for i in range(len(s))}
# {('test',), ('test', 'sample'), ('test', 'sample', 'check')}


text:
Q: SQL Update with join involving NVARCHAR(MAX) column balloons TEMPDB The following query causes the SQL Server 2014 TEMPDB.MDF to grow to 40Gb and takes about an hour to run.
Similar queries for columns that are not NVARCHAR(MAX) take a few minutes.
The table being updated has approximately 7 million rows.
Adding the AND C.SQLStmt IS NOT NULL to the end improved things to get to this point.
Any help would be appreciated.
UPDATE R
SET    R.SQLStmt = C.SQLStmt
FROM SampleResults R
  JOIN SampleTests T ON T.SampleCode = R.SampleCode
                    AND T.TestPosition = R.TestPosition
  JOIN TestComponents C ON T.TestCode = C.TestCode
                       AND T.TestVersion = C.AuditNumber
                       AND R.ComponentColumn = C.ComponentColumn
                       AND R.ComponentRow = C.ComponentRow
WHERE T.AuditFlag = 0
AND   R.AuditFlag = 0
AND   C.SQLStmt IS NOT NULL

This is following on from this question, which I don't have enough reputation to comment on.
The execution plan is:
Update
Cost: 0%
 |
Cluseterd Index Updated
[SampleResults].[pk_SampleResults]
Cost: 27%
 |
Top
COST: 0%
 |
Sort
(Distinct Sort)
Cost: 31%
 |
Nested Loops   Index Seek (NonClustered)
(Inner Join) - [SampleTests].[SampleTestsAuditFlag...
Cost: 0%       Cost: 10%
 |
Nested Loops   Key Lookup (Clustered)
(Inner Join) - [SampleResults].[pk_SampleResults]...
Cost: 0%       Cost: 15%
 |
Nested Loops   Index Seek (NonClustered)
(Inner Join) - [SampleResults].[SampleResultsCompo...
Cost: 0%       Cost: 9%
 |
Filter
Cost: 0%
 |
Clustered Index Scan (Clustered)
[TestComponents].[pk_TestComponents...
Cost: 9%

A: Because the maximum size of the actual data stored in the column was only 392 characters, the final solution was:
1) Temporarily alter the size of both the source and destination columns (SampleResults.SQLStmt and TestComponents.SQLStmt) to 392 characters.
2) Do the update.
3) Alter the size of both the source and destination columns to their new more sensible size of 4000 characters.
DECLARE @tempSQLStmtLength SMALLINT = (SELECT MAX(LEN(SQlStmt)) FROM TestComponents WHERE SQlStmt IS NOT NULL)
IF @tempSQLStmtLength IS NOT NULL AND @tempSQLStmtLength > 0
BEGIN
  -- Temporarily reduce size of SQLStmt columns so that update is as quick as possible.
  EXEC('ALTER TABLE SampleResults ALTER COLUMN SQLStmt NVARCHAR(' + @tempSQLStmtLength +') NULL')
  EXEC('ALTER TABLE TestComponents ALTER COLUMN SQLStmt NVARCHAR(' + @tempSQLStmtLength + ') NULL')

  -- Perform update.
  UPDATE R SET R.SQLStmt = C.SQLStmt FROM SampleResults R JOIN SampleTests T ON T.SampleCode = R.SampleCode AND T.TestPosition = R.TestPosition JOIN TestComponents C ON (T.TestCode = C.TestCode OR T.TestCode + '-' + CAST(T.TestPosition AS VARCHAR(5)) + '-' + T.SampleCode = C.TestCode) AND T.TestVersion = C.AuditNumber AND R.ComponentColumn = C.ComponentColumn AND R.ComponentRow = C.ComponentRow WHERE T.AuditFlag = 0 AND R.AuditFlag = 0 AND C.SQLStmt IS NOT NULL

  -- Now that update is finished, set SQLStmt columns to their final new size.
  ALTER TABLE SampleResults ALTER COLUMN SQLStmt NVARCHAR(4000) NULL
  ALTER TABLE TestComponents ALTER COLUMN SQLStmt NVARCHAR(4000) NULL
END;

TEMPDB.MDB only grew to 2.8Gb and took a few minutes.


text:
Q: Visual C++ ~ Not inlining simple const function pointer calls Dear StackOverflowers,
I got a simple piece of code which I am compiling on Microsoft Visual Studio C++ 2012:
int add(int x, int y)
{
    return x + y;
}

typedef int (*func_t)(int, int);

class A
{
public:
    const static func_t FP;
};

const func_t A::FP = &add;

int main()
{
 int x = 3;
 int y = 2;
 int z = A::FP(x, y);
 return 0;
}

The compiler generates the following code:
int main()
{
000000013FBA2430  sub         rsp,28h
int x = 3;
int y = 2;
int z = A::FP(x, y);
000000013FBA2434  mov         edx,2
000000013FBA2439  lea         ecx,[rdx+1]
000000013FBA243C  call        qword ptr [A::FP (013FBA45C0h)]
return 0;
000000013FBA2442  xor         eax,eax
}

I compiled this on the 'Full optimisation' (/Obx flag) and 'Any Suitable' for Inline function Expansion. (/Ob2 flag)
I was wondering why the compiler doesn't inline this call expecially since it's const. Does any of you have an idea why it is not inlined and if it's possible to make the compiler inline it?
Christian
EDIT: I am running some tests now and MSVC fails to inline the function pointers too when:
-I move the const pointer out of the class and make it global.
-I move the const pointer out of the class and make it local in main.
-I make the pointer non-const and move it in locally.
-When I make the return type void and giving it no parameters
I kind start believing Microsoft Visual Studio cannot inline function pointers at all...

A: The problem isn't with inlining, which the compiler does at every opportunity.  The problem is that Visual C++ doesn't seem to realize that the pointer variable is actually a compile-time constant.
Test-case:
// function_pointer_resolution.cpp : Defines the entry point for the console application.
//

extern void show_int( int );

extern "C" typedef int binary_int_func( int, int );

extern "C" binary_int_func sum;
extern "C" binary_int_func* const sum_ptr = sum;

inline int call( binary_int_func* binary, int a, int b ) { return (*binary)(a, b); }

template< binary_int_func* binary >
inline int callt( int a, int b ) { return (*binary)(a, b); }

int main( void )
{
    show_int( sum(1, 2) );
    show_int( call(&sum, 3, 4) );
    show_int( callt<&sum>(5, 6) );
    show_int( (*sum_ptr)(1, 7) );
    show_int( call(sum_ptr, 3, 8) );
//  show_int( callt<sum_ptr>(5, 9) );
    return 0;
}

// sum.cpp
extern "C" int sum( int x, int y )
{
    return x + y;
}

// show_int.cpp
#include <iostream>

void show_int( int n )
{
    std::cout << n << std::endl;
}

The functions are separated into multiple compilation units to give better control over inlining.  Specifically, I don't want show_int inlined, since it makes the assembly code messy.
The first whiff of trouble is that valid code (the commented line) is rejected by Visual C++.  G++ has no problem with it, but Visual C++ complains "expected compile-time constant expression".  This is actually a good predictor of all future behavior.
With optimization enabled and normal compilation semantics (no cross-module inlining), the compiler generates:
_main   PROC                        ; COMDAT

; 18   :    show_int( sum(1, 2) );

    push    2
    push    1
    call    _sum
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int

; 19   :    show_int( call(&sum, 3, 4) );

    push    4
    push    3
    call    _sum
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int

; 20   :    show_int( callt<&sum>(5, 6) );

    push    6
    push    5
    call    _sum
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int

; 21   :    show_int( (*sum_ptr)(1, 7) );

    push    7
    push    1
    call    DWORD PTR _sum_ptr
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int

; 22   :    show_int( call(sum_ptr, 3, 8) );

    push    8
    push    3
    call    DWORD PTR _sum_ptr
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int
    add esp, 60                 ; 0000003cH

; 23   :    //show_int( callt<sum_ptr>(5, 9) );
; 24   :    return 0;

    xor eax, eax

; 25   : }

    ret 0
_main   ENDP

There's already a huge difference between using sum_ptr and not using sum_ptr.  Statements using sum_ptr generate a indirect function call call DWORD PTR _sum_ptr while all other statements generate a direct function call call _sum, even when the source code used a function pointer.
If we now enable inlining by compiling function_pointer_resolution.cpp and sum.cpp with /GL and linking with /LTCG, we find that the compiler inlines all direct calls.  Indirect calls stay as-is.
_main   PROC                        ; COMDAT

; 18   :    show_int( sum(1, 2) );

    push    3
    call    ?show_int@@YAXH@Z           ; show_int

; 19   :    show_int( call(&sum, 3, 4) );

    push    7
    call    ?show_int@@YAXH@Z           ; show_int

; 20   :    show_int( callt<&sum>(5, 6) );

    push    11                  ; 0000000bH
    call    ?show_int@@YAXH@Z           ; show_int

; 21   :    show_int( (*sum_ptr)(1, 7) );

    push    7
    push    1
    call    DWORD PTR _sum_ptr
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int

; 22   :    show_int( call(sum_ptr, 3, 8) );

    push    8
    push    3
    call    DWORD PTR _sum_ptr
    push    eax
    call    ?show_int@@YAXH@Z           ; show_int
    add esp, 36                 ; 00000024H

; 23   :    //show_int( callt<sum_ptr>(5, 9) );
; 24   :    return 0;

    xor eax, eax

; 25   : }

    ret 0
_main   ENDP

Bottom-line: Yes, the compiler does inline calls made through a compile-time constant function pointer, as long as that function pointer is not read from a variable.  This use of a function pointer got optimized:
call(&sum, 3, 4);

but this did not:
(*sum_ptr)(1, 7);

All tests run with Visual C++ 2010 Service Pack 1, compiling for x86, hosted on x64.

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.40219.01 for 80x86

A: I think that you're right in this conclusion: "... cannot inline function pointers at all".
This very simple example also breaks optimization:
static inline
int add(int x, int y)
{
    return x + y;
}

int main()
{
    int x = 3;
    int y = 2;
    auto q = add;
    int z = q(x, y);
    return z;
}

Your sample is even more complex for the compiler, so it is not surprising.

A: You can try __forceinline. Nobody is going to be able to tell you exactly why it isn't inlined. Common sense says to me that it should be, however. /O2 should favor code speed over code size (inlining)... Strange.

A: This is not a real answer, but a "maybe workaround" one:
STL from Microsoft once mentioned that lambdas are more easily inlineable than f ptrs so you could try that.
As a trivia Bjarne often mentions that sort is faster thatn qsort because qsort takes function ptr, but like other people have noted gcc has no problems inlining them... so maybe Bjarne should try gcc :P


text:
Q: Issues with importing CSV file into MySQL when comma in address I'm using a script that I found online to import CSV file into MySQL:  http://www.johnboy.com/blog/tutorial-import-a-csv-file-using-php-and-mysql but when the script detects a comma in an address like this My address, CO 80113 in a cell, it also splits there as well.
I've seen a solution where you can save from excel to a Tab Delimited txt file.  Then you go into notepad and replace the tabs with semicolons.
Is this the best practice for "fixing the comma in the address" issue?
My end goal is to take a CSV file from Highrise full of hundreds of clients into our MySQL database, then make updates every couple of months so this seems to be a decent script but am I going at this the wrong way?
EDIT :  It appears that the part of the PHP code that splits up the cells is this
while ($data = fgetcsv($handle,1000,",","'"));

A: If you use comma as column separator, then you should quote all string field values, e.g. -
1,'My address, CO 80113'
2,'His address, CO 80114'
4,'Her address, CO 80115'
and so on

Try to use LOAD DATA INFILE statement with FIELDS ENCLOSED BY '\'' option.

A: comma (',') is the hart of CSV file so when you generate the csv file it divide cell when comma found.
So I think that you should replace the comma with the space or any other delimeter. you can use PHP 's default function str_replace() when your final code is generate for CSV.


text:
Q: Limit and differentiablility of $\ \sum \frac{(-1)^n\sin(\frac{x}{n})}{n} $ I have to estimate the value of the limit and test whether it is differentiable:
$$\ f(x)= \sum_{n=1}^\infty \frac{(-1)^n\sin(\frac{x}{n})}{n} $$
I was trying to escalculate the limit:
$$\ \frac{1}{n}\sin(\frac{x}{n}) $$
However it didn't lead to anything. I would apprecite any help.


text:
Q: Intent.ACTION_SEND to share text worked well before, but failed now I used the same code below to share text to Line, Wechat,...
It worked well before, but now it transfers nothing to the other apps. Though I trace to see everything going the same and correctly  in the sendIntent(below). Does anyone have similar experiences?
Thanks in advance for any suggestion!

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)  .setAction("Action", null).show();
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, editText.getText()); //EditText..getText() is Editable, still can get string
            sendIntent.setType("text/plain");
            startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
        }
    });

A:  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
 fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
          Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
          sharingIntent.setType("text/plain");
          sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
          sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, voiceTextView.getText());
          startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));

     }
});


text:
Q: big O notation of isset operation Having an array:
$array = (..., 'name' => 'foo', 'age' => 69, 'address' => 'bar');

I'll use the operation:
if(isset($array['address'])) { //Do something... }

Is the big O notation would be O(n)? How does the isset() works behind the scenes?

A: As stated by Mark Baker, it's O(1). However, take note that this is only in the average case.
As a matter of fact, it is still possible for a search operation in hash maps to take O(n) time due to hash collisions no matter how well you implement a hash map (chaining, probing, etc).
Nonetheless, that does not mean that hash tables are bad in practice. In fact, Big O is simply something that is often used to describe the worst-case scenario of an algorithm.


text:
Q: sudo chmod command from cocoa I would like to the run the following command from my Cocoa project. (hides the spotlight icon)
sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search

I have found two ways how to call the command and get the following output
1) Using NSTask
NSTask *writeTask = [[NSTask alloc] init];
[writeTask setLaunchPath:@"/bin/chmod"];

[writeTask setArguments: @[@"755",@"/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search"]];

[writeTask launch];

>>chmod: Unable to change file mode on /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search: Operation not permitted

2) Pipes
NSString *command = @"sudo chmod 755/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search";
fp = popen([command UTF8String], "r");

>>sudo: no tty present and no askpass program specified

I have not found a way how to run any of these in super user mode. How can I prompt the user to enter his password and eventually run this command with the required privileges?

A: Prior to 10.7 you could use AuthorizationExecuteWithPrivileges() to execute tasks with privileges. However, this has been deprecated in 10.7 and Apple recommends using the ServiceManagement framework to perform privileged tasks.

SMJobBless demonstrates how to securely install a helper tool that
  performs a  privileged operation and how to associate the tool with an
  application that invokes  it.
SMJobBless uses ServiceManagement.framework that was introduced in Mac
  OS X v10.6  Snow Leopard.
As of Snow Leopard, this is the preferred method of managing privilege
  escalation on  Mac OS X and should be used instead of earlier
  approaches such as  BetterAuthorizationSample or directly calling
  AuthorizationExecuteWithPrivileges.

Apple's sample code

A: Write the below apple script using Apple Script Editor and save it in a .scpt file.
do shell script "sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search" with administrator privileges

Now add this file to your bundle.
Then to call this script from your program use the following code:
- (void) runEmbeddedScriptFile: (NSString*)fileName
{
    NSString* path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"scpt"];
    NSURL* url = [NSURL fileURLWithPath:path];
    NSDictionary* errors = [NSDictionary dictionary];
    NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
   [appleScript executeAndReturnError:nil];
   [appleScript release];
}

This will prompt the password request from user.

A: You need to use Authorization Services to get the root privileges and then use chmod() from sys/stat.h


text:
Q: Show a toast (using alarmmanager) I've a service that runs after android starts. I'd like show a toast every days at 9am. The problem is: how can I implement the code (alarmamanger within service)?
Start service after boot:
public class AutoStart extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.startatboot.UnUsedService");
context.startService(serviceIntent);

}
}

public class Service extends Service {

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);

Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);    AlarmManager am = (AlarmManager)     context.getSystemService  (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,     MyClass.class),      PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),     AlarmManager.INTERVAL_DAY, pi);

A: Just replace your code with my code,
public class Service extends Service {

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);

Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);    AlarmManager am = (AlarmManager)     context.getSystemService  (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,     AlarmReceiver.class),      PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),     AlarmManager.INTERVAL_DAY, pi);

Now create a new class AlarmReceiver in the same package and add the following code to it.
 public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();

    }
 }

Now define it in the PendingIntent of the Alarm.
Add following code in the manifest file,
<receiver android:name=".AlarmReceiver" />

Now run your application. that's it. It will definitely show a toast at 9.
Let me know if it worked or not.


text:
Q: phtml file for checkout table
where do i find the phtml file for the picture above. i want to adjust the table itself. i actually know where the css is. i searched in already in /vendor/magento/module-costumer/view/frontend/
/app/design/frontend/.../magento-checkout
thank you

A: All files you will find here:
*app\design\frontend\base\default\template\checkout\onepage*


text:
Q: I'm having an issue making a react component play an mp3 file when a button is clicked, it looks like it should work to me but something is wrong I'm trying to make the buttons here each play the mp3 file they correspond to. The buttons wont
play the mp3 files and I'm not getting any errors I'm aware of. The files are located directly
in the src folder. I had the files in the public folder as was recommended by another stack overflow post but having them in the src folder seemed to work, then when i added the rest of the buttons the whole thing stopped working, so you see I'm stuck. Should i put the functions directly in the onClick? What am I doing wrong? Any help would be appreciated, thank you.
    function App() {

     let workIt = new Audio('/workit.mp3');
     let doIt = new Audio('/doit.mp3');
     let harder = new Audio('/harder.mp3');
     let faster = new Audio('/faster.mp3');
     let moreThan = new Audio('/morethan.mp3');
     let our = new Audio('/our.mp3');
     let ever = new Audio('/ever.mp3');
     let workIs = new Audio('/workis.mp3');
     let makeIt = new Audio('/makeit.mp3');
     let makesUs = new Audio('/makesus.mp3');
     let better = new Audio('/better.mp3');
     let stronger = new Audio('/stronger.mp3');
     let hour = new Audio('/hour.mp3');
     let never = new Audio('/never.mp3');
     let after = new Audio('/after.mp3');
     let over = new Audio('/over.mp3');

      const playWorkIt = () => {
        workIt.play()
      }
      const playDoIt = () => {
        doIt.play();
      }
      const playHarder = () => {
        harder.play();
      }
      const playFaster = () => {
        faster.play()
      }
      const playMoreThan = () => {
        moreThan.play()
      }
      const playOur = () => {
        our.play()
      }
      const playEver = () => {
        ever.play()
      }
      const playWorkIs = () => {
        workIs.play()
      }
      const playMakeIt = () => {
        makeIt.play()
      }
      const playMakesUs = () => {
        makesUs.play()
      }
      const playBetter = () => {
        better.play()
      }
      const playStronger = () => {
        stronger.play()
      }
      const playHour = () => {
        hour.play()
      }
      const playNever = () => {
        never.play()
      }
      const playAfter = () => {
        after.play()
      }
      const playOver = () => {
        over.play()
      }

      return (

            <button onClick = {playWorkIt} className = 'work-it'>Work it</button>
            <button onClick = {playDoIt} className = 'do-it'>Do it</button>
            <button onClick = {playHarder} className = 'harder'>Harder</button>
            <button onClick = {playFaster} className = 'faster'>Faster</button>
            <button onClick = {playMoreThan} className = 'more-than'>More Than</button>
            <button onClick = {playOur} className = 'our'>Our</button>
            <button onClick = {playEver} className = 'ever'>Ever</button>
            <button onClick = {playWorkIs} className = 'work-is'>Work is</button>

            <button onClick = {playMakeIt} className = 'make-it'>Make it</button>
            <button onClick = {playMakesUs} className = 'makes-us'>Makes us</button>
            <button onClick = {playBetter} className = 'better'>Better</button>
            <button onClick = {playStronger} className = 'stronger'>Stronger</button>
            <button onClick = {playHour} className = 'hour'>Hour</button>
            <button onClick = {playNever} className = 'never'>Never</button>
            <button onClick = {playAfter} className = 'after'>After</button>
            <button onClick = {playOver} className = 'over'>Over</button>

      );
    }

    export default App;

A: Looks like i did need it in the public folder my bad, sorry for the premature question


text:
Q: CORS issue when calling a localhost API hosted on one port from another port I have a localhost Rest API POST query hosted using Docker at port 8501: http://localhost:8501/v1/models/model:predict. I have an HTML file which runs with a JavaScript script and it is hosted at http://127.0.0.1:8887/ using WebServer for Chrome. I am able to call global Rest API POST queries from my HTML-JS files and my local Rest API works fine from POSTMAN. But I am unable to call my API from my HTML-JS files.
Below is my JS file:
function foo() {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin", "*");
    myHeaders.append("Access-Control-Allow-Methods", "POST");

    var raw = JSON.stringify({"instances":[[0]]});

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("http://localhost:8501/v1/models/model:predict", requestOptions)
        .then(response => console.log(response.text()))
        .then(result => console.log(result))
        .catch(error => console.log('error', error));

}

I get the below error:

Access to fetch at
  'http://localhost:8501/v1/models/model:predict' from origin
  'http://127.0.0.1:8887' has been blocked by CORS policy: Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. If an opaque response serves your needs, set the request's
  mode to 'no-cors' to fetch the resource with CORS disabled.

Can anyone please help me?

A: You seem to have understood CORS slightly "backwards" -- the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers are specified on HTTP responses, not requests. This obviously implies that it's the HTTP server that sets them, not the client.
It would make for a terrible cross site security model if a script of arbitrary origin could effectively dictate to the HTTP server what kind of requests and from which origins the latter must accept.
It's the HTTP service that ultimately controls access by specifying appropriate headers in the responses it serves, and the user agent validates the cross origin request where it refuses to proceed if the server didn't indicate it allows requests from the different origin the script was served from -- the response will be discarded and an error will be thrown.
In short, you need to add the headers to the responses your REST service at localhost:8501 generates, instead of specifying them for requests your client side script creates where they don't do anything.

A: Your server is missing header Access-Control-Allow-Origin in response, as it is responsible what to allow or not. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS


text:
Q: Method called as if it belongs to the class with this parameter suppressed I have the following WPF code:
    public Window1()
    {
        InitializeComponent();
        FlowDocument fd = new FlowDocument();
        fd.LoadFromWordML("../../testdoc.docx");

FlowDocument (in System.Windows.Documents namespace) does not have a LoadFromWordML method.  Rather this method is defined locally as follows:
    public static void LoadFromWordML(this FlowDocument doc, string path)

Yet as you can see, LoadFromWordML is being called as if it is a method of FlowDocument class, and in fact the 'this' argument is being suppressed.
What C# language facility allows this?  (And a comment against language design: this makes it very difficult to read legacy code.)

A: This is called extension methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods

I have encountered these problems using them

*

*Hunting documentation to figure out where the hell they are defined.

*They cannot be defined to be virtual so it can lead to problems. In one of the projects I worked on we had Arc deriving from Circle. Somebody decided that Transform method should be an extension method. So most of the time it worked. Transforming a Circle yielded a transformed Circle and same with Arc. But it lead to subtle errors when you transformed an Arc when it was being used as an Circle reference.


text:
Q: 'BaseVariant' is deprecated, what is the alternative of BaseVariant? 'BaseVariant' has been deprecated. I am using BaseVariant like this
  import com.android.build.gradle.api.BaseVariant

  var bundleForVariant: (BaseVariant) -> Boolean = { variant ->
    if (bundleIn.getting(variant.name).isPresent) bundleIn.getting(variant.name).get()
    else if (bundleIn.getting(variant.buildType.name).isPresent)
        bundleIn.getting(variant.buildType.name).get()
    else variant.isRelease
  }

  var disableDevForVariant: (BaseVariant) -> Boolean = { variant ->
    variant.name in devDisabledInVariants.get() || variant.isRelease
  }

My question is what is the alternative of it?


text:
Q: Lda using mallet I run the file simple lda.java and I got
 exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at cc.mallet.topics.SimpleLDA.main(SimpleLDA.java:560)

A: It looks like you are using the command line interface without any parameters.
If you look at the source file at https://github.com/mimno/Mallet/blob/master/src/cc/mallet/topics/SimpleLDA.java, you can see that line 560 is expecting to find that there is a command line argument specifying a file at the first position in the arguments array.
If you need to train a topic model from the command line, there is information here: http://mallet.cs.umass.edu/topics.php
The interface you are using is intended as a base for constructing new, custom topic models in Java. Without significant programming experience in Java this will be frustrating and unlikely to succeed.


text:
Q: Prevent graphql query in vue-apollo if input variable is null I've been doing some reading and have come up with a query setup for a contact input field.  I would like to avoid running this query at component startup with null input.  I could manually run the queries through computed methods maybe, but is there a simple way to prevent this?
apollo: {
    search: {
        query: () => contactSearchGQL,
        variables() {
            return {
                searchText: this.searchText,
            };
        },
        debounce: 300,
        update(data) {
            console.log("received data: " + JSON.stringify(data));
        },
        result({ data, loading, networkStatus }) {
            console.log("We got some result!")
        },
        error(error) {
            console.error('We\'ve got an error!', error)
        },
        prefetch() {
            console.log("contact search, in prefetch");
            if ( this.searchText == null ) return false;
            return true;
        },
    },
},

I think I'm not understanding something about prefetch, or if it's even applicable here?

A: You should utilize the skip option for that, as shown in the docs:
apollo: {
  search: {
    query: () => contactSearchGQL,
    variables() {
      return {
        searchText: this.searchText,
      };
    },
    skip() {
      return !this.searchText;
    },
    ...
  },
},

Anytime searchText updates, skip will reevaluate -- if it evaluates to false, the query will be ran. You can also set the skip property directly if you need to control this logic elsewhere in your component:
this.$apollo.queries.search.skip = true

The prefetch option is specific to SSR. By default, vue-apollo will prefetch all queries in server-side rendered components. Setting prefetch to false disables this functionality for a specific query, which means that particular query won't run until the component is rendered on the client. It does not mean the query is skipped. See here for more details about SSR in vue-apollo.

A: Apollo Client
const { loading, error, data } = useQuery(GET_SOME_DATA_QUERY, {
    variables: { param1 },
    skip: param1 === '',
  })

This query will be fired only when param1 is not empty.


text:
Q: Have got any (something): singular or plural?
I'm uncertain if the following sentence is correct:
Have you got any pet?
Searching for straight questions with "have got" and "any" I've found the noun sometimes as singular, sometimes as plural. Which is grammatically correct?
Thanks!

A: "Have you got any" is generally followed by the plural. Or, an "uncountable noun" like beer or water or ice cream where the singular functions as a plural also.

Have you got any pet?

Should be

Have you got any pets?


text:
Q: Spring roo limitations I want to start developing enterprise grade applications using spring stack.
to increase the productivity and to compete in the market, I would like to use RAD tools. I found spring roo, but for me, it looks like, it is suitable only to build simple crud based applications. Not suitable to build applications with custom UI. Can you please let me know, can we build any enterprise grade application using ROO or it is not suitable for enterprise grade applications.


text:
Q: How can I group data in datawindow I want to create a report on which data shows in group. I have tried but the report is not made as I require. If a number of rows have the same value, then data should be printed only one time.
name category value
FCL  1        3
FCL  1        9
FCL  1        3
FCL  2        2
FCL  2        5
gpl  3        13
gpl  3        15
gpl  1        10
gpl  1        3

but data should print
name category value
                  3
    1               9
FCL   ---------         3
    2           2
                5
----------------       13
    3          15
gpl   ----------       10
    1           3

For clarification, here is a link: Image report

A: I guess that you are looking at the "Rows / Suppress repeating values" menu from the datawindow design painter.
It will hide verticaly repeated values from the selected fields.

A: Yes you can do the group by in powerbuilder.
Open your datawindow object. And choose which column you want to do group by. Go to Rows Menu in the menu bar. Click the Create Group Option.
Drag the group by column from left side to right side. And then press ok
Now drag the columns which are all you want under that group.
Thats it

Regards
Raj~

A: try
String w_band; Long w_TabPos, w_row
w_band = GetBandAtPointer ( )
w_TabPos = Pos(w_band,'~t',1)
if  w_TabPos>0 then     w_row = Long(Mid (w_band,w_TabPos+1))
If w_row > 0 Then //Your corde


text:
Q: Search form with pagination I have a problem with the pagination of the records result.
I would like to show all the users saved in a db table using a search form and paginate them accordingly to following script:
http://papermashup.com/easy-php-pagination/

If I insert manually the gendre value in the query below,
"SELECT * FROM $tableName WHERE playerSex  = '0' LIMIT $start, $limit";

I have no problem to display all the female users,
If I send the value through the form like this
"SELECT * FROM $tableName WHERE playerSex  ='" . mysql_real_escape_string($_GET['gendre']) ."'
LIMIT $start, $limit";

Only the first page displays the female users. Clicking on page 2 the script shows all the records (male and female) and not the requested female ones.
How can I solve this problem?
Thanks

A: You should keep your gender option in your pagination href. something like this:
<?php
    foreach $key.... //pagination creator loop
    if(isset($_GET['gender']))
        $href = $key . '&gender=' . $_GET['gender'];
    else
        $href = $key;
?>

A: Append the GET parameter in pagination url.
e.g. you have page url "http://papermashup.com/easy-php-pagination/" and
pagination url
"http://papermashup.com/easy-php-pagination/?page=1" ,
"http://papermashup.com/easy-php-pagination/?page=2" ,
"http://papermashup.com/easy-php-pagination/?page=3".......

In pagination Url add the GET parameter like
if($_GET['playerSex'] !="")
{

    $playerSex = "&playerSex=".$_GET['playerSex'];

}

"http://papermashup.com/easy-php-pagination/?page=1$playerSex"
"http://papermashup.com/easy-php-pagination/?page=2$playerSex"
"http://papermashup.com/easy-php-pagination/?page=3$playerSex" .......


text:
Q: In Bootstrap, why does the invalid-feedback class increase the width of my input? My JSFiddle is here:
https://jsfiddle.net/jdpzh1g8/
and appears like this:

When I remove this code:

Some message about date

My input becomes narrower:

even though the size of the message ("Some message about date") didn't even take up half the input length.
I would like my input to be the narrower size at all times.
How do I stop the invalid-feedback class from increasing the size of my input?

A: So I did some research and invalid-feedback isn't very good. So instead I used text-danger. This is easier and you will have less problems. Here is my fiddle. Hope this is okay for you :)


text:
Q: selecting child react component under div is not working in app.jsx file App.jsx
....

<div className="twoItemsRow">
          <Input
            inputType="normal"
            titleText="<Input helperText="Some interesting text" />"
            headerText="Label"
            footerText="Some interesting text"
            placeHolderText="Placeholder"
          />
          <Input
            className="secondChildComponent"
            inputType="error"
            titleText="<Input helperText="Some interesting text" error />"
            headerText="Label"
            footerText="Some interesting text"
            placeHolderText="Placeholder"
          />
        </div>

....

App.css
I wish to style second child component under <div> as below
..
.secondChildComponent {
  background-color: green;
}
...

but it's not working, is my selector wrong or approach is wrong ?

A: You are passing className to Input component props. You should implement this in Input component. The react className property would work only on HTML elements.
e.g.
const Input = (props) => {
  const {className = ''} = props

  return <input className={`inputClassName ${className}`} />
}


text:
Q: Wheatstone Bridge strain gauge thermal compensation design I'm designing a full Wheatstone bridge for measuring the bending strain in a steel bar.
I have a circuit available to me that uses an ADS1232 to measure the output of the wheatstone bridge.
When looking at loadcells online I see that they have 6 cables (sense + and sense-). From what I understand, these cables go to the excitation points of the wheatstone bridge and allow the circuit to measure the voltages, which cannot be done with the excitation cables themselves as they would have a voltage drop due to the much larger current draw. The sense cables do not draw much current as they are going into an opamp. Is this understanding correct?

I also don't understand why there are two resistors in series with the bridge. I've read online that they are for temperature compensation, but nothing goes into more detail then that.
If I was to attach strain gauges onto a steel beam, would I need those resistors? and where would they go, and with what value?
Would I need anything apart from the 4 strain gauges in a full bridge configuration with sense cables going to the REF_P and REF_N terminals of the ADS1232 IC?

A: Strain gauge elements made of nickel have a positive temperature coefficient of about +0.6% per °C at room temperature. If you energize the bridge with a constant current, the "gain" of the bridge will have that coefficient as well since the percentage change in resistance is pretty much constant with temperature.
By energizing the bridge with a constant voltage and adding resistors that have a similar temperature coefficient, the output of the bridge a reasonable voltage (usually 2.5 to 10V) can be used and the output at off-balance will be more constant with temperature.
Because there are 4 wires, each with resistance, connecting the bridge to the measuring instrumentation, we would like that resistance to have minimal effect on the performance. By measuring the voltages (the difference is what matters) using the sense wires we can either compensate for the resistances or, more alternatively, drive the "input" wires such that the voltages at the strain gauge are fixed values, say with a couple of op-amps.
Here is the typical application for the ADS1232 from the datasheet:

This circuit assumes the bridge can be powered directly from +5V and there is no compensation for the wire resistances (no sense and force wires). If you want to compensate, you would either have to add that circuitry or find some way to use the ADC to measure those voltages and compensate digitally (there are two unused inputs). You can compare the bridge resistance with the wiring resistance to see if that's necessary in your case.
The typically application shows few additional components but if there is a cable attached you'd want to add protection and filtering, which would help with the anti-aliasing filtering.
Commercial instrumentation strain gauge signal conditioners are often galvanically isolated, because of the low level of the signals and the desire for the installation to be trouble-free.


text:
Q: R - Print specific country names in a map using rworldmap I am creating a heatmap using the map of Europe in rworldmap package in R (since I don't know how to do this with ggmap or ggplot2).
I need to plot the country names of the countries that are present in my dataframe only, not all european countries. How can I do this?
My code:
library(RColorBrewer)
#getting colours
colourPalette <- brewer.pal(5,'RdPu')

library(rworldmap)

europe <- data.frame(
  "country" = c("Greece",
                "France",
                "Spain",
                "Italy",
                "UK",
                "Finland","Norway","Sweden",
                "Germany",
                "Romania"),
  "x" = c(2.5, 3, 2.2, 1.8,2.32, 1.99, 2.01, 2.34, 1.88, 2.45))

matched <- joinCountryData2Map(europe, joinCode="NAME", nameJoinColumn="country")

mapParams <- mapCountryData(matched,
                            nameColumnToPlot="x",
                            mapTitle="my Titley",
                            addLegend=FALSE,
                            mapRegion="Europe"
                            ,colourPalette=colourPalette,
                            oceanCol="#404040", missingCountryCol="#A0A0A0")

#adding legend
do.call(addMapLegend
        ,c(mapParams
           ,legendLabels="all"
           ,legendWidth=0.5
           ,legendIntervals="data"
           ,legendMar = 2))

labelCountries()

Using labelCountries() prints all country names and it's not readable.
Thanks

A: With a little bit help of this previously answer:
# get the coordinates for each country
country_coord<-data.frame(coordinates(matched),stringsAsFactors=F)

# label the countries
country = c("Greece",
              "France",
              "Spain",
              "Italy",
              "UK",
              "Finland","Norway","Sweden",
              "Germany",
              "Romania")

#filter your wanted countrys
country_coord = country_coord[country,]

#insert your labels in plot
text(x=country_coord$X1,y=country_coord$X2,labels=row.names(country_coord))

you can add the country labels with text but you must extract the coordinates before from your matched coordinates.
Output:

You might play a bit with col = "color" in text, since some country can barely been read. Or maybe change the color scale in your map


text:
Q: Strange error in python 3.2 The following code is to find the mean of a given input set of numbers.
#!/usr/bin/env python3
print("Enter some integers")
count = 0
total = 0
while True:
    line = input("integer: ")
    if (line):
        try:
            number = int(line)
        except ValueError as err:
            print(err)
            continue
        total += number
        count += 1
        #print("Post",line)
    else:
        break
if count:
    print('Count is ',count ,'Total is ',total,'Mean is ',total/count)

However, whenever I run the program, the even numbered input gives me an error even though I enter a number. The following is the sample output.
Enter some integers
integer: 4
integer: 5
invalid literal for int() with base 10: 'integer: 5'
integer: 5
integer: 6
invalid literal for int() with base 10: 'integer: 6'
integer:
Count is  2 Total is  9 Mean is  4.5

However, this code works fine if I uncomment the line before the else: statement. Can anyone tell me what is going on here?
Thanks in advance.

A: Your problem is a question of cut and paste.
The line
number = int(line)

Generates the error
invalid literal for int() with base 10: 'integer: 6'

This means that the line
line = input("integer: ")

Must have recieved the input:
'integer: 6'

And the only way it could have recieved this, is if that is what you inputted.
Obviously, you would not be so daft as to type in "integer: 6". Hence the only reason this happens is that you have cut and pasted your previous input without noticing that you got to much when you copied, which is something that happens to me all the time.


text:
Q: Incorrect java -version on command prompt I already had JDK 5 on my machine. I have updated JDK  by installing Java Development Kit 7.  Now, I have set the Path and JAVA_HOME variables as per latest Java. but still "java -version" showing me older version.
C:\>java -version
java version "1.5.0_07"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-b03)
Java HotSpot(TM) Client VM (build 1.5.0_07-b03, mixed mode)

Please see the current states of my environment variables as below:
C:\>echo %JAVA_HOME%
C:\Program Files\Java\jdk1.7.0_03\

C:\>echo %Path%
C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;C:\Program Files\Barclays Capital\CommonApi\bin\
;C:\Program Files\Windows Imaging\;C:\WINNT\system32\WindowsPowerShell\v1.0;C:\Program Files\Citrix\ICAService\;C:\Program Files\Citrix\Syst
em32\;C:\Program Files\Perforce;C:\Program Files\Barclays Capital\P4CustomTools;C:\Program Files\Apache Software Foundation\apache-maven-3.0
.4\bin;C:\Program Files\Common Files\Adobe\AGL;C:\Apps\oracle\product\10.2.0.3\client\bin;C:\Apps\oracle\product\10.2.0\client\BIN;C:\APPS\o
racle\client\11.2.0.3\home1\bin;C:\WINNT\system32\;C:\WINNT\;C:\WINNT\system32\Wbem;C:\Program Files\Windows Imaging;C:\Program Files\Java\j
dk1.7.0_03\bin

C:\>javac -version
javac 1.7.0_03

I know how to change the environment variable and I have referred other post on stack overflow.
What should be reason behind incorrect path returned by java -version command ?

A: When installing a public JRE (used by the Java plugin), a java.exe file is also created in C:\WINNT\system32 (IIRC). It's probably this java command that is executed, since C:\WINNT\system32 comes before the JDK/bin directory in your PATH.
Put the JDK/bin directory at the beginning of the PATH.


text:
Q: Group by a result of case statement I'm trying to get a query with an aggregate function and case statement to work in my select and a group by on the case statement to work in SQL Server 2005 but I seem to be missing something.
declare @td int
set @td = 20130731

select
    count(*) as total,
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000'
        then '0-1'
    end as timestripe
FROM
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
GROUP BY
    timestripe

The count(*) part is a little weak, I know but the problem is with the group by statement. When I run this query, I get the following error:

Msg 207, Level 16, State 1, Line 15
  Invalid column name 'timestripe'.

It seems that the case statement is the root cause of the error but I shouldn't have to write a subquery or join just to get this to work. Any ideas?

A: For this query, logical Processing Order of the SELECT statement is:

*

*FROM,

*WHERE

*GROUP BY and

*SELECT.

Because SELECT comes after GROUP BY all aliases defined in SELECT clause (including timestripe) can't be used in previous step (GROUP BY).
One solution could be:
SELECT x.timestripe, COUNT(*) AS Cnt
FROM (
select
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000'
        then '0-1'
    end as timestripe
FROM
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
) x
GROUP BY x.timestripe

A: You can't reference an alias in the GROUP BY, so just put the entire case statement in it. Leave the "as timestripe" part off.
declare @td int
set @td = 20130731

select
    count(*) as total,
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000'
        then '0-1'
    end as timestripe
FROM
    [EXTERNAL_CDR].[dbo].[CDRMAIN] as cdm
WHERE
    cdm.LocalDay = @td
    AND cdm.targetnum IN ('500','600')
GROUP BY
    case
       when dateadd(s, cdm.[StartTime], '19700101') >= '2013-07-31 00:00:00.000' and dateadd(s, cdm.[StartTime], '19700101') < '2013-07-31 01:00:00.000'
        then '0-1'
    end


text:
Q: Date-picker - How to disable one monday only? I was wondering how it would be possible to disable the next monday, when the day now is a friday.
I can disable every monday, but I only want to disable one, when the day is friday and only the first monday, not every monday.
I was using this, I am getting in the if loop, but it's not returning anything.
minDate: new Date(y,m,fridayNotMonday),

function fridayNotMonday()
{
  var vdate = new Date();
  var vday = vdate.getDay();
  var vm = vdate.getMonth(), vd = vdate.getDate(), vy = vdate.getFullYear();
  var vd1 = vdate.getDate() + 2;
  var vd2 = vdate.getDate() + 4;

  if (vday == 5) {
    alert("friday");
    firstDate: new Date(vy,vm,vd2);
    return firstDate
  } else {
    firstDate1: new Date(vy,vm,vd1);
    return firstDate1;
  }
}

A: You should use the beforeShowDay option of the datepicker
var now = new Date();
var day = now.getDay();
// on the following line 5 means friday. Days start counting from 0=sunday to 6=saturday.
// so if now is friday then find the date of the following monday
var disabled = (day===5)? new Date(now.getFullYear(), now.getMonth(), now.getDate()+3): null;

$('#datepickerelement').datepicker({
    beforeShowDay:function(current){
        // if the disabled date we calculate is the same as the one the plugin tries to show
        // then set its selectable status to false..
        if (disabled !== null && disabled.getTime() === current.getTime() ) {
            return [false];
        } else {
            return [true];
        }

    }
});

Demo at http://jsfiddle.net/r6QUd/2/


text:
Q: How to send user to LogIn Page before Going to Profile, and how to Log User out I already did LogIn Page and Sign up Page that works fine but it doesn't redirect the user to LogIn Page. At first user will need to log in to be redirected to Profile Page and if the user email or password is wrong the App won't allow the user to continue and also i need help with Logging out user.
Check my flow of navigation here
Please help
I'm coding with Swift laters version

A: Let's you have from your back-end server, there is some kind of method that check if someone is currently logged in. It returned either true or false.
Now in your mobile app, you would call that method in didFinishLaunchingWithOptions in the appDelegate to check if you have a user
var currentUser = User()
//let's say that User class is where you established connection to your server.

if currentUser.isThereAnyUserLoggedIn(){
  // since this statement is true; then just show them your tabBar
 // give the tabBar an ID then initiate it from the storyboard
} else {
     // which means there is no one
   // then show the loginViewController
}

Now for the logout method
if currentUser.hasPressedLogoutButton() {
   // show the loginViewController
 }


text:
Q: Cannot search my documents in search in Sharepoint 2013 I moved some sub-sites to my new site collection.
I cannot search my documents through search box.
I enabled all settings to search but still I am not able to search .
How can I solve this issue?

A: Couple of stabs in the dark:

*

*Is your document library setting allowing to be crawled? To check, go to your document library > Library Settings > Advanced > Allow items from this document library to appear in search results? > Yes

*Are the documents published, or are they checked out / drafts. Depending on permissions, draft items will not appear in search results see this post > https://answers.microsoft.com/en-us/msoffice/forum/all/sharepoint-2013-search-function-missing-documents/757ca4ed-2531-420e-af98-6093adaf7b67

*Has the search engine (on the server) reported any access issues? Do the search crawler and super read etc have access to your sub sites?

*Has a crawl run since you added your sites / documents?
Just some things to get you started. Good luck!


text:
Q: Chaining together akka stream flows that each make HTTP requests I have a restful blog server (http://jsonplaceholder.typicode.com) that responds to these two URIs
/posts/{id}           : get a blog post by ID
/comments?postId={id} : get all the comments on a blog by the blog's id

Starting with a batch of blog IDs, I want to create a flow that executes this sequence of steps:

*

*Hit the /posts endpoint to get the json for a post

*Deserialize the json to a Blog case class

*Hit the /comments endpoint for each blog and fetch the JSON list of comments for that post

*Deserialize the comment JSON to a list of Comment case objects

*Do some processing on the comments (stat collection or spam analysis)

Yes, I know I could skip straight to step 3 if I have a blog id. Pretend I can't
I would like to get a bunch of HTTP requests going to the server in step 1. To achieve that, I use a cachedHostConnectionPool. Here is what I have so far:
final case class Blog(id: Int, userId: Int, title: String, body: String)
final case class Comment(id: Int, postId: Int, name: String, email: String,  body: String)

object AkkaStreamProcessor extends App {
  implicit val actorSystem = ActorSystem("blogProcessor")
  import actorSystem.dispatcher
  implicit val flowMaterializer = ActorMaterializer()

  private def getBlogUri(id: Integer): String = "/posts/" + id
  private def getCommentsUri(blog: Blog): String = "/comments?postId=" + blog.id
  private def parseBlogResponse(jsonResponse: String): Blog = Json.parse(jsonResponse).as[Blog]
  private def parseCommentsResponse(jsonResponse: String): List[Comment] = Json.parse(jsonResponse).as[List[Comment]]

  val pooledConnectionFlow = {
    val connectionSettings = ConnectionPoolSettings(actorSystem)
      .withMaxConnections(32)
      .withMaxOpenRequests(32)
      .withMaxRetries(3)
    Http().cachedHostConnectionPool[Int](host = "jsonplaceholder.typicode.com", settings = connectionSettings)
  }

  val source = Source(1 to 32)
  val fetchBlogsFlow = Flow[Int]
    .map((id: Int) => (getBlogUri(id),id))
    .map{ case(uri:String, id:Int) => (HttpRequest(method = HttpMethods.GET, uri = uri), id) }
    .via(pooledConnectionFlow)
    .map { case(response: Try[HttpResponse], id:Int) => handleBlogResponse(response, id) }
    .map((jsonText: Try[String]) => jsonText.map(j => parseBlogResponse(j)))

  val sink = Sink.foreach[Try[Blog]](blog => blog.map(b=> println(b)))
  source.via(fetchBlogsFlow).runWith(sink)

  private def handleBlogResponse(response: Try[HttpResponse], id: Int): Try[String] = {
    println(s"Received response for id $id on thread ${Thread.currentThread().getName}")
    response.flatMap((r: HttpResponse) => {
      r.status match {
        case StatusCodes.OK => {
          Success(Await.result(Unmarshal(r.entity).to[String], Duration.Inf))
        }
        case _ => Failure(new RuntimeException("Invalid response : " + r.status.toString()))
      }
    })
  }
}

Now what I want is to create another flow for doing steps 3 and 4 that I would chain after the first flow. However, I am struggling with the pesky Try[Blog] output from the first flow. How do I pipe a Try[Blog] into another HTTP request? Is there a way to split the pipeline, with failures going one way and success going another?
Here is what I have for the second flow, but I'm not sure how to make the chaining work without calling get on the Try:
val processBlogsFlow = Flow[Try[Blog]]
  .map((tryBlog: Try[Blog]) => tryBlog.get)
  .map((blog: Blog) => (HttpRequest(method=HttpMethods.GET, uri=getCommentsUri(blog)), blog.id ))
  .via(pooledConnectionFlow)

A: There is a very good blog entry for dealing with Try.  In your particular example I would preserve the Try so you can get information on the original failure:
def blogToTuple(blog : Blog) =
  (HttpRequest(method=HttpMethods.GET, uri=getCommentsUri(blog)), blog.id )

val processBlogsFlow : Flow[Try[Blog], Try[HttpResponse], _] =
  Flow[Try[Blog]]
    .map(_ map blogToTuple)
    .mapAsync(1) { _ match {
         case Success(req) =>
           Source.single(req).via(pooledConnectionFlow).runWith(Sink.head)
         case ex => Future { x }
       }
    }

Now the Try can be passed to your Sink which can report on any error messages as well as reporting valid responses.


text:
Q: Python Help: How to find if 3 or 4 strings are the same in a list of 7 strings? I am creating a game of rummy in which I enter in 7 cards.
A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K is the number of the card.
And S, H, C, D are the suits (spades, hearts, clubs, diamonds)
Ex. 8H is hearts of 8
Code:
card1, card2, card3, card4, card5, card6, card7 = input('1. ').split(', ')

c1p1, c1p2 = card1[:-1], card1[1:]

c2p1, c2p2 = card2[:-1], card2[1:]

c3p1, c3p2 = card3[:-1], card3[1:]

c4p1, c4p2 = card4[:-1], card4[1:]

c5p1, c5p2 = card5[:-1], card5[1:]

c6p1, c6p2 = card6[:-1], card6[1:]

c7p1, c7p2 = card7[:-1], card7[1:]

Im splitting the entry of the user from the card number and suit.
The objective of this program is to find if they are 3 to 4 cards that have the same number but I dont know how to compare all 7 numbers to find if 3-4 of them are equal.
Any help would be greatly appreciated, thanks :)

A: you can use something like
 list.count(listElement)
for item in list:
    c= list.count(item)
    if c>3:
        print "card %s is more than 3 times"%item

A: I would use a dictionary to count the times a number appears, try the following piece of code:
def method():
    cards_string = "8H,3S,4H,7D,5C,JH,AS"
    cards = cards_string.split(',')
    card_numbers_count = {'A':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0, '10':0, 'J':0, 'Q':0, 'K':0}

    for card in cards:
        card_number = card[:-1]
        card_numbers_count[card_number] += 1

    print card_numbers_count

if __name__ == "__main__":
    method()


text:
Q: Explanation of evaluation for this Scheme procedure using lambdas I was wondering how the following code evaluates to 3.
(define (foo y) ((lambda (x) y) ((lambda (y)(* y y)) y)))

(foo 3)

I have been looking at it for a while and cannot seem to understand why the evaluation does not result in 9. Could someone provide a detailed step by step instruction on how this evaluates to 3?

A: Let's start by indenting the code in a way that it's easier to understand:
(define (foo y)
  ((lambda (x) y)
   ((lambda (y) (* y y))
    y)))

Now let's evaluate it, from the inside-out:
(define (foo y)
  ((lambda (x) y)
   ((lambda (y) (* y y))
    3))) ; pass the parameter

(define (foo y)
  ((lambda (x) y)
   (* 3 3))) ; evaluate innermost lambda

(define (foo y)
  ((lambda (x) y) 9)) ; pass the result of evaluation

Aha! that's where we get the 3. Even though we're passing a 9 as parameter (bound to x), we're simply returning the value of the outermost y parameter, which was 3 all along:
=> 3

A: With let re-writing,
(define (foo y) ((lambda (x) y) ((lambda (y)(* y y)) y)))

(foo 3)
=
(let ([y 3])                                 ; by application
  ((lambda (x) y) ((lambda (y)(* y y)) y)))
=
(let ([y 3])
  (let ([x ((lambda (y)(* y y)) y)])       ; by application
     y ))
=
(let ([y 3])
  (let ([x ((lambda (z)(* z z)) y)])     ; by alpha-renaming
     y ))
=
(let ([y 3])
  (let ([x (let ([z y])                ; by application
               (* z z))])
     y ))
=
(let ([y 3])
  (let ([x  (* y y)])                ; by let-elimination
     y ))
=
(let ([y 3])
  (let ([x 9])                     ; by expression evaluation
     y ))
=
(let ([y 3])
     y  )                        ; by let-elimination
=
3                              ; by let-elimination

As you can see, the nested (lambda (y)(* y y)) is situated in a nested scope, not affecting the y which is finally returned, but only x, which value, 9, is evaluated and then discarded.


text:
Q: If an array has two items with same ID then compare and add key value pair I have an array of objects, if two objects in the array have the same ID I want to add the difference as new key value in the object. For example I have the array

let array = [
  {id: 'apple', prop_name: 'price_l', last_value: {id: 390897, timestamp: 1673262338, prop_value: 10}},
  {id: 'orange', prop_name: 'price_g', last_value: {id: 390898, timestamp: 1673262338, prop_value: 8}},
  {id: 'apple', prop_name: 'quantity_a', last_value: {id: 390899, timestamp: 1673262338, prop_value: 12}},
  {id: 'orange', prop_name: 'quantity_o', last_value: {id: 390900, timestamp: 1673262338, prop_value: 14}}
];

And I want the output to be like this (labels may be dynamic)

let array = [
  {id: 'apple', price_l: 10, quantity_a: 12},
  {id: 'orange', price_g: 8, quantity_o: 14}
];

Here's what I've tried so far

function addKeyValuePair(array) {
      for (let i = 0; i < array.length; i++) {
        for (let j = i + 1; j < array.length; j++) {
          if (array[i].id=== array[j].id) {
           //I'm stuck here
          }
        }
      }
      return array;
    }

     console.log(addKeyValuePair(array));

A: I think you are stuck because you are not using some sort of collector where you build the new objects in.
Here is a one-liner, where the new objects are collected as values of an object, adding prop names and values at each step:

let array = [
    {id: 'apple', prop_name: 'price_l', last_value: {id: 390897, timestamp: 1673262338, prop_value: 10}},
    {id: 'orange', prop_name: 'price_g', last_value: {id: 390898, timestamp: 1673262338, prop_value: 8}},
    {id: 'apple', prop_name: 'quantity_a', last_value: {id: 390899, timestamp: 1673262338, prop_value: 12}},
    {id: 'orange', prop_name: 'quantity_o', last_value: {id: 390900, timestamp: 1673262338, prop_value: 14}}
  ];

const res = Object.values(array.reduce( (r, {id, prop_name, last_value:{prop_value}}) => ({...r, [id]: {...(r[id] ?? {id}), [prop_name]: prop_value} }), {}))
console.log(res)

Here it is verbose:

let array = [
    {id: 'apple', prop_name: 'price_l', last_value: {id: 390897, timestamp: 1673262338, prop_value: 10}},
    {id: 'orange', prop_name: 'price_g', last_value: {id: 390898, timestamp: 1673262338, prop_value: 8}},
    {id: 'apple', prop_name: 'quantity_a', last_value: {id: 390899, timestamp: 1673262338, prop_value: 12}},
    {id: 'orange', prop_name: 'quantity_o', last_value: {id: 390900, timestamp: 1673262338, prop_value: 14}}
];

function wrap(arr){
  const collector = {}
  for(const entry of arr){
    const id = entry.id
    if (!collector[id]){
      collector[id] = {id}
    }
    collector[id][entry.prop_name] = entry.last_value.prop_value
  }
  return Object.values(collector)
}

console.log(wrap(array))


text:
Q: How do you set the axes on a histogram and swap the x and y axes? I have a dataset where I want to plot a histogram of the number of measurements at each depth. I want to plot a histogram of each the frequency of measurements in the depth column. I want to bin the data into 5m chuncks starting at 0m, going up to 155m. This code, gets me a histogram, which looks a reasonable shape, but the values seem wrong, and I can't quite get it to start at 0. In addition, I would like to be able to swap the x-axis and y-axis, so that depth is on the y-axis, and frequency, is on the x-axis.
    import numpy as np
    import datetime as dt
    import matplotlib.pyplot as plt
    import glob

    #The data is read in, and then formatted so that an array Dout (based on depth) is created. This is done since multiple files will be read into the code, and so I can create the histogram for all the files I have up until this point.

    Dout = np.array(depthout)

    bins = np.linspace(0, 130, num=13) #, endpoint=True, retstep=False)

    plt.hist(Dout, bins)
    plt.xlabel('Depth / m')
    plt.ylabel('Frequency')
    plt.show()

    # the end

The data is in this format:
TagID    ProfileNo   ProfileDirn     DateTime    Lat     Lon     Depth   Temperature

A: You want the orientation kwarg of hist (Docs).
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

data = np.random.randn(1500)
bins = np.linspace(-5, 5, 25, endpoint=True)

ax.hist(data, bins, orientation='horizontal')
ax.set_ylim([-5, 5])
plt.show()


text:
Q: Peer's Certificate has been revoked I just upgraded our web server with a renewed cert as our current cert expires later this week.  When I browse to our site via FF it is throwing this error:
Secure Connection Failed
An error occurred during a connection to www.rivworks.com.
Peer's Certificate has been revoked. (Error code: sec_error_revoked_certificate)
            *   The page you are trying to view can not be shown because the authenticity of the received data could not be verified.
            *   Please contact the web site owners to inform them of this problem. Alternatively, use the command found in the help menu to report this broken site.

When I try IE (v6 - v8) I do not get this error.  I've searched this site, Bing and Google and am not finding a solution for this.  If I had long hair I'd be pulling it out!
Any help is appreciated!

ADDITIONAL INFO:
After working the search engines over I have come to conclude this is a problem in FF and not with my cert.  My cert issuer has been going through it with a fine tooth comb and every thing they can do shows all of my cert chain is in working order.  FF just hates a renewed cert!
The one (and only one) link I got for a possible fix is here:  http://www.wallpaperama.com/forums/firefox-error-code-sec-error-revoked-certificate-t7301.html.  This leads to the solution this guy came up with here: http://www.wallpaperama.com/forums/installing-ssl-certificate-in-a-godaddy-dedicated-server-with-ispconfig-t7300.html.  Unfortunately - it is for a UNIX server and I don't know how to translate UNIX to WINDOWS SERVER 2003. Any help?

A: Have you looked at the cert in FF or IE to see if you can get any clue as to what's wrong? Could it be that the certificate chain is broken because an intermediate certificate is no longer valid?

A: Solution on other sites regarding uncheck OSCP query on browsers (firefox in options or certificate settings to uncheck OSCP query option) doesn't seems right solution. OSCP (Online Certificate Status Protocol) is internet protocol used for obtaining the revocation status of your digital certificate.
See details here
If OSCP response doesn't confirm certificate is OK, Browser will show Error such as sec_error_revoked_certificate . Better to check broken chain of certificate installed or its validity.

A: Browsers have options that will check for certificate revocation, and this check is most likely turned off for you in IE while enabled in FF.  The option in IE is in Internet Options on the Advanced tab under the Security Heading - "Check for server certificate revocation)".  Look to see if that's enabled on your browser.  If not, check it and restart IE and you should start seeing IE tell you the same thing.
Just a thought, but check to see what the beginning date is that the certificate is valid.  If it's some time in the future you should put your old cert back on the server.

A: I have had this problem too. To get around it in FireFox, you need to do the following:
Tools > Options > Advanced > Encryption > Validation > Disable OCSP.

As to why your certificate is on that list, I've no idea, but I had the same problem with our mail server, and is still currently unresolved.

A: I ran into this error and the reason was that major browsers have clamped down on CAs (Certificate Authorities) behaving badly.
The root certs of WoSign/StartCom and even some Symantec root certs have been revoked.
Annoyingly, looking at the cert didn't give me a clue as to what was wrong.

*

*Source (Mozilla)

*Source (Ars)


text:
Q: Magento, Postfix, or Elastic Mail adding slashes Magento transactional emails somehow get additional escape characters added to the headers.
Magic_quotes are disabled in PHP.
Postfix uses Elastic Email as a relay. According to Elastic, e-mail are received correctly.
Then majority of clients receive the emails correctly, except those who are behind messagelabs.com filter. After reviewing the logs, the messages are rejected by messagelabs.com because additional slashes are added to the emails.
Has anyone ever come across this issue? Which piece could be at fault?
Again, majority of customers receive emails perfectly fine.

A: When you say "perfectly fine", do you mean that most customers receive e-mails that don't have slashes in them?  Or are you simply complaining about messagelabs rejecting your e-mails?
As far as the extra quotes, if it's really happening to everyone, I'll wager that you're not really turning off magic_quotes_gpc and magic_quotes_runtime -- you've probably turned it off in the main config, and then something's turning it back on (a rogue .htaccess file, for instance).  Double (and triple) check by running phpinfo() in the same directory as the script that's causing the trouble.
Based on your comments, I'm going to have to say that it's a messagelabs problem -- if you send out an e-mail and it gets to the recipient differently to how you sent it, it's the fault of some intermediary mangling the data in transit.  I can't offer any suggestions to fix it, however; I can only shake my head at the continued insanity of the world.

A: The problem turned out to be a bug in Elastic Email service. After reporting it to them, they fixed it within a few hours.


text:
Q: Problem with displaying usernames in my flash[:notice] - Agile Web Development With Rails - Chapter 11 I can't figure out what I'm doing wrong here.
I can't seem to get the #{@user.name} to work in my flash[:notice]
Everything else works just fine I can add new users, but when I add a new user instead of saying "User John Doe was successfully created", it says "User #{@user.name} was successfully created."
I'm at this point in the depot app: depot_p/app/controllers/users_controller.rb to work.

A: This has to do with string interpolation which is for double quoted strings only, it has nothing to do with the flash.
You can substitute the value of any Ruby expression into a double quoted string using the sequence #{ expr }. If the expression is just a global variable, a class variable, or an instance variable, you can omit the braces.
"Seconds/day: #{24*60*60}"    » Seconds/day: 86400
"#{'Ho! '*3}Merry Christmas"  » Ho! Ho! Ho! Merry Christmas
"This is line #$."            » This is line 3

For more info, Programming Ruby is a free Ruby online book.

A: Ok, I figured this out.
Flash notices must be in double quotes, not single quotes. I had:
flash[:notice] = 'User #{@user.name} was successfully created.'
When it should have been flash[:notice] = "User #{@user.name} was successfully created."
That's a tricky detail for a total noob. FYI for others out there.

A: Agree with JRL.  If you want to use the #{foo} syntax in any string you need to use double quotes.


text:
Q: Oauth pkce flow impersonating someone else's client For confidential clients, there are scopes assigned to clients and the logged in user has to consent to them. Since there is client secret involved in exchange of auth code for access token, no one can impersonate them and take advantage of their scopes.
But when it comes to pkce flow on a native app, if I had someone else's clientId (clientIds are not considered private information) which has a lot of scopes, I could just start the flow with with their clientId. What is stopping a hacker from using some reputed clientId in the PKCE flow and have access to all their scopes?

A: NATIVE CALLBACK METHODS
If you look at RFC8252, certain types of callback URL can be registered by more than one app, meaning only a client ID needs to be stolen in order to impersonate a real app, as you say.
This still requires a malicious app to trick the user to sign in before tokens can be retrieved. And of course each app should use only the scopes it needs, and prefer readonly ones. After that it depends on the type of native app.
MOBILE
A mobile app can use Claimed HTTPS Schemes via an https callback URL to overcome this. It is backed by App Links on Android or Universal Links on iOS. Even if a malicious app uses the client ID, it cannot receive the login response with the authorization code, because it will be received on a URL like this, and the mobile OS will only pass this to the app that has proved ownership of the domain via the deep linking rehistration process:

*

*https://mobile.mycompany.com/callback?code=xxx
DESKTOP
For desktop apps there are gaps, since only Loopback and Private URI Scheme callback URLs can be used. It relies on users to avoid installing malicious apps. Eg only install apps from stores that require code signing, which also inform the user who the publisher is. If users install malicious apps then perhaps they have deeper problems.
ATTESTATION
A newer technique is to use a form of client authentication before authentication begins. For confidential clients, Pushed Authorization Requests are used, which uses the app's client credential, so this cannot be used by native clients by default.
Mobile apps could potentially provide proof of ownership of their Google / Apple signing keys during authentication, and there is a proposed standard around that.


text:
Q: How do I maintain the type of items in a collection of a base type across postbacks? I have a base class, a set of subclasses and a collection container that I am using to create and populate controls dynamically using partial views.
// base class
public class SQControl
{
    [Key]
    public int ID { get; set; }
    public string Type { get; set; }
    public string Question { get; set; }
    public string Previous { get; set; }
    public virtual string Current { get; set; }
}

// subclass
public class SQTextBox : SQControl
{
    public SQTextBox()
    {
        this.Type = typeof(SQTextBox).Name;
    }
}

//subclass
public class SQDropDown : SQControl
{
    public SQDropDown()
    {
        this.Type = typeof(SQDropDown).Name;
    }

    [UIHint("DropDown")]
    public override string Current { get; set; }
}

// collection container used as the Model for a view
public class SQControlsCollection
{
    public List<SQControl> Collection { get; set; }
    public SQControlsCollection()
    {
        Collection = new List<SQControl>();
    }

}

I populate the Collection control with different subclasses of SQControl as required at runtime, and in EditorTemplates I have a separate view for each subclass. Using  Html.EditorFor on the collection items I can dynamically generate the form with the appropriate controls.
This all works fine.
The problem I have is that when I save the form, MVC binding cannot tell what subclass each item in the Collection was created with and instead bind them to instances of the base class SQControl.
This confuses the View engine as it cannot determine the proper views to load anymore and simply loads the default.
The current workaround I have is to save the "Type" of the subclass as a field in the model, and on postback, I copy the collection into a new container, re-creating each object with the proper subclass based on the information in the Type field.
public static SQControlsCollection Copy(SQControlsCollection target)
    {
        SQControlsCollection newCol = new SQControlsCollection();

        foreach (SQControl control in target.Collection)
        {
            if (control.Type == "SQTextBox")
            {
                newCol.Collection.Add(new SQTextBox { Current = control.Current, Previous = control.Previous, ID = control.ID, Question = control.Question });
            }
            else if (control.Type == "SQDropDown")
            {
                newCol.Collection.Add(new SQDropDown { Current = control.Current, Previous = control.Previous, ID = control.ID, Question = control.Question });
            }
            ...

        }

        return newCol;
    }

So my Question is, is there any better way to maintain the type of items in a base-typed-collection between postbacks? I understand it's practice in MVC to have a typed view for each model, but I want to be able to build a view on the fly based on an XML document using reusable partial views.


text:
Q: `POST` request to script page The function below is contained in the Apps Script code.gs file:
function doPost(e) {
  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));
}

If I make a request using fetch from the background.js of my Chrome extension and include the id parameter in the URL, I get the expected result.
const url = 'https://script.google.com/.../exec?id=123';

fetch(url)
  .then(response => response.text())
  .then(data => { console.log(data) }) // {"id":"123"}

Instead of writing id as a parameter in the URL, I would like to make the request using the POST method.
I tried to use the object below, but I don't know how to include the variable I want to send:
{
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: {}
}

A: I believe your goal is as follows.

*

*You want to send the value of id=123 with the request body instead of the query parameter.

In this case, how about the following modification?
Google Apps Script side:
function doPost(e) {
  if (typeof e !== 'undefined') {
    const value = JSON.parse(e.postData.contents); // This is the value from the request body.
    return ContentService.createTextOutput(JSON.stringify(value));
  }
}

Javascript side:
const url = "https://script.google.com/macros/s/###/exec";
const data = { id: 123 };
fetch(url, { method: "POST", body: JSON.stringify(data) })
  .then((res) => res.text())
  .then((res) => console.log(res));

*

*By this modification, you can see the value of {"id":123} in the console.

Note:

*

*When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.

*You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:

*

*Web Apps

*Taking advantage of Web Apps with Google Apps Script (Author: me)

A: To include the data you want to send in the request body and to make a POST request using the fetch function, you can do the following:
const data = {id: '123'};

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(data)
})
  .then(response => response.text())
  .then(data => { console.log(data) })

This send a POST request to the URL with data in the request body. The server-side function (in this case, doPost) will receive the data in the e.parameter object.
I hope this helps you.