text:
Q: How to create a successful GET API with request parameters? I am creating a basic GET API that can fetch details with firstName, surName, email, and phone or it can be either of the ones that are mentioned. I have used the following code in the controller class.
    package com.example.employee.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.employee.entity.Employee;
import com.example.employee.repo.EmployeeRepo;
import com.example.employee.service.EmployeeService;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/employees",method = RequestMethod.GET)
    public List<Employee> getEmployees() {
        return employeeService.getEmployees();
    }

    @RequestMapping(value = "/employees", method = RequestMethod.POST)
    public Employee createEmployee(@RequestBody Employee employee) {
        return employeeService.createEmployee(employee);
    }

    @RequestMapping(value = "/employees/{Employee_Id}")
    public Optional<Employee> getEmployeeById(@PathVariable("Employee_Id") Integer employeeId) {
        return employeeService.getEmployeeById(employeeId);
    }

    @RequestMapping(value = "/employees", method = RequestMethod.PUT)
    public Employee updateEmployee(@RequestBody Employee incomingEmployee) {
        return employeeService.updateEmployee(incomingEmployee);
    }

    @RequestMapping(value = "/employees/{employeeId}", method = RequestMethod.DELETE)
    public String deleteEmployeeById(@PathVariable Integer employeeId) {
        return employeeService.deleteById(employeeId);
    }

    @RequestMapping(value= "/employees", method=RequestMethod.GET)
    public List<Employee>getEmployeeByParameter(@RequestParam(value="FirstName", required = false)String firstName,
        @RequestParam(value="LastName", required = false)String lastName,
        @RequestParam(value="Email", required = false)String email,
        @RequestParam(value="Phone", required = false)String phone)
        {

      return employeeService.findAllByFirstNameAndLastNameAndEmailAndPhone(firstName ,lastName, email,phone);

        }

}

I have included the following in the service class:
    package com.example.employee.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.employee.entity.Employee;
import com.example.employee.repo.EmployeeRepo;

@Service
public class EmployeeService {
    @Autowired
    private EmployeeRepo employeeRepo;

    public List<Employee> getEmployees() {
        List<Employee> employeeList = new ArrayList<>();
        employeeRepo.findAll().forEach(employee -> employeeList.add(employee));
        return employeeList;
    }

    public Employee createEmployee(Employee employee) {
        return employeeRepo.save(employee);
    }

    public Optional<Employee> getEmployeeById(Integer employeeId) {
        return employeeRepo.findById(employeeId);
    }

    public Employee updateEmployee(Employee incomingEmployee) {
        return employeeRepo.save(incomingEmployee);

    }

    public String deleteById(Integer employeeId) {
        employeeRepo.deleteById(employeeId);
        return "Deleted Successfully";
    }

    public List<Employee> getUserByEmail(String email){
        return employeeRepo.findAllByEmail(email);

}

    public List<Employee> findAllByFirstNameAndLastNameAndEmailAndPhone(String firstName, String lastName, String email,
            String phone) {
        if (firstName != null) return employeeRepo.findAllByFirstName(firstName);

        if (lastName != null) return employeeRepo.findAllByLastName(lastName);

        if (email != null) return employeeRepo.getUserByEmail(email);

        if (phone != null) return employeeRepo.findAllByPhone(phone);

        return null;
    }

}

I have included the following in the Repository class:
package com.example.employee.repo;

import java.util.List;
import java.util.Optional;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.example.employee.entity.Employee;

@Repository
public interface EmployeeRepo extends CrudRepository<Employee, Integer> {

    /*List<Employee> findAllByFirstNameOrLastNameOrEmailOrPhone(String firstName, String lastName, String email,
            String phone);*/
     @Query(value = "select * from user where firstName=?", nativeQuery = true)
      List<Employee> findAllByFirstName(String firstName);
      @Query(value = "select * from user where lastName=?", nativeQuery = true)
      List<Employee> findAllByLastName(String lastName);
      @Query(value = "select * from user where email=?", nativeQuery = true)
      List<Employee> findAllByEmail(String email);
      @Query(value = "select * from user where phone=?", nativeQuery = true)
      List<Employee> findAllByPhone(String phone);

    List<Employee> getUserByEmail(String email);

}

My POJO class:
package com.example.employee.entity;

import javax.annotation.Generated;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Size;

@Entity

public class Employee {
    public Employee(int employee_Id, String first_Name, String last_Name, String email, String phone) {
        super();
        employeeId = employee_Id;
        firstName = first_Name;
        lastName = last_Name;
        email = email;
        phone = phone;
    }

    public Employee() {

    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int employeeId;
    @Size(min = 3, max = 20, message = "Your name should be between 3 - 20 characters.")
    private String firstName;
    @Size(min = 3, max = 20, message = "Your name should be between 3 - 20 characters.")
    private String lastName;
    private String email;
    private String phone;

    public int getEmployee_Id() {
        return employeeId;
    }

    public void setEmployee_Id(int employee_Id) {
        employeeId = employee_Id;
    }

    public String getFirst_Name() {
        return firstName;
    }

    public void setFirst_Name(String first_Name) {
        firstName = first_Name;
    }

    public String getLast_Name() {
        return lastName;
    }

    public void setLast_Name(String last_Name) {
        lastName = last_Name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}
My application class:
package com.example.employee;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EmployeeApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmployeeApplication.class, args);
    }

}

My SQL file:
DROP TABLE IF EXISTS Employee;
CREATE TABLE Employee (
    Employee_Id INT AUTO_INCREMENT,
    First_Name VARCHAR(20) NOT NULL,
    Last_Name VARCHAR(20) NOT NULL,
    Email VARCHAR(50),
    Phone VARCHAR(20) NOT NULL,
    PRIMARY KEY (Employee_Id)
    );

INSERT INTO employee (First_Name, Last_Name, Email, Phone)
    VALUES ('John','Doe','john.doe@tcs.com','9840098400');

My properties file:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username= sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

When I hit the request, I have to mention all the parameters in order for it to work. I want it to be designed in such a way that even if I mention the firstName alone, I want the API to fetch the details for me. How is it possible? This code does not work that way instead I need to enter all the parameters for it to work.

A: This question already has an answer! Any way one solution is here.
Solution - 1 [please don't' forget to Handle exception Globally, code optimization, unit test, and API test]
Modify your Repository
 @Query(value = "select * from user where firstName=?", nativeQuery = true)
  List<User> findAllByFirstName(String firstName);
  @Query(value = "select * from user where surName=?", nativeQuery = true)
  List<User> findAllBySurName(String surName);
  @Query(value = "select * from user where email=?", nativeQuery = true)
  List<User> findAllByEmail(String email);
  @Query(value = "select * from user where phone=?", nativeQuery = true)
  List<User> findAllByPhone(String phone);

Service
 public List<User> findAllByFirstNameAndSurNameAndEmailAndPhone(String phone,String email,String firstName,String surName)
{
    if (firstName != null) return userRepository.findAllByFirstName(firstName);

    if (surName != null) return userRepository.findAllBySurName(surName);

    if (email != null) return userRepository.getUserByEmail(email);

    if (phone != null) return userRepository.findAllByPhone(phone);

    return null;
}

RestController
    @RequestParam(value="FirstName", required = false)String firstName,
    @RequestParam(value="SurName", required = false)String surName,
    @RequestParam(value="Email", required = false)String email,
    @RequestParam(value="Phone", required = false)String phone)
    {
      //TODO
       return userService.findAllByFirstNameAndSurNameAndEmailAndPhone(String phone,String email,String firstName,String surName);

    }

sir, I hope this will help you


text:
Q: Создание баз данных через цикл Занимаюсь изучением MS SQL, хочу создать процедуру, при вызове которой можно создать n-ое кол-во одинаковых баз данных, разница только в наименовании. Но ловлю ошибку на самом начальном этапе:
DROP PROCEDURE IF EXISTS createTable
GO
CREATE PROCEDURE createTable
AS
BEGIN
    DECLARE @count INT = 2;
    DECLARE @a INT = 0;
    DECLARE @statement nvarchar(500);
    DECLARE @stmt INT;
    WHILE @count > 0
        BEGIN
         SET @a = @a + 1;
            SET @statement = CONCAT('Create table Student#',@a,' (name varchar(20), age int);');
            PRINT @statement;
            EXEC sp_prepexecrpc @stmt OUTPUT, @statement;
         SET @count = @count - 1;
        END;
END
GO
EXEC createTable;

Получаю ошибку следующего типа:
Msg 2812, Level 16, State 62, Procedure sp_prepexecrpc, Line 1 [Batch Start Line 20]
Не удалось найти хранимую процедуру "Create table Student#1 (name varchar(20), age int)".

Подскажите, пожалуйста, где ошибка?

A: Исправил некоторые моменты, так как под рукой у меня только MS SQL Server 2008 R2, но работать будет всё аналогично. sp_prepexecrpc - подготавливает параметризованную процедуру, а не выполняет динамический код. Пользуйтесь в таком случае просто EXEC-ом. И смените тэг на "sql server", а не "mysql" =)
IF NOT EXISTS ( SELECT * FROM [dbo].[sysobjects] WHERE id = OBJECT_ID(N'[dbo].[createTable]') )
  EXEC ('CREATE PROCEDURE [dbo].[createTable] AS RETURN')
GO

ALTER PROCEDURE createTable
AS
BEGIN
    DECLARE @count INT = 2
    DECLARE @a INT = 0
    DECLARE @statement NVARCHAR(500)
    DECLARE @stmt INT
    WHILE @count > 0
        BEGIN
         SET @a = @a + 1
            SET @statement = 'CREATE TABLE Student#' + CAST(@a AS VARCHAR(10)) + ' (name VARCHAR(20), age INT)'
            PRINT @statement
            EXEC (@statement)
         SET @count = @count - 1
        END
END
GO

EXEC createTable

redpajama_set_name: RedPajamaStackExchange


text:
Q: What do screen readers do with an ellipsis unicode character? For example, the Unicode character "…" or the thing you get in HTML if you use the … entity. How will the various screen readers pronounce this?

A: This depends on the screen reader. In particular, most screen readers have a number of punctuation settings such as "some", "most", and "all". So it depends which category the screen reader puts the ellipses character into, which punctuation setting the user has selected, and what action the user is taking.
For example, in the JAWS for Windows screen reader (www.FreedomScientific.com) the ellipses isn't read when reading the document, but is read when navigating by letter or word.
I appreciate that's not a definitive answer, but my personal opinion is that you shouldn't avoid this character purely for accessibility reasons - each screen reader is different and this behaviour will probably change at some point in the future.

A: The tools provided with the microsoft speach SDK 5.1 just skip over ellipsis, including the one you quoted.  I was expecting it to at least pause but there was no noticeable pause.


text:
Q: Advanced jQuery selector that needs a jQuery ninja to answer I am looking for a jQuery guru to help me out on this. I have limited access to the code because it is a WordPress theme. My script has to go in the indicated area and if this can't be done with just jQuery, I would love suggestions that use JavaScript as well. Here is the problem I am trying to solve:
I need to grab the "href" link that is on EACH button of class 'gdlr-button' and wrap the href around the image that is inside EACH div.personnel-author-image

My Name

My Position

            Learn More

... And Repeat

A:

    $(function() {
        $('.personnel-author-image > img').wrap(function() {
            return $('',{href:$(this).closest('.personnel-item').find('.gdlr-button').attr('href')});
        });
    });

My Name

My Position

      Learn More

Include the script in wp_enqeue_script as suggested by @adeneo:
    $('.personnel-author-image > img').wrap(function() {
        return $('',{href:$(this).closest('.personnel-item').find('.gdlr-button').attr('href')});
    });

A: This will go through each .personnel-item and grab the href and wrap the img tag in an a tag
$(".personnel-item").each(function(){
    var href = $(this).find(".gdlr-button").attr("href");
    $(this).find(".personnel-author-image img").wrap( "" );
});

Heres a jsFiddle

A: Thanks to @adeneo for this script. He truly is a Ninja!
jsfiddle.net/qs8Lps00
jQuery(function($) {
    $('.gdlr-button').each(function() {
        var img = $(this).closest('.personnel-content').siblings('.personnel-author-image').find('img');
        img.wrap('');
    });
});

A: Here a short snippet to do what you suggest:

$('.personnel-item').each(function(){
 var href =$(this).find('.gdlr-button').prop('href');
 var img = $(this).find('.personnel-author-image').html();
 $(this).find('.personnel-author-image').html(''+ img +'');
});

  [...]

            Learn More

  [...]

      [...]

            Learn More

      [...]

Greetings from Vienna


text:
Q: Google API Data Transfer Insert: missing resource.applicationDataTransfer I'm creating simple PHP script for transfering ownerships of drive files between users in the same domain.  I want to use Admin SDK Transfers and Insert method.
Google has documentation about transfers here
I tried to transfer data through their webpage GUI and it went fine. What I can't do is how to make it work with PHP Client library.
Let's say I have prepared object for creating requests to Transfers resource
$transfers = new \Google_Service_DataTransfer($googleConnection);

googleConnection handles service account authorization so i can make requests like this:
$data = $this->transfers->transfers->listTransfers();

This returns data of all existing transfers in domain. Based on documentation and PHP Client library insert operation should work also.
$transferParams = new \Google_Service_DataTransfer_ApplicationTransferParam();
    $transferParams->setKey("PRIVACY_LEVEL"); //what kind of docs I want to transfer
    $transferParams->setValue(['SHARED', 'PRIVATE']);

    $appDataTransfer = new \Google_Service_DataTransfer_ApplicationDataTransfer();
    $appDataTransfer->setApplicationTransferParams($transferParams);

    $appDataTransfer->applicationId = "iDString";    //set application ID

    $newTransfer = New \Google_Service_DataTransfer_DataTransfer();

    $newTransfer->setOldOwnerUserId('accountID'); //origin account IDs are placeholders
    $newTransfer->setNewOwnerUserId('account2ID'); //destination account
    $newTransfer->setApplicationDataTransfers($appDataTransfer);

    $result = $this->transfers->transfers->insert($newTransfer); //execute insert

After executing insert I am getting code 400 with message Missing required field: [resource.applicationDataTransfer].
If I test real parameters via web they work.
I must be missing something, because that exception doesn't make sense at all.
I'm also open to alternative solutions.

A: setApplicationDataTransfers method expects an array of Google_Service_DataTransfer_DataTransfer so you just need to update the following line (note the [] in the params)
$newTransfer->setApplicationDataTransfers([$appDataTransfer]);


text:
Q: Local native module cannot be null I am building a native module locally.
To test the changes I make to the native module I am using a local app which has a dependency on the local module.
The problem I am facing is the whenever I try to run the ios app, I get an error saying "Native Module can not be null"
Native Module:
package.json:
  "name": "my-package-name",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "types": "index.d.ts",
  "scripts": {
    "test": "jest --coverage"
  },
  "keywords": [
    "react-native"
  ],
  "author": "AwesomeAuthor",
  "peerDependencies": {
    "react": "^16.8.6",
    "react-native": "^0.60.0"
  },
  "devDependencies": {
    "babel-jest": "23.0.1",
    "babel-preset-react-native": "4.0.0",
    "jest": "23.1.0",
    "jshint": "^2.9.5",
    "react": "16.8.6",
    "react-native": "0.60.0",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native",
    "coverageDirectory": "coverage",
    "collectCoverageFrom": [
      "**/*.{js,jsx}",
      "!**/coverage/**/*.{js,jsx}"
    ],
    "collectCoverage": true,
    "coverageThreshold": {
      "global": {
        "lines": 95
      }
    }
  }
}

Podspec file:
Pod::Spec.new do |s|
  s.name         = "MyPackageName"
  s.version      = "0.0.1"
  s.summary      = "MyPackageName"
  s.description  = <<-DESC
                  MyPackageName
                   DESC
  s.homepage     = "https://www.mypackagename.com"
  s.platform     = :ios, "8.0"
  s.source_files  = "MyPackageName/**/*.{h,m}"
  s.requires_arc = true
  s.authors =  { 'Some Author' => 'someauthor@gmail.com' }
  s.source            = { :http => 'file:' + __dir__ + '/MyPackageName.zip' }
  s.dependency "React"
end

AwesomeProject
package.json
{
  "name": "AwesomeProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.8.6",
    "react-native": "0.60.0",
    "my-package-name": "file:../my-package-name",
    "react-native-reanimated": "1.4.0",
    "react-native-segmented-control-tab": "^3.4.1",
    "react-native-uuid-generator": "6.1.1"
  },
  "devDependencies": {
    "@babel/core": "7.7.5",
    "@babel/runtime": "7.7.6",
    "@react-native-community/eslint-config": "0.0.3",
    "babel-jest": "24.9.0",
    "eslint": "6.7.2",
    "jest": "24.9.0",
    "metro-react-native-babel-preset": "0.54.1",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

App.js
import {
  Platform,
  StyleSheet,
  Text,
  View,
  Button,
  TextInput,
  ScrollView,
  Switch,
  FlatList,
  TouchableOpacity,
  Alert,
} from 'react-native';
import SegmentedControlTab from 'react-native-segmented-control-tab';
import MyPackageName from 'my-package-name';

Podfile for AwesomeProject
platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'AwesomeProject' do
  # Pods for AwesomeProject
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/React'
  pod 'React-DevSupport', :path => '../node_modules/react-native/React'
  pod 'React-fishhook', :path => '../node_modules/react-native/Libraries/fishhook'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-RCTWebSocket', :path => '../node_modules/react-native/Libraries/WebSocket'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  target 'AwesomeProjectTests' do
    inherit! :search_paths
    # Pods for testing
  end

  use_native_modules!
end

target 'AwesomeProject-tvOS' do
  # Pods for AwesomeProject-tvOS

  target 'AwesomeProject-tvOSTests' do
    inherit! :search_paths
    # Pods for testing
  end

end

Tried react-native link but that did not work too.


text:
Q: Help regarding rEFInd I have a Macbook Pro and I am in the process of trying to create a triple boot with Windows 8 and Ubuntu 14.04.3 LTS. Using the disk utility in OSX to create the other two partitions and rEFInd to work as my boot manager but I have run into some difficulties. I installed the rEFInd manager via ./install.sh and I would like to customize the theme but I cannot locate the file EFI in my Macintosh HD location. Any advice? I am also new to trying to create a triple boot so any other additional information would be greatly appreciated. Thanks.

A: If you used install.sh, without any options, to install rEFInd from OS X, then the rEFInd binary and support files ended up on your EFI System Partition (ESP), which OS X does not mount by default. Given your plans, the easiest way to access it is to wait until after you install Ubuntu. If you install Ubuntu in EFI mode, the ESP will be mounted at /boot/efi, and rEFInd will be in /boot/efi/EFI/refind. You should have no problems modifying the files from Ubuntu, although you'll need to use sudo to do anything with those files.
Alternatively, you can mount the ESP in OS X. There are several ways to do this; one is:
mkdir /Volumes/ESP
sudo mount -t msdos /dev/disk0s1 /Volumes/ESP

Note that this example assumes that your ESP is /dev/disk0s1, which is the default location for the ESP on Mac systems. If you've repartitioned your disk from scratch with non-Apple software, it might be somewhere else. You can check with diskutil, gdisk, parted, GParted, or other tools to be sure you're using the right partition. (OS X's Disk Utility deliberately hides the ESP, though, so it's useless for this task.) Once you mount the ESP like this, rEFInd will be in /Volumes/ESP/EFI/refind.
One more point: Before proceeding with your Windows installation, you may want to read this question and its answers. If you created any FAT partitions with Disk Utility, that tool probably turned your disk into a hybrid MBR, which is an ugly and dangerous hack used by Apple to enable BIOS-mode booting of Windows. This might indeed be necessary, but Windows 8 and later often boot fine in EFI mode on Macs, and to do this, the disk must not have a hybrid MBR. Understanding the interactions between boot mode (EFI vs. BIOS) and partition table type (straight GPT, GPT with hybrid MBR, and straight MBR) will help you keep your hair as you set up a triple-boot on a Mac.


text:
Q: Is this possible to change the arrow heads like as tikz-qtree? Currently using (qtree, tree-dvips) My codes are follows:
\documentclass[12pt]{book}

\usepackage{times}
\usepackage{qtree,tree-dvips}%commented purposely
\usepackage{linguex}

\begin{document}

\ex.\label{crossnestschema} \textit{Crossing and nested dependencies}
\a.\label{crossschema} {\node{5} X$_{\textrm{j}}$}  \ldots {\node{7}Y$_{\textrm{i}}$} \ldots {\node{5.5} X$_{\textrm{h}}$} \ldots  {\node{8}{\raisebox{-1pt}{\underline{\hspace{.5cm}}}}$_{\kern1.5pt\textrm{j}}$} \ldots {\node{6}{\underline{\hspace{.5cm}}}$_{\kern1.5pt\textrm{i}}$} \ldots {\node{8.5}{\underline{\hspace{.5cm}}}$_{\kern1.5pt\textrm{h}}$}
\anodecurve[br]{6}[b]{7}{.3in}
\anodecurve[br]{8}[b]{5}{.25in}
\anodecurve[br]{8.5}[b]{5.5}{.25in}

\end{document}

It works fine, and the output is:

I need a small change in this, I need the arrow heads should be as like as tikz arrow heads, e.g.,

I aware that it is possible if we go with tikz-qtree, but the problem is there are more occurrences are there in the entire file, so changing all items will require huge time, so please suggest how to get the arrow heads without changing tree-dvips.sty
Thanks a lot...


text:
Q: How do you get items from animals? I am in the town of Jolly Roger and have used Jet's radar to scan for items. It highlights one of the cats as having an item. This also applies to various other animals found in different towns.
I have tried all the tools I have available and only two things have any response: Clive's bomb, and Gallows' freezer doll. However, neither results in an item.
How do I get the item from the animal?

A: OK, so I finally worked out how to do it.
The tool you need is called the Changecrest. It is Virginia's 3rd and final tool, and it also happen to be the last of the 12 tools you obtain (3 per character).
The location of this tool is:

 Quite a while into the game (about 18 hours for me) you have to get access to a dungeon called "Cradle of the Metal God". This is accessed by a path called "Dim Root Path", in order to enter you must have all 12 guardians obtained. The Changecrest tool is the first treasure you find along the way.


text:
Q: Extra user card and two "log out" links in the Stack Exchange menu Update Feb 19, 2022:
This was partially fixed a while ago (i.e., on desktop mode) but just reappeared on all pages of Meta Stack Exchange, specifically (I can't repro on other sites):

Original post:
I noticed that when I open the Stack Exchange menu on desktop while on the profile page (mine or another user's), it includes my user card, which a) takes some real estate from the drop-down menu, b) messes up with my muscle memory when I try to visit a site, and c) is redundant because it's already there in the top bar.
Actually, it depends on the device / screen resolution. Here are the details:

Device/Screen
Page
Behavior

Desktop, full window
Any page except profile
The menu looks normal (the way it used to)

Desktop, full window
profile page
Extra user card + extra "log out" link

Mobile / narrow screen (responsive)
Any page
User card + extra "log out" link

For desktop, here are the two views side by side:

Profile Page
Other pages

This bug was likely introduced by this recent fix.
I think the user card should be removed from both the "wide view" (e.g., desktops) and narrow-screen view (e.g., responsive design on mobile phones). But if it's decided that it should be shown on narrow-screen views (for rep and badges), then at least one "log out" link should be removed.
This is how it currently looks on responsive design on mobile (all pages):

Addendum: As zcoop98 pointed out in the comments, the two "log out" links are also shown on the mobile view (not responsive).


text:
Q: Adding screenshot in extent report 4 for the failed scenarios I'm using extent report 4.Actually I'm trying to add Screenshot in extent report when the test fails. I'm using below code to achieve this. Screenshot gets attached in the end of my report (please refer the screenshot), but I want screenshot to get attached in the appropriate step i.e. when the test cases fail. Please help me with solutions or workaround
            case FAIL:
            String path = WrapperMethods.captureScreenshot();
            try
            {
                test.log(logStatus, message + test.addScreenCaptureFromPath(path));
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            break;

A: for version 4  you can work as below
if (result.getStatus() == ITestResult.FAILURE) {
            test.fail(MarkupHelper.createLabel(result.getName() + "Test Failed", ExtentColor.RED));
            test.fail(result.getThrowable());
            String screencastPath = null;
            try {
                screencastPath = Screeshot.captureScreenshot(WebDriverManager.driver);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                test.fail("" + "Screenshot Name: " + Screeshot.sendScreenName() + "");
                test.fail(""
                        + " Click the below link OR check the report folder by above screenshot Name to get the Screenshot of failure "
                        + "", MediaEntityBuilder.createScreenCaptureFromPath(screencastPath).build());
            } catch (IOException e) {
                test.fail("Test Failed, Cannot attach screeshot");
            }
            WebDriverManager.driver.close();
        }


text:
Q: Find minimum value from four columns and compare it with range in different column? I have an excel sheet which has below data:
col1    col2    col3    col4     col5       output          range
-----------------------------------------------------------------------------
-1      -1      -1      -1       -1                         99.9% - 100%
-1      -1      -1      -1       -1                         98% - 99.8%
87.8    78.6    95.2    98.2    94.7                        95% - 98.9%
100     100     100     100     100                         90% - 94.9%
90.4    86      96.6    73.2    95.5                        80% - 89.9%
92.9    88.9    93.1    100     100                         0% - 79.9%
85.7    80      82.2    100     100
85.7    80      82.2    100     100
98.3    100     97.9    100     94.4

Now I need to come up with a formula which can do below things:

*

*I need to figure out out minimum of col2, col3, col4, col5 and if that minimun is falling under any of those range mentioned in Range column, then I need to print that range in output column.

*But if col1 has value -1 then in output column I want to write "Fail". We will ignore point 1 above if col1 has value -1.

So for example output will be:
col1    col2    col3    col4     col5       output          range
-----------------------------------------------------------------------------
-1      -1      -1      -1       -1          Fail           99.9% - 100%
-1      -1      -1      -1       -1          Fail           98% - 99.8%
87.8    78.6    95.2    98.2    94.7         0% - 79.9%     95% - 98.9%
100     100     100     100     100          99.9% - 100%   90% - 94.9%
90.4    86      96.6    73.2    95.5         0% - 79.9%     80% - 89.9%
92.9    88.9    93.1    100     100          80% - 89.9%    0% - 79.9%
85.7    80      82.2    100     100          80% - 89.9%
85.7    80      82.2    100     100          80% - 89.9%
98.3    100     97.9    100     94.4         90% - 94.9%

Is this possible to do by any chance in excel? It looks like pretty complex so I am kinda confuse on how to do this in excel automatically using some formula?

A: Here's one way. Columns K through N are a reference.
Formula for H2:
=MIN(B2:E2)

Formula for I2:
=IF(A2=-1,"z",IF(H2>$L$2,"a",IF(H2>$L$3,"b",IF(H2>$L$4,"c",IF(H2>$L$5,"d",IF(H2>$L$6,"e","f"))))))

Formula for F2:
=VLOOKUP(I2,K:N,4,FALSE)

Drag 'em down and you're done.

Granted, you could accomplish this with fewer columns, but I've laid it out this way for illustration.

A: Order the ranges in ascending order, create a column of the lower bounds of the ranges and use LOOKUP function to find the appropriate range.


text:
Q: NaCl port : Excluding getopt from gawk build I've been trying to port gawk for over a few days now, but I've been stuck at this issue for some time. I'm trying to make a standalone gawk nexe that runs on my Dev Environment (so I am using a static newlib build). Actually, GNU Awk 4.1.1 has its version of getopt.c, getopt.h and and few files, the definitions of which contradict with the ones provided in GNU C Library. I'm getting a multiple definition error. Here's the relevant console output :
[... more lines ...]
Making all in .
make[2]: Entering directory '/home/agaurav77/Programs/NaCl/naclports/src/out/build/gawk/build_x86-64_newlib'
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary//toolchain/linux_x86_newlib/bin/x86_64-nacl-gcc  -DNDEBUG -O2 -DNDEBUG  -Dmain=nacl_main -D__GNU_LIBRARY__ -o gawk.nexe array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o     -lmpfr -lgmp -lm -lm
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o): In function `getopt_long_only':
getopt.c:(.text+0x1600): multiple definition of `getopt_long_only'
getopt1.o:getopt1.c:(.text+0xa0): first defined here
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o):(.bss+0x4): multiple definition of `optind'
getopt.o:(.data+0x0): first defined here
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o):(.data+0x0): multiple definition of `opterr'
getopt.o:(.data+0x4): first defined here
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o):(.data+0x4): multiple definition of `optopt'
getopt.o:(.data+0x8): first defined here
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o): In function `getopt_long':
getopt.c:(.text+0x16c0): multiple definition of 'getopt_long'
getopt1.o:getopt1.c:(.text+0xe0): first defined here
/home/agaurav77/Programs/NaCl/nacl_sdk/pepper_canary/toolchain/linux_x86_newlib/bin/../lib/gcc/x86_64-nacl/4.4.3/../../../../x86_64-nacl/lib/../lib64/libcrt_common.a(lib_a-getopt.o): In function `getopt':
getopt.c:(.text+0x1780): multiple definition of `getopt'
getopt.o:getopt.c:(.text+0x1e60): first defined here
collect2: ld returned 1 exit status
Makefile:643: recipe for target 'gawk.nexe' failed
make[2]: *** [gawk.nexe] Error 1
make[2]: Leaving directory'/home/agaurav77/Programs/NaCl/naclports/src/out/build/gawk/build_x86-64_newlib'
Makefile:727: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/agaurav77/Programs/NaCl/naclports/src/out/build/gawk/build_x86-64_newlib'
Makefile:546: recipe for target 'all' failed
make: *** [all] Error 2
naclports: Building gawk: failed.

Any pointers on how to get past this?
Thanks in advance.

A: As the gawk build likely functions in the presence of other libc's with getopt, I would suggest you figure out why configure is adding in the fallback version.
Most likely some sort of test executable is being built by configure and something is failing. I would suggest searching the configure script for getopt to get some idea where it might be trying to do this. Then searching the config.log file generated during configure to find out what's failing.
One possibility is that some builds which need to run test executables to check for broken functionality have a tendency to assume the broken functionality for cross-compiled builds.
If all else fails you could gate out the built in version by ifdefing the contents of getopt.c out when defined(native_client)


text:
Q: Changing a single word in an comma-separated multi-line text file in Python without using CSV or mapping Text file rf.txt:
user1, task1
user2, task2
user3, task3

The intention is to change user2 to user4:
user1, task1
user4, task2
user3, task3

How is it done without using csv module, mapping or anything beyond the most basic file read/write operations?

A: Read, modify, write back
with open("test.txt") as fic:
    content = fic.read()

content = content.replace("user2", "user4")

with open("test.txt", "w") as fic:
    fic.write(content)

Using pathlib.Path
from pathlib import Path
file = Path("test.txt")
file.write_text(file.read_text().replace("user2", "user4"))

A: bit dumb but basic:
f = open('file', 'r')
lines = f.readlines()
f.close()
f = open('file', 'w')

for l in lines:
    if 'user2' in l:
        l = l.split(', ')
        l[0] = 'user4'
        l = ', '.join(l)
        #print(l)
        f.write(l)
    else:
        f.write(l)

f.close()


text:
Q: why is so differult between the app generated by fastify-cli and the example in the documentation? where is the start.js in the project which is generated by fastify-cli ?
i think its big different between the  getting start example and the app generated by fastify-cli?
should i write the start function like this in the project created by fastify-cli?
const start = async () => {
  try {
    await sequelize.sync({})
    app.log.info('database sync correctly')
    await app.listen(PORT, '0.0.0.0')
    app.swagger()
  } catch (err) {
    app.log.error(err)
    process.exit(1)
  }
}
start()

there are just a app.js in the project generated by fastify-cli.what a different!

A:
where is the start.js in the project which is generated by fastify-cli ?

There is not, it is replaced by the CLI utility fastify your-file.js in the package.json (like mocha, jest etc.. does to run tests)
Usually the starter file is always the same, so it has been integrated in the cli and you can use the args to set the PORT or to reload the server automatically when you edit one file.

i think its big different between the getting start example and the app generated by fastify-cli?

The docs teach all you need to know about the framework, the plugins and utility around it want to ease the developer experience.. like manage a mongodb-connectio: it is one line with the official plugin.

should i write the start function like this in the project created by fastify-cli?

If you use fastify my-file.js you don't need it.
After some experience you will understand when you need the fastify-cli or not.
I think the cli is useful in the most use cases and it suggests good ways to implement configurations loading and encapsulation.
You won't need it for special use cases that need to run some async operation before the server is created


text:
Q: can any unused object escape from Garbage Collector? Is there any possibility that a object which is not referenced anywhere and still existing on heap. I mean is there a possibility that a unused object getting escaped from garbage collector and be there on the heap until the end of the application.
Wanted to know because if it is there, then while coding i can be more cautious.

A: If an object is no longer referenced, it does still exist on the heap, but it is also free to be garbage-collected (unless we are talking Class objects, which live in PermGen space and never get garbage-collected - but this is generally not something you need to worry about).
There is no guarantee on how soon that will be, but your application will not run out of memory before memory from those objects is reclaimed.
However, garbage collection does involve overhead, so if you are creating more objects than you need to and can easily create less, then by all means do so.
Edit: in response to your comment, if an object is truly not referenced by anything, it will be reclaimed during garbage collection (assuming you are using the latest JVM from Sun; I can't speak toward other implementations).  The reason why is as follows:  all objects are allocated contiguously on the heap.  When GC is to happen, the JVM follows all references to "mark" objects that it knows are reachable - these objects are then moved into another, clean area.  The old area is then considered to be free memory.  Anything that cannot be found via a reference cannot be moved.  The point is that the GC does not need to "find" the unreferenced objects.  If anything, I would be more worried about objects that are still referenced when they are not intended to be, which will cause memory leaks.

A: You should know that, before a JVM throws an out-of-memory exception, it will have garbage collected everything possible.

A: It depends on when and how often the object is used. If you allocate something then deallocate (i.e., remove all references to it) it immediately after, it will stay in "new" part of the heap and will probably be knocked out on the next garbage collection run.
If you allocate an object at the beginning of your program and keep it around for a while (if it survives through several garbage collections), it will get promoted to "old" status. Objects in that part of the heap are less likely to be collected later.
If you want to know all the nitty-gitty details, check out some of Sun's gc documentation.

A: If an instance is no longer referenced, it is a possible candidate for garbage collection. This means, that sooner or later it can be removed but there are no guaranties. If you do not run out of of memory, the garbage collector might not even run, thus the instance my be there until the program ends.
The CG system is very good at finding not referenced objects. There is a tiny, tiny chance that you end up keeping a weird mix of references where the garbage collector can not decide for sure if the object is no longer referenced or not. But this would be a bug in the CG system and nothing you should worry about while coding.

A: Yes; imagine something like this:
Foo foo = new Foo();

// do some work here

while(1) {};

foo.someOp(); // if this is the only reference to foo,
// it's theoreticaly impossible to reach here, so it
// should be GC-ed, but all GC systems I know of will
// not Gc it

I am using definition of: garbage = object that can never be reached in any execution of the code.

A: Garbage collection intentionally makes few guarantees about WHEN the objects are collected.  If memory never gets too tight, it's entirely possible that an unreferenced object won't be collected by the time the program ends.

A: The garbage collector will eventually reclaim all unreachable objects. Note the "eventually": this may take some time. You can somewhat force the issue with System.gc() but this is rarely a good idea (if used without discretion, then performance may decrease).
What can happen is that an object is "unused" (as in: the application will not use it anymore) while still being "reachable" (the GC can find a path of references from one of its roots -- static fields, local variables -- to the object). If you are not too messy with your objects and structures then you will not encounter such situations. A rule of thumb would be: if the application seems to take too much RAM, run a profiler on it; if thousands of instances of the same class have accumulated without any apparent reason, then there may be some fishy code somewhere. Correction often involves explicitly setting a field to null to avoid referencing an object for too long.

A: This is theoretically possible (there is no guarantee the GC will always find all objects), but should not worry you for any real application - it usually does not happen and certainly does not affect a significant chunk of memory.

A: In theory, the garbage collector will find all unused objects. There could, of course, be bugs in the garbage collector…
That said, "In theory there is no difference between theory and practice, in practice, there is." Under some, mostly older, garbage collectors, if an object definition manages to reach the permanent generation, then it will no longer be garbage collected under any circumstances. This only applied to Class definitions that were loaded, not to regular objects that were granted tenured status.
Correspondingly, if you have a static reference to an object, that takes up space in the "regular" object heap, this could conceivably cause problems, since you only need to hold a reference to the class definition from your class definition, and that static data cannot be garbage collected, even if you don't actually refer to any instances of the class itself.
In practice though, this is a very unlikely event, and you shouldn't need to worry about it. If you are super concerned about performance, then creating lots of "long-lived" objects, that is, those that escape "escape-analysis", will create extra work for the garbage collector. For 99.99% of coders this is a total non-issue though.

A: My advice - Don't worry about it.
Reason - It is possible for a non-referenced object to stay on the heap for some time, but it is very unlikely to adversely affect you because it is guaranteed to be reclaimed before you get an out of memory error.

A: In general, all objects to which there are no live hard references, will be garbage-collected. This is what you should assume and code for. However, the exact moment this happens is not predictable.
Just for completeness, two tricky situations [which you are unlikely to run into] come into my mind:

*

*Bugs in JVM or garbage collector code

*So called invisible references - they rarely matter but I did have to take them into account one or two times during the last 5 years in a performance-sensitive application I work on


text:
Q: What is the command for importing a sql file and its schema? I have an empty sqlite3 db. I would like to import a pre-existing one with all of its schema and data. What is the proper code command for that?
I tried :
sqlite3 db/development.sqlite3 < new-sql.sql

It flashes by all the data, and a bunch of junk, and the CPU beeps a few times, and nothing changes.
Any ideas?

A: For all those interested:
sqlite3 new-sql.sql .dump | sqlite3 db/development.sqlite3


text:
Q: stop auto direct contact form Hello so I have this contact form
HTML
<form action="mail.php" method="POST">

Team Name
 <input type="text" name="name">

Your Email
 <input type="text" name="email">

Players
<textarea name="message" rows="6" cols="25"></textarea>

<input type="radio" name="region" value="Europe" checked>Europe

<input type="radio" name="region" value="North America">North America

<input type="submit" value="Send">
</form>

PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$region = $_POST['region'];
$message = $_POST['message'];
$formcontent=" From: $name $email $region $message";
$recipient = "myemail@email.com";
$subject = "$name";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>

However when I click submit it auto redirects to a new page mail.php, how can I get it to stay on the same page and replace the form with thankyou or if not possible have the message at the bottom of the form below the send button.
One final thing I want to change it so when it sends the email itself the data is in this format with breaks inbetween
Team Name
Email
Region
Players

Vs what It does at the moment when I read the email I've sent
From: My Team myemail@email.com Europe Player1
Player2
Player3
Player4
Player5

A: The quick answer: change your form action to <?php echo $_SERVER['PHP_SELF']; ?>.
In doing that however, you will need to detect whether the form has been submitted or not. The usual example you see in tutorials and books etc. is either to check whether $_POST['submit'] has been set (note: you'd need to add a 'name' attribute to your submit <input> tab above to make this work>; or to verify whether the page has been loaded as the result of a POST or a GET request (example below courtesy of Checking if form has been submitted - PHP):
if ($_SERVER['REQUEST_METHOD'] == 'POST')


text:
Q: 3DES on iOS 8+ with Objective-C I have to encrypt a password with 3DES and send it as parameter to login service on backend.
I'm struggling searching an algorithm to achieve 3DES during last week but I can't be able to find it.
I need to crypt the password with a key and an initializer vector (aka iv).
Someone knows a free library or an algorithm appropriate?
Thanks.


text:
Q: Update DB values via ajax on changing select value I'm trying to update values in the database when select is changed. But the code isn't working and can't find why. Client side and server side codes are as following.
Client side - js
$("select.changeStatus").change(function(){

  var project_status = $(this).children("option:selected").attr("value");
  var reference_number = $(this).parent("td").parent("tr").find("td.project_reference_number").text();

  if (project_status == "complete") {
  var confirmation_status = confirm("You really need to mark this project as complete?");
    if (confirmation_status == true) {
    $.ajax({
        type: "POST",
        url: "../../includes/changestatus.php",
        data: 'status=' + project_status + '&ref=' + reference_number,
        success: function() {
            $("body").fadeOut(250, function(){
            window.location.reload(true);
                });
        }
    });
    return false;
  }
  if (confirmation_status == false) {
     $(this).val("");
  }
}

server side - php
$reference_number = $_POST["ref"];
$status = $_POST["status"];

$update_command = "UPDATE projects ";
$update_command = "SET status = '$status' ";
$update_command .= "WHERE id = '$reference_number'";
$update_projects_to_db = mysqli_query($connection, $update_command);
if (!$update_projects_to_db) {
    die ("Database query faild");
}

Any help on this?

A: It was because of some syntax errors. Edited the query and it worked. Removed quotations from the numeric value :)


text:
Q: Caesar cipher and reverse text program I'm trying to make a function that gets a string and a number and if the number is bigger the '0' so it will make the caesar cipher with the string and the number that the user entered.
for example -> 'stack' and the number is '3' -> 'uvdfn'.
if the number is '0' so it will reverse the string.
for example - 'stack' -> 'kcats'
I don't know what is the issue with the code, i don't see anything wrong.

/*********************************
* Class: MAGSHIMIM C2    *
* Week 3                         *
**********************************
* Thank you for Ofek and Dor for *
* Editing this template :)       *
**********************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void decryptText(char* encText, int n);

#define STR_SIZE 50
int main(void)
{
 char str[STR_SIZE];
 int num = 0;

 printf("Please enter the string : ");
 fgets(str, STR_SIZE, stdin);

 printf("Please enter a number : ");
 scanf("%d", &num);

 decryptText(str, num);

    system("PAUSE");
 return 0;
}

void decryptText(char* encText, int n)
{
 int i = 0;
 int j = 0;
 char temp = 0;

 int strLen = strlen(encText);

 if (n > 0)
 {
  for (i = 0; i < strLen; i++)
  {
   if (*(encText + i) == ' ') { }
   else
   {
    if (*(encText + i) >= 'x')
    {
     *(encText + i) = (*(encText + i)) - 26;
    }
    *(encText + i) = (*(encText + i)) + n;
   }
  }

  printf("The array after the program deciphered it : \n");
  printf("%s", encText);
 }

 else if (n == 0)
 {
  for (i = 0; i < strLen; i++)
  {
   for (j = 0; j >= 0; j--)
   {
    temp = *(encText + i);
    *(encText + i) = *(encText + j);
    *(encText + i) = temp;
   }
  }

  printf("The array after the program cracked it : \n");
  printf("%s", encText);
 }
}

A: When reversing the string you are swapping letters from front to back and then from back to front and so you end up with the same string that you started with. You also don't need to use all the pointers because you can use array subscripting which makes it more readable. Try something more like this:
j = strLen-1;
for (i = 0; i < strLen/2; i++, j--) {
    temp = encText[i];
    encText[i] = encText[j];
    encText[j] = temp;
}


text:
Q: Continous function to be solved by using intermediate value property A continuous function $f:[0,1] \to \mathbb{R}$ attains each of its values finitely many times and $f(0) \neq f(1)$.
Show that $f$ attains at least one of its values an odd number of times

A: Hint. Assume wlog that $f(0)<f(1)$. Start by showing that in the interval $f([0,1])$ there are at most a countable set $E$ of local maximum/minimum values of $f$. Since $(f(0),f(1))$ is uncountable there exists $y\in (f(0),f(1))\setminus E$. By using intermediate value property, show that the cardinality of $f^{-1}(y)$ is odd.


text:
Q: How are DC offset square wave transmission waveforms generated? The balanced serial transmission shown in the picture is similar to rs485 except that the square wave has a DC offset (e.g. 24VDC) with an alternating offset.

The transceiver chip "drives" the bus using capacitors that are in series with the bus.

How does one generate plus-minus ~3Volt offsets with a 1uF series capacitor? Blue and Purple signals are created this way.
Edit: Clarifying the DC offset part.  The bus is powered by a DC power supply (e.g. 24VDC) and an "AC blocking" inductor (which looks like a transformer).


text:
Q: CollectionView cell Snapkit constraints fail when applying offset I have the follwowing constraints applied to my Cell via SnapKit and they work fine.
    self.imageView.snp.makeConstraints { make in
      make.leading.top.trailing.equalToSuperview()
      make.bottom.equalTo(self.nameLabel.snp.top)
      if let width = self.imageView.image?.size.width {
          make.height.equalTo(width)
      }
    }

    self.nameLabel.snp.makeConstraints { make in
      make.leading.trailing.equalToSuperview()
      make.top.equalTo(self.imageView.snp.bottom)
      make.bottom.equalTo(self.priceLabel.snp.top)
    }

    self.priceLabel.snp.makeConstraints { make in
      make.top.equalTo(self.nameLabel.snp.bottom)
      make.leading.trailing.bottom.equalToSuperview()
    }

but when i try to add space between the imageView and the nameLabel i get errors
    self.productImageView.snp.makeConstraints { make in
      make.leading.top.trailing.equalToSuperview()
      make.bottom.equalTo(self.productNameLabel.snp.top).inset(-8) // change here
      if let width = self.productImageView.image?.size.width {
          make.height.equalTo(width)
      }
    }

    self.productNameLabel.snp.makeConstraints { make in
      make.leading.trailing.equalToSuperview()
      make.top.equalTo(self.productImageView.snp.bottom).offset(8) // change here
      make.bottom.equalTo(self.productPriceLabel.snp.top)
    }

    self.productPriceLabel.snp.makeConstraints { make in
      make.top.equalTo(self.productNameLabel.snp.bottom)
      make.leading.trailing.bottom.equalToSuperview()
    }

What i dont understand is if i move the minus in the constraints to the other 8 then the errors dissapear but the views are now overlapping. I feel im missing something basic but dont know what.
Here is what i am hoping for:

A: So this had nothing to do with the cell itself but the size of the collectionView containing the cells


text:
Q: Добавление товара в корзину .build Rails У меня есть список товаров, у каждого товара кнопка добавления в корзину, которая редиректит на путь контроллера line_items.
Код экшена из line_items_controller.rb
    def create
      item = Item.find(params[:item_id])
      @line_item = @cart.line_items.build(item: item)

      respond_to do |format|
        if @line_item.save
          format.html { redirect_to @line_item.cart, notice: 'Line item was successfully added.' }
          format.json { render :show, status: :created, location: @line_item }
        else
          format.html { render :new }
          format.json { render json: @line_item.errors, status: :unprocessable_entity }
        end
      end
    end

Какой хеш нужно передать в .build(), чтобы товар добавился в корзину?
По идее, нужно передать хеш параметров товара, но как бы я не пытался передать его, не выходит.
Сейчас выдает ошибку can't write unknown attribute item_id

A: Проблема решена.
Суть заключалась в неправильном файле миграции line_items, т.к. указал неверное имя.
Вместо t.references :item было прописано t.references :product
Так что я сделал rake db:rollback и исправил файл миграции.


text:
Q: ESXi - Programming I am looking to run a script which outputs the hardware for a vm solution and I was wondering how to do this.
I have a VC on the solution with multiple hosts and guests.
I am assuming I can do this through the VIX API on the VC server but I don't know.
What I ideally would like is to run a batch file/script which told me how many hosts and then went through the hosts outputting the hardware (such as OS/RAM/CPU etc).
Any help would be greatly appreciated.  I am aware that this can be done through the VC manually however I would like a script to do this.

A: You would need to look at VMware's powerCLI which can connect and pull the information for VM's if that is what you're looking for. Below is a cmdlet of powerCLI pulling a VMs hardware information.
Get-VM

Name                PowerState   Num CPUs    Memory (MB)
----                ----------   --------    -----------
NW                  PoweredOff      1        512
PowerCLI            PoweredOn       1        1024

VMWare KB this should help


text:
Q: Can someone please explain energy of electrons in Bohr's model? Energy of and electron is $$E = \text{kinetic energy} + \text{negative of potential energy}. \tag{eq-1}$$
But energy of electron in the $n$th orbital is also $$E = -\frac{13.6}{ n^2} \tag{eq-2}$$ Which means that the energy of the electron would get less and less negative as we go to further orbitals, which means that the kinetic energy of the electron is increasing (from eq-1). However that is counter-intuitive because as the electron goes from lower orbital to higher its going from a lower potential (closer to the nucleus) to a higher potential (away from nucleus i,e. against the electric field). And thus the potential energy should increase and the total energy should be more negative.
Another thing which is mind boggling is that the velocity of electron in the $n$th orbit  is, $$v = \frac{e^2}{nh\epsilon_0}$$ which suggests that velocity decreases as we go from inner to outer orbitals, which means that kinetic energy decreases! All this does not make sense to me. I know I made a mistake somewhere so if someone can help me please explain.
At the same time my textbook says that the outer energy level electrons would have more energy so, they would need less energy to be excited. But what energy do they have? The velocity equation suggests that outer electrons have less and less kinetic energy as we go to oter orbitals and eq 2 suggest that the electron even decrease in potential energy as they go in further energy levels(which should increase)

A: You write

E = kinetic energy + negative of potential energy. (eq-1)

and then

as the electron goes from lower orbital to higher […] the potential energy should increase and the total energy should be more negative.

Remember that the electrostatic potential energy between two charges $q_1,q_2$ separated by some distance $r$ is
$$ U = \frac{1}{4\pi\epsilon_0}\frac{q_1 q_2}{r} $$
This potential is not strictly positive: it has the same sign as the product of charges $q_1\cdot q_2$.  From the definition of the force $\vec F = -\vec\nabla U$ (or, in one dimension, $\vec F = -\hat x\frac{\mathrm d}{\mathrm dx}U$), you should be able to convince yourself that this sign convention is required to make opposite charges attract and like charges repel.
When an electron moves from a lower to a higher orbit, the potential energy increases by becoming less negative.  Your equation (eq-1) is wrong. The total energy is kinetic plus potential; it's just that the potential energy between opposite charges happens to be negative.


text:
Q: Remove price increase on configurable swatches I am having trouble removing the price increase from configurable swatches. As you can see in the image it says +$10.00 - this bit is what i am trying to remove. The price should still change but the area in red should not be shown.

The indigo colored area is:

The red colored ares is:
The swatch buttons are wrapped in:
I have unsuccessfully tried to remove this using this bit of code

    //

    jQuery("swatch-label").click(function(){
        checkswatches();
    });
});

function checkswatches(){
  jQuery("#select_label_wd_sssg").select(function(){
    var optiontext = jQuery(this).text();
    var addsignpos = optiontext.indexOf('+');
    var subtractsignpos = optiontext.indexOf('-');
    if(addsignpos>0){
        var result = optiontext.substring(0,addsignpos-1);
        jQuery(this).html(result);
    }

    if(subtractsignpos>0){
        var result = optiontext.substring(0,subtractsignpos-1);
        jQuery(this).html(result);
    }
  });
}
// ]]>

Can't get code to format correctly
I have put the code above inside of
app/design/frontend/[package]/[theme]/template/catalog/product/view/type/options/configurable.phtml
and app/design/frontend/[package]/[theme]/template/configurableswatches/catalog/product/view/type/options/configurable/swatches.phtml with no luck.
Any advice is appreciated.

A: In skin/frontend/rwd/default/js/configurableswatches/swatches-product.js find this:
/**
     * Return text that should be displayed in attribute label for a certain option
     *
     * @param {object} option
     * return {string}
     */
    getOptionLabel: function(option) {
        return this.productConfig.getOptionLabel(option, option.price);
    },

and change it to this:
/**
     * Return text that should be displayed in attribute label for a certain option
     *
     * @param {object} option
     * return {string}
     */
    getOptionLabel: function(option) {
        return this.productConfig.getOptionLabel(option);
    },

A: Try to add:
Event.observe(window, 'load', function() {
    Product.ConfigurableSwatches.prototype.getOptionLabel = function(option){
       return option.label;
    };
});

Into any script to overwrite default swatches-product.js behaviour


text:
Q: How can I train my Python based OCR with Tesseract to train with different National Identity Cards? I am working with python to make an OCR system that reads from the ID Cards and give the exact results from the image but it is not giving me the righteous answers as there are so many wrong characters that the tesseract reads. How can I train tesseract in a way that it reads the ID card perfectly and gives us the right and exact details, furthermore how can I get myself to the .tiff file and to make tesseract work for my project.

A: Steps to improve Pytesseract recognition:

*

*Clean your image arrays so there is only text(font generated, not handwritten). The edges of letters should be without distortion. Apply threshold (try different values). Also apply some smoothing filters. I also recommend to use Morpholofical opening/closing - but thats only a bonus. This is exaggerated example of what should enter pytesseract recognition in form of array: https://i.ytimg.com/vi/1ns8tGgdpLY/maxresdefault.jpg

*Resize the image with text you want to recognize to higher resolution

*Pytesseract should generally recognize letters of any kind, but by installing font in which the text is written, you are superbly increasing accuracy.
How to install new fonts into pytesseract:

*

*Get your desired font in TIFF format

*Upload it to http://trainyourtesseract.com/ and receive trained data into your email (EDIT: This site doesnt exist anymore. At this moment you have to find alternative or train font yourself)

*add the trained data file (*.traineddata) to this folder C:\Program Files (x86)\Tesseract-OCR\tessdata

*add this string command to pytesseract reconition function:

*

*lets say you have 2 trained fonts:  font1.traineddata and font2.traineddata

*To use both, use this command
txt = pytesseract.image_to_string(img, lang='font1+font2')
Here is a code to test your recognition on web images:
import cv2
import pytesseract
import cv2
import numpy as np
import urllib
import requests
pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract'
TESSDATA_PREFIX = 'C:/Program Files (x86)/Tesseract-OCR'
from PIL import Image

def url_to_image(url):
    resp = urllib.request.urlopen(url)
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image

url='http://jeroen.github.io/images/testocr.png'

img = url_to_image(url)

#img = cv2.GaussianBlur(img,(5,5),0)
img = cv2.medianBlur(img,5)
retval, img = cv2.threshold(img,150,255, cv2.THRESH_BINARY)
txt = pytesseract.image_to_string(img, lang='eng')
print('recognition:', txt)
>>> txt
'This ts a lot of 12 point text to test the\nocr code and see if it works on all types\nof file format\n\nThe quick brown dog jumped over the\nlazy fox The quick brown dog jumped\nover the lazy fox The quick brown dog\njumped over the lazy fox The quick\nbrown dog jumped over the lazy fox'


text:
Q: Include Select inside pagination - bootstrap I'm trying to include a dropdown inside the bootstrap pagination.
http://jsfiddle.net/Z4dsD/6/

*

*The dropdown is not aligned properly.

*There is a gap between the Next & Prev buttons.

How can it be fixed.
HTML:

First

Prev

        <select class="form-control">
            <option>1</option>
            <option>2</option>
        </select>

Next

Last

CSS:
.custom-pagination select {
    display:inline-block;
    width:85px;
    border-radius:0px;
}

A: Just add the following to your css of the select:
vertical-align: top;

This will align the select at the top level.
Also you need to add a margin-left: -1px; to align it properly with the other elements.
Also remove the display: inline-block style from the last 2 li elements and set the float of the select to left.
Working jsfiddle: Select jsfidle


text:
Q: JxBrowser cannot upload file in version 6.12 & 6.13 Go to gmail.com, click the avatar button and select a photo to upload but nothing happens! 6.9 is OK
I think this is similar to JxBrowser 6.12: Saved file does not appear

A: This is a known issue in 6.12 and 6.13. It is not reproducible in 6.11.1. Please consider using JxBrowser version 6.11.1 while we are working on the fix.

A: I'm writing you to let you know that the issue has been fixed. You can download EAP build with the fix from https://storage.googleapis.com/cloud.teamdev.com/downloads/jxbrowser/eap/jxbrowser-6.14-b13-eap-cross-desktop-win_mac_linux.zip
The fix will be included in official 6.14 release probably this month.


text:
Q: Custom Price Display Precision without Roundings in Magento On this Question Member shivam helps me to figure out a problem for a custom price format...
How to get custom price format (with 3 Precision) in magento
Here i use now Precision of 3
public function customformatPrice($price, $includeContainer = true)
   {
          if ($this->getCurrentCurrency()) {
          //sets the floating point precision to 4 points

          return $this->getCurrentCurrency()->format($price, array('precision'=>3),     $includeContainer);

         }
         return $price;
   }

But i used a Round Precision of 4
public function roundPrice($price,$roundTo=4)
 {
 return round($price, $roundTo);
 }

All works fine when i use Backend Input Price Like 9.2400 € The Output in frontend are fine then. But When i input in backend something like 9.2450 € the output on fronend are roundet. It seams that i miss somewhere to round price the right way.
This Code i use for List view... (wrong Display in Roundings):
<?php echo  ''.Mage::helper('checkout')->customformatPrice($_minimalPriceDisplayValue /1.19 /$_bbase_qty, false) ?>

This Code i use for Product View. (Perfekt Roundings) But i cants use this code in List or Price phtml.
<?php echo ''.Mage::helper('checkout')->customformatPrice(min($product_price)*1.19/($_bbase_qty),true,false); ?>``

Hope someone can help me Figuring out where is the problem in roundings or can help me how can i use the last code in  directly in list.phtml.
Thanks for any Help

A: open file [magento]\app\code\core\Mage\Core\Model\Store.php
    public function roundPrice($price)
    {
        return round($price, 4);//change 2 to 4
    }

    public function customformatPrice($price, $includeContainer = true, $options=array())
    {
        if ($this->getCurrentCurrency()) {
            return $this->getCurrentCurrency()->format($price,$options, $includeContainer);
        }
        return $price;
    }

echo Mage::helper('checkout')->customformatPrice(3000.12313,true,array('precision'=>4));

hope this help you
Note: Don't change in core files directly instead override it


text:
Q: induction for SCIPopt's setppc Regarding SCIP's "constraint handler for the set partitioning / packing / covering":

*

*Is it smart enough to deduce all forms that it supports without me having to call the setppc functions directly?

*Can it handle/detect forms of sum(x) == y where x is a list of binary variables and y is also a binary variable? Same question for less than or equal?

*The docs for it state that it requires a right-hand-side equal to 1. What about RHS=0?

A: *

*If I understand you correctly you are asking if SCIP will see that a linear constraint is a setppc constraint and automatically upgrade it? Yes.

*Yes, it should not matter how you write it.

*A sum of binary variables with rhs = 0 will just propagate and fix all variables to 0. (if only lhs is 0 then that is redundant)
If some of the coefficients are -1 instead of +1 SCIP will still try to make it work by negating all negative variables (or all positive ones and multiply by -1 afterwards). SCIP will check for any linear constraint that has only binary variables and +1/-1 coefficients if it can be upgraded in such a way.


text:
Q: How to escape opening curly brace in Angular? How to escape the first opening curly brace below?

    {
        <ng-container *ngFor="let x of [1,2,3,4]; let last=last">
            {{x}}
            <ng-container *ngIf="!last">,</ng-container>
        </ng-container>
    }

The expected output: {1,2,3,4}

A: You can use {{ '{' }} to escape it.

A: I am not sure if I get your question right.

    {
        <ng-container *ngFor="let x of [1,2,3,4]; let last=last">
            {{x}}
            <ng-container *ngIf="!last">,</ng-container>
        </ng-container>
    }

Output: {1,2,3,4}
If you are asking on how to escape the curly brace then the method is by using interpolation syntax
UPDATE:
Use ngNonBindable/ng-non-bindable depends on your angular version.

A:    ..some html above
    <ng-container *ngFor="let x of [1,2,3,4]; let last=last">
        {{x}}
        <ng-container *ngIf="!last">,</ng-container>
    </ng-container>
   ..some html below


text:
Q: doc file created in iPhone documents encoding issue I'm trying to write a MSword file in document directory by the following code:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString* path;
NSString* gradeDoc = [self fetchCommentsDesc];
NSString* str = [self.objStudent.strName stringByAppendingFormat:@".doc"];
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:str];
[gradeDoc writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

[self fetchCommentsDesc] returns NSString.
self.student.strName is a String

Issue:
When i Open the doc file created in document directory of iphone, all the special characters in the doc appears as boxes or some arabic chars.
Please help!

A: You're writing some UTF-8 bytes, which is not a ".doc". Try writing it to a ".txt" file.
Also, you may have to write a "byte order mark" for some text editors to notice that it's UTF-8 or UTF-16 (in NS/CF-land, this is known as an "external representation"):
NSData * d = [(id)CFStringCreateExternalRepresentation(NULL, (CFStringRef)gradeDoc, kCFStringEncodingUTF8, 0) autorelease];
[d writeToFile:path atomically:YES];

Also try kCFStringEncodingUnicode and kCFStringEncodingUTF16.


text:
Q: Return string when inside a while loop I've tried google, and the advance search here. No luck.
Class SomeClass
{
    public string MethodName()
    {
    //Some Code
        While(conditions)
        {
            //More Code
            string X;
            X = "string stuff";
            return X;
        }
    }
}

I get a 'not all code paths return a value' error. I'm sure I can work around this but I'd like to know how to solve this for future reference.

A: Think if while loop condition is not met, would your method return string? So put the return just before end of method to ensure that your method will always return string, this MSDN error page not all code paths return a value would further help you to understand.
I believe the sample code is just to show the problem as it does not make much sense to me.
public string MethodName()
{
    //Some Code
    While(conditions) {
        //More Code
        string X;
        X = "string stuff";
        return X;
    }
    return "somestringifnotX";
}

A: The problem is that the compiler believes there is a path where conditions is NOT met on the first time it hits the while:
//Some Code
while(conditions)
{
  //More Code
  string X;
  X = "string stuff";
  return X;
}
.. Problem!
return "not found"; // or throw new Exception("I'm not supposed to be here")

What you need to do is also return (or throw!) in the instance where conditions aren't met at all.

A: You are getting error because you are trying to return value from while loop which is not possible
Problem here if your while loop condition is not satisfied than no value get return that is the reason compiler giving you error.
Solution to this is , return empty string outside while loop that you function is returning value.
public string functionname
{
    while(conditions)
    {
      //More Code
      string X;
      X = "string stuff";
      return X;
    }
    return string.Empty;
}

A: I think you mean this
 static void Main(string[] args)
    {

        for (int i = 0; i < MethodName().Count; i++ )
        {
            var result = MethodName()[i] as string;
            Console.WriteLine(result);
        }

        Console.ReadLine();
    }

    private static List<string> MethodName()
    {
        var items = new List<string>();

        while (Condition)
        {
            items.Add("SString to return");
        }

        return items;
    }

I hope it will help

A: Your problem is that you will not return anything when you don't pass your while loop
Class SomeClass
{
  public string MethodName()
  {
    //Some Code
    While(conditions)
    {
      //More Code
      string X;
      X = "string stuff";
      return X;
    }
    return "Nothing to return Actually";
    //OR
    Throw new Exception("Conditions where false");
  }
}

Imagine you're conditions = false and you never entered the while. This means you will never get to the return. your function on the other hand needs one. End your statement with a return or throw an error when you don't want that behaviour.

A: public static string binarySearch(int [] dataArray, int dataDicari)
{
      int first = 0;
      int last = list.length – 1;
      int mid;

      while (first <= last)
      {
          mid = (first+last)/2;
          if (dataArray[mid] == dataDicari)
              return ......;               //ISIAN 1
          else if (dataArray[mid] < dataDicari)
              first = mid + 1;
          else if (dataArray[mid] > dataDicari)
              last = mid – 1;
      }

      return .....;    //ISIAN 2
}


text:
Q: Get the rolling sum of values of id from two different column? df:
id1     id2     value1    value2
-----------------------------------
a       b       10        5
c       a       5         10
b       c       0         0
c       d       2         1
d       a       10        20
a       c       5         10

get sum of values associated with id 'a' from column ['id1','id2']:
id1     id2     a.rolling(2).sum()
-----------------------------------
a       b       NaN
c       a       20
d       a       30
a       c       25

How would I get the rolling sum of values of id 'a' from two different column with a df.groupby function?
I tried this df.groupby(['id1','id2])['value1','value2'].transform(lambda x: x.rolling(2).sum()), but that did't work.

A: Here's one way to do it
i = df.filter(like='id')
v = df.filter(like='va')

x, y = np.where(i == 'a')

df.iloc[x].assign(A=v.values[x, y]).assign(Roll=lambda d: d.A.rolling(2).sum())

  id1 id2  value1  value2   A  Roll
0   a   b      10       5  10   NaN
1   c   a       5      10  10  20.0
4   d   a      10      20  20  30.0
5   a   c       5      10   5  25.0

A: Using concat after filter
df1=df.filter(like='1')
df2=df.filter(like='2')
df2.columns=df1.columns
s=pd.concat([df1,df2]).sort_index().groupby('id1').rolling(2).sum()
s=s.loc['a']
df.loc[s.index].assign(new=s)
Out[99]:
  id1 id2  value1  value2   new
0   a   b      10       5   NaN
1   c   a       5      10  20.0
4   d   a      10      20  30.0
5   a   c       5      10  25.0


text:
Q: Metal performance on iPhone XR I have a kernel Metal function which basically looks like this:
struct Matrix {
    half arr[562500]; //enough to store 750x750 matrix
};

struct Output {
    half arr[12288];
};

kernel void compute_features(device Output& buffer [[ buffer(0) ]],
                             const device Matrix& mtx_0 [[ buffer(1) ]],
                             const device Matrix& mtx_1 [[ buffer(2) ]],
                             constant short2& matSize [[ buffer(3) ]],
                             constant float& offset [[ buffer(4) ]],
                             ushort2 gid [[ thread_position_in_grid ]]) {

for (int i = 0; i < 12; i++) {
    for (int j = 0; j < 12; j++) {

        int mat_id = i * matSize.x + j;

        half matrixValue_0 = mtx_0.mat[mat_id];
        half matrixValue_1 = mtx_1.mat[mat_id] - offset;

        short someId_0 = 0;
        short someId_1 = 0;
        short someId_2 = 0;
        short someId_3 = 0;  //those ids will be calculated at the code below
        half value = 0.h;  //this value will be calculated at the code below

        //some math where `someId` and `value` are calculated with usage of `matrixValue_0` and `matrixValue_1`

        if (some_condition0) {
            buffer.arr[someId_0] += value;
        }

        if (some_condition1) {
            buffer.arr[someId_1] += value;
        }

        if (some_condition2) {
            buffer.arr[someId_2] += value;
        }

        if (some_condition3) {
            buffer.arr[someId_3] += value;
        }
     }
}

I understand that this code has its down-sides - dynamic indexing and big loop. But unfortunately the algorithm I'm trying to express can not be implemented differently at that point.
Now, this code runs very good at iPhone 7+, it takes around 200 us per iteration, and I'm very happy with this number.
BUT, I tried to run the exact same algorithm on iPhone XR and I was surprised to see that this algorithm takes around 1.0-1.2 ms to complete.
With the help of XCode and it's magnificent GPU pipeline debugging tool I found out that my bottlenecks are:
1)
    half matrixValue_0 = mtx_0.mat[mat_id];
    half matrixValue_1 = mtx_1.mat[mat_id] - offset;

It seems that significant part of processing time are spent in Memory Load operation.
2)
if (some_condition0) {
    buffer[someId_0] += value;
}

if (some_condition1) {
    buffer[someId_1] += value;
}

if (some_condition2) {
    buffer[someId_2] += value;
}

if (some_condition3) {
    buffer[someId_3] += value;
}

The major processing time are spent for Memory Store operation.
For me it seems like iPhone XR quite struggles operating with device memory because bottle-necks are in places where I work with containers from device memory.
I understand that I'm using dynamic indexing - compiler can not really predict what address in the container will be loaded/stored in certain iteration. But the code works very good on iPhone 7+, but not on iPhone XR.
I suspect that it might have something to do with byte alignment. Can it be somehow related to that?
I would love to hear some suggestions on this. Thanks in advance!


text:
Q: How to open Whatsapp through a Xamarin.Android (not Xamarin.forms) app? I've been researching a way to open whatsapp through a xamarin app, but all i found were recommendations using xamarin.forms and not xamarin.android (which the app I work on is based on). Is there a way to do this in xamarin.android?

A: Well, a basic code like that should do it I guess:
 private void OpenWhatsApp(Activity activity, string number, string message)
    {

        try
        {
            PackageManager packageManager = activity.PackageManager;
            Intent i = new Intent(Intent.ActionView);
            String url = "https://api.whatsapp.com/send?phone=" + number + "&text=" + URLEncoder.Encode(message, "UTF-8");
            i.SetPackage("com.whatsapp");
            i.SetData(Uri.Parse(url));
            if (i.ResolveActivity(packageManager) != null)
            {
                activity.StartActivity(i);
            }
            else
            {
                //Error message
            }
        }
        catch (Exception e)
        {
            // exception
        }

    }

Let me know if you have any queries!


text:
Q: Create Set (String) variable of unique values occuring in a Column grouped by Identification Column df <- data.frame(ID=c("1", "1", "2", "2", "3", "3", "4", "4", "4", "4"), Product=c("A", "B", "B", "A", "C", "C", "A", "B", "C", "C"))

I would like to get a Set of values of column 'Product' grouped by the column 'ID'.
The Set should be a string delimited by a comma. It should represent a string value where each possible combination of Product values occurs just once.
The outcome is unique ID values with possible combinations of Product values  without value repetition.
My approacch that gets me half the way is:
library(dplyr)
df2<-df %>% group_by(ID) %>% summarise(Set = toString(unique(Product)))

Output:
     ID     Set
    (fctr)   (chr)
1    A, B
2    B, A
3       C
4 A, B, C
The output is a string variable Set that has the combinations of values of variable Product however they can repeat itself, that is A, B != B, A which is undesirable.
I would like to use a function that would allow my workflow to get a Set variable where A, B = B, A etc, hence also the Product Frequencies will consequently match a different rule.
Expected output:
ID Set (fctr) (chr) 1 A, B 2 A, B 3 C 4 A, B, C so when I do summary statistics it will show that value A, B is in the data set 2x (as compared to A, B 1 time and B, A 1 time)
Who knows?

A: We can use sort in between to sort the 'Product' within each 'ID'
df %>%
  group_by(ID) %>%
  summarise(Product = toString(unique(sort(Product))))
#     ID Product
#  (fctr)   (chr)
#1      1    A, B
#2      2    A, B
#3      3       C
#4      4 A, B, C

An alternative using data.table syntax would be
library(data.table)
setDT(df)[, list(Product = toString(unique(sort(Product)))) , by = ID]

Or with base R
aggregate(Product~ID, df,FUN= function(x) toString(unique(sort(x))))


text:
Q: I'm having more text inputs text that was supposed I want to select pdfs in my input and after I select pdfs I want to show text inputs.
For example: If I select 2 pdfs to upload I want to show 2 text inputs, because I want to change title of each pdf.
If I select all pdfs that I want at once it is working fine.
But If I select one pdf at a time, I getting always more text inputs that my number of selected pdfs.
For example If I Want to select 2 pdfs, but I select the first and I forgot my second, if this situation happens, after I select my first I´ll select my  second forgotten pdf, but in this case Im getting two text inputs for this second pdf. And I´ll have a total of 3 text inputs for just two pdfs. (So, Im having one text input more)
Do you see why this can be happening?
You can see here my issue demonstration: http://jsfiddle.net/j5yeq/4/
This is jQuery script Im using:
$('.j_gsendp').click(function(){
$('.j_galleryp').click().change(function () {
    var allFiles = this.files;
    var numFiles = this.files.length;
    alert(numFiles);
    $('.j_gfalsep').animate({
        width: '400'
    }, 500, function () {
        $(this).html('You select ' + numFiles + 'files.');
        for (var i = 0; i < numFiles; i++) {
            var file = allFiles[i],
                name = file.name;
            $('#test').append('Title of pdf ' + name + ':<input type="text" name="title[]" value="' + name + '"/>

');
        }
    });
});
});

A:

I added a this.val(''); This clears the number of files in the input after it has displayed the current count.


text:
Q: Spring, SockJS - error during WebSocket handshake: Unexpected response code 400 I have implemented BE application with WebSockets support using Spring Boot. I use SockJS in order to connect to my WebSocket endpoint and during the connection process I get a following error:
error during WebSocket handshake: Unexpected response code: 400

but then (as you can see at the image above) everything is working fine and websocket  opened.
Right now I don't understand what can be a reason of this issue and how to fix it. Please help.
UPDATED
Thanks for the paweln1986 help I have fixed version issue with SockJS lib but the issue with Unexpected response code 400 still exists:

I also using nginx in front of Tomcat 8. This is my nginx config:
server {
    listen          443 ssl;
    server_name  myserver.com;
    ssl on;

    location /api/ {
        proxy_pass_header X-XSRF-TOKEN;
        proxy_pass        http://localhost:8081/api/;
        proxy_set_header Origin "http://localhost:8081/api/";

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_http_version 1.1;
    }

    location /dashboard/ {
        proxy_pass        http://localhost:8081/dashboard/;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /manager {
        proxy_pass        http://localhost:8081/manager/;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location / {
        root   /srv/www/htdocs/myserver/;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /srv/www/htdocs/;
    }

}

A: You have wrong version of SockJS.

On the browser side, applications can use the sockjs-client (version 1.0.x) that emulates the W3C WebSocket API

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
You are missing two things under your /api/ section

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

https://www.nginx.com/blog/websocket-nginx/

A: This complication also occurs if you are using SSL with Amazon load balancers. The listener of the elb should have an entry of SSL(instead of HTTPS) with load balancer port as 443 and instance protocol as TCP with instance port as 80 (Don't forget to add certificate)
This will enable WebSocket traffic to pass through.
For detailed reference :
https://blog.jverkamp.com/2015/07/20/configuring-websockets-behind-an-aws-elb/


text:
Q: Weird redirection caused by SSL in all browsers I have 2 websites, mydomain.com and mydomain.co. Here is the comparison of the 2 websites.
mydomain.com | production site  | purchased SSL certification from GoDaddy

mydomain.co  | development site | self generated SSL certification

The following issues comes up randomly.

*

*When I visit http://mydomain.co, the content of http://mydomain.com shows up but the address keeps as http://mydomain.co.

*When I try to sign in on https://mydomain.co/login, SSL warning shows. When I approve it, I get redirected to https://mydomain.com/login.

*After I sign in on mydomain.co and try to upload an image, I get redirected to mydomain.com and it tells me to login to upload. But the image does get uploaded to the place on mydomain.co.
Since mydomain.co does not have a certified SSL, my guess is the browsers are trying to correct the url for me?
This happens on all my browsers(firefox, safari, chrome and opera, all latest version) on Mac OS Lion. When I switch to windows on the same computer and test with all browsers, everything works as expected.
Any idea why this is happening? I do need some help.
Thanks in advance,
Milo


text:
Q: Processes tracing each other I am trying to create a child process, wich asks its parent to trace him. After this the child tries to attach to its parent. Because of some protection reasons processes can trace only their children, so I have to execute my code with sudo. I want to create some communication between the two processes, therefore I put a do-while loop in the parent. If the child terminates the parent should terminate too. My output is only Child is traced, so I assume that the child does not attach to the parent.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ptrace.h>
#include <sys/wait.h>

void child();
void parent(pid_t pid);

int main() {
    pid_t pid = fork();
    if(pid == 0)
        child();
    else if(pid > 0)
        parent(pid);
    else{
        perror("fork");
        exit(EXIT_FAILURE);
    }
}

void child(){
    if(ptrace(PTRACE_TRACEME, 0, 0, 0) < 0){
        perror("ptrace");
        exit(EXIT_FAILURE);
    }
    printf("Child is traced\n");

    pid_t ppid = getppid();
    if(ptrace(PTRACE_SEIZE, ppid, NULL, NULL) != 0) {
        perror("ptrace");
        exit(EXIT_FAILURE);
    }

    printf("Child is tracing\n");

    raise(SIGTRAP);

    ptrace(PTRACE_DETACH, ppid, NULL, NULL);

    printf("%s\n", "Child exiting...");
    exit(EXIT_SUCCESS);
}

void parent(pid_t pid){
    int status;
    do{
        waitpid(pid, &status, WUNTRACED | WCONTINUED);
        if(WIFSTOPPED(status)){
            printf("Child stopped: %d\n", WSTOPSIG(status));
            if(WSTOPSIG(status) == 5){
                printf("Stopsig status 5.\n");
            }
            ptrace(PTRACE_CONT, pid, 0, 0);
        }
    } while(!WIFEXITED(status) && !WIFSIGNALED(status));

    ptrace(PTRACE_DETACH, pid, NULL, NULL);

    printf("%s\n", "Parent exiting...");
    exit(EXIT_SUCCESS);
}

Commenting out the raise(SIGTRAP) I get:
Child is traced
Child is tracing
Child exiting...
Parent exiting...

A: A ptraced process will, by default, get stopped when a signal is delivered to it. When your child raises SIGTRAP, a SIGCHLD signal is sent to the parent. Since the parent is being traced, it stops, as does the child. Deadlock.
If you add code to have the parent ignore SIGCHLD, the program runs as expected:
Child is traced
Child is tracing
Child stopped: 5
Stopsig status 5.
Child exiting...
Parent exiting...


text:
Q: Get a result of a column by comparing the condition with two other columns I am working on my project and new to R. I have a data frame like this
#   AwayTeam  HomeTeam  TeamWon
# 1     A        B      AwayTeam
# 2     C        A      AwayTeam
# 3     A        D       Draw
# 4     A        E      HomeTeam
# 5     F        A      HomeTeam

From this data set, I want to find the result of team A like this
#   AwayTeam  HomeTeam  TeamWon   Result_A
# 1     A        B      AwayTeam    Win
# 2     C        A      AwayTeam    Loss
# 3     A        D       Draw       Draw
# 4     A        E      HomeTeam    Loss
# 5     F        A      HomeTeam    Win

A: You can try using case_when from dplyr and specify the conditions.
library(dplyr)

df %>%
  mutate(Result_A = case_when(TeamWon == "Draw"~"Draw",
                              AwayTeam == "A" & TeamWon == "AwayTeam" |
                              HomeTeam == "A" & TeamWon == "HomeTeam"~"Win",
                              TRUE~"Loss"))

#  AwayTeam HomeTeam  TeamWon Result_A
#1        A        B AwayTeam      Win
#2        C        A AwayTeam     Loss
#3        A        D     Draw     Draw
#4        A        E HomeTeam     Loss
#5        F        A HomeTeam      Win

data
df <- structure(list(AwayTeam = structure(c(1L, 2L, 1L, 1L, 3L), .Label = c("A",
"C", "F"), class = "factor"), HomeTeam = structure(c(2L, 1L,
3L, 4L, 1L), .Label = c("A", "B", "D", "E"), class = "factor"),
TeamWon = structure(c(1L, 1L, 2L, 3L, 3L), .Label = c("AwayTeam",
"Draw", "HomeTeam"), class = "factor")), class = "data.frame",
row.names = c("1","2", "3", "4", "5"))

A: Beside using case_when you can go another way. In my opinion this simplifies the case_when statement. I used the pivot_longer function of tidyr to get which side the team is playing. Afterwards, I compare the side and the team which has won, where no team name has to be in the case_when statement.
library(tidyr)
library(dplyr)

data <- data.frame(AwayTeam = c("A", "C", "A", "A", "F"),
            HomeTeam = c("B"  ,"A"  ,"D"  ,"E"  ,"A"  ),
            TeamWon = c("AwayTeam" ,"AwayTeam" ,"Draw" ,"HomeTeam" ,"HomeTeam"))

data %>%
    mutate(matchNumber = row_number()) %>%
    pivot_longer(c(AwayTeam, HomeTeam), names_to = "SideOfTeam", values_to = "TeamName") %>%
    mutate(Result = case_when(TeamWon == SideOfTeam ~ "Won",
                        TeamWon == "Draw" ~ "Draw",
                        TeamWon != SideOfTeam ~ "Loss")) %>%
    filter(TeamName == "A")

I inserted the column matchname to be able to find the opponent afterwards if necessary.

A: To add the column of Result_A, you can use the following code
df$Result_A <- apply(df, 1,
                     function(v) ifelse(!is.na(v[v["TeamWon"]]) & v[v["TeamWon"]]=="A","Win",
                                               ifelse(v["TeamWon"]=="Draw","Draw","Loss")))


text:
Q: ERROR 1136: Column count doesn't match value count at row 1 - still happening Well although I was looking for the same questions in SO to find a solution there is nothing to solve my problem.
The problem is:
INSERT INTO `mydb`.`users` (`username`, `password`, `info_id`)
VALUES ('myname', '123456', 2)`

and I can't understand where is the problem.
The table looks like that: users(id, username, password, info_id) where the id is auto incremented.
Thank you in advance

A: Triggers can cause this kind of behaviour if the insert in the trigger is malfunctioning.


text:
Q: How to get the batch size inside lambda layer I'm trying to implement a layer (via lambda layer) which is doing the following numpy procedure:
def func(x, n):
    return np.concatenate((x[:, :n], np.tile(x[:, n:].mean(axis = 0), (x.shape[0], 1))), axis = 1)

I'm stuck because I don't know how to get the size of the first dimension of x (which is the batch size). The backend function int_shape(x) returns (None, ...).
So, if I know the batch_size, the corresponding Keras procedure would be:
def func(x, n):
    return K.concatenate([x[:, :n], K.tile(K.mean(x[:, n:], axis=0), [batch_size, 1])], axis = 1)

A: You should not use K.int_shape, but something like tf.shape, which will give you a dynamic shape.

New updates
Here is a solution without using tile
from keras.layers import *
from keras.models import *

# define the lambda layer
n = 5
MyConcat = Lambda(lambda x: K.concatenate([x[:,:n],
                                           K.ones_like(x[:,n:]) * K.mean(x[:,n:], axis=0)],
                                          axis=1))

# make a dummy testing model
x = Input(shape=(10,))
y = MyConcat(x)
mm = Model(inputs=x, outputs=y)

# test code
a = np.arange(40).reshape([-1,10])
print(a)

[[ 0  1  2  3  4  5  6  7  8  9]
   [10 11 12 13 14 15 16 17 18 19]
   [20 21 22 23 24 25 26 27 28 29]
   [30 31 32 33 34 35 36 37 38 39]]

b = mm.predict(a)
print(b)

[[ 0.  1.  2.  3.  4. 20. 21. 22. 23. 24.]
   [10. 11. 12. 13. 14. 20. 21. 22. 23. 24.]
   [20. 21. 22. 23. 24. 20. 21. 22. 23. 24.]
   [30. 31. 32. 33. 34. 20. 21. 22. 23. 24.]]

The last thing that wants to mention is --- in keras you are not allowed to change the batch-size within a layer, namely the output and input batch size of a layer MUST be the same.

A: Just as @pitfall says, the second argument of K.tile should be a tensor.
And according to the doc of keras backend, K.shape returns a tensor and K.int_shape returns a tuple of int or None entries. So the correct way is to use K.shape. Following is the MWE:
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
import numpy as np

batch_size = 8
op_len = ip_len = 10

def func(X):
    return K.tile(K.mean(X, axis=0, keepdims=True), (K.shape(X)[0], 1))

ip = Input((ip_len,))
lbd = Lambda(lambda x:func(x))(ip)

model = Model(ip, lbd)
model.summary()

model.compile('adam', loss='mse')

X = np.random.randn(batch_size*100, ip_len)
Y = np.random.randn(batch_size*100, op_len)
#no parameters to train!
#model.fit(X,Y,batch_size=batch_size)

#prediction
np_result = np.tile(np.mean(X[:batch_size], axis=0, keepdims=True),
                    (batch_size,1))
pred_result = model.predict(X[:batch_size])
print(np.allclose(np_result, pred_result))

A: Create a functor and give it the batch size at the initialization.
class SuperLoss:
    def __init__(self,batch_size):
        self.batch_size = batch_size
    def __call__(self,y_true,y_pred):
        self.batch_size ....