text:
Q: Leaflet-Image() and Leaflet.print() not working I'm trying to access a map webservice online. I want to export a map as a png ou jpg image.
I managed to display an online map with OSM. I followed instructions here. The next step is to save or export the map into an image.
I found this and this, and I tried both.
No need to say, it doesn't work. In fact I think the problem comes from me, I don't think I understood correctly how to use these functions.
Regarding Leaflet-Image(), I tried the following code :
leafletImage(map, function(err, canvas) {
// now you have canvas
// example thing to do with that canvas:
var img = document.createElement('img');
var dimensions = map.getSize();

console.log('dimensions :');
console.log(dimensions);

img.width = dimensions.x;
img.height = dimensions.y;
img.src = canvas.toDataURL();
document.getElementById('images').innerHTML = '';
document.getElementById('images').appendChild(img);});

An I got this error :
leaflet-image.js:87 Uncaught TypeError: layer._adjustTilePoint is not a function

The code seems strange to me. My goal is to export the map as an image, in the folder I wish. But I don't give a filepath or a filename...
Regarding leaflet.print(), I tried this :
var printProvider = L.print.provider({
method: 'GET',

outputFormat : '.png',
outputFilename: 'Desktop/carte',
autoLoad: true,
dpi: 90

});

var printControl = L.control.print({
   provider: printProvider
});
map.addControl(printControl);

Honestly, I'm completely lost here. So if anyone had an idea or could explain to me how this works, that would be a great help.

A: At the end, I managed to access the image using its online path (http//...). Depending on the source, it may lead to an access problem, but it works fine with the online mapping service and the provided key. I am not using leaflet at all.
Thanks for the help !


text:
Q: Get tabbarcontroller from another view on my storyboard In my Delegate i am trying to select my TabBarController so that i can style it with a different background. However the problem is that my TabBarController is not located on the rootView..
My current code:
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];

In my interface builder i have my TabBarController setup with a Segue name: mainView (This is where the TabBarController is located).
How could i select my TabBarController?

A: If you want to get it from ONE OF the VIEWS
//if Custom class
TabBarController *tabBar = (TabBarController *) self.tabBarController;

//if Custom class with Navigation Controller
TabBarController *tabBar = (TabBarController *) self.navigationController.tabBarController;

//if Not Subclassed
UITabBarController *tabBar = (UITabBarController *) self.tabBarController;

//if Not Subclassed with Navigation Controller
UITabBarController *tabBar = (UITabBarController *) self.navigationController.tabBarController;

A: First, you have to know in your view hierarchy where is your TabBarController. If it's not your root controller, Locate the UIViewController that are calling the TabBarController, and get it's reference by segue or something like it.
What might work for you, it's accessing the tabBarController property in the viewDidLoad of the first child UIViewController in a tab inside your tabViewController. All child ViewControllers of the tabBarController have this property.
For example, assuming first UIViewController displayed in the tabBar is MyViewController, perform something like this:
- (void)viewDidLoad
{
   UITabBar *tabBar = self.tabBarController.tabBar;
   UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
   UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# and null return value from SQL procedure I call SQL procedure (SQL Server 2008) from a C# service:
var retval = sqlCommand.Parameters.Add("@ret", SqlDbType.Int);
retval.Direction = ParameterDirection.ReturnValue;

SqlDataReader reader = null;
try
{
    try
    {
        reader = sqlCommand.ExecuteReader();
    }
    catch (Exception ex)
    {
        if (retval.Value != null && retval.Value != DBNull.Value && (int)retval.Value != 0)
        {
            var errorCode = (int)retval.Value;
            throw new ApiForwardingException(ex.Message, errorCode); //прокидываем пользователю
        }
        else throw; //не прокинется пользователю
    }

    //исключения не было, но код != 0
    if (retval.Value != null && (int)retval.Value != 0)
    {
        var errorCode = (int)retval.Value;
        if (getErrorCodeMessage) // получаем сообщения по коду и прокидываем его пользователю
        {
            var codes = GetErrorCodes();
            if (codes.ContainsKey(errorCode) == false)
                throw new Exception(
                    string.Format("Процедура {0} завершилась с кодом возврата {1}. Cообщение, соответствующее коду найти не удалось.",
                    sqlCommand.CommandText, errorCode)
                );
            else throw new ApiForwardingException(codes[errorCode], errorCode);
        }
        else
        {
            throw new Exception(string.Format("Процедура {0} завершилась с кодом возврата {1}.",
                sqlCommand.CommandText, (int)retval.Value));
        }

In most cases it works fine except one procedure. It returns error code inside try-catch block and my service gets null return value.
    begin try
        -- сохраняем задание
        insert into [IPAddressTask](
            , IPAddressTaskTypeId
            , TaskCreationDate
            , TaskStateID
        )
        select @TaskTypeId       as IPAddressTaskTypeId
            , @TaskCreationDate as TaskCreationDate
            , @ScheduledStateId as TaskStateID

        set @TaskId = scope_identity()

    end try
    begin catch
        return -1000
    end catch

If a call this procedure directly from SSMS and get its return value, it; all ok
declare @ret int
exec @ret = rsi.p_CreateIPAddressDeleteTask 1, 1, null, null, null
select @ret

---
-1000

I've changed return block in procedure from try-catch to an old-style
if (@@error <> 0) return -1000

It works fine, I get return value and can handle it. But I want to have universal solution, which can handle with any variant of setting return value in SQL
Update: forgot C# code handling not-zero ret-value

A: If possible change the catch block in the SP. Use raiseerror (or throw in SQL Server 2012++) in the catch block. If an error is caught in SQL your C# code will also catch the error.
BEGIN CATCH
    RAISERROR ('Error raised in TRY block.', -- Message text.
        16, -- Severity.
        1 -- State.
    );
END CATCH


text: Q: App Store Connect Export Compliance for StoreKit 1 and 2 I use both StoreKit 1 and 2 in my app where I use TPInAppReceipt (uses ASN1) to decrypt the App Store Receipt and StoreKit 2 uses JWS to verify purchases. Considering I would like to make my app available in France, do I have to fill out the ANSSI form as encryption is only used for local verification? Judging by the contents of the form, it seems to apply to encrypted transmission between devices.


text:
Q: DLL load failed in opencv with python I wish if anyone could give me a hand with my prob,
I have installed python 3.6 amd64 and add it to path then installed opencv 3.2 successfully using "pip" ... However, when I'm trying to import the cv2 (the library of opencv) and here is the error that I have got:
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ImportError: DLL load failed: The module specified is not found.

A: I'm guessing you've installed pip2(for python2) instead of pip3.(for python3)
Try this to install pip for python3
sudo apt-get install python3-pip

Now use
pip3 install python3-opencv

A: Make sure that cv2.pyd is in your Python's lib\site-packages\ directory.
Also check if OPENCV_DIR = C:\Program Files\OpenCV 3.2.0\x64\vc14, or similar, is in your Windows' system variables setting. The sample path OPENCV_DIR is for the binary compiled with VC14 which is Visual Studio 2015 VC++.


text:
Q: Add legend to a ggplot2 from empty plot I am creating a circular plot of correlations and I want to draw two type of information:

*

*A circle from -1 to 1 in both axis

*Add those correlations where the first component and the second component are different from 0 as arrows

*Add as dots those correlations having the first or the second component equal to 0

The colour used to draw each arrow/dot is integrated in the data.all all:

*

*1st column: X axis

*2nd column: Y axis

*3th column: feature (colour)

(UPDATED) What I code is:
## Colors for datasets
fColor <- c("yellow", "blue", "green", "red")
names(fColor) <- c("background", "isolation_p", "media", "solution")
## /

## Filters for 0s
f1 <- all[ , 1] != 0 & all[ , 2] != 0
f2 <- all[ , 1] == 0 | all[ , 2] == 0
## /

## Draw Circle
theta <- c(seq(-pi, pi, length = 50), seq(pi, -pi, length = 50))
circle <- data.frame(xcircle = cos(theta), ycircle = sin(theta))
p <- ggplot2::ggplot(data = circle, ggplot2::aes_string("xcircle", "ycircle")) +
  ggplot2::geom_path(ggplot2::aes_string("xcircle", "ycircle")) +
  ggplot2::geom_hline(yintercept = 0, linetype = "dashed") +
  ggplot2::geom_vline(xintercept = 0, linetype = "dashed")
## /

## Draw arrows
p <- p + ggplot2::geom_segment(data = all[f1, ],
   ggplot2::aes_string(x = 0, y = 0, xend = "x", yend = "y"),
   arrow = grid::arrow(length = grid::unit(0.2, "cm")),
   color = fColor[all$feature[f1]], linetype = "solid")
## /

## Draw points
p <- p + ggplot2::geom_point(data = all[f2, ],
   ggplot2::aes_string("x", "y"),
   color = fColor[all$feature[f2]], shape = 19, size = 2)
## /

## Add axis labels
p <- p + ggplot2::scale_y_continuous("First Component") +
  ggplot2::scale_x_continuous("Second Component")
## /

Now I want to add a legend for the colours used in the plots, but I am not capable of adding it. ¿Some ideas?
(UPDATE) What I would like to see into the legend is a red-bullet for solution, a green-bullet for media, a yellow-bullet for background and a blue-bullet for background (with the labels from feature, 3th column of all).
+info
(UPDATE) Fragment of my all data.frame:
all <- read.table(text = "x y   feature
yc01002711  -0.1755657  0.0000000000    background
yc02001111  0.0000000   -0.0006935916   background
yc03001287  0.0000000   -0.3966829792   background
yc04001667  0.0000000   -0.0575593341   background
xx00000091  -0.4205095  0.0000000000    isolation_p
xx00000092  0.0000000   -0.0085758016   isolation_p
sc78    0.03099176  -0.1425365  media
sc88    0.03897109  0.0000000   media
sc09    -0.05278946 0.0000000   media
inm10058    -0.05277376 0.0000000   solution
inm10099    -0.05286904 0.0000000   solution
inm10101    -0.08174610 -0.1315094  solution")

Example for the drawn plot:

A: when I run your code I don't get exactly the same figure you are showing but if you run this code I get the same figure I get when I run your code but with a legend as you wanted.
instead of using aes_string() I subset prior to plotting.
f2_s <- all[f2, ]
p <- p + geom_point(data = f2_s, aes(x, y, color=feature), shape = 19, size = 2)
p
p + scale_color_manual(values=c("yellow", "blue", "green", "red"))
p + scale_color_manual(values=c("yellow", "blue", "green", "red")) + scale_y_continuous("First Component") + scale_x_continuous("Second Component")


text:
Q: How to use run time downloaded localization arb/json file in flutter? I have read so many tutorials and blogs on flutter localization. They use arb/json file for localization from the assets folder or l10n folder. That is the fixed language list. Means if I use English localization and now at run time I want to provide Spanish/Chinese/Italian/French to the user then I have to put that localization arb/json file in the project and then user can use that language. So is there any way that I can download the localization file at run time and use it in the app? Is there any library available to do that?

A: I made a simple multilanguage Android app with GetX and Hive.
This project does the following tasks, it:

*

*toggles between different languages,

*installs new languages packages from external sources, and

*offers local data persistence.

After installing new language packages the app needs to restart for the changes to take effect.
The source code can be found here.
UPDATE August 7, 2021
A new version of this project was released here.

A: I used the flutter_i18n package on a Flutter project. It allows to retrieve translations from a remote source, thanks to the NetworkFileTranslationLoader class.
To use it, you need to add it to your localizationsDelegates as shown in the documentation. The example below shows how to load all translations files from the static directory on a remote server.
localizationsDelegates: [
        FlutterI18nDelegate(translationLoader:
          NetworkFileTranslationLoader(baseUri: Uri.https("example.com", "static")),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
],

A: All the default localization approaches via l10n or arb/json are not capable of runtime localizing. It is because they use InheritedWidget/BuildContext resolving of the localization - thus the assets bundle with resources should be prebuilt beforehand - as with fonts, images, etc(otherwise you will have an error Unable to load asset).
But what you want is possible. You will have to set up your own approach though. The easiest way to do it is to on app load download all the needed JSON localization files and store them in shared prefs(db/file system). Before entering each screen check current localization and retrieve the needed(language-wise) file, parse it and use it in your Text widgets.
Also, you can do it backends style - each request to the backend should contain locale query in its URL or locale field in body. It will retrieve not only values but also titles in key-value style like
some-get/data?locale=en
{
   "userName": {
       "key":"User name",
       "value": "John Dou"
   }
}

All the approaches of dynamic localization will need additional work both on the frontend(flutter) and backend.
I assume there are services already that provide some solutions for that(not flutter specific maybe) but quick googling was unsuccessful.


text:
Q: wp_insert_term doesn't want to enter its data into custom taxonomy so I'm working on a code to take data from an array and put it in a custom taxonomy using wp_insert_tem, but the data won't go in. this is the json i want to fetch, this is from a url
{
"genres": [
    {
      "name": "Military"
    },
    {
      "name": "Sci-fi"
    },
    {
      "name": "Shounen"
    }
  ],
}

this is the code i made
$result = file_get_contents($url);
$array = json_decode($result, true);
foreach($array['genres'] as $gen){
    wp_insert_term(
        $gen["name"],
        "genres",
        array(
            "description" => "",
            "slug" => sanitize_title($gen["name"]),
        ),
   );
}

please help me


text:
Q: Impossible to write a simple ~ tilde while using bash in codecademy i have a problem with the bash in Codecademy command line.
i'm a french speaker so my ~(tilde) is the same button as é, but i have a weird problem with that command; when i use alt + 2 it should make normaly a (~)tilde, but when i make it it gave me a 'é'... and while i do it twice it gave me that exact input 'éé~' is litteraly impossible for me to juste make a simple ~(tilde).
The weirdes thing is this problem is only valid for bash in CodeCademy and i have this problem since 2 days now.
somebody have an explication for that ?


text:
Q: returning ArrayList method java When I compile I don't get any errors but the ArrayList<File> from the method is not getting into the main.
All the entries got added into the Folders ArrayList but it doesn't get passed into the main method.
public static ArrayList<File> Process(File aFile)
 {
  ArrayList<File> Folders = new ArrayList<File>();

  if(aFile.isFile())
  {
     String filenom = aFile.getPath();
     if (filenom.toLowerCase().endsWith(".java")){
        Folders.add(aFile);
     }
  }
  else if (aFile.isDirectory()) {
     File[] listOfFiles = aFile.listFiles();
     if(listOfFiles!=null) {
        for (int i = 0; i < listOfFiles.length; i++)
           Process(listOfFiles[i]);
     }
     else {
        System.out.println(" [ACCESS DENIED]");
     }
  }
  return (Folders);
}

public static void main(String[] args) throws IOException
{
  ArrayList<File> FAddress = new ArrayList<File>();
  File dir = new File("C:/");
  FAddress = Process(dir);
     if (FAddress.isEmpty())
     System.out.println("WTF?!");
  else{
     for (File fl : FAddress) {
        String FileAddress = fl.getName();
        System.out.println(FileAddress);
     }
  }
}

A: The problem is with your recursion - you correctly identify if a File object is a directory, and call Process on it:
for (int i = 0; i < listOfFiles.length; i++)
    Process(listOfFiles[i]);

But you forgot to add its result to the return value (Folders), so any result from subdirectories won't be added to the return value:
for (int i = 0; i < listOfFiles.length; i++)
    Folders.addAll(Process(listOfFiles[i]));

A: You create
ArrayList<File> Folders = new ArrayList<File>();

in every time when run Process. This function have recursion, so because you start at C:/ folder you never update this array.
for correct processing you should use something like:
public static ArrayList<File> Process(File aFile) {
    ArrayList<File> Folders = new ArrayList<File>();
    Process(aFile, Folders);
    return folders;
}

private static void Process(File aFile, ArrayList<File> Folders) {
    ... //your implementation without defining Folders and returning it
}

this will be usefull if you need process many levels of tree for files.

A: You can define a class level variable static ArrayList<File> Folders = new ArrayList<File>(); and then use the same for populating files.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class test {
    static ArrayList<File> Folders = new ArrayList<File>();
    public static void Process(File aFile) {

        if (aFile.isFile()) {
            String filenom = aFile.getPath();
            if (filenom.toLowerCase().endsWith(".log")) {
                Folders.add(aFile);
            }
        } else if (aFile.isDirectory()) {
            File[] listOfFiles = aFile.listFiles();
            if (listOfFiles != null) {
                for (int i = 0; i < listOfFiles.length; i++)
                    Process(listOfFiles[i]);
            } else {
                System.out.println(" [ACCESS DENIED]");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        File dir = new File("C:/ukba/");
        Process(dir);
        if (Folders.isEmpty())
            System.out.println("WTF?!");
        else {
            for (File fl : Folders) {
                String FileAddress = fl.getName();
                System.out.println(FileAddress);
            }
        }
        Folders = null;
    }
}


text:
Q: Migrate my test utils from React Router V5 to V6 I am in the process of migrating my project to React V6 router but I have a problem in my test utility function. When I run my test all my expectation fails because jest can't see the object. Has anyone ever encountered this error during this migration or know what is going on?
Thank you in advance
My TestUtils file :
/* eslint-disable no-console */
import React, { ReactElement, ReactNode } from 'react'

import { render } from '@testing-library/react'
import { I18nextProvider } from 'react-i18next'
import { QueryClientProvider, setLogger, QueryClient } from 'react-query'
import { Route, MemoryRouter, Routes } from 'react-router-dom'
import { ToastContainer } from 'react-toastify'
import { ThemeProvider } from 'styled-components'

import bo from '../../themes/bo'

import i18n from '../../../i18n'

import '@testing-library/jest-dom'

setLogger({
     log: () => console.log,
     warn: () => console.warn,
     error: () => {
        // do nothing
     }
})
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retryDelay: 1,
            retry: 0
        }
    }
})

const AllTheProviders = ({ children, route, path }: { children?: ReactNode; route:
string; path: string }) => {
    return (
       <I18nextProvider i18n={i18n}>
            <QueryClientProvider client={queryClient}>
                <MemoryRouter initialEntries={[route]}>
                    <ThemeProvider theme={bo}>
                        <ToastContainer />
                        <Routes>
                            <Route path={path} element={() => children} />
                        </Routes>
                    </ThemeProvider>
                </MemoryRouter>
            </QueryClientProvider>
        </I18nextProvider>
    )
}

const customRender = (ui: ReactElement, { route = '/', path = '/' }: { route?:
string; path?: string } = {}) =>
    render(ui, { wrapper: (props) => <AllTheProviders {...props} route={route} path=.
{path} /> })

export * from '@testing-library/react'
export { customRender as render }

An example of insertion
 await expect(screen.findByTestId('Test#Element')).resolves.toHaveTextContent('test')
 expect(screen.queryByTestId('Test#Element')).not.toBeInTheDocument()

A: The Route component takes a React.ReactNode, a.k.a. JSX on the element prop. The AllTheProviders component is passing a function instead.
Pass children prop (typed as a ReactNode) directly to element.
interface AllTheProvidersProps {
  children?: ReactNode;
  route: string;
  path: string
}

const AllTheProviders = ({ children, route, path }: AllTheProvidersProps) => {
  return (
    <I18nextProvider i18n={i18n}>
      <QueryClientProvider client={queryClient}>
        <MemoryRouter initialEntries={[route]}>
          <ThemeProvider theme={bo}>
            <ToastContainer />
            <Routes>
              <Route path={path} element={children} />
            </Routes>
          </ThemeProvider>
        </MemoryRouter>
      </QueryClientProvider>
    </I18nextProvider>
  );
};


text:
Q: iPad Frame scroll issue I am trying to display a PDF in an iframe..So there are 2 frames and the bottom frame has the pdf. It is coded as;
<frame src="ebook.pdf" title="Content Frame" name="content" id="content" frameborder="0" border="0" noresize scrolling="yes" marginwidth="0" marginheight="0" noresizescrolling="AUTO" framespacing="0" />

For some reason, I am unable to scroll through the PDF in iPad Safari...More specifically within the iframe..
Is this a PDF issue or is it an iframe issue?
I have tried the using the  instead of frame..Still does not work..
Please help.
Thank you.

A: Heres a link to an iframe that doesnt scroll on the ipad:
I have to redesign all my pages in iWeb now since the iPad won't scroll iFrames made with iWeb on my iPad. I get quite a few hits from people using iOS.

A: When you insert the <iframe> into a <div> with height specification and set overflow-y to scroll (maybe auto i did'nt try) you can scroll using two fingers on iPad. It has no effect on pc browsers.

A: Scrolling within frames is a tricky UX thing with the iPad -- try scrolling with two fingers.  I don't know about PDFs, but that's how scrolling is done for other frames in Safari.

A: Use (iOS App) Opera Mini browser instead, when clicking on a pdf in Opera Mini it induces Safari to open the PDF in a non-frame mode. Weird I know but it works.


text:
Q: Assigning field inside javascript class from ajax I have code like this:
class Korisnik
{
    constructor(korisnikId)
    {
        this.KORISNIKID = korisnikId;
        this.IME = "";
        this.UNIQUE_KEY = "";

        this.Initialize();
    }

    Initialize(kid)
    {
        $.ajax({
           type: "POST",
           url: "../Php/Korisnik_Get.php",
           data: {"korisnikId" : this.KORISNIKID},
           success: function(result)
           {
               var arr = result.split('|');
               this.IME = arr[0];
               this.UNIQUE_KEY = arr[1];
           }
        });
    }

    get naziv()
    {
        alert("IME: " + this.IME); //Undefined
        return this.IME;
    }
}

I initialize this class as let myClass = new Korisnik(1);
When I try to get naziv() It returns nothing. I have tested it and when I alert this.IME from inside success code it has value but outside it doesn't. I have read and tried from this question but anything from there is not working for some reason. What to do?

A: Js getters aren't functions, so you need to access it as myClass.naziv
The other problem you have is that your success function isn't running in the same scope as the rest of your function.
You can use a fat-arrow function to ensure you have the right scope.
       success: result =>
       {
           var arr = result.split('|');
           this.IME = arr[0];
           this.UNIQUE_KEY = arr[1];
       }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get


text:
Q: REST API test cucumber steps best practice Trying to write up cucumber feature steps for REST API test.
I am not sure which approach is better:
Given I log in with username and password
When I add one "tv" into my cart
And I check my cart
Then I should see the item "tv" is in my cart

or
Given the client authenticate with username and password
When the client send POST to "/cart/add" with body "{item: body}"
Then the response code should be "200"
And the response body should expect "{success: true}"
When the client send GET to "/cart"
Then the response code should be "200"
And the response body should expect "{"items": ["tv"]}"

Is there any convention to follow when people trying to write cucumber steps for REST API?

A: Here's a (close enough) example to what the Pragmatic Programmer's "the Cucumber Book" says about testing REST APIs via Cuke,and it seems to more closely relate to your second example:
Feature: Addresses
  In order to complete the information on the place
  I need an address

Scenario: Addresses
  Given the system knows about the following addresses:
   [INSERT TABLE HERE or GRAB FROM DATABASE]
  When client requests GET /addresses
  Then the response should be JSON:
  """
    [
     {"venue": "foo", "address": "bar"},
     { more stuff }
    ]
  """
STEP DEFINITION:

Given(/^the system knows about the following addresses:$/) do |addresses|
# table is a Cucumber::Ast::Table
  File.open('addresses.json', 'w') do |io|
    io.write(addresses.hashes.to_json)
  end
end

When(/^client requests GET (.*)$/) do |path|
   @last_response = HTTParty.get('local host url goes here' + path)
end

Then /^the response should be JSON:$/ do |json|
   JSON.parse(@last_response.body).should == JSON.parse(json)
end
ENV File:

require File.join(File.dirname(__FILE__), '..', '..', 'address_app')
require 'rack/test'
require 'json'
require 'sinatra'
require 'cucumber'
require 'httparty'
require 'childprocess'
require 'timeout'

server = ChildProcess.build("rackup", "--port", "9000")
server.start
Timeout.timeout(3) do
  loop do
    begin
      HTTParty.get('local host here')
      break
    rescue Errno::ECONNREFUSED => try_again
      sleep 0.1
    end
  end
end

at_exit do
  server.stop
end

A: I've been using cucumber to test and more importantly to document the API that I created using rails-api in my current project. I looked around for some tools to use and I ended up using a combination of cucumber-api-steps and json_spec. It worked well for me.
There is no convention on how to write the cucumber steps. The way you write your steps depends on how you want to use your cucumber suite. I used the cucumber output as the reference for our Angular JS client devs to implement the API client. So my cucumber steps contained the actual JSON requests and responses along with the status code for each scenario. This made it really easy to communicate with a client side team whenever something changed ( especially when the client side team was not physically present at my workplace ).
Everytime I would create or update an API, the CI server would run cucumber as part of the build and move the HTML formatted output to a "build_artifacts" location that can be opened in the browser. The client side devs would always get the most recent reference that way.
I've written all of this down in a blog post about creating a tested, documented and versioned JSON API, hope it helps you in some way.

A: One of Cucumber's original intents, which contributes to its design, is to bridge the gap between technical implementation, and people who know the business needs, so that the test descriptions could be written and/or understood by non-developers. As such, it's not a great fit to detailed technical specs, or blow-by-blow unit testing.
So that would point me to your first test description, if that's also the reason you are using Cucumber.
There is no major problem with implementing tests like the second version, Cucumber can support it.  There probably are not a large number of statement types you would need to parse either. But you could end up fighting the test framework a little, or going against your rationale for using Cucumber in the first place.
As for a convention, I am not aware of enough REST API tests in practice to comment, and none that I have seen tested have used Cucumber as the framework.
Update: Browsing around SO on the subject, I did find a link to this: https://github.com/jayzes/cucumber-api-steps which is more similar to your second format.

A: There are a few libraries now for server side REST testing with cucumber in Ruby. Here's a couple:

*

*Cucumber-API-Steps. (Recommended)

*Cucumber-API. A small tutorial for that is here.

The library I've been using for server side REST testing with cucumber is Cucumber-API-Steps.
Cucumber-API-Steps
Here's how I'd write your test using 'cucumber-api-steps' (Recommended):
@success
Scenario: Successfully add to cart
  Given I am logged in
  When I send a POST request to "/cart/add" with the following:
       | item | body |
  Then the response status should be "200"
  And the JSON response should have "success" with the text "true"
  When I send a GET request to "/cart"
  Then the response status should be "200"
  And the JSON response should be "{'items': ['tv']}"

And here's what my tests look like using 'cucumber-api-steps':
@success
Scenario: Successfully log in
  Given I am logged out
  When I send a POST request to "/login" with:
       | username | katie@gmail.com |
       | password | mypassword |
  Then the response status should be "200"
  And the JSON response should have "firstName" with the text "Katie"

Cucumber-API
Here's how I'd write your test using 'cucumber-api':
@success
Scenario: Successfully add to cart
  Given I am logged in
  When I send a POST request to "/cart/add"
       And I set JSON request body to '{item: body}'
  Then the response status should be "200"
  And the response should have key "success" with value "true"
  When I send a GET request to "/cart"
  Then the response status should be "200"
  And the response should follow "{'items': ['tv']}"

And here's what my tests look like using 'cucumber-api':
@success
Scenario: Successfully log in
  Given I am logged out
  When I send a POST request to "/login" with:
       | username | katie@gmail.com |
       | password | mypassword |
  Then the response status should be "200"
  And the response should have key "firstName"

*

*Note about Cucumber-API: There is no way currently to do should have key "firstName" with value "Katie". The "with value" part has not been done yet.

*Also "Follow" expects a JSON file

Another resource is here, but it is old (2011).

A: I just stumbled on this helpful article: https://www.gregbeech.com/2014/01/19/effective-api-testing-with-cucumber/
To summarize...
Scenario: List fruit
  Given the system knows about the following fruit:
    | name       | color  |
    | banana     | yellow |
    | strawberry | red    |
  When the client requests a list of fruit
  Then the response is a list containing 2 fruits
  And one fruit has the following attributes:
    | attribute | type   | value  |
    | name      | String | banana |
    | color     | String | yellow |
  And one fruit has the following attributes:
    | attribute | type   | value      |
    | name      | String | strawberry |
    | color     | String | red        |

Validating a result against JSON is tricky business because if the result is an array, the elements may not be the same order as how you are validating in the test.
Edit: Updated link using finderAUT's comment. Thanks!

A: I would recommend your first scenario.
From my own experiences I personally feel that the biggest value you get from using BDD as a software delivery method, is when you place the emphasis on business value.
In other words the scenarios should be examples of what behaviour the business wants, rather than technical implementation. This ensures that the development is driven by the goals of the business and the deliverables match their expectations.
This is known as outside-in development.
Additional tests of the system behaviour can and should be used to cover the technical requirements but I think there's less value in spending effort writing these up in natural language, which is often time consuming and laborious across a large number of scenarios.
I recommend the following approach:
1) Work with the BAs and POs to develop examples of the behaviour they want using non-implementation specific language (like your first example).
2) Engineers use these to drive the development from a test first approach, automating them as integration tests - with the majority below the browser (against your REST API for example) and the most core scenarios also through the browser(if you are developing one).
3) Engineers TDD the feature code with unit tests until both the unit tests and BDD examples pass.

A: I think the first one is better. I would put the technical in the ruby classes and modules. E.g like module cart.add(items) in the when step and in the then step put expect(cart.item).to include('items' => a_string_matching(item))
By this, the ruby classes and modules can be reuse in another features steps. E.g like maybe you have another scenario which would add multiple items into the cart then validate the total amount.
However, the second 1 I think can make it like technical features. E.g like common/global header or body request is expected across all the api.

A: See here: https://github.com/ctco/cukes-rest. It provides a Cucumber DSL to test RESTful APIs.


text:
Q: How to test a custom global exception page for azure ad b2c? I am using custom policies and I have defined the location of the custom exception page as follows:
<ContentDefinition Id="api.error">
        <LoadUri>https://{Settings:BlobStorageAccount}.blob.core.windows.net/{Settings:BlobContainer}/html/global_exception.html</LoadUri>
        <RecoveryUri>~/common/default_page_error.html</RecoveryUri>
        <DataUri>urn:com:microsoft:aad:b2c:elements:contract:globalexception:1.2.0</DataUri>
        <Metadata>
          <Item Key="DisplayName">Error page</Item>
        </Metadata>
      </ContentDefinition>

However, how do you go about triggering an internal API exception within Azure AD B2C to see this page in action? I tried also using a default user policy and adjust the location but there doesn't seem to be a way to view the page that way as well.

A: You can set the client_id parameter in the authorization request to an unknown value where this should display the error page with the following text:
AADB2C90018: The client id '<client_id>' specified in the request is not registered in tenant '<your_tenant_name>.onmicrosoft.com'.


text:
Q: Randomly throwing darts at a dartboard I have $x$ darts that I randomly throw on a dartboard with $y$ slots (the v shaped slices like you get when you cut a cake).
Now I select a particular slice on the dartboard . What's the probability that no dart would have hit that slice?

A: I assume the whole board is made out of perfectly the same slices and there is no center neutral zone.
Example for y=20
We have 19/20 chances to not hit a dead slice with one dart. With two darts (19/20)^2
So for y darts it would be:
((y-1)/y)^x


text:
Q: ISBN-10 Checker in Python I'm using this example ISBN: 0199160503
I know it's not great at the moment, but for not, I just want it to work.
I've checked the calculations over and over, and CheckDigit10 DOES equal CheckingCheckDigit at the final part (hence the overuse of print statements...), and yet it still comes out as an invalid ISBN.
Can someone please help? I'm not too advanced at coding, so it could be a super simple error that I'm not seeing.
print("You will be asked to enter an ISBN-10 Number. Please enter it digit by digit.")

ISBN10NumberList = []
ISBN10NumberAdder = 0
for count in range (10):
    if (count <= 8):
        ISBN10NumberList.append(int(input("Please enter the ISBN digit: ")))
    elif (count == 9):
        CheckDigit10 = input("Please enter the ISBN digit: ")
        print("CheckDigit: ", CheckDigit10)
        if CheckDigit10 == "X" or CheckDigit10 == "x":
            CheckDigit10 = 10
            print("CheckDigit: ", CheckDigit10)

for count in range (0, 9):
    ISBN10NumberAdder += int(ISBN10NumberList[count]) * (10 - count)
    print(ISBN10NumberAdder)

CheckingCheckDigit = ISBN10NumberAdder % 11
print("CheckingCheckDigit after mod 11:",CheckingCheckDigit)

CheckingCheckDigit = 11 - CheckingCheckDigit
print("CheckingCheckDigit final:",CheckingCheckDigit)
print("CheckDigit: ", CheckDigit10)

if (CheckDigit10 == CheckingCheckDigit):
    print("This is a valid ISBN!")
else:
    print("This is not a valid ISBN!")


text:
Q: Get data in Azure ML directly from SQL Server I currently have a pipeline in Azure machine learning that's taking in data from the datastore and then training a model on it. In order to get the data into the datastore to begin with I have to manually add it from the SQL Server by using their UI.
My question is, is there a way to automate the process of retrieving the data from a SQL Server into an Azure ML pipeline, or at least into the datastore?

A: Go to Azure ML studio and click a datastore and provide required details .

Go to Data and register the data assert .Please follow below Steps:
Step 1:

Step 2:

Step 3:

Step 4:

Visualize the data in workflow


text:
Q: Exoplayer2 OutOfMemoryError exeption and app crash in my play console, i am getting this crash report how can I deal with it?
here is the crash report.

java.lang.OutOfMemoryError:     at
  android.media.AudioTrack.getTimestamp (AudioTrack.java:1396)    at
  com.google.android.exoplayer2.audio.AudioTrack$AudioTrackUtilV19.updateTimestamp
  (AudioTrack.java)       at
  com.google.android.exoplayer2.audio.AudioTrack.maybeSampleSyncParams
  (AudioTrack.java)       at
  com.google.android.exoplayer2.audio.AudioTrack.getCurrentPositionUs
  (AudioTrack.java)       at
  com.google.android.exoplayer2.audio.MediaCodecAudioRenderer.getPositionUs
  (MediaCodecAudioRenderer.java)      at
  com.google.android.exoplayer2.ExoPlayerImplInternal.updatePlaybackPositions
  (ExoPlayerImplInternal.java)    at
  com.google.android.exoplayer2.ExoPlayerImplInternal.doSomeWork
  (ExoPlayerImplInternal.java)    at
  com.google.android.exoplayer2.ExoPlayerImplInternal.handleMessage
  (ExoPlayerImplInternal.java)    at android.os.Handler.dispatchMessage
  (Handler.java:98)       at android.os.Looper.loop (Looper.java:154)     at
  android.os.HandlerThread.run (HandlerThread.java:61)

A: USE Exoplayer newest version library and check player different video may be problem is in your video codec.


text:
Q: are there any methods/hooks to force JVM to run Finalization? System.gc() is suggests way to run GC and so does System.runFinalization();
but the use Jmap to do heap dump, it will force to do GC/full GC.
so my question is: are there any tools/methods/hooks just like Jmap heap dump that can be used to force execute runFinalization?
I'd like to describe my situation a little bit more:
my heap size won't decrease after a certain time and when I do a head dump I can see that:
1:       6793014      271720560  java.lang.ref.Finalizer
2:       7251647      232052704  java.util.HashMap$Node
3:       6791349      162992376  XX.WP<--- which has override finalize method
so I assumed that it could be caused by finalize method and I'd like give it a quick verification by force execute runFinalization.


text:
Q: Is the facebook php sdk 3.2.3 still useable? Is the facebook php sdk 3.2.3 still useable? Because it seems like the very basic examples are not working anymore.
I've tried to look for an official statement, but could not find one.
I'm using the example from: https://developers.facebook.com/docs/php/gettingstarted/3.2.3
I've seen the note at the top, that says:

This document refers to an outdated version of PHP SDK. Please use the latest version.

...but "please use" sounds not like you have to...right?

A: Yes, you can still use it - after all it uses CURL calls like the PHP SDK 4. Although it is recommended to use the latest SDK. My personal opinion is that you should not use any PHP SDK at all for smaller projects. User the JS SDK for authorization and API calls and custom PHP CURL calls for stuff that needs to happen on the server.
Bonus: You don´t need PHP5.4+ for your own CURL calls.


text:
Q: how to change tableView Cell button on click in iphone I have table view with custom cell and it has button i want that when user click on that button then the image of button should be changes any idea how to do this becuase i want that cellImage button image to be changed in another method.
    [cell.theSyncButton addTarget:self action:@selector(syncButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.theSyncButton setTag:indexPath.row];

method:
-(IBAction)syncButtonAction:(id)sender{
    //   I want to change the cell.SyncButton image here
}

any idea how to do this.

A: [btnSync setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
[btnSync setImage:[UIImage imageNamed:@"refresh-active.png"] forState:UIControlStateHighlighted];

A: -(IBAction)syncButtonAction:(id)sender{
    UIButton *btn = (UIButton *)sender;
   [btn setImage:img forState:UIControlStateSelected];
}

A: try this..
-(IBAction)syncButtonAction:(id)sender
{
    UIButton * syncButton = (UIButton *) sender;
    [syncButton setBackgroundImage: <NormalImage.png>
                          forState: UIControlStateNormal];
    [syncButton setBackgroundImage: <HighlightedImage.png
                          forState: UIControlStateHighlighted];
}

A: Instead of all that code you have all you have to do is:
  UIImage *img = [UIImage imageNamed:@"yourImage.png"];
  [cell.theSyncButton setImage:img forState:UIControlStateSelected];

A: Here is my solution:
 i use UIImageVIew as button
for example , the starIcon is an UIImageView ,which i add into my custom UITableViewCell as button.
and ArticleCell is my custom UITableViewCell class.
in UITableView dataSource method cellForRowAtIndexPath:
ArticleCell* cell = [tableView dequeueReusableCellWithIdentifier:@"reused"];
if (cell==nil) {
    NSLog(@"init tableViewCell");
    cell = [[ArticleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reused"];
    UITapGestureRecognizer* gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(buttonCallback:)];
    gesture.numberOfTapsRequired=1;
    gesture.numberOfTouchesRequired=1;
    [cell.starIcon addGestureRecognizer:gesture];
    cell.starIcon.userInteractionEnabled=YES;
    NSLog(@"init tableViewCell end");
}

make sure you set userInteractionEnabled == true;
then , in your buttonCallback method ,you can get UIimageView by
    -(void)buttonCallback:(UIGestureRecognizer*)gestureRecognizer{
       UIImageView* star = (UIImageView*)[gestureRecognizer view];
    }

so , you can change your imageView.

A: -(IBAction)syncButtonAction:(id)sender{
        [button setImage:[UIImage imageNamed:@"yourimage.png"] forState:UIControlStateNormal];

}


text:
Q: Is there a regex pattern that can change different values based on different matches in python I am appending a column in data-frame column name  = 'Name' which is a string comprising of a few different columns concatenation.
Now, I want to replace certain characters with certain values. Lets say
& -> and
< -> less than

-> greater than
' -> this is an apostrophe
" -> this is a double quotation

Now how can I efficiently apply this regex on entire column. Also, Can I put it in certain function as I need to apply the same in 4 other columns as well.
I tried this
df = pd.DataFrame({'A': ['bat<', 'foo>', 'bait&'],
                   'B': ['abc', 'bar', 'xyz']})
df.replace({'A': r'<','A':r'>','A':r'&'}, {'A': 'less than','A': 'greater than','A': 'and'}, regex=True, inplace=True)

I am expecting this
         A    B
0     batless than  abc
1     foogreater than  bar
2  baitand  xyz

But this happened.
         A    B
0     bat<  abc
1     foo>  bar
2  baitand  xyz

A: One can use pandas.DataFrame.apply with a custom lambda function, using pandas.Series.str.replace as follows
regex = r'(<|>|&)'

df_new = df.apply(lambda x: x.str.replace(regex, lambda m: 'less than' if m.group(1) == '<' else 'greater than' if m.group(1) == '>' else 'and', regex=True))

[Out]:

                 A    B
0     batless than  abc
1  foogreater than  bar
2          baitand  xyz

A: Your replacement dict has three keys named A so all but the last is being overwritten. Use a nested dict instead to make multiple replacements to one column:
df.replace({'A': {r'<': 'less than', r'>': 'greater than', r'&': 'and'}}, regex=True, inplace=True)

See pandas.DataFrame.replace

A: You can use a dictionary for the mapping, but it has to look like this:
mapping = {'<': 'less than', '>': 'greater than', '&': 'and'}

Then you can compile the keys into a regex and proceed similar to Gonçalo Peres's answer:
df.apply(lambda col: col.str.replace("|".join(mapping),
                                     lambda match: mapping.get(match.group())))


text:
Q: socket.io and pm2 : how does version number in node.js works? when I run
node -v

I got 4.2.1 which is very strange since I remember I worked with 0.10 versions: I am totally lost with nodejs versions
reading the pm2 doc

Warning: If you want to use the embedded load balancer (cluster mode),
  we recommend the use of node#0.12.0+ or node#0.11.16+. We do not
  support node#0.10.*'s cluster module anymore.

*

*I don't understand how node.js versions works: looks like we jumped form 0.10
to 4.2

*Does pm2 works with latest version of node.js ?

regards

A:
don't understand how node.js versions works: looks like we jumped form 0.10 to 4.2

When io.js and node.js merged, then node.js jump directly to 4.x series. This happened due to difference in versions of io.js (3.x series) and node.js (0.x series). So next common version was named 4.x series and this lead to some confusion. See this announcement.

Does pm2 works with latest version of node.js ?

You can give it a try yourself, but IMO it should work well.

A: At the end of 2014, node was forked into io.js for reasons I won't cover here.
The io.js project adopted the semver notation and, as the pace of changes was very fast (we got all the recent advances of ES6 that were already available in V8), came to version 3.
In september 2015, io.js was merged back into node, and it was decided to keep the semver versionning, and to go to version 4. More details here, including the LTS.
This makes it possible to deal with a monotonous version order, thus a 4.0 version of node is greater than a 0.11 version. But be wary, many changes were introduced and the ecosystem is big. You'll probably have changes to do when going from 0.x to a new version, especially if you use many modules.


text:
Q: Low validation accuracy in parallel DenseNet I've taken the code from https://github.com/flyyufelix/cnn_finetune and remodeled it so that there is now two DenseNet-121 in parallel, with the layers after each model's last Global Average Pooled removed.
Both models were joined together like this:
print("Begin model 1")
    model = densenet121_model(img_rows=img_rows, img_cols=img_cols, color_type=channel, num_classes=num_classes)
    print("Begin model 2")
    model2 = densenet121_nw_model(img_rows=img_rows, img_cols=img_cols, color_type=channel, num_classes=num_classes)

    mergedOut = Add()([model.output,model2.output])
    #mergedOut = Flatten()(mergedOut)
    mergedOut = Dense(num_classes, name='cmb_fc6')(mergedOut)
    mergedOut = Activation('softmax', name='cmb_prob')(mergedOut)

    newModel = Model([model.input,model2.input], mergedOut)

    adam = Adam(lr=1e-3, decay=1e-6, amsgrad=True)
    newModel.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['accuracy'])

    # Start Fine-tuning
    newModel.fit([X_train,X_train], Y_train,
              batch_size=batch_size,
              nb_epoch=nb_epoch,
              shuffle=True,
              verbose=1,
              validation_data=([X_valid,X_valid],Y_valid)
              )

The first model has its layers frozen, and the one in parallel is suppose to learn additional features on top of the first model to supposedly improve accuracy.
However, even at 100 epochs,
the training accuracy is almost 100% but validation floats around 9%.
I'm not quite sure what could be the reason and how to fix it, considering I've already changed the optimizer from SGD (same concept, 2 densenets with the first trained on ImageNet, the second has no weights to begin with same results) to Adam (2 densenets, both pre-trained on imagenet).
Epoch 101/1000
1000/1000 [==============================] - 1678s 2s/step - loss: 0.0550 - acc: 0.9820 - val_loss: 12.9906 - val_acc: 0.0900
Epoch 102/1000
1000/1000 [==============================] - 1703s 2s/step - loss: 0.0567 - acc: 0.9880 - val_loss: 12.9804 - val_acc: 0.1100


text:
Q: Как последовательно отвечать на вопросы в тесте? Ниже представлен фрагмент api сервиса тестирования, пользователь отвечает на вопросы.

Отправив post запрос с нужными параметрами по маршруту api/edu_service/test-result/create/ я могу создать результат решения теста ну то есть отправить ответы на вопросы теста, как сделать возможным отвечать не на все вопросы сразу, а последовательно, при этом валидировать каждый ответ и выводить комментарий в response ? Погуглив пока напрашивается решение создания еще одной модели в БД (допустим UserAnswer) которая будет хранить ответ на каждый конкретный вопрос, тогда вопрос как на их основе создать объект Test_Result. И как дополнить стандартный response своим комментарием ?
Есть модель результат теста (Test_Result), которая состоит из следующих полей:
class Test_Result(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    result = models.CharField(verbose_name='Результат', max_length=300)

    class Meta:
        verbose_name = 'Результат'
        verbose_name_plural = 'Результаты'
        ordering = ['id']

    def __str__(self):
        return self.user.username

Есть сериализатор который вычисляет значение поля result при создании объекта. По ключу username передаётся имя пользователя, по ключу testId - id теста в БД, по ключу answers передаются ответы пользователя на вопросы теста - ответы на все вопросы передаются единоразово то есть все вместе. Как сделать возможным отвечать последовательно на каждый вопрос т.е. дописывать значения в поле answers, при этом нужно проверять является ли ответ верным и выводить комментарий если не верно.
class TestResultSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(many=False)

    class Meta:
        model = Test_Result
        fields = ('__all__')

    def create(self, request):
        data = request.data
        print(data)

        test = Test.objects.get(id=data['testId'])
        user = User.objects.get(username=data['username'])

        test_result = Test_Result()
        test_result.test = test
        test_result.user = user

        questions = [q for q in test.questions.all()]
        answers = [data['answers'][a] for a in range(len(data['answers']))]

        answered_correct_count = 0
        for i in range(len(questions)):
            answers_for_question = questions[i].answers.all()
            num_right = questions[i].num_right
            right_answer = []
            if num_right == len([answers[i]]):
                for j in answers_for_question:
                    if j.right:
                        right_answer.append(j)
                if right_answer.sort() == [answers[i]].sort():
                    answered_correct_count += 1

        result = answered_correct_count / len(questions) * 100
        test_result.result = str(result)
        test_result.save()
        return test_result

Вот представление которое связывает сериализатор с моделью
class TestResultsCreateView(CreateAPIView):
    serializer_class = TestResultSerializer
    queryset = Test_Result.objects.all()
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        print(request.data)
        serializer = TestResultSerializer(data=request.data)
        serializer.is_valid()
        test_result = serializer.create(request)
        if test_result:
            return Response(status=HTTP_201_CREATED)
        return Response(status=HTTP_400_BAD_REQUEST)


text:
Q: Display IOException into Primefaces Messages I am trying to display IOException into Primefaces messages but the text is not formated properly

In my code I catch the exception:
} catch (Exception ex) {
      System.out.println(ex);
      msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, null,ex.toString());
      facesGetCurrentInstance(msg);
}

Then add the message:
public void facesGetCurrentInstance(FacesMessage msg) {
    FacesContext.getCurrentInstance().addMessage(null, msg);
 }

In the XHTML I am using growl to display the message
<p:growl id="messages" showDetail="true" sticky="true" autoUpdate="true"   />

Thus far everything works, but I am having an issue with how the message is getting displayed. I am assuming this because I am using .toString. So, is there another way to do this?

A: try this:
FacesContext.getCurrentInstance().addMessage(FacesMessage.SEVERITY_ERROR,exception.getMessage());


text:
Q: Converting POJO to SOLR query Is there any way to convert the POJO to SOLR query.
class Sample{
@Field("id")
String id;
@Field("name")
String name;
.
.
.
}

Is there any way to convert the above pojo to SOLR query
Example : id:"123" AND name:"qwerty"
Thanks in advance

A: Spring Data With Solr Maybe??
You may find these of some help:

*

*http://docs.spring.io/spring-data/solr/docs/current/reference/html/

*http://projects.spring.io/spring-data-solr/

A: There is none: you will need to write your own, taking care of escaping etc.


text:
Q: Fabric.js geometric shapes I want to use different geometric shapes (like hexagon, star...) apart from Rect, Triangle, Ellipse.What else can I do? How can I do?
var canvas = new fabric.Canvas('c');
var rect = new fabric.Rect({
  left: 50,
  top: 50,
  fill: 'green',
  width: 40,
  height: 80
});
var circle = new fabric.Circle({
  radius: 20,
  fill: 'red',
  left: 100,
  top: 100
});

A:
You can build any polygon (hexagon,star,etc) using a Fabric.Polygon.
var myPoly = new fabric.Polygon(points, {
    stroke: 'red',
    left: 50,
    top: 50,
    strokeWidth: 2,
    strokeLineJoin: 'bevil'
},false);
canvas.add(myPoly);

You can calculate the vertex points of any regular polygon with your desired side count like this:
// get the vertices of a hexagon with a radius of 30
var points=regularPolygonPoints(6,30);

function regularPolygonPoints(sideCount,radius){
    var sweep=Math.PI*2/sideCount;
    var cx=radius;
    var cy=radius;
    var points=[];
    for(var i=0;i<sideCount;i++){
        var x=cx+radius*Math.cos(i*sweep);
        var y=cy+radius*Math.sin(i*sweep);
        points.push({x:x,y:y});
    }
    return(points);
}

You can calculate the vertex points of any star with your desired spike count like this:
// get the vertices of a hexagon with a radius of 30
var points=starPolygonPoints(5,50,25);

function starPolygonPoints(spikeCount, outerRadius, innerRadius) {
  var rot = Math.PI / 2 * 3;
  var cx = outerRadius;
  var cy = outerRadius;
  var sweep = Math.PI / spikeCount;
  var points = [];
  var angle = 0;

  for (var i = 0; i < spikeCount; i++) {
    var x = cx + Math.cos(angle) * outerRadius;
    var y = cy + Math.sin(angle) * outerRadius;
    points.push({x: x, y: y});
    angle += sweep;

    x = cx + Math.cos(angle) * innerRadius;
    y = cy + Math.sin(angle) * innerRadius;
    points.push({x: x, y: y});
    angle += sweep
  }
  return (points);
}

So, in general, for any geometric shape you desire, you must calculate the vertices and feed those vertices into a Fabric.Polygon
Here's example code and a Demo:

// create a wrapper around native canvas element (with id="c")
var canvas = new fabric.Canvas('canvas');

// make a hexagon
var points=regularPolygonPoints(6,30);

var myPoly = new fabric.Polygon(points, {
  stroke: 'red',
  left: 10,
  top: 10,
  strokeWidth: 2,
  strokeLineJoin: 'bevil'
},false);
canvas.add(myPoly);

// make a star
var points=starPolygonPoints(5,50,25);

var myStar = new fabric.Polygon(points, {
  stroke: 'red',
  left: 100,
  top: 10,
  strokeWidth: 2,
  strokeLineJoin: 'bevil'
},false);
canvas.add(myStar);

function regularPolygonPoints(sideCount,radius){
  var sweep=Math.PI*2/sideCount;
  var cx=radius;
  var cy=radius;
  var points=[];
  for(var i=0;i<sideCount;i++){
    var x=cx+radius*Math.cos(i*sweep);
    var y=cy+radius*Math.sin(i*sweep);
    points.push({x:x,y:y});
  }
  return(points);
}

function starPolygonPoints(spikeCount, outerRadius, innerRadius) {
  var rot = Math.PI / 2 * 3;
  var cx = outerRadius;
  var cy = outerRadius;
  var sweep = Math.PI / spikeCount;
  var points = [];
  var angle = 0;

  for (var i = 0; i < spikeCount; i++) {
    var x = cx + Math.cos(angle) * outerRadius;
    var y = cy + Math.sin(angle) * outerRadius;
    points.push({x: x, y: y});
    angle += sweep;

    x = cx + Math.cos(angle) * innerRadius;
    y = cy + Math.sin(angle) * innerRadius;
    points.push({x: x, y: y});
    angle += sweep
  }
  return (points);
}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="canvas" width=300 height=300></canvas>

A: You can do it with the Polygon function:
var pol = new fabric.Polygon([
  {x: 200, y: 0},
  {x: 250, y: 50},
  {x: 250, y: 100},
  {x: 150, y: 100},
  {x: 150, y: 50} ], {
    left: 250,
    top: 150,
    angle: 0,
    fill: 'green'
  }
);

For more complex shapes you should load SVGs


text:
Q: Can't access computer because keyboard doesn't work in GRUB I just used mainline to install the latest kernel on Ubuntu 22.10 on an HP Envy x360. I rebooted, and now it's stuck at GRUB because I can't do anything with the keyboard. I can't boot from a USB either.
When I start up, it shows these screens and gets stuck at the last one. Please help, I literally just bought this computer.

Edit: OK, I was able to get into my computer by using an external keyboard and am now installing Ubuntu 22.04. Still curious why the internal keyboard didn't work.
Edit2: And I realize now that the internal keyboard never worked in the boot menu from the first time I went to install Ubuntu and even now. I've been using the touch screen. But for the above screen, the touch screen was not working either.
The boot menu automatically starts with onscreen touch buttons for the required F and arrow keys, so maybe HP knows the keyboard doesn't work.

A: You installed an unsigned mainline kernel with enabled Secure Boot. That's why it is not booting.
You should be able to boot from a LiveUSB. It is not related to the installed OS.


text:
Q: iPhone - parsing nsdata to get multiple files stored there I'm trying to find the new line and returns that are inside an nsdata object that I'm parsing .  Here's some code:
    uint8_t *arr = [receivedData bytes];
    NSUInteger begin1 = 0;
    NSUInteger end1 = len;
    uint8_t *arr1 = (Byte *)malloc(sizeof(Byte)*((end1-begin1+1)));
    int j = 0;
    for (int i = begin1; i < end1; i++){
        arr1[j] = arr[i];
        j++;
        if (arr[i] == 10) NSLog(@"---new line code---");  //edit: working - data was a problem
    }

I just need to know when I hit a new line or return.
Thank You.

A: That certainly looks correct.  Are you certain that the data you're parsing has newlines?  Could it be a /r instead of a /n?  If you can, try using the debugger and step through to see what the values actually are, and compare with what you expect them to be, to make sure they are correct.


text:
Q: Use multiple texture when rendering cause low framerate I tried use different to render the ground of a game. First, I create some texture and upload to GPU.
void initialize(float width,float height)
{
    for(int i = 0;i < 10;i++)
    {
        glActiveTexture(GL_TEXTURE1 + i);
        GLuint gridTexture;
        glGenTextures(1, &gridTexture);
        glBindTexture(GL_TEXTURE_2D, gridTexture);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        setPngTexture(gameMap->texture);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
}

Then I use the textures when render in every frame.
void render() const
{
   for(int i = 0; i < map -> maps.size();i++)
   {
      glUniform1i(uniforms.Sampler,i);
      glBindBuffer(GL_ARRAY_BUFFER, gameMap -> verticesbuffer);
      glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, stride, 0);
      glVertexAttribPointer(normal, 3, GL_FLOAT, GL_FALSE, stride, offset);
      glVertexAttribPointer(texture, 2, GL_FLOAT, GL_FALSE, stride, texCoordOffset);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gameMap -> indicesbuffer);
      glDrawElements(GL_TRIANGLES, gameMap -> indexCount, GL_UNSIGNED_SHORT, 0);
   }

}

The code work properly on iPhone simulator, but when I testing the app on device, it gives me a very low framerate : 2fps. If I change the line  glUniform1i(uniforms.Sampler,i); to  glUniform1i(uniforms.Sampler,0); the app work fine!
I'm a freshman on OpenGL ES and I'm not sure I use multiple texture in a correct way. Who can kindly tell me what's the reason of this problem and how can I correct it? Thanks a lot!

A: there are many things that could be wrong with this. You don't provide enough code to really diagnose the issue (shader source). I'd start with moving the glUniform1i(uniforms.Sampler,i); outside of your loop. It makes no sense the way your are currently using it (basically you're trying to bind uniforms.Sampler to the nth value inside your shader for map.size(). I'm pretty sure this is throwing tons of OpenGL errors. Re-read the documentation on glUniform1i


text:
Q: Binding to object not property While using a converter, I want to bind to the entire object and send it to the converter to use, rather than binding to each of the individual properties, so I can do this:
Order thisOrder = (Order)values[0];

(note, its a multibinding, other values are being sent in besides the thisOrder object. Now the Order class implements the INotifyPropertyChanged interface, and raised the appropriate events when any of its properties are changed. The converter needs access to multiple properties of the Order, although it actually only needs to rerun on changes to one of the properties. Is there any way to either bind to the entire object so that if any of the properties change, the converter is evaluated again, or bind to only one property, but have the rest of the object also available as a parameter for the converter to work on?

Example Details:
  Order has following fields:

*

*ID

*MarketPrice

*Name

  When MarketPrice changes, the converter needs to recalculate based on
  ID and MarketPrice.
  Presently, the binding is applied on the DataRecordCellArea of a xamDataGrid, as follows:

<MultiBinding Converter="{StaticResource MarketPositionToBrushConverter}">
     <Binding RelativeSource="{RelativeSource Self}" Path="Record.DataItem"/>
...
</MultiBinding>

A: As far as i know there currently is no clean solution to this. I would suggest you add two bindings, one to the Order object so you have access to all the values and another to the MarketPrice so that the binding updates if that property changes. You then have access to the object and all properties via the first binding and you get the respective updates.
The is another method which is quite a hack, you can subscribe to PropertyChanged in the class owning the Order instance and then fire a change notification for the Order instance property whenever the MarketPrice in the instance changes. I would avoid doing this but it would allow you to get rid of the second binding.


text:
Q: What's Julia's equivalent of R's seq(..., length.out = n) I can see from this link that R's equivalent of seq is n:m in (http://www.johnmyleswhite.com/notebook/2012/04/09/comparing-julia-and-rs-vocabularies/).
But the case of seq(a,b, length.out = n) is not covered.
For example seq(1, 6, length.out=3) gives c(1.0, 3.5, 6.0). It is a really nice way to specify the number of outputs.
What's its equivalent in Julia?

A: As of Julia 1.0:
linspace has been deprecated. You can still use range:
julia> range(0, stop = 5, length = 3)
0.0:2.5:5.0

As @TasosPapastylianou noted, if you want this to be a vector of values, you can use collect:
julia> collect( range(0, stop = 5, length = 3) )
3-element Array{Float64,1}:
0.0
2.5
5.0

A: You are looking for the linspace function. Note this is synonymous to the equivalent function in matlab / octave.
Also note that this returns a "steprange" type object:
julia> a = linspace(1,5,9)
1.0:0.5:5.0

julia> typeof(a)
StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}

julia> collect(a)
9-element Array{Float64,1}:
 1.0
 1.5
 2.0
 2.5
 3.0
 3.5
 4.0
 4.5
 5.0

PS: similarly, there exists a range function which is equivalent to the start:step:stop syntax, similar to the seq(from=, to=, by=) syntax in R.


text:
Q: How to map some data to the data fetched from API before showing it on screen? I am new to React Native. I am trying to make an app of my own to try out the different things that I learnt and also get to know new things and one such thing that I came across and is giving me a hard time is the following issue:
I have an API which gives me certain data about an item. The properties of the item are listed in the API like "sizeofitem" , "nameofitem" or "itemacategory". Now there are multiple items for different items and not all properties are present in each item. What I was trying to achieve is to somehow map these properties in the following manner:
If let's say "sizeofitem", should become "Size of Item", "nameofitem" should become "Name of Item". Now these properties are different of all the items so for example, sizeofitem might be in one item detail list but might not be in another, but I have all the properties that are can be there. Can someone help me how to do this?
Till now I have the following:
const [itemDtl , setItemDtl] = useState([]);

const getItemInfo = async (id) => {
        try{
            const response = await api.get(`myAPI/${id}`);
            setItemDtl(response.data.obj.itemutils);

        }catch(err){
            console.log(err);
        }
    }
let arr = [];
for(let i in itemDtl){

   arr.push(itemDtl[i].util_type);
}
console.log(arr);

useEffect(() => {
    getItemInfo(id);
})

arr array has whatever the properties where listed for the item in the API i.e. [sizeofitem, nameofitem , etc].
I want an array to have [Size of Item, Name of Item , etc].
Basically just, to sum up, I want to rename the list of properties that can be there for when whatever property comes up is then stored in an array with the mapped string I have given, so for example if an item has 'sizeofitem : 50', I want it to be stored as  "Size of item"  so that I can show that on the screen. And there are like a total of 5 properties that can exist for an item so I can code it somewhere maybe like sizeofitem : 'Size Of Item' so that when sizeofitem property is top be shown on the screen I can use this and show Size of Item on the screen.

A: try this:
const [itemDtl , setItemDtl] = useState([]);

const getItemInfo = async (id) => {
        try{
            const response = await api.get(`myAPI/${id}`);
            let arr = [];
            for(let i in itemDtl){
              arr.push(itemDtl[i].util_type);
            }
            setItemDtl(arr);

        }catch(err){
            console.log(err);
        }
    }

useEffect(() => {
    getItemInfo(id);
})


text:
Q: pyodbc session error when django project is downloaded from gitlab i have a django project which works fine when not uploaded
i have uploaded it to gitlab with following command:
1. git clone ssh://git@gitlab****dcms-api.git
2. git checkout dcms_sso
3.git add .

then i took the same code from git lab:
1. git clone ssh://git@gitlab****dcms-api.git
2. git checkout dcms_sso

just changed the application name in manifest file.
when i tried to run it throws following error:
File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
self.connect()
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect
ERR     self.connection = self.get_new_connection(conn_params)
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/sql_server/pyodbc/base.py", line 307, in get_new_connection
  ERR     timeout=timeout)
ERR pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")
ERR The above exception was the direct cause of the following exception:
ERR Traceback (most recent call last):
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner
ERR     response = get_response(request)
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__
ERR     response = self.process_response(request, response)
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response
ERR     request.session.save()
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 81, in save
ERR     return self.create()
ERR   File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 51, in create
 ERR     self._session_key = self._get_new_session_key()

please let me know if more log to be uploaded or if my backend.py should be uploaded

A: error was with .profile file while uploading it to cloudfoundry. Worked after copying the .profile file


text:
Q: How to work out rampup period in jmeter I had got stats from log which stated that on avg we have peak load of 3000 logons in 1 hour.
How do I work out the rampup period for jmeter to replicate the same behaviour in 1 hour or 30 mins or 2hr duration

A: It is not about the ramp-up period, it is more about limiting the rate of requests which are being sent by JMeter to certain rate. So you should be looking at Constant Throughput Timer in order to limit JMeter's throughput to the desired rate.
For example,

*

*If you want 3000 logins per hour it stands for 50 logins per minute add Constant Throughput Timer as a child of the "Login" request and configure it as follows:

*

*Target Throughput: 50.0

*Calculate Throughput based on: all active threads

*Similarly if you want 3000 logins in 30 minutes - Throughput should be 2x times higher: 100.0 samples per minute

*And finally if you want 3000 logins in 2 hours - the Throughput should be 2x times lower: 25.0 samples per minute

You might also be interested in Throughput Shaping Timer, it acts similar to the Constant Throughput Timer but it is more precise when it comes to periods lesser than 1 minute and you can also create "Load Profiles" with it. You can install Throughput Shaping Timer using JMeter Plugins Manager.


text:
Q: How to append a git repository on top of another I am in the process of converting a project from TFS to git, and I want to keep all history.
The problem is that the TFS project was moved in TFS one year ago.
Using git-tfs I can convert both locations to git, but now I have two git repositories: A and B.
I have managed to get both A and B into the same repository as different branches. Would it be possible to change the parent of first commit in B to the last commit in A?
Branch A: a -> b -> c
Branch B: d -> e -> f

I want to have
a -> b -> c -> d' -> e' -> f'

Solution:
git filter-branch --parent-filter 'sed "s/^\$/-p <last-commit-in-A>/"' HEAD_OF_B

A: Sure, set a graft, that does exactly that. If you are satisfied with the result you can do a filter-branch to make this permanently. Or you can use filter-branch right away with a --parent-filter.

A: I can think of two solutions:

*

*Create a parent repository and add repositories A and B as submodules. You can learn more about this by reading the documentation for git submodule.

*Add repository B as a remote to repository A:
$ git remote add repoB <directory where repo B is located>

Now you can fetch, pull, merge, and rebase from repo B, for example:
$ git checkout master
$ git pull repoB master

(If it makes more sense, you can do this the other way around: add repo A as a remote to repo B. The same concepts apply.)


text:
Q: how to sum time and handle null value using case in sql server i want the result in single row, GROUP BY sys_service_id,stat.---------------
SELECT sys_service_id,
  CASE WHEN stat='Idle' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end  AS 'Idle',

  CASE WHEN stat='Long Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else ''  end  AS 'Long Halt',

  CASE WHEN stat='Short Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end AS 'Short Halt',

  CASE WHEN stat='Running' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end AS 'Running'
  FROM testing1 GROUP BY sys_service_id,stat

but, this given result as follows:-
sys_service_id  Idle           Long Halt         Short Halt     Running
2823    00:33:12.0000000    00:00:00.0000000 00:00:00.0000000   00:00:00.0000000
2823    00:00:00.0000000    10:56:19.0000000 00:00:00.0000000   00:00:00.0000000
2823    00:00:00.0000000    00:00:00.0000000 00:00:00.0000000   01:03:13.0000000
2823    00:00:00.0000000    00:00:00.0000000 00:18:48.0000000   00:00:00.0000000

i want as :-
sys_service_id  Idle           Long Halt         Short Halt     Running
2823    00:33:12.0000000    10:56:19.0000000 00:18:48.0000000   01:03:13.0000000

A: A simple MAX clause can give you the desired results
SELECT
  sys_service_id,
  MAX(CASE WHEN stat='Idle' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else NULL end)  AS 'Idle',

  MAX(CASE WHEN stat='Long Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else NULL  end ) AS 'Long Halt',

  MAX(CASE WHEN stat='Short Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else NULL end) AS 'Short Halt',

  MAX(CASE WHEN stat='Running' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else NULL end) AS 'Running'

  FROM testing1
GROUP BY sys_service_id,stat

A: First, don't include Stat in your group by clause, because you want a single record for multiple values of it.
Second, wrap your cases with a MAX function :
SELECT sys_service_id,
       MAX(CASE WHEN stat='Idle' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end)  AS 'Idle',
       MAX(CASE WHEN stat='Long Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else ''  end)  AS 'Long Halt',
       MAX(CASE WHEN stat='Short Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end) AS 'Short Halt',
       MAX(CASE WHEN stat='Running' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end) AS 'Running'
FROM testing1
GROUP BY sys_service_id

EDIT:
SELECT t.sys_service_id,
       MAX(t.Idle),
       ...
FROM(
    SELECT sys_service_id,
           CASE WHEN stat='Idle' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end)  AS 'Idle',
           CASE WHEN stat='Long Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else ''  end)  AS 'Long Halt',
           CASE WHEN stat='Short Halt' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end) AS 'Short Halt',
           CASE WHEN stat='Running' THEN cast(dateadd(millisecond,sum(datediff(millisecond,0,cast(trip_leg as datetime))),0) as time) else '' end) AS 'Running'
    FROM testing1
    GROUP BY sys_service_id,stat) t
GROUP BY t.sys_service_id

A: You want conditional aggregation.  Move the case inside the sum() . . . and remove stat from the group by:
SELECT sys_service_id,
       cast(dateadd(millisecond,
                    sum(datediff(millisecond, 0,
                                 cast(case when stat = 'Idle' then trip_leg end as datetime)
                                )
                       ),
                       0) as time
           ) as Idle,

       cast(dateadd(millisecond,
                    sum(datediff(millisecond, 0,
                                 cast(case when stat = 'Long Halt' then trip_leg end as datetime)
                                )
                       ),
                    0) as time
           ) as [Long Halt],

       cast(dateadd(millisecond,
                    sum(datediff(millisecond, 0,
                                 cast(case when stat = 'Short Halt' then trip_leg end as datetime)
                                )
                       ),
                    0) as time
           ) as [Short Halt],

       cast(dateadd(millisecond,
                    sum(datediff(millisecond, 0,
                                 cast(case when stat = 'Running' then trip_leg end as datetime)
                                )
                       ),
                    0) as time
           ) as Running
FROM testing1
GROUP BY sys_service_id;


text:
Q: Re-upload: Can someone check the addresssanitizer result? I ran AFL fuzzer to open source program and I ran the program with the output crash from the fuzzing.
This is the result of address sanitizer but I am not sure what this error actually is.
ubuntu@ifn657:~/fuzz3/dact-0.8.42$ ./dact -dcf output/crashes/id:000023,sig:06,src:000013,time:312754,op:flip1,pos:20
=================================================================
==4163826==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7f321f8fe80b at pc 0x000000495900 bp 0x7ffebce27520 sp 0x7ffebce26ce8
WRITE of size 747621 at 0x7f321f8fe80b thread T0
    #0 0x4958ff in __asan_memcpy (/home/ubuntu/fuzz3/dact-0.8.42/dact+0x4958ff)
    #1 0x4ce218 in comp_plain_algo /home/ubuntu/fuzz3/dact-0.8.42/comp_plain.c
    #2 0x4cc623 in dact_blk_decompress /home/ubuntu/fuzz3/dact-0.8.42/dact_common.c:176:9
    #3 0x4cc623 in dact_process_file /home/ubuntu/fuzz3/dact-0.8.42/dact_common.c:658:20
    #4 0x4d4fc1 in main /home/ubuntu/fuzz3/dact-0.8.42/dact.c:689:8
    #5 0x7f322262a0b2 in __libc_start_main /build/glibc-YYA7BZ/glibc-2.31/csu/../csu/libc-start.c:308:16
    #6 0x41e50d in _start (/home/ubuntu/fuzz3/dact-0.8.42/dact+0x41e50d)

0x7f321f8fe80b is located 0 bytes to the right of 524299-byte region [0x7f321f87e800,0x7f321f8fe80b)
allocated by thread T0 here:
    #0 0x49640d in malloc (/home/ubuntu/fuzz3/dact-0.8.42/dact+0x49640d)
    #1 0x4cbda1 in dact_process_file /home/ubuntu/fuzz3/dact-0.8.42/dact_common.c:581:17
    #2 0x4d4fc1 in main /home/ubuntu/fuzz3/dact-0.8.42/dact.c:689:8
    #3 0x7f322262a0b2 in __libc_start_main /build/glibc-YYA7BZ/glibc-2.31/csu/../csu/libc-start.c:308:16

SUMMARY: AddressSanitizer: heap-buffer-overflow (/home/ubuntu/fuzz3/dact-0.8.42/dact+0x4958ff) in __asan_memcpy
Shadow bytes around the buggy address:
  0x0fe6c3f17cb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe6c3f17cc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe6c3f17cd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe6c3f17ce0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe6c3f17cf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x0fe6c3f17d00: 00[03]fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0fe6c3f17d10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0fe6c3f17d20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0fe6c3f17d30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0fe6c3f17d40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x0fe6c3f17d50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==4163826==ABORTING

And where do I have to look in?
Do I have to look in main function of dact.c?


text:
Q: How to set the PATH in .profile or .bash_profile in ubuntu I have a script which uses jmeter. Now, instead of giving the path in the script like sh /home/ubuntu/apache-jmeter-3.0/bin/jmeter.sh -n -t fileName.jmx in the script I just want to give sh jmeter.sh -n -t fileName.jmx in the script. So, I want to set up the PATH of the jmeter in ubuntu. I didn't understand how to do it. Can some one help.
Path to my jmeter is: /home/ubuntu/apache-jmeter-3.0

A: Add the directory /home/ubuntu/apache-jmeter-3.0/bin to your path:
export PATH="$PATH":/home/ubuntu/apache-jmeter-3.0/bin

Then you can use it directly:
jmeter.sh -n -t fileName.jmx

To make it permanent, add the new PATH declaration to your ~/.bashrc.


text:
Q: JSON If Statement Not Working I'm not use to coding in JSON so I don't know what I'm doing wrong. Basically, what I'm trying to achieve is that there is a variable for a web hook that basically says "alert type = 1" means website is up, and "alert type =2" means website is down.
I'm trying to create a webhook JSON code to send a different message if the alert type is set to either 1 or 2. Please help me in understanding what I'm doing wrong.
Here is the code I've got so far;
{.if (* alertType *) = "2"
}
Our Website is Offline {.if
}


text:
Q: Manhua: Cultivator emerges or reincarnates after a long time of absence Couple months ago I remember reading a cultivation manga at my usual site, Mangabat, and now I have no idea what the title was.
Characters:
The main character is a young looking male who is quite reluctant (laidback) to do anything that is requested of him. He is supposedly extremely powerful and friend and/or master to a sect master who looks like a dwarf (short, beard) but actually isn't a dwarf. The dwarf looking sect master is really worried that the mc might get angry and just destroy the whole sect in one go.
Main character is know for his temper. If he get's angry then most of the time someone or everyone who made him angry is going to die.
Sect master provided him with a advisor who informs him about the sect rules.
Most memorable scenes:
Dwarf looking sect master wishes him to become successor for the next sect master (to avoid someone else getting it?), mc is quite reluctant but ultimately accepts his request. Advisor now and then tells him to attend this and that while following the rules to get the successor position. Later it is planned that someone else steps up and takes the position because mc doesnt want it.
I remember the mc sitting in something akin to a beach chair in the sect master's garden and drinking alcohol with the advisor next to him.
General information:
I'm quite sure that this manga was actually a manhua (chinese production).
What it isn't:
(This will get filled as I get suggestions and rule out manga.)

A: The answer is: Above All Gods. Thank somebody for the answer.
From Anime-Planet:

The ancient Sirius of the Red King, the capital of the Demon Lord, was besieged by everyone, jealous of heaven, besieged in Chiyan Ridge, judged by heaven, deprived of the foundation of the fairy path, the throne of the magic path, and died However, the ancient Sirius was born 500 years later with a mysterious ancient jade! The enemies of the last life, the revenge of this life, the shame of the last life, the snow of this life! I am an ancient Sirius, and I speak for myself ...


text:
Q: Basis of the subspace of $\mathbb R^4$ Find a basis of the subspace of R4 consisiting of all vectors of the form:
$$\begin{bmatrix}x_1\\
6 x_1 + x_2\\
4 x_1 + 5 x_2\\
8 x_1 - 9 x_2\end{bmatrix}$$
Now, I really have no clue how to set this up in order to find a basis. Maybe because of the way it's set up?
Any hints on how to proceed?

A: Hint: you can split up this vector as the sum of two vectors:
$$
\left[\begin{array}{c}x_1 \\ 6x_1+x_2\\ 4x_1+5x_2\\ 8x_1-9x_2\end{array}\right]=\left[\begin{array}{c}x_1 \\ 6x_1\\ 4x_1\\ 8x_1\end{array}\right]+\left[\begin{array}{c}0\\ x_2\\ 5x_2\\ -9x_2\end{array}\right]
$$
Each of these vectors only depends on one parameter.  Do you see what the basis should be now?
To see why the original format makes sense, think about the following $4\times 2$ matrix:
$$
A=\left[\begin{array}{cc} 1 & 0\\6 & 1\\4&5\\8&-9\end{array}\right]
$$If you multiply $A$ by the column vector $[x_1,x_2]^T$, you'll get exactly the original vector.  Thus by finding the basis for this set, you're essentially characterizing the range of the linear transformation from $\Bbb{R}^2$ to $\Bbb{R}^4$ defined by the matrix $A$.

A: {(1,6,4,8),(0,1,5,-9)} are inedpendence and gnerate this space so they can be basis of space
independence is clear
they generate space since:
$(x_{1},6x_{1}+x_{2}, 4x_{1}+5x_{2},8x_{1}-9x_{2})=x_{1}(1,6,4,8)+x_{2}(0,1,5,-9)$

A: Another approach: observe the generic vector depends only of two variables, so set once $\,x_1=1\;,\;\;x_2=0\,$ , and then set $\,x_10\;,\;\;x_2=1\,$ , and the two vectors you obtain will automatically be linearly independent and a basis of the wanted vector subspace (why? Can you see the wanted subspace is of dimension $\,2\,$ ?)


text:
Q: How to scrape from a Jquery table using Python I am trying to scrape the first ten items from this website. I am using Python Selenium/BeautifulSoup. It seems the table is loading using some jquery script. I am honestly stumped where to start as the tutorials and guides aren't matching up with this website.
EX: A lot of them are saying check the Network tab in inspect element to find the XHR data. This website however doesn't have anything worth value load in the XHR tab but rather in the JS tab. I found the request URl https://www.anime-planet.com/dist/3p/jquery.min.js?t=1657108207 but it doesn't seem to do me any justice.
Am I overthinking things and should scrape from the html directly? Any advice would be very appreciated.

A: Here is a solution based on pandas & requests:
import requests
import pandas as pd

headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'
}

url = 'https://www.anime-planet.com/manga/top-manga/week'

r = requests.get(url, headers=headers)
df = pd.read_html(r.text)[0]
print(df[:10])

Result printed in terminal:

Rank
Title
Year
StatusEpsRating

0
1
The Beginning After the End
2018
Unread Reading Want to Read Stalled Dropped Won't Read

1
2
Damn Reincarnation
2022
Unread Reading Want to Read Stalled Dropped Won't Read

2
3
One Piece
1997
Unread Reading Want to Read Stalled Dropped Won't Read

3
4
Omniscient Reader
2020
Unread Reading Want to Read Stalled Dropped Won't Read

4
5
The Swordmaster's Son
2022
Unread Reading Want to Read Stalled Dropped Won't Read

5
6
My School Life Pretending To Be a Worthless Person
2022
Unread Reading Want to Read Stalled Dropped Won't Read

6
7
Player Who Returned 10,000 Years Later
2022
Unread Reading Want to Read Stalled Dropped Won't Read

7
8
Jujutsu Kaisen
2018
Unread Reading Want to Read Stalled Dropped Won't Read

8
9
Grim Reaper's Floating Moon
2022
Unread Reading Want to Read Stalled Dropped Won't Read

9
10
Villains Are Destined to Die
2020
Unread Reading Want to Read Stalled Dropped Won't Read

Relevant pandas docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html
And for requests: https://requests.readthedocs.io/en/latest/

A: This table is NOT loaded from jQuery. It is server-rendered and easily scrapable. You only need requests and beautifulsoup; Selenium is unnecessary.
With some quick DOM inspection, this should be pretty simple. You can do something like this:
import requests
from bs4 import BeautifulSoup

# send HTTP request to page and parse
page = requests.get('https://www.anime-planet.com/manga/top-manga/week')
soup = BeautifulSoup(page.text, 'html.parser')

top_ten = []
count = 0

for link in soup.select('td.tableTitle > a.tooltip'):
  if count == 10:
    break
  top_ten.append(link.getText())
  count += 1

print(top_ten)


text:
Q: How can I append to a file in grub 2.06? I'm building a simple operating system (github.com/aarikpokras/aarikos). I searched the entire internet and I can't seem to find a single effective method to append to a file! For some reason, when I try something like echo "content" >> /file, it says that there's some syntax error. I tried the same with cat, but it didn't help either. Any help is appreciated. Thanks.

A: grub has very limited write support. Usually it just writes into a single sector, see the save_env (docs) command which writes into a pre-populated sector. There is also a lack of shell redirection, which is the reason for the failure.


text:
Q: How to make .jar file from custom java class in android-studio for use other project I create my android application in android-studio it's work well.
In my project has my custom 3 class "ClassA.java", "ClassB.java" and "ClassC.java"
I want to convert 3 class to 1 java libary file(.jar) for use in another project.
How can i do it's? Please let me know step by step.

A: You can create a Java only gradle project.

*

*Create a new directory elsewhere.

*Create a build.gradle file there and don't apply the android plugin, just apply "java".

*Create src/main/java directory structure and move your code there.

*Add any needed dependencies to the build file.

*"./gradle build" will create your jar,

*You can publish the jar to an artifact repo (locally or to someplace like jCenter) using a plugin such as gradle-mvn-push

*Then any project that needs your 3 classes can add a maven or gradle dependency.

If your classes depend on Android you will want to make an "aar" instead of a jar.


text:
Q: Combining 2 projects within same workspace I have to combine 2 separated projects in same workspace in XCode.
I want to navigate project 1 to project 2 when button click.
Can anyone guide me the best way?

A: drag your project in parent project, like any other file and just set proper search Paths in parent build setting for child project, where you pasted the project. then try to build. it should work. If something went wrong, means you are not setting right paths.


text:
Q: Change native code calling convention on ARM (VS2012) I'm working on a project on windows phone 8 and I'm calling static functions by pointers, but without the type of the parameters (I have the number of parameters and a function type that has int or float as parameters).
I've checked this thread What is the Windows RT on ARM native code calling convention?
And I've also looked at the assembly and it seems it treats differently floats from int (floats passed in S0).
Well my question, is there any way to force some functions (or even all) to be called the old fashion ?

A: OK, I'm going to clarify things by pretending you asked the underlying question:

How can I call a (void *)(float) function when I only have a genericised (void *)(int) pointer to it?

Jumping directly to asking how to change the calling convention sounds like this:

How can I make one implementation's undefined behaviour behave like another implementation's undefined behaviour, because I've written a ton of code that relies on this and don't want to have to fix it?

First, let's see what the C standard says...

If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

Yup, there's the problem. Sad face :(
But wait, what's that the previous sentence says?

A pointer to a function of one type may be converted to a pointer to a function of another
  type and back again; the result shall compare equal to the original pointer

Hooray, we can do it in a well-defined way without resorting to shims and assembly hacks, simply by converting back to the proper function signature when we call!
In short; cast the function pointer, not the arguments, and not only will it work, it will be correct. Since you must know the true signature of the function you're calling (else you couldn't pass the appropriate arguments), you can always make the correct cast, and the intermediate pointer type becomes a non-issue.
Here's a demonstration:

#include <stdio.h>

void fn(float x){
    printf("%.1f\n", x);
}

int main(void) {
    float f = 27.3;
    void (*fptr)(float) = fn;
    void (*iptr)(int) = fn;     /* LA LA COMPILER WARNING I CAN'T HEAR YOU */

    printf("expected:\t");
    fptr(f);
    printf("casting arg:\t");
    iptr(*(int *)&f);           /* double-undefined behaviour */
    printf("casting iptr:\t");
    ((void(*)(float))iptr)(f);
}

Note that *(int *)&f is itself undefined, but in this case (VS2013) the "expected" code (float used as int without conversion) does get generated in both builds. Hey, it's a valid form of undefined behaviour (as is anything else...)
And the output:
expected:       27.3
casting arg:    27.3
casting iptr:   27.3
Press any key to continue . . .

Huh? Why bother? Both methods "work". Let's try the x64 build...
expected:       27.3
casting arg:    0.0
casting iptr:   27.3
Press any key to continue . . .

Ah. There it is. In fact, if you'd written the original code on any of the other 3 currently-supported Windows platforms you wouldn't have this problem, because it wouldn't have worked in the first place - x86-64, IA-64 and ARM all use register-based calling conventions with floats and ints handled separately, whilst x86 is the stack-based anachronism.
Or, if you really really really want a portable attempt at exploiting undefined behaviour, try rewriting all the functions to take a load of dummy ints and floats before the real arguments, and a similar load of ints and floats afterwards, to ensure the ones in the middle get spilled to the stack regardless of evaluation order. Yes, that would be insane...


text:
Q: Get content from subpages using HTML Agility Pack for WP8 I've managed to parse HTML (content) from a newssite (ryfylke.net) and displayed it in my WP8-app. But how can i parse content from subpages (the "Read more" links)?
For now, when I click the links the app launches IE and displays the actual site. But what I would like to do is parse the content from the site and display it in the app.
EDIT (This is my current MainPage.xaml.cs)
        protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        string htmlPage = "";
        using (var client = new HttpClient())
        {
            htmlPage = await client.GetStringAsync("http://ryfylke.net/kategori/nyheter/");
        }

        HtmlDocument htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(htmlPage);

        List<Nyheter> nyheter = new List<Nyheter>();
        foreach (var div in htmlDocument.DocumentNode.SelectNodes("//article[starts-with(@class, 'post-')]"))
        {
            Nyheter newNyheter = new Nyheter();
            newNyheter.Link = div.SelectSingleNode(".//a[@href]").Attributes["href"].Value;
            newNyheter.Bilde = div.SelectSingleNode(".//img[@class='attachment-entry-medium wp-post-image']").Attributes["src"].Value;
            newNyheter.Tittel = div.SelectSingleNode(".//h2[@class='entry-title entry-small-title']").InnerText.Trim();
            newNyheter.Sammendrag = div.SelectSingleNode(".//p[@class='entry-excerpt']").InnerText.Trim();
            nyheter.Add(newNyheter);
        }
        lstNyheter.ItemsSource = nyheter;
    }

And I then use public strings like this to use the content...
public string Bilde { get; set; }