text:
Q: How to collect the list of differnces of file between local changes and Head changes in a Map using JGIT Library? I need a list of file differences between a local (worktree) and the Head
eg
public void localDiffAndHead(Git git) throws IOException {
    try (DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
          diffFormatter.setRepository(git.getRepository());
          String lastCommit = getLastCommitOfCurrentBranch(git).get().getName();
          AbstractTreeIterator commitTreeIterator = prepareTreeParser( git.getRepository(),  lastCommit );
          FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
          List<DiffEntry> diffEntries = diffFormatter.scan(workTreeIterator, commitTreeIterator);
          for(DiffEntry diffEntry: diffEntries) {
              if (diffEntry.getOldPath().contains("/ui.xml")) {
                  FileHeader fileHeader = diffFormatter.toFileHeader(diffEntry);
                  ListIterator<Edit> edits = fileHeader.toEditList().listIterator();
                  while(edits.hasNext()) {
                      Edit edit = edits.next();
                      System.out.println(edit.getType());
                      System.out.println(edit.getBeginA());
                      System.out.println(edit.getEndA());
                      System.out.println(edit.getBeginB());
                      System.out.println(edit.getEndB());
                  }
              }

          }
          System.out.println();
        }
}

My above code presenting the below output for my selected file "ui.xml".
Replace
0
1
0
1
but my expected result should be like below
Type | content
Replace |xyz
Delete | abc
Insert | bbc


text:
Q: Rails 7: Turbo stream is showing partial only I am having a problem with the turbo-rails gem. First I installed the latest version in my Rails 7 application. On my site, I have a select input which is wrapped in a form, with a partial below that form that shows the data. Now I want to apply a filter using the select and dynamically update the data using this turbo-rails package. My form html looks like this:

        <%= form_with url: '/users/load', method: :get, data: { turbo_frame: :form_response } do |form| %>
            <%= render partial: "shared/select", locals: {
                placeholder: 'Gender',
                width: '90px',
                options: @genders,
                classes: 'filter',
                name: 'gender',
            } %>
            <%= form.submit %>
        <% end %>

    <%= turbo_frame_tag :form_response do %>
        <%= render partial: "users/user_list", locals: {
            users: @users
        } %>
    <% end %>

In my routes, I created this get request which is forwared to a load method in my controller like this:
get '/users' => "users#index"
get '/users/load' => "users#load"

And then in my controller I have the 2 methods written like this:
class UsersController < ApplicationController

    before_action :require_user

    USERS_PER_PAGE = 15

    def index
        @genders = ["Male", "Female"]
        @users = User
                            .limit(USERS_PER_PAGE)
                            .order(:creation_date).reverse_order
    end

    def load
        @users = User
                            .limit(USERS_PER_PAGE)
                            .order(:creation_date).reverse_order

        if params[:gender]
            @users = @users.where(gender: params[:gender])
        end

        respond_to do |format|
            format.html { render partial: 'users/user_list', locals: { users: @users } }
        end
    end
end

The problem is that when I go to this page, select a gender and hit the submit button, I get to see the user data with the correct genders, but I only see the partial loaded, so the rest of the page is gone. I can see in the network tab of developer tools in Chrome that the request headers is set to:
text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

I want to use the turbo-streams instead of the turbo frames, because I need to update more of these items on the same page. Why is it not rendering the content inside the page, instead of rendering the partial only?
How can this be fixed?

A: To answer your question, you're rendering a partial without turbo stream or turbo frame, so you're only getting a partial as response.
I think, a few examples will explain everything.
# config/routes.rb
resources :users

# app/controllers/users_controller.rb
def index
  scope = User.order(created_at: :desc)
  scope = scope.where(name: params[:search]) if params[:search]
  @users = scope
end

"Preserve log" is quite useful when working with turbo frame and it redirects and clears the console:
https://developer.chrome.com/docs/devtools/console/reference/#persist

Turbo FRAME using GET request with HTML response
We are in index action and the form is submitting back to index.
# app/views/users/index.html.erb

# expect :users_index turbo frame in a response      vvvvvvvvvvvvvvvvvvvvvvvvv
<%= form_with url: users_path, method: :get, data: { turbo_frame: :users_index } do |f| %>
  <%= f.text_field :search %>
  <%= f.submit %>
<% end %>

# turbo frame in a response needs to match turbo frame on the current page,
# since we're rendering the same page again, we have the matching frame,
# only content inside this frame is updated.
<%= turbo_frame_tag :users_index do %>
  <%= render @users %>
<% end %>

# If you render some other page, you have to wrap it in
# `turbo_frame_tag :users_index`

If you want to update the url as well, so you don't lose the search on refresh:
<%= turbo_frame_tag :users_index, data: { turbo_action: :advance } do %>
  <%= render @users %>
<% end %>

Turbo STREAM using GET request with TURBO_STREAM response
You have to set data-turbo-stream="true" to send a GET stream.
# app/views/users/index.html.erb

<%= form_with url: users_path, method: :get, data: { turbo_stream: true } do |f| %>
  <%= f.text_field :search %>
  <%= f.submit %>
<% end %>

<%= tag.div id: :users_index do %>
  <%= render @users %>
<% end %>

Add turbo_stream format to respond to this request:
# app/views/users/index.turbo_stream.erb

# update content inside

<%= turbo_stream.update :users_index do %>
  <%= render @users %>
<% end %>

# add another `turbo_stream` here if you'd like.

Turbo STREAM using POST request with TURBO_STREAM response
# config/routes.rb

resources :users do
  # # add `search` action
  # post :search, on: :collection

  # i'll be lazy and post to :index
  post :search, action: :index, on: :collection
end

POST form submissions are sent as TURBO_STREAM by default and it will render index.turbo_stream.erb.
# app/views/users/index.html.erb

<%= form_with url: search_users_path do |f| %>
  <%= f.text_field :search %>
  <%= f.submit %>
<% end %>

<%= tag.div id: :users_index do %>
  <%= render @users %>
<% end %>

# app/views/users/index.turbo_stream.erb

<%= turbo_stream.update :users_index do %>
  <%= render @users %>
<% end %>

Test set up
Just do a simple set up:
rails --version
# Rails 7.0.4

rails new turbo-test -j esbuild
cd turbo-test
bin/rails g scaffold User name
bin/rails db:migrate
open http://localhost:3000/users
bin/dev

# app/controllers/users_controller.rb

def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      # Add this line:
      format.turbo_stream { render turbo_stream: turbo_stream.prepend(:users, partial: "user", locals: { user: @user }) }

      format.html { redirect_to user_url(@user), notice: "User was successfully created." }
    else
      format.html { render :new, status: :unprocessable_entity }
    end
  end
end

# app/views/users/index.html.erb

# submit form
<%= render "form", user: User.new %>

# new user gets prepended here

  <%= render @users %>

redpajama_set_name: RedPajamaStackExchange


text:
Q: "bash: [: : integer expression expected" I want this function to return one random word if there aren't any command-line arguments.
I am modifying linuxconfig.org's random-word generator to run even when #$ -ne 1.
function random-word {
    if [ $# -eq 0 ] ;
    then
        echo "I only take one argument, dummy"
        # previously was exit 0
    fi

    # Constants
    X=0
    ALL_NON_RANDOM_WORDS=/usr/share/dict/words

    # total number of non-random words available
    non_random_words=`cat $ALL_NON_RANDOM_WORDS | wc -l`

    # while loop to generate random words
    # number of random generated words depends on supplied argument
    while [ $X -lt "$1" ]
    do
    random_number=`od -N3 -An -i /dev/urandom |
    awk -v f=0 -v r="$non_random_words" '{printf "%i\n", f + r * $1 / 16777216}'`
    sed `echo $random_number`"q;d" $ALL_NON_RANDOM_WORDS
      let "X = X + 1"
    done

The statement executes, but there's a bash error:
$ bob
I only take one argument, dummy
bash: [: : integer expression expected

How do I fix this so the bash error won't display?

A: while [ $X -lt "$1" ] is being evaluated even when there is no $1.
Move the rest of the code into an else block so this doesn't happen.
function random-word {
    # from linuxconfig.org

    if [ $# -eq 0 ]
    then
        echo "I need an argument, dummy"
        # To be extra friendly, give them a random word.
        echo "Here's a random word:"
        random-word 1
    else
        # Constants
        X=0

         ...

        sed `echo $random_number`"q;d" $ALL_NON_RANDOM_WORDS
          let "X = X + 1"
        done
    fi
}

A: You don't need an else block. And you don't need to fail if you receive more than one argument. You only need to fail if you don't get an argument and you can then just ignore everything else or quit if you don't get at least the one.
set -- "${1?ERR: Where\'s my argument?!?!}"

That statement does all of that. This does the same but also fails if the first argument is only the '' nullstring :
set -- "${1:?ERR: Where\'s my argument?!?!}"

Of course, if the point is to be a shell function called from an interactive shell, this might kill the interactive shell as well, so you can do:
(: "${1:?Where\'s my argument?}") || return && set -- "$1"

...which will handle that as well. But, in my opinion, a shell function should never affect an interactive shell unless absolutely necessary - like if it needs to alter a current shell variable or something. And so better than the above would be to declare the function as a subshell, like:
fn() (set -- "${1:?Where\'s my argument?}" && echo "$1")

...does.
Another way to do this is to accept all arguments and concatenate them - so all arguments are only treated as one in every case. You can do that like:
fn() (
    : "${1:?ERR: Where\'s my argument?}"
    set -- "$*" && echo "$1"
)
fn '' ; fn here are a lot of arguments that will all be treated as one
###OUTPUT###
sh: line 2: 1: ERR: Where's my argument?
here are a lot of arguments that will all be treated as one

I personally don't much like the sh: line 2: 1: bit that usually happens - at least not in interactive shells. I usually stick a CTRL+V CTRL+M in before ERR: so it does a return to the head of the line in a terminal and writes over that bit but still outputs the more useful info into a log. Like:
fn() (
    : "${1:?^MERR: Where\'s my argument?}"
    set -- "$*" && echo "$1"
)
fn ; fn 2>&1 | cat -A
###OUTPUT###
ERR: Where's my argument?
sh: line 2: 1: ^MERR: Where's my argument?$


text:
Q: Print elements from a db table with confirmation buttons ( Magento - system.xml ) I'm developing a custom module with admin configuration.
How can i add a section in the system.xml file in which i can print elements from a db table, with confirm/reject button for each? (it's a variable number of elements, so i cannot create a section for each element)
Is there a way to create a section in which i can add my php code (and only that code) ?
For example, this section has to look like this:
Element-1 {Confirm} {Reject}
Element-2 {Confirm} {Reject}
...


text:
Q: TypeError: books.map is not a function in react import React from 'react';

export class Books extends React.Component {
state = {
    loading: true,
    books: []
}

componentDidMount() {

    fetch('**url**')
        .then(res => res.json())
        .then((data) => {
            this.setState({ books: data })
        })
        .catch(console.log)
  }
 render() {

    const { books } = this.state;
    console.log("this.state contains:", this.state);

/*  this.state contains: {loading:true, books: status:'success',data:(10)[{id:1, name:xyz,..},{}..] */
    const b = books.data;
    return (

            {b.map((k) => (

{k.name}

            ))}

    );

}

}
I want to display all the values(for example: id:1, name:xyz, id:2 , name:xxx)
Since 1 week I'm trying to fix this. But couldn't. getting map is not a function.
Please help me to fix this issue.

A: try following:
let b = books.data || [];

since you're getting data in componentDidMount, there's fair chance it doesn't get the result when you want to render.

A: The books object in the state is initially empty, therefore books.data does not exist and hence books.data.map is not function. So do conditional render
    const {data} = this.state.books

        {data && data.map((k) => (
{k.name}
))}

A: Try making a condition to check if b is an array or not! like this:
const b = books.data;
return (

        {
         if(Array.isArray(b)){
        b.map((k) => (

{k.name}

        ))
           }
            }

);

}


text:
Q: No exe file being generated in C using recent Cygwin versions

GCC 4.9.2 does not create an executable, neither a.out or -o hello.exe.  Adding -v to the compile line indicates that -o is switched to a non-existent temporary file, for example: -o /tmp/ccr6nMlO.s
Recent installs of Cygwin NT-6.1 over the last few months onto both Windows XP and Windows 7 have all failed to produce an executable.  I found Cygwin 1.7.3 on an old laptop that works perfectly.
Have the compile flags or their syntax changed? This command fails to generate an executable:
gcc hello.c -o hello.exe

This is the version I have. I thought it came from a Cygwin mirror. $ uname -a gives
CYGWIN_NT-6.1-WOW Gary-PC 1.7.35(0.287/5/3) 2015-03-04 12:07 i686

Here's a compile example:
$ gcc hello.c -o hello.exe

echo $? returns a 1, without comment. So the compiler is failing.
All attempts to compile any code fails to produce anything in the current directory and no errors or warnings are reported. ctgcheck -c bash binutils bzip2 cygwin gcc-core gcc-g++ gzip m4 make unzip zip indicates everything is installed:
Cygwin Package Information
Package              Version        Status
bash                 4.3.33-1       OK
binutils             2.25-1         OK
bzip2                1.0.6-2        OK
cygwin               1.7.35-1       OK
gcc-core             4.9.2-3        OK
gcc-g++              4.9.2-3        OK
gzip                 1.6-1          OK
m4                   1.4.17-1       OK
make                 4.1-1          OK
unzip                6.0-14         OK

Compiling with -v gives this report:
$ gcc hello.c -o hello.exe -v

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/i686-pc-cygwin/4.9.2/lto-wrapper.exe
Target: i686-pc-cygwin
Configured with: /cygdrive/i/szsz/tmpp/gcc/gcc-4.9.2-3.i686/src/gcc-4.9.2/configure --srcdir=/cygdrive/i/szsz/tmpp/gcc/gcc-4.9.2-3.i686/src/gcc-4.9.2 --prefix=/usr --exec-prefix=/usr --bindir=/usr/bin --sbindir=/usr/sbin --libexecdir=/usr/libexec --datadir=/usr/share --localstatedir=/var --sysconfdir=/etc --libdir=/usr/lib --datarootdir=/usr/share --docdir=/usr/share/doc/gcc --htmldir=/usr/share/doc/gcc/html -C --build=i686-pc-cygwin --host=i686-pc-cygwin --target=i686-pc-cygwin --without-libiconv-prefix --without-libintl-prefix --libexecdir=/usr/lib --enable-shared --enable-shared-libgcc --enable-static --enable-version-specific-runtime-libs --enable-bootstrap --enable-__cxa_atexit --with-dwarf2 --with-arch=i686 --with-tune=generic --disable-sjlj-exceptions --enable-languages=ada,c,c++,fortran,java,lto,objc,obj-c++ --enable-graphite --enable-threads=posix --enable-libatomic --enable-libgomp --disable-libitm --enable-libquadmath --enable-libquadmath-support --enable-libssp --enable-libada --enable-libjava --enable-libgcj-sublibs --disable-java-awt --disable-symvers --with-ecj-jar=/usr/share/java/ecj.jar --with-gnu-ld --with-gnu-as --with-cloog-include=/usr/include/cloog-isl --without-libiconv-prefix --without-libintl-prefix --with-system-zlib --enable-linker-build-id
Thread model: posix gcc version 4.9.2 (GCC)
COLLECT_GCC_OPTIONS='-o' 'hello.exe' '-v' '-mtune=generic' '-march=i686' /usr/lib/gcc/i686-pc-cygwin/4.9.2/cc1.exe -quiet -v -Dunix -idirafter /usr/lib/gcc/i686-pc-cygwin/4.9.2/../../../../include/w32api -idirafter /usr/lib/gcc/i686-pc-cygwin/4.9.2/../../../../i686-pc-cygwin/lib/../../include/w32api hello.c -quiet -dumpbase hello.c -mtune=generic -march=i686 -auxbase hello -version -o /tmp/cc8W4cOy.s

I've also installed Cygwin on Windows XP that reports this version: CYGWIN_NT-5.1 lt-love6 1.7.35(0.287/5/3) 2015-03-04 12:07 i686 Cygwin
The compile results for hello.c are the same. No executable is made and $?=1 indicating the compile has failed. Also there are no reported errors or warnings. Using -v provides a report similar to the one above.

A: I had a similar problem (and started a bounty) but have now managed to resolve my own problem by re-installing Cygwin. @CristiFati added a comment to the question asking for clarification of versions but ironically, having added a bounty leaves me with insufficient reputation to be able to reply - so I'll have to answer here instead.
Cygwin setup was used to bring the system up to date and to install the GCC packages (by adding package 'gcc-objc++') as the original Cygwin was installed without GCC support. However, this installation was on a system with multiple users running with restricted privileges. I believe that this interfered with the upgrade and resulted in some files being inaccessible to some users and so the installation of GCC was corrupt.
The behavior was that a successful compilation worked and produced the correct object files but any errors would silently fail, with no output and no error messages (but an exit status of '1').
The solution was to completely remove Cygwin and re-install as my own user. This ensured the permissions were correct so the installation/upgrade could correctly upgrade all files and GCC compilation and error reporting is now working as expected.
To summarize:

*

*Incorrect Windows permissions caused package installation issues.

A: I am not sure if you are only interested in having a working system (in which case you could simply reinstall Cygwin, possibly a newer version),
or in being certain about forensics, i.e., determining the cause of your problem.
For the second objective, one thing you could do is isolating the 3 phases of going from hello.c to hello.exe:

*

*Preprocessing (using -v for verbosity)
gcc -E hello.c -v -o hello.i

*Compiling
gcc -c hello.c -v -o hello.o

(or you could also compile hello.i)

*Linking
gcc hello.o -v -o hello.exe

and checking which of the three fails first.
That may give you a clue on possible sources of failure.
PS: I cannot reproduce your problem with
$ uname -a
MSYS_NT-10.0-WOW P522806 2.11.2(0.329/5/3) 2018-11-26 08:59 i686 Msys

$ gcc --version
gcc.exe (Rev3, Built by MSYS2 project) 8.2.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

A: As per I've used, a simple GCC command in Cygwin terminal as
$ gcc filename.c

produces output file "a". You can run it as follows:
$ ./a

Hope it helps.

A: I have faced similar issue.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version should
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.


text:
Q: How can I get name from this json. Basically I need name of folders like My Box Notes, Roboitc SPOT etc {
  "type": "folder",
  "id": "0",
  "sequence_id": null,
  "etag": null,
  "name": "All Files",
  "created_at": null,
  "modified_at": null,
  "description": "",
  "size": 0,
  "path_collection": {
    "total_count": 0,
    "entries": []
  },
  "created_by": {
    "type": "user",
    "id": "",
    "name": "",
    "login": ""
  },
  "modified_by": {
    "type": "user",
    "id": "",
    "name": "abc",
    "login": ""
  },
  "trashed_at": null,
  "purged_at": null,
  "content_created_at": null,
  "content_modified_at": null,
  "owned_by": {
    "type": "user",
    "id": "",
    "name": "abc1",
    "login": ""
  },
  "shared_link": null,
  "folder_upload_email": null,
  "parent": null,
  "item_status": "active",
  "item_collection": {
    "total_count": 6,
    "entries": [
      {
        "type": "folder",
        "id": "",
        "sequence_id": "0",
        "etag": "0",
        "name": "My Box Notes"
      },
      {
        "type": "folder",
        "id": "",
        "sequence_id": "0",
        "etag": "0",
        "name": "Roboitc SPOT"
      },
      {
        "type": "folder",
        "id": "",
        "sequence_id": "0",
        "etag": "0",
        "name": "Salesforce1"
      },
      {
        "type": "folder",
        "id": "",
        "sequence_id": "0",
        "etag": "0",
        "name": "SF2"
      },
      {
        "type": "folder",
        "id": "",
        "sequence_id": "0",
        "etag": "0",
        "name": "testfolder"
      },
      {
        "type": "file",
        "id": "",
        "file_version": {
          "type": "file_version",
          "id": "",
          "sha1": ""
        },
        "sequence_id": "1",
        "etag": "1",
        "sha1": "",
        "name": "SF Assets Single Slider.pptx"
      }
    ],
    "offset": 0,
    "limit": 100,
    "order": [
      {
        "by": "type",
        "direction": "ASC"
      },
      {
        "by": "name",
        "direction": "ASC"
      }
    ]
  }
}


text:
Q: Problem with AD-HOC wifi option I have internet access by ethernet and I want to use my notebook as a wifi point. I want to have internet access on various devices, too.
I am trying to make my notebook as wifi access point by using ad-hoc option.
I did everything like in this movie http://www.youtube.com/watch?v=gAvnh8TsFEU.
I suppose I did everthing ok, according the advices - I checked it a few times.
When configuration of ad-hoc network is finished, then my wifi detector going mad. Ubuntu tries to get access to ad-hoc network and it can but only four about 3 seconds. After that there is disconnected. Ubuntu tries to get access again and again.
In general it seems like this: ubuntu informational cloud on my desktop still shows information about connect and disconnet to ad-hoc network alternately. Without any break. Connected, disconnected, connected, disconnected.
Does anyone have any idea how can i fix it and create my ad-hoc network as stable thing?
Thanks

A: Hi you need to configure hostapd
I have configure following in hostapd /etc/hostapd/hostapd.conf with WPA authentication options for wireless users
01 interface=wlan0
02 driver=nl80211
03 ssid=dontMessWithVincentValentine
04 hw_mode=g
05 channel=6
06 macaddr_acl=0
07 auth_algs=1
08 ignore_broadcast_ssid=0
09 wpa=3
10 wpa_passphrase=KeePGuessinG
11 wpa_key_mgmt=WPA-PSK
12 wpa_pairwise=TKIP
13 rsn_pairwise=CCMP
sudo hostapd /etc/hostapd/hostapd.conf
In graphical way u can try this link
http://www.howtogeek.com/116409/how-to-turn-your-ubuntu-laptop-into-a-wireless-access-point/


text:
Q: Having a SwiftUI Toggle control a Bool of a Core Data object causes a crash I have a model called Note that is an NSManagedObject automatically generated by Core Data. It has a pinned property that is a non-optional Bool. I am trying to pass the Bool into a Toggle view, but this causes a crash:
2019-09-09 12:38:11.647030-0500 MyApp[12336:2688627] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Note pinned]: unrecognized selector sent to instance 0x2837e42d0'
*** First throw call stack:
(0x1a665897c 0x1a63810a4 0x1a655c42c 0x1a665cdf8 0x1a665ebdc 0x104f83cd4 0x1b37f0900 0x1b37f0528 0x1b37f02b8 0x1b37f2278 0x1dbcd19f0 0x1dc2aa43c 0x1dc2ab504 0x104f83bf4 0x1dbf41f30 0x1dbf42a64 0x104f83680 0x1dc2c4f98 0x104f826c4 0x1dbd8b484 0x104f82450 0x104f85124 0x1dbd158e4 0x1dbd16070 0x1d0600458 0x1d05e8a60 0x1d05e8d24 0x1d05eda0c 0x1dbe41838 0x1dbe41b64 0x1dbe418ec 0x1dc1a82bc 0x1dc1a7d24 0x1dc19e600 0x1dc32122c 0x1dc321258 0x1aaaed5e8 0x1acfd6460 0x1acfdac90 0x1aaad989c 0x1a9f891c4 0x1a9f86b7c 0x1a9f8b0cc 0x1aaae0080 0x1a9f8b000 0x1aa0817b0 0x1aa07e160 0x1aaadfe50 0x1aaab4e18 0x1aaab3cc4 0x1aaab1408 0x1aaae179c 0x1aaae1d28 0x1aaaacc88 0x1aaae22ec 0x1aaaac8a8 0x1aaaac344 0x1aa07a790 0x1aa0823d0 0x1aa18ea58 0x1aa082360 0x1aaadfd38 0x1aa0821c8 0x1a9f7a648 0x1aa66c3c4 0x1aa65bfec 0x1aa68bdc0 0x1a65d5c38 0x1a65d0b24 0x1a65d10f0 0x1a65d08ac 0x1b042b328 0x1aa662f00 0x104f716d0 0x1a645b460)
libc++abi.dylib: terminating with uncaught exception of type NSException

My view that contains the Toggle:
struct NoteInfo: View {

  @Binding var note: Note

  var body: some View {
    NavigationView {
      Form {
        Section {
          Toggle(isOn: $note.pinned) {
            Text("Pinned")
          }
        }
      }
    }
  }

}

Automatically generated Note code:
@objc(Note)
public class Note: NSManagedObject {

}

extension Note {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    @NSManaged public var modifiedAt: Date?
    @NSManaged public var pinned: Bool
    @NSManaged public var trashed: Bool
    @NSManaged public var unsecuredContent: String?

}

A: This works for me:
import SwiftUI

struct TaskRow: View {

    var task: Task

    // States of the Task
    @Binding var isCompleted: Bool

    var body: some View {
        HStack {
            // Toggle
            Toggle(isOn: $isCompleted) {
                EmptyView()
            }
            // And so on...
        }
    }
}

import CoreData
import SwiftUI

struct TableView: View {

    @EnvironmentObject var model: TasksViewModel

    var body: some View {
        List {
            ForEach(model.items) { task in
                TaskRow(task: task,
                isCompleted: model.toggleCompletion(of: task))
            }
        }
    }
}

import Combine
import CoreData
import SwiftUI

class TasksViewModel: NSObject, ObservableObject {

    func toggleCompletion(of task: Task) -> Binding<Bool> {

        let binding = Binding<Bool>(get: { () -> Bool in
            return task.completedAt != nil

        }) { (newValue) in
            // This func updates the database
            toggleCompletion(of: task, isCompleted: newValue)
        }
        return binding
    }
}

Article on Medium - https://medium.com/@voevodin/swiftui-list-with-toggle-coredata-5eb6f52a390a

A: My bad, it turns out that somehow the pinned field of my Core Data model got deleted, but the generated code was out of sync with that, so this wasn't an issue with SwiftUI.


text:
Q: How to start Alarm when device is rebooted? I have this Alarm and I am trying to make a BroadcastReceiver for recreating the alarms when the device is rebooted. The problem is I don't know what to put in the BroadcastReceiver.
This is the BroadcastReceiver for recreating the alarms when the device is rebooted
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;

 public class AlarmSetter extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    //I don't know what to put here
    // Do your work related to alarm manager
}

}

This are the other classes
AlarmActivity Class
 import android.app.Activity;
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.view.Window;
 import android.view.WindowManager;
 import android.widget.TextView;
 import android.widget.TimePicker;
 import android.widget.ToggleButton;
 import java.util.Calendar;
 import java.util.concurrent.TimeUnit;

 public class AlarmActivity extends Activity {

AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;

public static AlarmActivity instance() {
    return inst;
}

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm);

    alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
    alarmTextView = (TextView) findViewById(R.id.alarmText);
    ToggleButton alarmToggle = (ToggleButton)   findViewById(R.id.alarmToggle);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}

public void onToggleClicked(View view) {
    if (((ToggleButton) view).isChecked()) {
        Log.d("MyActivity", "Alarm On");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
        calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        long time = calendar.getTimeInMillis();
        if(time < System.currentTimeMillis()) calendar.setTimeInMillis(time + TimeUnit.DAYS.toMillis(1));
        Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

    } else  {
        alarmManager.cancel(pendingIntent);
        setAlarmText("");
        Log.d("MyActivity", "Alarm Off");
    }
}

public void setAlarmText(String alarmText) {
    alarmTextView.setText(alarmText);
}
}

AlarmReceiver Class
  import android.app.Activity;
  import android.content.ComponentName;
  import android.content.Context;
  import android.content.Intent;
  import android.media.MediaPlayer;
  import android.media.RingtoneManager;
  import android.net.Uri;
  import android.support.v4.content.WakefulBroadcastReceiver;
  import android.view.WindowManager;

 public class AlarmReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
    //this will update the UI with message
    AlarmActivity inst = AlarmActivity.instance();
    inst.setAlarmText("Alarm! Wake up! Wake up!");

    //this will sound the alarm tone
    //this will sound the alarm once, if you wish to
    //raise alarm in loop continuously then use MediaPlayer and setLooping(true)
    Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alarmUri == null) {
        alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    }

    //this will send a notification message
    ComponentName comp = new ComponentName(context.getPackageName(),
            AlarmService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);

   intent.setClass( AlarmActivity.instance(), WelcomePage.class);

   AlarmActivity.instance().startActivity(intent);

}
}

AlarmService Class
 import android.app.IntentService;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.Intent;
 import android.support.v4.app.NotificationCompat;
 import android.util.Log;

public class AlarmService extends IntentService {

private NotificationManager alarmNotificationManager;

public AlarmService() {
    super("AlarmService");
}

@Override
public void onHandleIntent(Intent intent) {
    sendNotification("Wake Up! Wake Up!");
}

private void sendNotification(String msg) {
    Log.d("AlarmService", "Preparing to send notification...: " + msg);
    alarmNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AlarmActivity.class), 0);

    NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
            this).setContentTitle("Alarm").setSmallIcon(R.drawable.icon)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    alamNotificationBuilder.setContentIntent(contentIntent);
    alarmNotificationManager.notify(1, alamNotificationBuilder.build());
    Log.d("AlarmService", "Notification sent.");
}
}

I already inserted this permission in AndroidManifest.xml
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />


text:
Q: C : freeing a reallocated pointer I found out today that when I try to free a pointer that has been reallocated the program crashes and prints "Segmentation Fault".
A realloc() is called on this pointer (array) in order to sizeup the array and merge the old array and another one.
Further in the program I must free it, how can I bypass this problem without having to make some sort of buffer array, adding the 2 other arrays to it and then to free them?

*

*PARTICLE: structure

*newCount: sum of the size of the old array + array that is being added

Code:
group1->particleList =
         (PARTICLE *) realloc(group1->particleList, newCount * sizeof(PARTICLE));

A: There should be no problem freeing a reallocated pointer.  A program called valgrind can give you some valuable information about what is going on in your code.

A: Did you include "stdlib.h" ?
Casting the return of realloc and friends can hide the problem of having no prototype for it. Older compilers then take it to return an int, cast that int to a pointer type and the damage is done.
The problem that realloc would return 0 as others mention, shouldn't result in a fault when you free the buffer, but much earlier.

A: First, make sure you assign the result of realloc to a temporary variable; if the request fails, realloc will return NULL, and you'll lose your handle on the memory you've already allocated:
PARTICLE *tmp = realloc(group1->particleList, ...); // cast is unnecessary
if (tmp)
  group1->particlelist = tmp;
else
  /* handle realloc failure */

Make sure you aren't accidentally overwriting group1->particleList (possibly in your merge code?) before the free call.  Even if it was getting overwritten with NULL in the event of a failed realloc call, free should be able to handle a NULL argument (basically, it'd be a no-op).


text:
Q: how to pass data from table row in PHP to another page on click the table row SEE TABLE
table shows final output. So i want the user to be able to click on the BlockName field and on click the data at BlockName should be sent to another page.

                     	 -->
                    title
                    initials
                    surname
                    phone
                    email
                    office
                    BlockName
                    department
                    photo

                ";
                 $index = 0;

               $querynum ="SELECT csi315_dir_staff.title,csi315_dir_staff.initials,csi315_dir_staff.surname,csi315_dir_staff.phone,csi315_dir_staff.BlockName,csi315_dir_staff.email,csi315_dir_staff.office,csi315_dir_departments.department_name, csi315_dir_staff.photo FROM csi315_dir_staff, csi315_dir_departments WHERE csi315_dir_staff.department_id=csi315_dir_departments.department_id AND $search_query";
               $resultnum = mysqli_query($db_link,$querynum);

              $num_members = mysqli_num_rows($resultnum);
             // echo "search for  $search_name :" ;
              echo " $num_members staff  found. ";

                while ($row = mysqli_fetch_assoc($result)){
                $image="";
                if(file_exists("profile_pics/".$row['photo']))
                {
                    $image="profile_pics/".$row['photo'];
                }
                else{
                    $image="profile_pics/default.jpg";
                }

                 echo "
",
                "{$row['title']} 	",
                "{$row['initials']}	",
                "{$row['surname']}	",
                "{$row['phone']}	",
                "{$row['email']}	",
                "{$row['office']}	",
                "{$row['department_name']}	",
                " 	",
                "
";

            }
            echo "

";

            // render the pagination links
            $pagination->render();`

A: You can send the data as query parameters.


text:
Q: SSRS Function with Regex Match In a report I'm trying to filter rows where a values does not match the pattern of ten digits and zero or more hyphens.
As I need the data in other tables, I thought the best way is to use the tablix filter. In the expression match the field with a regex: ^([\d]{10})-*$ and set it to equal false.
I'm trying this expression:
=System.Text.RegularExpressions.Regex.IsMatch(Fields!Number.Value, "^([\d]{10})-*$")

However, it returns the error that the filter failed to evaluate.
Any ideas how to fix it?
Alternatively I can take the left 10 characters and test if they are an integer, but then I can't think of a simple clean way for testing for the hyphens, and prefer the regex.

A: The expression works fine after a reboot:
=System.Text.RegularExpressions.Regex.IsMatch(Fields!Number.Value, "^([\d]{10})-*$")


text:
Q: Angular 2 Error: (SystemJS) Can't resolve all parameters for Component Service: (?) I tried to call the web API from my Angular2 Component service in Visual Studio, but continuously I am getting the error like "(SystemJS) Can't resolve all parameters for anniversary service: (?)".
My sample application is working fine if I remove my component service.
ComponentService:
       import { Injectable } from '@angular/core';
       import {Http, Response } from '@angular/http';
       import { IData } from '../Common/details';
       import { Observable } from 'rxjs/Observable';
       import 'rxjs/add/operator/map';

       export class AniversaryService {
         constructor(private _http:Http) { }
         getImages(): Observable<IData[]> {
                return this._http.get("/api/ImageService/Details")
                .map((response: Response) => <IData[]>response.json()
                };
        }

and my Corresponding Component:
        import { Component, OnInit } from '@angular/core';
        import { DomSanitizer } from '@angular/platform-browser';
        import { IData } from '../Common/details';
        import { AniversaryService } from './Aniversary.service';

        @Component({
        selector: 'my-AniversaryComponent',
        providers: [AniversaryService]
        })

        export class AniversaryComponent implements OnInit {
           data: IData[];
           constructor(private _aniversaryservice: AniversaryService) { }
           ngOnInit() {
           this._aniversaryservice.getImages().subscribe((details) => this.data
           =details);
           }
         }

        }

I tried different solutions from stack overflow but nothing works for me.
Please help me to overcome this problem.
Thanks in Advance for the help

A: The service appears to be missing the @Injectable decorator.


text:
Q: Application Error when I deploy to heroku I'm trying to deploy my node js app on Heroku but I keep on gettin an application Error when I open the page :

So I decided to go into logs to see what was happening :

It says something about module.js 471 ,I don't exactly know where I'm going wrong ,can you please tell if you know .


text:
Q: Упаковать python Есть входной main.py скрипт, который использует разные модулей, нужно чтобы в главный скрипт подтянулись все зависимости.
Естественно, если я использую requests.get, нужно подтянуть в main.py requests.get и все, от чего он зависит.

В итоге должен получится некий joined_main.py, не зависящий от других модулей.

Я задавал вопрос на Habr Q&A, и не получил разумного ответа. Может быть здесь есть кто-то кто может помочь.

Мне не подходят pyinstaller / nsis / py2exe и другие.
.pyc, .pyi, .egg, и другие такие штуки лучше не учитывать.
Мне интересно есть ли что-то уже готовое, а если нет - то как это можно реализовать.

A: В общем случае вы не сможете собрать все зависимости в один файл с кодом на Python.
Банально потому, что зависимости могут быть написаны не на Python. Это также может быть:

*

*Байт-код самого языка (файлы с расширением .pyc)

*Файлы, содержащие типизацию (.pyi)

*Пакеты, написанные на C/C++ и вызывающие Python C API

*Динамические библиотеки

В итоге всё сводится к тому, что вам нужно некоторое окружение. А в этом окружении должен быть установлен интерпретатор, который сможет обработать зависимости. Именно это вам и предлагают pyinstaller / nsis / py2exe.


text:
Q: Failure to discover property with reflection Taking the following minimal example:
type IMyInterface =
    interface
        abstract member Name: string with get
    end

let testInstance =
    { new IMyInterface with
        member _.Name = "Hello Word" }

I would have naively expected a call to testInstance.GetType().GetProperties() to contain a PropertyInfo element corresponding to Name.
However, only an empty array is returned.
Using testInstance.GetType().GetProperty("Name") yields no better as it simply returns a <null> object.
More confusing still, Visual Studio 2022 IntelliSense lists Name as a valid property (as I'd expect).
How can I get a PropertyInfo corresponding to the Name property?

A: In F# all interface implementations are private. This means that interface methods and properties do not appear as methods and properties of the implementing class.
In C# this works a bit differently: if you define a public member that happens to match an interface member, you don't have to explicitly tell the compiler that it's meant to be the interface implementation, the compiler will map it to the interface automatically for you.
So, for example, if you write this:
class MyClass : IMyInterface {
  public string Name { get; }
}

The C# compiler will actually compile it as this:
class MyClass : IMyInterface {
  public string Name { get; }
  string IMyInterface.Name { get { return this.Name; } }
}

(well, it's not exactly like that, but you get the idea)
But the F# compiler doesn't do that. If you want a class property in addition to the interface property, you have to roll one yourself:
type MyClass() =
  member __.Name = "Hello Word"
  interface IMyInterface with
    member this.Name = this.Name

But if you just want the interface property, you can get it off of the interface type:
let nameProp = typeof<IMyInterface>.GetProperty("Name")
let helloWorld = nameProp.GetValue testInstance

Or, if you don't know the interface type in advance, you can get it from the object type as well:
let intf = testInstance.GetType().GetInterfaces().[0]
let nameProp = intf.GetProperty("Name")
let helloWorld = nameProp.GetValue testInstance


text:
Q: How do I change the color of a selected label in Ionic? I want to change the color of the selected label. I'm using --color-selected in CSS, but it doesn't work.
Html
  <ng-container *ngFor="let item of daily">
        <ion-label id="daysName" class="favorites-label" (click)="dayName($event)">{{item.day}}</ion-label>
      </ng-container>

TS
 dayName($event) {
    console.log('dayName', $event.target.innerHTML)
}

CSS
   #daysName {
        color: white;
        --color-selected: red;
    }
    ion-label.favorites-label {
        --color-selected: red;
    }

A: You can use ngClass:
[ngClass]="{'favorites-label': step === 'step1'}"

Or
[class.favorites-labels] = "step === 'step1'"


text:
Q: My emulator wont work and I keep getting these error messages I have tried searching the forum for answers but cannot find anything to resolve my problem. These are the error messages I am getting when running my app in the emulator.
    WARNING: userdata image already in use, changes will not persist!
WARNING: cache image already in use, changes will not persist!
WARNING: SD Card image already in use: /Users/glenmcmurchy/.android/avd/Nexus_5_API_22_x86.avd/sdcard.img
emulator: The memory needed by this AVD exceeds the max specified in your HAXM configuration.
HAX is not working and emulator runs in emulation mode
emulator: AVD      RAM size = 1536 MB emulator: HAXM max RAM size = 512 MB emulator: You might want to adjust your AVD RAM size and/or HAXM configuration to run in fast virt mode. emulator:
emulator window was out of view and was recentered

I got told to delete my emulator and reinstall it, would that work? however I cannot figure out how to delete/uninstall it :/
I have also tried increasing the memory but that doesnt seem to work either, either that or I have not done it properly.


text:
Q: AWT window listener doesn't respond I'm studying AWT and swing, and I'm beginning with some simple GUIs to get the hang of it.I wrote the following code,which works fine until I try to close the application and it won't exit.
import java.awt.*;
import java.awt.event.*;

public class AWTCounter extends Frame{
    private Button button;
    private Label label;
    private TextField txt;
    private int count=0;
    public AWTCounter(){
        super("AWT Counter");
        addWindowListener(new WindowListener(){

            @Override
            public void windowActivated(WindowEvent arg0) {}

            @Override
            public void windowClosed(WindowEvent arg0) {
                System.out.println("closing time!");
                System.exit(0);
            }

            @Override
            public void windowClosing(WindowEvent arg0) {}

            @Override
            public void windowDeactivated(WindowEvent arg0) {}

            @Override
            public void windowDeiconified(WindowEvent arg0) {}

            @Override
            public void windowIconified(WindowEvent arg0) {}

            @Override
            public void windowOpened(WindowEvent arg0) {}

        });
        label = new Label();
        add(label);
        label.setText("Counter");
        txt = new TextField();
        txt.setEditable(false);
        add(txt);
        button = new Button("count");
        add(button);
        setSize(400,100);
        setLayout(new FlowLayout());
        setVisible(true);
        button.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                ++count;
                txt.setText(Integer.toString(count));
            }
        });

    }
    public static void main(String [] args){
        Thread t =new Thread(new Runnable(){
            public void run(){
                new AWTCounter();
            }
        });
        t.start();
    }
}

I "registered" the WindowListener in the source component (the AWTCounter in this case, which is a Frame) and implemented the only method I was going to use, but it never respond... any idea as to why it behaves like that?
thanks a lot guys!

A: See the API for Frame - for the WINDOW_CLOSING event: "If the program doesn't explicitly hide or dispose the window while processing this event, the window close operation is canceled." - if you move your logic into the windowClosing method the application should exit. A Swing JFrame is a bit more friendly (you can set the default closing behavior to exit on close if you wish to exit the application upon closing the JFrame without the need for the WindowListener).
Last but not least, I'd recommend creating your GUI on the EventDispatchThread. For instance:
public static void main(String [] args) throws Exception{
    Runnable t = new Runnable(){
        public void run(){
            new AWTCounter();
        }
    };
    SwingUtilities.invokeAndWait(t);
}

A: Try doing this:
@Override
public void windowClosing(WindowEvent event) {
    System.exit(0);
}


text:
Q: mongodb failed to launch with mup setup (Cannot connect to the Docker daemon) First i installed UBUNTU 14.04 64bit/32bit (Tried it too with UBUNTU 16.04 64bit).
When i launch mup setup, i get this error message:
----------------------------------
Started TaskList: Setup Docker
[xx.xx.xx.xx] - Setup Docker
[xx.xx.xx.xx] - Setup Docker: SUCCESS

Started TaskList: Setup Meteor
[xx.xx.xx.xx] - Setup Environment
[xx.xx.xx.xx] - Setup Environment: SUCCESS

Started TaskList: Setup Mongo
[xx.xx.xx.xx] - Setup Environment
[xx.xx.xx.xx] - Setup Environment: SUCCESS
[xx.xx.xx.xx] - Copying mongodb.conf
[xx.xx.xx.xx - Copying mongodb.conf: SUCCESS

Started TaskList: Start Mongo
[xx.xx.xx.xx] - Start Mongo
[xx.xx.xx.xx] x Start Mongo: FAILED

        -----------------------------------STDERR-----------------------------------
        Warning: failed to get default registry endpoint from daemon (Cannot connect to the Docker daemon at unix:///var
/run/docker.sock. Is the docker daemon running?). Using system default: https://index.docker.io/v1/
        Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
        -----------------------------------STDOUT-----------------------------------
        ----------------------------------------------------------------------------

I created a username inside the VPS and granted it in order to work without sudo, i tried too with root access but all time the same error.
And launched this command before everything inside the VPS: apt-get update
Here is my MUP version: 1.3.7 (Under Windows 7 64bit)
And here mup.js file:
module.exports = {
 servers: {
  one: {
      host: 'xx.xx.xx.xx',
      username: 'myusername',
      password: 'password',
  }
 },
 meteor: {
  name: 'myApp',
  path: '../myApp',
  servers: {
   one: {}
  },
  buildOptions: {
   serverOnly: true
  },
  env: {
   ROOT_URL: 'https://m.domain.com',
   MONGO_URL: 'mongodb://localhost/meteor'
  },
  docker:{
   image: 'abernix/meteord:base'
  },
  deployCheckWaitTime: 96,
  enableUploadProgressBar: false
 },
 mongo: {
  oplog: true,
  port: 27017,
  version: '3.4.1',
  servers: {
   one: {}
  }
 }
};

When i try to restart docker from VPS, here the error message:
Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.

Here the error inside the logs:
Your Linux kernel version 2.6.32-042stab127.2 is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.

A: It's seem to me that you misconfigured the
env: {
   ROOT_URL: 'https://m.domain.com',
   MONGO_URL: 'mongodb://localhost/meteor'
},

mup create a mongo container and the database is named using the name of your app
 env: {
       ROOT_URL: 'https://m.domain.com',
       MONGO_URL: 'mongodb://localhost/myapp'
 },

And it should work


text:
Q: "runtime 1004: application-defined or object-type defined error" on calculating average of cells I am trying to calculate the average of cells in col b.
The average is calculated by determining the last row with data. e.g. if first row in col B with data is B6 and the last row is B24, then the average is b6:b24 or if last row with data is B8 then average should be for b6:b8.
Sub average()
'
' average Macro
'

'
Range("B6").Select

lr = Selection.End(xlDown).Row
fr = lr + 1
r = 6
last = -fr + r

Range("B" & fr & "").Select
activecell.formulaR1C1 = "=AVERAGE(R[last]C:R[-1]C)"

End Sub

When I run the code, it gives me the error 1004.
I also tried with
activecell.formula = "=AVERAGE(R[last]C:R[-1]C)"

A: If you only have either text or data in column B, why not just average the whole column:
Application.Worksheetfunction.Average(Activesheet.Range("B:B"))


text:
Q: A Collection of Bogus Proofs Hello M.S.E. people,
This question is just for fun, don't take it seriously :). We have all encountered Bogus Proofs, which seem logical and reasonable, but they prove some claims which are completely wrong and unreasonable. Lets collect a list of very convincing, yet Bogus Proofs. Let me show one down below;

I understand this isn't really a 'question', but its just a fun post to make M.S.E. more interesting and fun.

A: Here's a classic one;
\begin{align*}
\frac{\text{d}}{\text{d}x}\left(x^2\right)
&=\frac{\text{d}}{\text{d}x}\left(\underbrace{x+x+\cdots+x}_{x\text{ times}}\right)\\
&=\underbrace{\frac{\text{d}}{\text{d}x}\left(x\right)+\frac{\text{d}}{\text{d}x}\left(x\right)+\cdots+\frac{\text{d}}{\text{d}x}\left(x\right)}_{x\text{ times}}\\
&=\underbrace{1+1+\cdots+1}_{x\text{ times}}\\
&=x.
\end{align*}
But since $\frac{\text{d}}{\text{d}x}\left(x^2\right)=2x,$ we have;
\begin{align*}
2x &=x\\
\implies 2 &=1.
\end{align*}


text:
Q: Asymptotes Problem In photography, Focal length of a lens, $F$, is linked to the distance from the object ($x$) and the distance to the image ($y$) by the equation:  $$\frac 1F = \frac 1x+\frac 1y$$
See, for example, Focal Length
Given that $F=65$, Why would it be the case that both horizontal and vertical asymptote would be at $65$?

A: Note that the basic equation can be rewritten as $$x=\frac {Fy}{y-F}\quad \text {or}\quad y=\frac {Fx}{x-F}$$
Writing it this way makes it clear that letting $x$ or $y$ approach $F$ will cause the other to go to $\pm \infty$, which I believe is what you are asking.


text:
Q: How to configure scons to link using rpath on mac? It works on Ubuntu to link my task using RPATH, but on mac, it doesn't work
env.Program(source = Glob("*.cpp") + Glob("../*.cpp"),
            LIBS = [
                "l_util",
                "boost_system",
                "boost_timer",
            ],
            LIBPATH = libPath,
            RPATH = libPath,
            CPPPATH = includePath)

On Ubuntu, using ldd, I can see shared libs are linked with absolute path. But using otool -L on mac gives me relative path to top dir of my Sconstruct file. Anyone setup RPATH correctly on mac using scons?


text:
Q: what is MSVC -L equivalent? I'm trying to compile a library with a UNIX makefile, but using Visual Studio 2010. I modified the makefile so it should work, but I have trouble with the linker.
My compiler options are simple :
CSWITCHES = -O2 -I$(INC_DIR) -L$(LIB_DIR)

(with INC_DIR and LIB_DIR pointing to VC's include and lib directories).
I don't have include problems so I assume -I is ok, but the -L option is ignored by the compiler :
ignoring unknown option -Lblahblah

I have checked msdn site http://msdn.microsoft.com/en-us/library/y0zzbyt4(v=vs.80).aspx linker options, I tried to use the LIBPATH option, but I doesn't work either.
so here is my question : what is the msvc command line option to specify a library directory path to the linker ?

A: Duplicated.
You should provide /LIBPATH as a linker option, after the "/link". Assure you have cl.exe in the system path. This is my bat file for compilation:
call "D:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86

cl %CompilerFlags% ..\src\main.cpp /I %IncludePaths% /link %LinkerFlags% /LIBPATH:%LibraryPaths%

A: MSVC has no equivalent of -L option, paths are provided directly to LINK. As for standard library search path, it is set correctly by vcvar32.bat (see this MSDN article)


text:
Q: cannot read/ get file when try to upload using java struts action i'm trying to upload excel file below my code:
im using bootstrap, blueimp plugin and struts action.
this is the request:
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="fileName"
SMSMassploadOladDate.xls
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="fileInput"; filename=""
Content-Type: application/octet-stream
------WebKitFormBoundary5peQFGFm3lEKCOB5
Content-Disposition: form-data; name="sub"
------WebKitFormBoundary5peQFGFm3lEKCOB5--
the file is being set null in java action
i was trying to get file using httpServletReques:
public String uploadMassContentsFromExcelSheetNew() {
    HSSFSheet sheet = null;
    HSSFWorkbook workbook = null;
    FileInputStream inputStream = null;
    result=new JSONObject();

    try {
            if (fileName != null){
            fileName=fileName.trim();

        if  (fileName.endsWith(".xls") || fileName.endsWith(".xlsx") )  {
            String  filePath = servletRequest.getSession().getServletContext().getRealPath("/");
            servletRequest.getSession().getServletContext();
            HttpServletRequest request = ServletActionContext.getRequest();
            System.out.println("Parts*******:"+request.getParts()); //return null

            Part filePart =request.getPart("fileInput");//return null
            MultiPartRequestWrapper multiWrapper=(MultiPartRequestWrapper)ServletActionContext.getRequest();
            File[] f=multiWrapper.getFiles("fileInput"); //return null
            String fileName=multiWrapper.getFileNames("fileInput")[0];
            Enumeration fileParameterNames = multiWrapper.getParameterNames();
            String param = request.getParameter("fileInput");
        }
            }
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
}

jsp code:

<form name="massUploadForm" id="fileupload" action="uploadMassContentsFromExcelSheetNew.action" method="post" enctype="multipart/form-data" onsubmit="doMassValidate();">
                                          <input type="hidden" id="fileName" name="fileName" value=""/>

                                            addFile
                                            <input type="file"  name="fileInput" id="fileInput"  accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">

                                                        <button  name="sub" type="submit" ></button>
                                                        </form>


text:
Q: Calling asynctask from GCMBaseIntentService? Hello I have this code in my GCMIntenBaseIntenService
 @Override
    protected void onMessage(Context context, Intent intent) {

        AsyncTask taskDoStuff= new AsyncTask (context);
        taskDoStuff.execute();

    }

my AsyncTask is looking like:
public class AsyncTask extends AsyncTask<String,String,String> {

Context mContext;

    public AsyncTask(Context mContext) {
    this.mContext = mContext;

}

when I call my asynctask from my main ACTIVITY directly it works - AsyncTask runs and does its job...
But when I try to call asynctask from GCMBaseIntentService it does not does it job - surely because of wrong context...
How can I solve that?
used: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ as basic
EDIT:
I did some change, now it works in the background , but app crashes:
In my MainActivity i set
public static Context getAppContext() {
        return MainActivity.mContext;
    }

in onCreate:
MainActivity.mContext = MainActivity.this;

in gcm onMessag()
AsyncTask taskDoStuff = new AsyncTask(MainActivity.getAppContext());
        taskDoStuff.execute();

A: GCMBaseIntentService extends IntentService which per the documentation:

the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Which means that as soon as onMessage completes, the service is killed.
As onMessage() is already on a worker thread, you can do your background work directly in onMessage() rather than needing an AsyncTask at all.
If you really, really need to reuse an AsyncTask, you can use taskDoStuff.get() instead of taskDoStuff.execute() to retrieve the results using the current thread.


text:
Q: Change my custom logo 'home destination' in Wordpress header.php question here. I have a custom logo being used on a specific set of listings pages https://carolroyseteam.com/our-nice-home/ , I've assigned it using a body class assignment to swap the header $logo in the header.php. Then the rest of the site with the branding of the domain https://carolroyseteam.com/. Is there anything that can be done to assign a different url to the two $logo's?
To clarify my custom logo for Our Nice homes logo goes to '/our-nice-home/' and then have standard domain home logo link to the default logo cotainer ">
Using Divi Theme

<?php ob_start(); ?>
  <header id="main-header" data-height-onload="<?php echo esc_attr( et_get_option( 'menu_height', '66' ) ); ?>">

   <?php
    $logo = ( $user_logo = et_get_option( 'divi_logo' ) ) && ! empty( $user_logo )
     ? $user_logo
     : $template_directory_uri . '/images/logo.png';

    ob_start();
   ?>
   <?php
    $classes = get_body_class();
if (in_array('ournicehomeslogo',$classes)) {
$logo="/wp-content/uploads/2019/10/1-ONH-Logo-05-carolroyseteam.png";}
    ?>

    <?php
    $classes = get_body_class();
if (in_array('single-listing',$classes)) {
$logo="/wp-content/uploads/2019/10/1-ONH-Logo-05-carolroyseteam.png";}
    ?>
    <?php
    $classes = get_body_class();
if (in_array('search-results',$classes)) {
$logo="/wp-content/uploads/2019/10/1-ONH-Logo-05-carolroyseteam.png";}
    ?>

      <img src="<?php echo esc_attr( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo" data-height-percentage="<?php echo esc_attr( et_get_option( 'logo_height', '54' ) ); ?>" />

   <?php
    $logo_container = ob_get_clean();

A: Got it! Wordpress Divi Theme users will appreciate that this logo_container is a default in the header.php file. This has been the easiest way to both custom logo a specific page or pages and then modify the home url.

     <a href="<?php $classes = get_body_class();
          if (in_array('ournicehomeslogo',$classes)) {
echo esc_url( home_url( '/our-nice-homes/' ) );}

else if (in_array('single-listing',$classes)) {
echo esc_url( home_url( '/our-nice-homes/' ) );}

else if (in_array('search-results',$classes)) {
echo esc_url( home_url( '/our-nice-homes/' ) );}

else{
 echo esc_url( home_url( '/' ) );
} ?>">
      <img src="<?php echo esc_attr( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo" data-height-percentage="<?php echo esc_attr( et_get_option( 'logo_height', '54' ) ); ?>" />

   <?php

    $logo_container = ob_get_clean();


text:
Q: Parsing JSON with Python to retrieve values within a dictionary I am trying to parse JSON and retrieve a certain value (ID) but I am getting the following error:
TypeError: string indices must be integers

The following is my code and JSON:
import json

# JSON string
info_symbol = '{"status":{"timestamp":"2023-01-21T15:18:43.937Z","error_code":0,"error_message":null,"elapsed":21,"credit_count":1,"notice":null},"data":{"BITCOIN":{"id":15907,"name":"HarryPotterObamaSonic10Inu","symbol":"BITCOIN"}}}'

# Convert string to Python dict
test_dict = json.loads(info_symbol)

print(test_dict['data'])
for name in test_dict['data']['BITCOIN']:
    print(name['id'])

Id like to grab solely the ID - so: 15907
"id":15907,

A: You don't need the looping in that case to get only the id. If you need all the key and values from the dictionary then you can iterate like below-
import json

# JSON string
info_symbol = '{
  "status": {
    "timestamp": "2023-01-21T15:18:43.937Z",
    "error_code": 0,
    "error_message": null,
    "elapsed": 21,
    "credit_count": 1,
    "notice": null
  },
  "data": {
    "BITCOIN": {
      "id": 15907,
      "name": "HarryPotterObamaSonic10Inu",
      "symbol": "BITCOIN"
    }
  }
}'

# Convert string to Python dict
test_dict = json.loads(info_symbol)

data = test_dict['data']['BITCOIN']
print(f"only id = {data['id']}")
print("--------")
for key, value in test_dict['data']['BITCOIN'].items():
    print(key, value)

Output
only id = 15907
--------
id 15907
name HarryPotterObamaSonic10Inu
symbol BITCOIN

A: for name in test_dict['data']['BITCOIN']:
    print(name)

output
{'BITCOIN': {'id': 15907, 'name': 'HarryPotterObamaSonic10Inu', 'symbol': 'BITCOIN'}}
id
name
symbol

So, if you do name['id'], you will get id in first iteration and in second iteration it will throw error
you can get value of id by:
for key, value in test_dict['data']['BITCOIN'].items():
    if key=='id':
      print(value)
#15907

with comprehension:
[value for key, value in test_dict['data']['BITCOIN'].items() if key=='id']
[15907]

A: Keys Error
Fellow, test_dict['data]['BITCOIN'] is represented as:
{
'id': 15907,
'name': 'HarryPotterObamaSonic10Inu',
'symbol': 'BITCOIN'
}

Your are iterating the above dictionary, so when you print(name[id]), name iterator take the key:Value of id, name, and symbol.
Literally tour code is accesing as id.['id'], name.['id'], symbol.['id]'.
SOLUTION
just access to the id adding one more bracket:
print( test_dict['data']['BITCOIN']['id'] )

get rid of for loop.


text:
Q: unable to create a new user in firebase using android studio I don't have any errors and i have copied the code from the documentation and other tutorials but i am not sure why the registration is failing. everything works till i hit the button and it just shows that the registration failed,

*

*I placed my permissions in the manifest file

*I enabled the email/password authentication in the firebase console

*I registerd it exactly how it is supposed to be done

I wanted to register and check the users in the firebase console
package com.example.auth;

import static androidx.constraintlayout.widget.StateSet.TAG;

import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {
EditText email,password,confirmpasswordreg;
Button register;
TextView alreadylogin;
FirebaseAuth mauth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        email=findViewById(R.id.editTextTextEmailAddressreg);
        password=findViewById(R.id.passwordregister);
        alreadylogin=findViewById(R.id.textView4reg);
        register=findViewById(R.id.buttonreg);
        confirmpasswordreg=findViewById(R.id.cnfmpassreg);
        mauth=FirebaseAuth.getInstance();

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username=email.getText().toString();
                String passwords=password.getText().toString();
                String confirmpassword=confirmpasswordreg.getText().toString();

                    mauth.createUserWithEmailAndPassword(username,passwords)
                            .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (task.isSuccessful()) {
                                        // Sign in success, update UI with the signed-in user's information
                                        Log.d(TAG, "createUserWithEmail:success");
                                        FirebaseUser user = mauth.getCurrentUser();
                                        Toast.makeText(MainActivity.this, "sign up success", Toast.LENGTH_SHORT).show();
                                    } else {
                                        // If sign in fails, display a message to the user.
                                        Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                        Toast.makeText(MainActivity.this, "sign up failed", Toast.LENGTH_SHORT).show();

                                    }

                            });
                }
            }
        });

    }
}

I just wanted to the emails and the passwords on firebase


text:
Q: Eclipse code setup build error Eclipse: Neon/Luna SR2/Luna R
Set
JAVA_HOME=$(/usr/libexec/java_home)
M2_Home=ECLIPSE FOLDER PATH
M2=$M2_HOME/bin
Added all other such configuration: Still facing issues.
Activities performed:
1. Import GIT project (Clone URL)
2. Import MAVEN Project
3. Eclipse point to Java JDK installed
4. Run Configuration (clean install)
5. Apply --> Okay --> Generates Errors as below
Any insight here will be appreciated
Error: -- [INFO] BUILD FAILURE [INFO] Total time: 1.420 s [INFO] Finished at: 2017-06-05T19:19:54+05:30 [INFO] Final Memory: 17M/309M [INFO] [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.5.1:compile (default-compile) on project mail-client: Compilation failure [ERROR] Failure executing javac, but could not parse the error: [ERROR] /bin/sh: /bin/javac: No such file or directory [ERROR] -> [Help 1]


text:
Q: I Don't Understand This Array Syntax I don't understand this array accessing syntax:
$target[$segs[count($segs)]]

Is it really possible to use variables as multidimensional array keys?

A: That might result in an error, if $segs is a numerical array with continuous indices only.
 Meaning, it would fail for:
array("foo","bar");

but work for
array("foo", 2=>"bar");

Assuming now, that we deal with the first case, then this would work:
$target[$segs[count($segs) - 1]]

First, count($segs) - 1 will be evaluated and return a number. In this case the last index of $segs (provided it is a numerical array).
$segs[count($segs) - 1] will therefore return the last element in $segs. And whatever that value is, will be used as index for $target[...].

To sum up: It is nested array indexing and evaluated inside out.
See it in action.
Whether or not such a method is necessary depends on the problem you are trying to solve. If you don't know where you would use such nested, variable array indexing then you probably don't need it.

A: That syntax is fine, provided $segs is an array. It's worth noting, though, that if you're using a numerically indexed array for $segs, calling count($segs) is a non-existent key because indexing starts at zero.


text:
Q: Every $\mathbb{P}-$integrable function $u\in\mathcal{L}^1(\mathbb{P})$ is bounded (Counterexample) Let $(Ω,\mathcal{A},\mathbb{P})$ be a probability space. Find  a counterexample to the claim that every $\mathbb{P}-$integrable function $u\in\mathcal{L}^1(\mathbb{P})$  is bounded.

Countableexample
$(Ω,\mathcal{A},\mathbb{P}) = (\mathbb{R},\mathcal{B}(\mathbb{R}),\delta_n)$
$\delta_n$ is the Dirac measure in point $n\in\Bbb N$.
The function I have constructed is $u=\sum_{n=1}^\infty n \mathbb{1}_{A_n}$. $\mathbb{1}_{A_n}$ is the indicator function and $A_n=[-n,n]$. $u$ is unbounded, but have is it integrable?

A: On $\mathbb N$, consider the probability measure $\mathbb P$ defined by
$$\mathbb P(\{n\}) = p_n \propto \frac 1{n^3}.$$
The identity function $f:\mathbb N\to\mathbb R$ given by $f(n) = n$ is not bounded and
$$\int_{\mathbb N}|f|d\mathbb P \propto \sum_{n=1}^\infty \frac 1{n^2} < \infty.$$

Another counterexample could be the expectation of a random variable following a Poisson distribution.


text:
Q: href not working in greasemokey I have following code in my greasemonkey script. In case, i am unable to save my order to server, i display an error message and then a link (created using  to save it again. this link is save_order method again. But this is not working. I tried debugging into it but no luck. (I have basic understanding of JavaScript)
function save_order() {
    server_url = 'https://server.com/api/put_order?user_id=' + form.user.value +'&order_id=' + orderId;
    GM_xmlhttpRequest({
        method: "GET",
        url: server_url,
        onload: function(response){
            if(response.status == 200){
                localstorage.removeItem(orderId);
                messageBar.innerHTML += '
Order has been saved successfully.';
            } else {
                if (errorBar.style.display === 'none'){
                    errorBar.style.display = 'block';
                }
                errorBar.innerHTML += '
Error saving. Try Again';
            }
        }
    });
}

=======
FULL CODE
// ==UserScript==
// @name         SaveOrder
// @version      1.0
// @author       myname
// @include      https://xx*.xxxxxxxx.com*/*
// @run-at       document-end
// @grant        GM_xmlhttpRequest
// ==/UserScript==

var saveButton = document.getElementById('save-button');
saveButton.addEventListener("click", save_order,true);
var info_bar = document.getElementById('info_bar');
var error_bar = document.getElementById('error_bar');
var form = document.getElementById('place_order_form');
var order_id = form.order_id.value;

var localstorage = window.localStorage;

if (localstorage.getItem(order_id)){
    save_to_db();
}

function save_order(){
    localstorage.setItem(order_id, order_id);
}

function save_to_db() {
    var random_boolean = false;//Math.random() >= 0.5;

    console.log(random_boolean);

    server_url = 'https://xxx.xxxx.com/api/put_order?user_id=' + form.user.value +'&order_id=' + order_id;
    GM_xmlhttpRequest({
        method: "GET",
        url: server_url,
        onload: function(response){
            if(response.status == 200 && random_boolean){
                localstorage.removeItem(order_id);
                info_bar.innerHTML += '
Order saved successfully';
            } else {
                if (error_bar.style.display === 'none'){
                    error_bar.style.display = 'block';
                }
                error_bar.innerHTML += '
Error saving. Try Again';
            }
        }
    });
}

A: Your method works just fine, as you can see in this example.
You probably have an error elsewhere.

function test(){
  document.body.innerHTML += 'Test';
}
Test

EDIT : I did some digging, and found a way around your issue.
Instead of adding an onclick on your link, create an event handler in javascript attached to a save-to-db class like this :
document.addEventListener("click", function(e) {
    if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
        save_to_db();
    }
});

Now all you need to do is get rid of your onclick and replace it with class="save-to-db"
document.body.innerHTML += '
Error saving. Try Again';

It works like a charm now :

document.addEventListener("click", function(e) {
    if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
        save_to_db();
    }
});

save_to_db();

function save_to_db() {
    console.log('Function called');
    document.body.innerHTML += '
Error saving. Try Again';
}


text:
Q: Define macro with colon at the end i want something like
#define TEXT: "something "
int main(){

}

99% example "lala" is a new instance of a class

A: Macro names should only consist of alphanumeric characters and underscores, i.e. 'a-z', 'A-Z', '0-9', and '_', and the first character should not be a digit. Some preprocessors also permit the dollar sign character '$', but you shouldn't use it; unfortunately I can't quote the C standard since I don't have a copy of it.
From the GCC documentation:
Preprocessing tokens fall into five broad classes: identifiers, preprocessing numbers, string literals, punctuators, and other. An identifier is the same as an identifier in C: any sequence of letters, digits, or underscores, which begins with a letter or underscore. Keywords of C have no significance to the preprocessor; they are ordinary identifiers. You can define a macro whose name is a keyword, for instance. The only identifier which can be considered a preprocessing keyword is  defined. See Defined.
This is mostly true of other languages which use the C preprocessor. However, a few of the keywords of C++ are significant even in the preprocessor. See C++ Named Operators.
In the 1999 C standard, identifiers may contain letters which are not part of the "basic source character set", at the implementation's discretion (such as accented Latin letters, Greek letters, or Chinese ideograms). This may be done with an extended character set, or the '\u' and '\U' escape sequences. The implementation of this feature in GCC is experimental; such characters are only accepted in the  '\u' and '\U' forms and only if  -fextended-identifiers is used.
As an extension, GCC treats '$' as a letter. This is for compatibility with some systems, such as VMS, where '$' is commonly used in system-defined function and object names. '$' is not a letter in strictly conforming mode, or if you specify the -$ option. See Invocation.

A: Preprocessor identifiers can be any sequence of letters, digits, or underscores that start with a letter or underscore. In other words, you can't have one that ends with (or generally contains) a colon.

A: It is usually poor taste to define a macro ending with colon or semi-colon. Try instead
#define OUT(name) do {std::cout << name;} while(0)

See this explanation.
If it is some logging macro, consider instead
#define LOG(Out) do {std::cout << __FILE__ << ":" << __LINE__ << " " \
                     << Out << std::endl; } while(0)

and you could use it as: LOG("x=" << x << " and y=" << y);
BTW, you could ask your compiler to show you the result of the preprocessing. If using GCC you could compile your source code mysource.cc  with g++ -C -E -H mysource.cc > mysource.ii (perhaps add other relevant preprocessor options, like -Isomedir, before the -H) and look with an editor or a pager into the generated mysource.ii which contains the preprocessed form.


text:
Q: Producing two outputs from a Linker script There is a Quad-SPI NOR device on the STM32F746G-Discovery Board that I would like to use to store read only data.
So the ideal would be that the linker file produces an ELF file for the F746G flash and a hex file to program the NOR.
Then I could use the STM32 ST-LINK Utility to program the target and the External Loader to program the NOR.
Can anyone kindly point me to how this might be done?

A: How about you invoke the linker two times, one time for the ELF output and the other time for the HEX output and for each invocation feeding in only those compilation units / object files that shall go into the respective binary.


text:
Q: CefSharp AnyCPU Support (Option 4) I have a VB.NET project (WinForms) which uses the CefSharp libraries and I want to apply the AnyCPU support using the option 4 based on the guide mentioned here.
Based on the requirements,

*

*I'm not including the "CefSharpAnyCpuSupport" in the project file.

*My application has an "app.config"

*My copy of Visual Studio (2013) has the "Web Developer Tools" installed.

*My CefSharp version is greater than the needed v87.1.132

It is written that based on the above, the generated "app.config" on the "bin" folder will include the below section but in my case I'm not getting anything.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
        <assemblyIdentity name="CefSharp.Core.Runtime" processorArchitecture="x86" publicKeyToken="40c4b6fc221f4138" culture="neutral"/>
        <codeBase version="89.0.170.0" href="x86/CefSharp.Core.Runtime.dll"/>
    </dependentAssembly>
    <dependentAssembly>
        <assemblyIdentity name="CefSharp.Core.Runtime" processorArchitecture="amd64" publicKeyToken="40c4b6fc221f4138" culture="neutral"/>
        <codeBase version="89.0.170.0" href="x64/CefSharp.Core.Runtime.dll"/>
    </dependentAssembly>
</assemblyBinding>

Does anyone has tried to implement this specific option? I'm missing something? In order to trigger the generation process, I added the following line into the project file but without any positive result.
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.Publishing.targets" />

Any suggestions are welcome. Thanks!


text:
Q: Compare Dates Pipe Angular 6 - How get Data from Observable? I use Angular CLI6
What is wrong ?
I want to hide DateEnd if the month and the year is equal to the month and year of the start date?
@Component({
  selector: 'my-app',
  template: `
    <div>
<mat-list *ngIf="!SameDates()">({{ ppsToDisplay?.EndDate | date:'MMMM y'}}) </mat-list>
    </div>
  `,
  providers: [DatePipe]
})

constructor(private datePipe: DatePipe)
SameDates(): boolean {
   return datePipe.transform(this.StartDate, 'MM-yyyy') ===
            datePipe.transform(this.EndDate, 'MM-yyyy');
}

All my dateend are hidden ....
I obtain my data like this :
Service :
return this.database.list('/ppss', ref => ref.orderByChild("Patientid").equalTo(Patientid)).valueChanges();
}

Component :
this.route.params.forEach((urlParameters) => {
   this.patientid = urlParameters['id'];});
this.ppssToDisplay = this.ppssService.getPPSByPatientid(this.patientid);


text:
Q: Magento 2.3.4: Why doesn't Magento admin configuration take any effect on the `fax` field? The option for fax under Store->Configuration->Customer->Customer Configuration->Name and Address options was set to NO right from the beginning of the installation of Magento 2. It is strange to see the fax field on the storefront where it shouldn't be. Is this a bug or am I supposed to have done something? Also, if I remove the fax field via default.xml then the Place Order button becomes inactive leaving nothing in the log files for us to debug. Can anyone say if there is a fix? Does it have anything to do with the event handlers that are being made use of in our Magento site?

A: Setting Show Fax to No does definitely work after clearing cache.


text:
Q: Scraping pin coordinates from an interactive map with Selenium I am trying to scrape the dropped pin coordinates on  this Interactive map.
The map is made with Leaflet library for JavaScript. It's getting the coordinates somehow but this information cannot be found on the website itself.
Question: How can I assess coordinate information with Selenium if I don't even know where it is?
To save some time:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

PATH = "..."
driver = webdriver.chrome(PATH)

driver.get("https://kaupunkipyorat.hsl.fi/en/helsinki/stations")
driver.quit()

Thanks!

A: The page makes a request to https://api.digitransit.fi/routing/v1/routers/hsl/bike_rental, which contains exactly the information you want.
To get the names of the first five stations, we could write:
import requests
response = requests.get("https://api.digitransit.fi/routing/v1/routers/hsl/bike_rental")
json = response.json()
for station in json["stations"][:5]:
     print(station["name"])

Which prints:
Luhtimäki
Petikontie
Martinkyläntie
Vantaanpuisto
Vehkala station


text:
Q: Apache 2.2 does not load custom module i build an custom apache module mod_spnego using visual studio 2015 and c++ sources, using apache 2.2.31 libs (apr, apr_util) and header files on testing machine. I loaded that module successfully in that apache 2.2.31 on testing machine, but after migrating module on production machine, it fails to load and apache 2.2.31 on that machine throws misleading error "The specified module cannot be found"
I believe, that underlying error is with some missing os .lib, or incompatible os lib, because apache 2.2.31 libs on production machine are the same as on testing machine.
One difference during compile was necessisty to add wss2tcip.header file. Linker then linked ws2_32.lib, but this library is not on production machine
I am really new to c++. Please help me find out the reason why apache on production machine does not load module.

A: I solved that issue. Production machine missed vc15 redistributables. After installing vc15, module loaded ok


text:
Q: Change Or Delete Label with Cypher in Neo4j In a Test, I made many types of nodes and relationships with Cypher syntax.
After all, I delete all of unneccessary nodes and their relations.
Actually, there are Types and Labels still there in my Browser
Are there any method to clear Or change name of unneccessary Type, Label with Neo4j and Cypher..??
Best regards

A: All the information is stored in the browser local storage. So If you are using chrome browser, once you are in localhost:7474/browser. right click your mouse and select "Inspect Element", this will open a chrome developer tool, then go to Resources and under resources, go to "Local Storage", you should see "http: //localhost:7474". select it. and select the key neo4j.grass, you can modify the value, by copying out and copying it back. or you can just delete the whole record (key and value) and close your browser. Open your browser again. start clicking on the labels. you will only see the labels you want. You can repeat this to clean up until neo4j come out with a better way.
if you are using firefox, you can install firebug, and click on the firebug then dom then local storage. then you can do the similar thing
for other browser I am sure that you can figure out ways(google) to clear the local storage

A: This cypher query deletes all nodes and relationships:
start n=node(*) match n-[r?]-() delete n, r;
You can customize it adding index or asking if it has attributes:
start n=node:users(':') match n-[r?]-() delete n, r;

A: If you've removed the labels from all nodes you should be able to get a clean result visualization stream by clearing your web browser's cache/cookies. This will not remove them from the info bar on your left, only from the graph vis. frame. Since labels and relationship types are database global constructs, unlike properties, they can exist in the database also after all their instances have been deleted. That may be the intended behavior, but I would expect there to also be a way to remove them completely from the database when 2.0 is released (if there isn't a way already that I've missed). If you want a clean start you can always stop your server, delete your database directory, and restart the server. You may still have to clear your browser or you may see ghost labels from your old database still haunt your visualization stream.

A: Searching for a removed label, I found that they are still left in data/graph.db/neostore.labeltokenstore.db.names, wh.

A: Remove nodes you don't want, backup DB, purge DB data dir, stop / start server, reinsert DB, enjoy.
I tried following on both Firefox and Chromium and it didn't work:

*

*removing all nodes of types I no longer used

*clearing localStorage neo4j.grass key - it does contain labels, but this doesn't help

*clearing whole localStorage (completely)

*stopping / killing server and bringing it back after points above

*removing files with labels in their names from DB data dir

*removing all neo4j cookies (in fact, later, whole browser cache as well)

Since purging DB and reinserting data worked, and since clearing local storage and launching another browser gets you same labels you had, I'm guessing the info is held partially in localStorage AND partially in files in graph.db dir (or however your DB dir is called). Files there are often binary, so I picked redoing whole DB (since it wasn't big anyway) over blind edits or decoding binaries - simply faster.
EDIT:
You may try something I've just spotted:
label > properties > view Stylesheet > click on drop icon (looks like extinguisher). This should drop the grass key.
You may need to have at least one node of given type for that, to open a view where you actually set up node display (colors and other properties) to get to it's stylesheet.


text:
Q: JSON issue: can't get data required, fault occuring all the time I previously asked a question with regards to parsing json, since then I found an example that should work correctly but its not. The code I now have is as followed:
  public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final TextView tv = (TextView)findViewById(R.id.result);

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            String username = "exampleusername";
            String password = "examplepassword";
            String url = "http://www.example.com/api/core/v1/my/";
            String unp = username+":"+password;

            class MyUser {
                  public String firstName;
                  public String lastName;
            }

            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet header = new HttpGet(url);
                String encoded_login = Base64.encodeToString(unp.getBytes(), Base64.NO_WRAP);
                header.setHeader(new BasicHeader("Authorization", "Basic "+encoded_login));
                HttpResponse response = client.execute(header);
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                for (String line; (line = reader.readLine()) != null;) {
                    if (line.isEmpty()) break; // Stop when headers are completed. We're not interested in all the HTML.
                    final String newjson = line.replaceAll("throw 'allowIllegalResourceCall is false.';", "");

                    JSONObject mainObject = new JSONObject(newjson);
                    JSONObject uniObject = mainObject.getJSONObject("firstName");

               // System.out.println(newjson + newjson.contains("firstName") + "," + newjson.contains("lastName"));
               System.out.println(uniObject);
             //   System.out.println(uniURL);
                }

With this code i am now getting the following error:
W/System.err(910): org.json.JSONException: End of input at character 0 of
W/System.err(910): at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err(910): at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err(910): at org.json.JSONObject.<init>(JSONObject.java:154)
W/System.err(910): at org.json.JSONObject.<init>(JSONObject.java:171)
W/System.err(910): at basic.authentication.BasicAuthenticationActivity.onCreate(BasicAuthenticationActivity.java:84)
W/System.err(910): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(910): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(910): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(910): at android.os.Looper.loop(Looper.java:137)
W/System.err(910): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(910): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(910): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(910): at dalvik.system.NativeStart.main(Native Method)

part of the json string that i am pulling down is as followed:
{
  "enabled" : true,
  "email" : "example@gmail.com",
  "firstName" : "example firstname",
  "lastName" : "example lastname",
  "name" : "example fullname",
  "level" : {

I am so so confused with json right now and why this is not working

A: try this read function
public static JSONObject read(String url, String unp){

    System.out.println("Connecting to service URL : "+url);
    InputStream is = null;
    String result = "";
    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        String encoded_login = Base64.encodeToString(unp.getBytes(), Base64.NO_WRAP);
        httppost.setHeader(new BasicHeader("Authorization", "Basic "+encoded_login));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    JSONObject json = null;
    try {
        json = new JSONObject(result);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return json;
}

}

*

*here i connects to the service first

*downloads the response

*pass it for JSONObject creation, instead of doing it in loop

A: you might want to try writing your Json without whitespaces..
for eg
{"foo":"bar"}

instead of
{
    "foo":"bar"
}


text:
Q: Android start intent via string name  String c="MainActivty.class";
 Intent ints =new Intent(getApplication(),c);
 startActivity(ints);

How can i do this on the click of the button i.e specify c to an Intent,or is there any other way i can do this?
The problem is that i have set c to intent but it is not working.

A: I understand your problem , so many guys giving you - point :
Lets assume i have a class here : com.mydomain.myproject.activity.MyActivity
And string must be like : "com.mydomain.myproject.activity.MyActivity"
then start intent like :
Class newclass = null;
//add this outside of OnCreate
final Activity thisActivity = this;
String activityString="com.mydomain.myproject.activity.MyActivity";
    try {
      newclass = Class.forName(activityString);
    } catch (ClassNotFoundException c) {
        c.printStackTrace();
    }

    if(newclasss != null) {
        nextIntent = new Intent(thisActivity, newclass);
        startActivity(nextIntent);
    } else {
        Toast.makeText(getApplicationContext(),"new class null",Toast.LENGTH_SHORT).show();
    }

Also another good answer is here : https://stackoverflow.com/a/37060977/5047398

A: There is not Constructor Intent(Context context, String s). So you can't pass a String to create a Intent. You can only use a String to set the Action of that Intent. The Constructor that you are trying to use takes as second argument a Class cls not a String. When you use Intent(getContext(), "MainActivity.class") the compiler does not create a String it creates a Class instance.
https://developer.android.com/reference/android/content/Intent.html


text:
Q: Как работает GROUP BY в MySQL? Привет.
Вопрос по sql по клаузуле GROUP BY.

*

*Рассмотрим группировку по ОДНОМУ столбцу. Пример:
SELECT DEPARTMENT_ID, SUM(SALARY)
FROM Employees
GROUP BY DEPARTMENT_ID;

То есть, в столбце DEPARTMENT_ID ищется уникальное (похоже на DISTINCT) значение отдела, например, 30, затем ищутся все строки, где упоминается отдел 30 в данной таблице, из этих строк берутся значения из столбца SALARY и суммируются (SUM). Потом ищется другой покупатель и все повторяется. В итоге я получаю сколько получил вообще денег каждый отдел.
Не понимаю момент: у меня есть 6 строк, в которых есть столбец DEPARTMENT_ID со значением 30. Какая из строк пойдет в таблицу-SELECT и почему? То есть, в таблице Employees было шесть строк с DEPARTMENT_ID 30, а в таблице-SELECT такая строка только одна. Как вообще эта группировка работает?

*Рассмотрим группировку по двум столбцам. Ее я вообще не понимаю. Даже картинки нормальной не нашел, из которой было бы понятно. Просмотрел кучу статей и книг по этому вопросу, но не понял ничего.

A: В выборку после group by не попадет ни одна из изначальных строк. На выходе агрегат - сумма данных в нужном разрезе. К колонкам, к которым вы явно не применили никаких групповых функций (таких как sum()), будет применена функция "первое попавшееся". Причем только в MySQL и только при выключенной опции ONLY_FULL_GROUP_BY. В остальных СУБД запрос, в котором хотя бы к одной колонке, не являющейся разрезом указанным в group by, "забыли" применить групповую функцию выдаст ошибку.
Как работает group by можно прикинуть в экселе. Запишите данные на лист, отсортируйте по тем полям, которые должны быть в group by. Читая отсортированные данные подряд в любом случае когда значение в очередной строке в колонках, указанных в group by отличается от значений в предыдущей - вставьте новую строку, скопируйте значения колонок group by, а в остальные поместите формулы вроде СУММ() ячеек группы под которой подводится итог. Результат group by - это именно эти вставленные итоговые записи. СУБД работает примерно по такому же алгоритму - сначала сортирует, потом суммирует идущие подряд одинаковые записи.
Добавлю про MySQL - он все таки слишком вольно к этому относится. Старайтесь всегда явно применять групповые функции ко всем колонкам, что бы самому понимать что именно в них окажется, ибо 'первое попавшееся' ни чем не стандартизировано и может меняться от версии к версии и в зависимости от физического расположения записей на диске и плана выполнения запроса.

A: Добавлю с примером запросов и вывода GROUP BY по двух полях.
Смотреть можно по таблице в которую, например, сохраняеться какой пользователь (user_id) вносил деньги, на какой счет (account) и сколько (balance).
Например, нужно узнать сколько каждый пользователь внес на каждый из своих счетов.
SELECT MIN(user_id), MIN(account), SUM(balance) FROM `t1` GROUP BY user_id, account;

Работает GROUP BY по двум полям так же как и по одному, сначала сортирует, а потом смотрит, если оба значения в строке такие же как и в предыдущей строке, тогда групирует эти строки. Если хотя бы одно значение не такое как в предыдущей строке, тогда групировки не будет. Для 3 и больше полей GROUP BY работает так же.

Результат:


text:
Q: How to select and insert data into a hive table with php I want to know if you can select and insert data into a hadoop hive table using a web application? (like you would with PHP for MySql).
If so then how?
If not then how could/would you go about doing something like this?

A: Yes, it is possible. Hive gives you the option to create clients written in differents programming languages through Hive Thrift Service.
Please check the HiveServer documentation and I think would be a good idea read about Apache Thrift to understand in a better way how Hive Thrift works.
Finally, here explains how to build a simple client with Php.