text:
Q: How to handle `process.env` in client-side javascript files when running E2E tests in Cypress? Embarrassingly, this problem has been holding me up for days, and I must, must get on with my task for work, so I'm reaching out for help.
When running Cypress, I get said error: process is not defined and it points to a JavaScript file in the client portion of my project (shown below). I understand process is a nodeJS property, but I can obviously call this on the FE of my application, and must, so I don't understand why Cypress is throwing an error here. Any help would be much appreciated. I'm running node v14.x.x.

vue.config.js
const { defineConfig } = require('@vue/cli-service')
// const { VueLoaderPlugin } = require('vue-loader')

module.exports = defineConfig({
  css: {
    loaderOptions: {
      sass: {
        additionalData: '@import src/styles/base/entry.scss',
      },
    },
  },

  lintOnSave: false,

  publicPath: '/',

  transpileDependencies: true,
})

Package.json
{
  "name": "test2",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@sentry/apm": "^5.27.1",
    "@sentry/browser": "^7.28.1",
    "@sentry/integrations": "^7.28.1",
    "auth0-js": "^9.20.0",
    "axios": "^1.2.2",
    "axios-retry": "^3.3.1",
    "big.js": "^6.2.1",
    "core-js": "^3.8.3",
    "css-loader": "^6.7.3",
    "moment": "^2.29.4",
    "moment-timezone": "^0.5.40",
    "style-loader": "^3.3.1",
    "toastr": "^2.1.4",
    "uuid": "^9.0.0",
    "vue": "^2.6.14",
    "vue-router": "^3.5.2"
  },
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/eslint-parser": "^7.19.1",
    "@babel/preset-env": "^7.20.2",
    "@cypress/webpack-preprocessor": "^5.16.1",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-e2e-cypress": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-unit-jest": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "@vue/test-utils": "^1.1.3",
    "@vue/vue2-jest": "^27.0.0-alpha.2",
    "babel-jest": "^27.0.6",
    "babel-loader": "^8.0.2",
    "cypress": "^9.7.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "jest": "^27.0.5",
    "node-sass": "^4.14.0",
    "sass-loader": "^12.6.0",
    "ts-jest": "^27.0.4",
    "vue-loader": "^15.0.1",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^5.75.0"
  }
}

Cypress webpack config
/// <reference types="cypress" />
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
const { VueLoaderPlugin } = require('vue-loader')
const webpackPreprocessor = require('@cypress/webpack-preprocessor')

/**
 * @type {Cypress.PluginConfig}
 */
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
  const defaults = webpackPreprocessor.defaultOptions
  // Add to existing rules
  defaults.webpackOptions.module.rules.push(
    {
      test: /\.vue$/,
      loader: 'vue-loader',
    },
    {
      test: /\.sass$/i,
      use: [
        // creates 'style' nodes from JS strings
        "vue-style-loader",
        // Translates CSS into CommonJS
        "css-loader",
        // Compiles Sass to CSS
        {
          loader: "sass-loader",
          options: {
            additionalData: '@import src/styles/base/entry.scss',
            // sass-loader >= 8
            sassOptions: {
              indentedSyntax: true,
            },
          },
        },
      ],
    }
  )
  // Add first plugin
  defaults.webpackOptions.plugins = [ new VueLoaderPlugin() ]
  console.log(defaults)

  on('file:preprocessor', webpackPreprocessor(defaults))
}

sentryMixin.js
...

const environment = process.env.VUE_APP_ENV
                    ^ this is where it points to the error
...


text:
Q: Dynamic Excelformula using jquery and php I have a problem when calculating dynamic formula,i have a form when remove cursor from calculated field function will cal with formula parameter value.here fields are dynamic means we can't estimate the field id or class for getting vlaues.i will provide code below..
function inlineclick(formula, element) {
  var xyz = formula.split('*').join(' ').split('%').join(' ').split('+').join(' ').split('-');
  var xyz1 = (xyz[0].split(' '));
  for (var count = 0; count < xyz1.length; count++) {

    var value1 = $('.' + xyz1[count] + '').val();
  }
  $("input[name='" + element.name + "']").val(eval(formula));
}

i want split formula,based on splited name have to fetch that value and calculate formula using that values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript/Razor Request.Params A potentially dangerous Request.QueryString value was detected from the client This javascript line gives me A potentially dangerous Request.QueryString value was detected from the client
$('a[href=#tabs1-pane' + @Request.Params["index"] + ']').tab('show');

Normally i would solve these issues by setting [ValidateInput(false)]  on the controller, but how do i solve this in a view/javascript?

A: Check if this helps you
var tempdate=@Request.Params["index"];
$('a[href=#tabs1-pane' + tempdate.tostring()  + ']').tab('show');


text:
Q: In British English, should it be "licensee" or "licencee"? We all know that "license" in American English is "licence" in British English.  But what about the person to whom the licence is given?
Various dictionaries show the 'c' version, e.g.:

*

*Dictionary.com
Additionally, I can see other resources in my own country using this spelling, e.g.:

*

*Centennial Parklands
But managers in my own company (in Australia) claim to have done "a lot of research" on the subject and decided to use the 's' version.  This seems wrong to me, but I would like a better answer to the question before I decide whether to request a change or just change our spell checking to allow their spelling.

A: I would suggest using either 's' or 'c' to match the spelling of the verb in whichever variety of English you're writing in, on the basis that the -ee ending is generally used to derive a noun from the verb, not the noun.
(Cf. train/training -> trainee, not *trainingee, or evacute/evacuation -> evacuee, not *evacuationee)

A: Obviously, in American English one would expect to see something like the following:

What is not so obvious is that British English has a similar graph on these words:

To prove that these graphs are reliable (at least reliable enough for this answer), graphs of American and British English on license vs. licence follow:
American English:

British English:

This ties in with what we already know about British vs. American preferences about the word licence/license. And to a degree it proves a point about licensee vs. licencee. It seems certain that licensee is the preferred spelling in either corpus.
And I'm terribly sorry for the gargantuan scale of this answer, but I thought the graphs would be helpful.

A: There is no such word, "licencee".
Licence = noun; the licence document.
License = verb; i.e. to grant licence.
Licensee = the holder of the licence.
The Americans don't like the noun/verb distinction and just use license for both.
However, licencee has never been a word.


text:
Q: Equation for $x^2+y^2=1$ in exponential space? Consider the unit circle $x^2+y^2=1$ in exponential space. Is there an equation for the set of points under the mapping?
Here's what I tried:
I took each coordinate pair on the unit circle and exponentiated it.
For example, $(x,y)\mapsto(e^x,e^y).$
This is what I have so far:

I also tried to come up with an equation for this set of points but have not been able to so far.

A: The equation for the set of points under the prescribed mapping is $\ln(x)^2+\ln(y)^2=1.$
Start with $(x,y) \mapsto (e^x,e^y).$ Define $u=\ln(x)$ and $v=\ln(y).$ In the pre-image space, we simply have $x^2+y^2=1.$ In the image space (after the prescribed mapping) we get $u^2+v^2=1.$ Substituting back to get an explicit equation in terms of $x$ and $y$ we get the above equation $\ln(x)^2+\ln(y)^2=1.$
Notice that in a $u-v$ coordinate system, we actually do have the equation for a circle, but using an $x-y$ coordinate system for the image space, we get a nonlinear equation in the coordinates $x-y.$ So if you ever have to deal with $\ln^2(x)+\ln^2(y)=1,$ just remember that you can always simplify it down to the equation of a circle using a change of coordinates which acts to linearize the equation from the image space to the pre-image space.


text:
Q: Partition seems shrunk after cloning with Macrium Reflect I started getting SMART warnings on my 1TB WD disk, so to prevent losing the data, I went to buy a replacement. Since the disk was almost full, I decided to buy a 2TB one (a Seagate). I installed it, reformatted (verifying it was 2TB) and went to look how to clone the failing one.
I looked up on the net how to copy the data over in such a way as not to lose any system properties etc; one of pages suggested Macrium Reflect Free - I didn't need anything fancy, so I got it, the cloning went through, and as I went to check the result, there was the cloned partition, exactly the same size as original. I went to disk manager - and it's 2TB there. I ran the disk through chkdsk but it didn't help.
F: is the old, failing disk. E: is the new one.

What can I do to make it appear as 2TB in the OS, not just disk manager?

A: Most filesystems have their own "size" independent of the underlying device (partition). It seems a bit like Reflect simply dumped the original filesystem into a larger partition, but did not update any NTFS structures to match.
From within Windows, you can probably fix this via DISKPART. Select the volume using list vol and select vol num, then grow the filesystem using extend filesystem.
Within Linux, you can use ntfsresize on the partition device.


text:
Q: How to have constant number of worker functions executing at all times? Lets say I have a list of 10 worker functions and I want 2 (or more) to be running at all times in parallel, advancing through the list when one finishes and then loop around and continue forever. So not to overload the server.
workers := make([]func(), 10)
for i := 0; i < 10; i++ {
  workers[i] = createWorker()
}

func createWorker() func() {
  return func() {
    fmt.Println("I am working")
    time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
  }
}

// My idea, keep sending workers to a buffered channel of size 2,
// so when one finishes it's no longer filled up and another worker is sent
workerChan := make(chan func(), 2)
go func() {
  worker := <-workerChan
  worker()
}()

for {
  for _, worker := range workers {
    workerChan <- worker
  }
}

This runs the first worker function, and no more. Maybe the idea is correct and I need some guidance on how to implement it correctly.

A: You were getting there.
func worker(ch chan func()) {
    // worker needs to read from a channel until channel is closed,
    // then it will stop
    for work := range ch {
        work()
    }
}

func main() {
    workers := 2
    workerChan := make(chan func(), 10)

    for i := 0; i < workers; i++ {
        // start workers
        worker(workerChan)
    }

    // add work to channel
    workerChan <- func() {
        // do work
    }
}

If you wrap it in a struct, you can make a very general worker pool with it, executing whatever you give to it.


text:
Q: Receive json in android I want to receive this json in android
json:
["Coupe","Coupe","Couleurs","Shampoing"]

and for read i have this:
protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
        try {
            JSONArray json = new JSONArray(result);

            String str = "";

            str += "id: "+json.getJSONObject(0).getString("Coupe");

            Reponse.setText(str);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

And i want to read this json in a spinner.
Help me please!
----UPDATE----
For receive Json and read it in a spinner i use this:
public class MainActivity extends Activity {

Spinner s;
List<String> str = new ArrayList<String>();
String URL;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    s=(Spinner)findViewById(R.id.acte);

    URL = "http://trymyjson.com";

    // call AsynTask to perform network operation on separate thread

    new HttpAsyncTask().execute(URL);
    addItemsOnSpinner();

}

public void addItemsOnSpinner() {

    str.add("choix coupe");
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, str);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(dataAdapter);
}

public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        return GET(urls[0]);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
        try {
            JSONArray json = new JSONArray(result);
            int len=json.length();
            for(int i=0;i<len;i++)
            {
                str.add(json.get(i).toString());
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

And it's work :-)
Thx for help!

A: JSONArray json = new JSONArray(result);

First calculate the length of the array!
int len=json.length();
String[] str=new String[len];
for(int i=0;i<len;i++)
 {
  str[i]=json.get(i).toString();
 }

First add a spinner to your activity
Spinner s=(Spinner)findViewById(R.id.Spinner);
ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_spinner_item,str);
s.setAdapter(adapter);


text:
Q: Разница между получением данных через Storage Access Framework и получением контента через Intent.ACTION_GET_CONTENT В чем принципиальная разница между обращению к файлам на устройстве используя Storage Access Framework:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent, READ_REQUEST_CODE)

И вот таким кодом:
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select Picture"), READ_REQUEST_CODE)}

Я попробовал оба метода и визуальный результат одинаковый. Очень хочется понимать чем первый способ лучше второго.

A: *

*ACTION_GET_CONTENT - работает с  API=1

*ACTION_OPEN_DOCUMENT - введен с API=19 (одновременно с SAF)

Если у вас targetSdk >=19, то оба Intentа будут работать одинаково, если нет, то 2-й не будет работать, только 1-й.
В совсем старых Android'ах ACTION_GET_CONTENT ничего не вызывал и надо было самому лепить Activity, который его обрабатывал. Были популярные либы, в которых был реализован обработчик ACTION_GET_CONTENT - например как такой

A: В Android версии 4.3 и ниже для того, чтобы приложение могло получать файл от другого приложения, оно должно активизировать намерение, например, ACTION_PICK или ACTION_GET_CONTENT. После этого пользователь должен выбрать какое-либо одно приложение, чтобы получить файл, а оно должно предоставить пользователю интерфейс, с помощью которого он сможет выбирать и получать файлы.
Начиная с Android 4.4 и выше, у разработчика имеется дополнительная возможность — намерение ACTION_OPEN_DOCUMENT, которое отображает пользовательский интерфейс элемента выбора, управляемого системой. Этот элемент предоставляет пользователю обзор всех файлов, доступных в других приложениях. Благодаря этому единому интерфейсу, пользователь может выбрать файл в любом из поддерживаемых приложений.
Намерение ACTION_OPEN_DOCUMENT не является заменой для намерения ACTION_GET_CONTENT. Разработчику следует использовать то, которое лучше соответствует потребностям приложения:

*

*используйте ACTION_GET_CONTENT, если приложению нужно просто прочитать или импортировать данные. При таком подходе приложение импортирует копию данных, например, файл с изображением.

*используйте ACTION_OPEN_DOCUMENT, если приложению нужна возможность долговременного, постоянного доступа к документам, принадлежащим поставщику документов. В качестве примера можно назвать редактор фотографий, позволяющий пользователям обрабатывать изображения, хранящиеся в поставщике документов.


text:
Q: How do i declare a variable global so that it persists? Applescript This is my code
 on button873_(sender)
    set thePath to POSIX path of (choose folder with prompt "Please choose a folder to Hide")
    set otterthan to "chflags hidden "& thePath
do shell script otterthan
end

on button874_(sender)
    set otterthando to "chflags nohidden "& thePath
    do shell script otterthando
    end

But it tells me that the path is not defined, the thing i want to do is make the script remember thePath so i can use it after end.

A: The path is defined but you're using a local variable (if not defined globally somewhere else globally or as a property). Anyway looking at the way you named the handlers you're using AppleScriptObjC. AppleScriptObjC makes use of script objects which can have properties that can be used in all handlers within that script object.
-- AppleScriptObjC using AppleScript 2.3 syntax
script theObject
    property parent : class "NSObject"
    property thePath : missing value

    on button873:sender
        set thePath to POSIX path of (choose folder with prompt "Please choose a folder to Hide")
        set otterthan to "chflags hidden " & thePath
        do shell script otterthan
    end button873:

    on button874:sender
        set otterthando to "chflags nohidden " & thePath
        do shell script otterthando
    end button874:
end script


text:
Q: isomorphisms of $\pi_{1}(T^2, x_{0})$ with itself. I1m studying fundamental group and its relation with covering maps, I was thinking about an exercise:
every isomorphism of $\pi_{1}(T^2, x_{0})$ with itself is induced by a homomorphism $f:T^2 \rightarrow T^2$ . $T^2 = S^1 \times S^1.$
I probably have to use a matrix with integer entries and induce a continus function, but I don't know hou to that.


text:
Q: mjpeg mov created by the newest FFMPEG looks in Windows Media Player like half sized videos I have new version of FFMPEG installed and created mov compressed with mjpeg. Is looks pretty in Afx, Premiere and QucikTime player but it looks like half-sized video in Windows Media Player. There was no such problem in previous version of ffmpeg. Have you any idea how to solve this problem?
ffmpeg -i "content/test1080.mov" -sameq -vcodec mjpeg -qmin 1 -qmax 1 -y -s 640x360 -f mov "content/test Big Web.mov"
ffmpeg version 1.0 Copyright (c) 2000-2012 the FFmpeg developers
  built on Nov  5 2012 11:15:58 with gcc 4.4.6 (GCC) 20110731 (Red Hat 4.4.6-3)
  configuration: --enable-avfilter --enable-libmp3lame --disable-mmx --arch=x86_32 --enable-libfaac --enable-nonfree --enable-filter=movie --enable-avfilter --enable-libx264 --enable-gpl
  libavutil      51. 73.101 / 51. 73.101
  libavcodec     54. 59.100 / 54. 59.100
  libavformat    54. 29.104 / 54. 29.104
  libavdevice    54.  2.101 / 54.  2.101
  libavfilter     3. 17.100 /  3. 17.100
  libswscale      2.  1.101 /  2.  1.101
  libswresample   0. 15.100 /  0. 15.100
  libpostproc    52.  0.100 / 52.  0.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'content/test1080.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    creation_time   : 2012-11-08 14:34:46
  Duration: 00:00:03.23, start: 0.000000, bitrate: 172538 kb/s
    Stream #0:0(eng): Video: mjpeg (jpeg / 0x6765706A), yuvj422p, 1920x1080 [SAR 72:72 DAR 16:9], 172517 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 30k tbc
    Metadata:
      creation_time   : 2012-11-08 14:34:46
      handler_name    : Procedura obsługi skrótów danych Apple
      timecode        : 00:00:10;11
    Stream #0:1(eng): Data: none (tmcd / 0x64636D74)
    Metadata:
      creation_time   : 2012-11-08 14:34:58
      handler_name    : Procedura obsługi skrótów danych Apple
      timecode        : 00:00:10;11
Output #0, mov, to 'content/test Big Web.mov':
  Metadata:
    major_brand     : qt
    minor_version   : 537199360
    compatible_brands: qt
    encoder         : Lavf54.29.104
    Stream #0:0(eng): Video: mjpeg (jpeg / 0x6765706A), yuvj422p, 640x360 [SAR 1:1 DAR 16:9], q=1-1, 200 kb/s, 30k tbn, 29.97 tbc
    Metadata:
      creation_time   : 2012-11-08 14:34:46
      handler_name    : Procedura obsługi skrótów danych Apple
      timecode        : 00:00:10;11
Stream mapping:
  Stream #0:0 -> #0:0 (mjpeg -> mjpeg)
Press [q] to stop, [?] for help
frame=   97 fps= 14 q=1.0 Lsize=   14282kB time=00:00:03.23 bitrate=36149.5kbits/s
video:14280kB audio:0kB subtitle:0 global headers:0kB muxing overhead 0.012432%


text:
Q: Compiling simple C++ SFML file with network code using MinGW throws error "undefined reference to IpAddress" I keep getting errors when compiling a C++ project using SFML 2 on Windows using MinGW.
At C:\MinGW\include\ there is the SFML header files folder including Network.hpp and I also copied the libsfml-[...].a files into C:\MinGW\lib\ as well as the sfml-[...]-2.dll files into C:\MinGW\bin\.
This is my sample file:
#include <iostream>
#include <SFML/System.hpp>
#include <SFML/Network.hpp>

int main(int argc, char** argv)
   {
   sf::TcpListener listener;

   listener.listen(4444);

   sf::TcpSocket client;

   std::cout << "Waiting for client to connect..." << std::endl;

   if (listener.accept(client) == sf::Socket::Done)
      {
      std::cout << "Client connected: " << client.getRemoteAddress() << std::endl;
      listener.close();
      }
   else
      {
      std::cout << "Client didnt connect" << std::endl;
      }

   return 0;
   }

If I try to compile it using the following command
g++ test.cpp -lsfml-system -lsfml-network

I get these errors:
C:\Users\me\AppData\Local\Temp\cc6XzH1R.o:test.cpp:(.text+0x28): undefined reference to `_imp___ZN2sf9IpAddress3AnyE`
C:\Users\me\AppData\Local\Temp\cc6XzH1R.o:test.cpp:(.text+0x3a): undefined reference to `_imp___ZN2sf11TcpListener6listenEtRKNS_9IpAddressE`

Thanks for any help :D
   Matze

A: Simple , try to link correct version of library.
If you are making x86 app use the 32bit version of library and if you are making x64 app use 64bit version. I also got the same error and this fixed.


text:
Q: Tricky C Program to find even and odd This is a challenging problem I came across while I was giving my internship exam in Microsoft. The question goes like this:

User inputs a decimal number.  The output should show whether the number is even or odd subject to constraint that only one printf, and no binary operator, logical operator, arithmetic operator, if-else and switch-case can be used.

So any ideas?

A: Let x be the variable to determine. The following code will print 0 if x is even, 1 - if odd:
union
{
    unsigned char tmp:1;
} u;

u.tmp = x;
printf("%d", u.tmp);

A: Silly questions call for silly answers.
printf("Yes, the number is even or odd\n");

A: I consider the accepted answer using fmod to be breaking the "no arithmetic operators" rule. Here's a solution using only structs and casts to find out what the least significant bit is (signifying odd or even):
float f = ...;

struct intStruct {
    int i;
};
struct intStruct is;
is.i = (int)f;

struct bitField {
    unsigned int odd : 1;
    unsigned int padding: 15; // to round out to 16 bits
};
struct bitField *bf_ptr;
bf_ptr = (struct bitField *)&is;
struct bitField bf = *bf_ptr;

printf("Odd? %d", bf.odd);

A: This will work:
printf("Number is odd? %d\n", (int)fmod((float)i, (float)2));

Or better if you can use the conditional operator:
printf("Number is %s\n", (int)fmod((float)i, (float)2) ? "odd" : "even");

A: No ternary operator:
int n;
char *answers[] = { "even", "odd" };
scanf("%i", &n);
printf("%s\n", answers[(int) fmod(n, 2.0)]);

A: Here's a solution that avoids using fmod at all. It works using the character representation of the number, checking whether the last digit is in {0, 2, 4, 6, 8}.
The big trouble is finding the last digit.
The restrictions of the problem are onerous.

*

*no binary operators:  no assignments (=) or array indexing ([]) or even structure reference (.)

*no logical operators: no negation (!) or shortcut tricks (&&) or equality (==)

*no arithmetic operators: no increment (++)

*no if or switch

*only one printf
About the only operators left are *, &, ~, ?: and sizeof.
Most of the code is trying to find the last digit in the string. The only binary operator used is in the main() driver, to get argv[1]. (The square brackets for c[2] are declaration syntax, not an operator)
I worked around assignment by using a function call, and memcpy.
I worked around if by using while and munging the test.
I worker around != by assuming NULL == 0.
On the plus side, this function works with really big numbers!
#include <string.h>
#include <stdio.h>

void* null_pointer;
char c[2];

// If s is not null, copy *s to *save, and change *s to '~'
// Return s
char* copy_zap_char_not_null(char* save, char* s) {
    char* p;
    memcpy(&p, &s, sizeof(char*));
    while (p) {
        memcpy(save, p, sizeof(char));
        memcpy(p, "~", sizeof(char));
        memcpy(&p, &null_pointer, sizeof(void*));
    }
    return s;
}

int print_even_odd(char* s)
{
    while (copy_zap_char_not_null(c, strpbrk(s, "0123456789"))) {}
    printf("%s\n", ( strpbrk(c, "02468") ? "even" : "odd" ) );
}

int main(int argc, char** argv)
{
    print_even_odd(argv[1]);
}

A: Seth Carnegie's answer can fail for certain inputs. In particular, on my system, it fails for an input of 2147483647, indicating that it's even (at least on my system), because converting that value to float loses precision.
Here's an improved solution based on his:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char **argv) {
    const char *const even_or_odd[] = { "even", "odd" };
    for (int i = 1; i < argc; i ++) {
        const int n = atoi(argv[i]);
        printf("%d is %s\n",
               n,
               even_or_odd[(int)fmod((unsigned char)n, 2.0)]);
    }
    return 0;
}

The for (int i = ... syntax is "new" in C99; if your compiler doesn't support it, declare int i; above the loop.
The values to be tested are taken from the command line arguments.  It would be easy enough to modify the program so they're taken from stdin or elsewhere.
The atoi() function does no error checking, so don't expect meaningful results if you give it something that's not a decimal integer.
Converting the value of n to unsigned char before passing it to fmod() give a result with the same parity (odd-or-evenness) as n, but that won't lose precision when converted to double (that conversion happens implicitly because fmod() takes double arguments).  The standard-defined semantics of conversion to an unsigned type are such that this will work correctly even on systems that use a representation other than two's-complement.
It's just barely possible that converting from unsigned char to double could lose precision.  This would require unsigned char to have an implausibly large upper bound.  double must have at least 10 decimal digits of precision, or about 33 or 34 bits; losing precision would require unsigned char to be at least 34 or so bits (it's likely I have an off-by-one error or two in there).  Such a system could be conforming, but I doubt that any such systems exist in the real world.

A: #include <stdio.h>
#include <string.h>

int main(){
    int i, count;
    char c, *p, strnum[32];

    printf("enter input number:");
    scanf("%d%*c", &i);
    sprintf(strnum, "%d", i);//or itoa, deprecated.
    p=&strnum[strlen(strnum)];
    count=sscanf(&p[-1], "%[02468]c", &c);
    printf("%d is %s\n", i, count ? "even" : "odd");
    return 0;
}

//p=strrev(strnum);//strrev is deprecated. But It works Microsoft C Compiler.
//count=sscanf(p, "%[02468]c", &c);

//printf("%d is %s\n", i, sscanf(strrev(itoa(i,(char*)malloc(32),10)), "%[02468]c", (char*)(malloc(1)) ? "even" : "odd");

A: int main()
{  int  number;
   scanf("%d",&number);
    number&1 && printf("Odd") || printf("even");

}

or
int main()
{
int number ;
char arr[][2]={"Even","Odd"};
printf("%s\n",arr[number%2]);
}

A: n&1? puts("NO"):puts("YES");

A: If the user is referring decimal numbers as floating point numbers and not base 10 numbers then this could be a possible answer.
printf("Floating point numbers are neither even nor odd.");

An even number is an integer that is "evenly divisible" by 2, i.e., divisible by 2 without remainder; an odd number is an integer that is not evenly divisible by 2.

A: I think you can do this by using bitwise AND operator...
scanf("%d",&n);
if( n & 1 == 1) // if last bit in numbers is 1, 'n' is odd , 0 for even

Later you can use if else and switch to display whether the number if even or odd.

A: The best I could come up with...
#include <stdio.h>
int main() {
    int number;
    char oddness[4+1];
    printf("Type an integer: ");
    scanf("%d", &number);
    printf("I need some help here, user. Is it even or odd? ");
    scanf("%s", oddness);
    printf("%d is %s.\n", number, oddness);
    return 0;
}


text:
Q: Is recurring payment gateway supported by payubiz? I am working on Zend framework 2 and need to add Payubiz payment gateway. but before going further, i need to clarify this question; Is recurring payment gateway supported by Payubiz or not?
If it is supported then how can i implement. Kindly provide some references.


text:
Q: Execute classic ASP code on mouse over I would like to execute this Classic ASP code when passing the mouse over a div.
<%
  dim s
  s=Request.QueryString("undercity")
  Response.Write(s)
  set fs=Server.CreateObject("Scripting.FileSystemObject")
  if s<>"" then
    set f=fs.OpenTextFile(Server.MapPath("RDS/rds.txt"),2,true)
    f.WriteLine(s)
    f.Close
    Set f=Nothing
  else
    if (fs.FileExists(Server.MapPath("RDS/rds.txt")))=true then
      set f=fs.OpenTextFile(Server.MapPath("RDS/rds.txt"),1)
      Response.Write("On air: "+f.ReadAll)
      f.Close
      Set f=Nothing
    end if
  end if
  set fs=Nothing
%>

I tried creating a function on my js file using the .innerHTML="<% code %>" but it didn't work.
How should this be done?

A: You can't really do that that way. The key is the "passing mouse" event occurs on the client machine. Where ASP code runs on the server machine. So you have to have some way to hook them together.
They way that they appear to work together is, When user request an asp page with the browser on their machine, their browser sends a request to your web server, your web server runs your asp code, which generates HTML code. It then send the result HTML code to the client, the client browser receives the result HTML code and then takes over from there. After this user can move the mouse to trigger some JavaScript code, but this is long after your ASP code has run and it happens in the client computer.
In order for a client event to "call" server side code, you would have to trigger some kind of server request. A "form.submit" a typical example where client JavaScript code can call form.submit function to submit the form, which causes the browser to post back the page to the server, then your server code get called again, then it generates some new HTML and send back to the client browser, then the client browser takes over, over and over like this.
You can use AJAX to "call" back to the server any time in your page. I am familiar with ASP.NET AJAX but I do not know what you can use with ASP. However the concept is the same, which is you have to somehow go back to the server side in order to run server side code.
Hope this helps a little bit.

A: The fastest way would be to create mini-form that point to your ASP file as an action, e.g.
<form id="myForm" action="mycode.asp?undercity=somedata">
    <div onmouseover="document.getElementById('myForm').submit()" >
        Mouse over me!
    </div>
</form>

The above code defines a form "myForm" and DIV with mouseover function that submits the form. You can add required query string parameters to the page specified in Action.
Basic demo: http://jsfiddle.net/S5GFN/3/
NOTE: This action will reload entire page. If you need to replace .innerHTML of an element - you will have to perform an AJAX call. I recommend using jQuery's .load() method, using it you can do a simple call in client-side code e.g.:
$("#mouseOverDiv").mouseover(function() {
   $("#myElement").load("mycode.asp?undercity=somedata")
});

Here's an example: http://jsfiddle.net/S5GFN/5/


text:
Q: Hibernate named query issue I have below name query
@NamedQuery(name="ScInstantTrack.getCustomerDetails",
query="select b.cardDetail.mstCustomer.customerId, last_day(b.endDate), " +
        "LISTAGG(b.txnId,'|') WITHIN GROUP (ORDER BY b.endDate), " +
        "count(b.txnId), sum(b.amount), sum(b.balanceAmt), sum(b.redemptionAmt) " +
        "from ScInstantTrack b " +
        "where b.cardNo = b.cardDetail.cardBarcode " +
        "AND b.cardDetail.mstCustomer.customerId = :customerId " +
        "and b.startDate <= trunc(:todayDate) " +
        "and b.endDate >= trunc(:todayDate) " +
        "and b.cardDetail.mstStatus.statusId = 3003 group by b.cardDetail.mstCustomer.customerId, last_day(b.endDate)")

When I am executing this query then getting below error :
unexpected token: WITHIN

I am using Oracle Database.
Why I am getting this error? How to solve this issue?

A: Try to use @NamedNativeQuery instead of @NamedQuery.
Also check this explanation of difference between them.
Basically you are using expressions that are exclusive in Oracle DB. In other words - you want to execute native query (query in native for Oracle DB language). Named queries use Java Persistence Query Language (HQL i.e.).

A: The error happen because LISTAGG is an oracle specific function.
That function is not avaliable in HQL and there is nothing you can use instead for HQL.
In order to get the result you have to use a SQLQuery wich perform native SQL queryes. This way You have to implement a version of thw query for each database, but it will work.


text:
Q: Alternate to Redirect Page I am attempting to figure out how to do history state manipulation and I saw a site that had a nice feature that if you put anything after the slash, the site will still load but in an incomplete state due to a flaw in the state machine. I was wondering how do you get the site to catch the address and forward like that? My only guess is to change the .htaccess file, but I'm not sure where to start for that...
http://bufmi.org/ (this is the site)
http://bufmi.org/about (this is the example of a site)
http://bufmi.org/foobar (this still loads the site, but not an actual page)
They have it set up that no matter what you put in after the slash it goes to the site, how did they accomplish that?

A: This is achieved by some script that fires depending if you are at the root URL or not and a .htaccess rewrite rule to add the hash to anything other than the base url.
The .htaccess part is handled with something like this:
RewriteRule ^([a-zA-Z0-9_-]+)$ /#$1 [NE,R]

This section of scripts.js is responsible for the root URL check looks kind of like this:
if (document.URL == urlroot){
    //Applies Class to set of elements
    $('.example').removeClass('example-class', 0);
} else {
    //Applies Class to different set of elements
    $('.example2').removeClass('example-class', 700);
}

If you are not at the root URL a series of if/else if check to see if the content for the fragment identifier exists. If it exists, content is loaded into a specific section on the page from one html file using anchors on that page. If the fragment identifier does not match any of the if/else if sections in scripts.js, then the anchor Blank on the mater.html page is used to display an empty content section.

A: This is a feature available since Html5.
You can override default actions.
Here is an implementation with jQuery :
$( document ).on( 'click', 'a', function( e ) {

    // prevent the page reload
    e.preventDefault();

    // change the content of the <body> tag
    changeContent($(this).attr('href'));

} );

Forward and Back buttons of the browser are handled like this
window.addEventListener( 'popstate', function( e ) {

    // Change the content of the <body> tag
    changeContent(location.pathname);

} );

And your changeContent function would be like
function changeContent(url) {

    $.get(url, function(new_content) {
        $('body').html(new_content);
    })

}

This will let you change any part of your website without refreshing the whole page.


text:
Q: What's the use and advantages of using ImageDecoder of Android P? Background
Android P presents a new API for loading images, using ImageDecoder class.
The problem
Not much is documented about this class, so I'm just curious about its usage, and whether I should consider using it when possible, instead of Glide library, for example, which Google itself recommends on using:

For most cases, we recommend that you use the Glide library to fetch,
  decode, and display bitmaps in your app. Glide abstracts out most of
  the complexity in handling these and other tasks related to working
  with bitmaps and other images on Android. For information about using
  and downloading Glide, visit the Glide repository on GitHub.

What I've found
I've found some articles about it, giving clues of what it can do and how to use it:

*

*https://blog.stylingandroid.com/imagedecoder-error-handling-cropping-scaling/

*https://vivekc.xyz/whats-new-in-android-p-the-breaking-changes-and-amazing-features-8f4e864802a9 - says that as opposed to BitmapFactory, it can also handle "animated GIFs and WebP images", creating AnimatedImageDrawable

*https://www.androidpolice.com/2018/03/07/google-announces-android-p-notch-support-multi-camera-api-indoor-positioning/ - says it does better decoding. Not sure in which way it's better...

*https://youtu.be/LBBqTd6uOd4?t=116 - says you can do some operations that are similar to Glide : crop, have listeners, etc...

*https://developer.android.com/preview/features?authuser=1#decoding-images

*https://blog.stylingandroid.com/imagedecoder-error-handling-cropping-scaling/
However, according to my tests, loading a GIF animation is worse using this API (takes more memory, uses about the same CPU) compared to Movie class, which in itself is worse than third party libraries such as android-gif-drawable . What I've tested is a rather long GIF animation. On the third party library it took about 59MB. Using Movie class it took about 168MB, and using the new ImageDecoder API it took 200-300MB ...
So in short, what I've found about this API, is that:

*

*It's supposed to replace BitmapFactory

*It supports loading animated GIF/WEBP

*It has some listeners for pre/post processing

*It's supposed to be more efficient, but I don't see it, at least not in terms of memory usage.

The questions

*

*Are there any advantages of using this API, over what we already have in third party libraries ? Meaning Glide for static images, and "android-gif-drawable" for GIF (and maybe something for WEBP that I didn't search) ?

*Does it perform better behind the scenes, and I shouldn't care about its memory usage?

*Does it have a memory/disk cache? If so, how does it manage its memory cache now that Android doesn't store Bitmaps in the heap memory (wrote about it here) ?

*Is it possible this API will be available in the support library? Otherwise I don't see much need to use it at all... EDIT: seems it might be on the support library. Link here.


text:
Q: Android: Undo function in Painting app not working I am working on a painting app, code as follows:
DrawActivity
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.coloring_activity3);
    ....

    mv = (MyDrawView2) findViewById(R.id.drawerView);
    mv.setDrawingCacheEnabled(true);
    Constants.mPaint = new Paint();
    Constants.mPaint.setAntiAlias(true);
    Constants.mPaint.setDither(true);
    Constants.mPaint.setColor(0xFF000000);
    Constants.mPaint.setStyle(Paint.Style.STROKE);
    Constants.mPaint.setStrokeJoin(Paint.Join.ROUND);
    Constants.mPaint.setStrokeCap(Paint.Cap.ROUND);
    Constants.mPaint.setStrokeWidth(Brush_size);

    ....
    case R.id.btn_eraser:
        Constants.mPaint.setXfermode(null);
        Constants.mPaint.setAlpha(0xFF);
        Constants.mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        layout_eraser_size.startAnimation(eraser_move_from_bottom_into_screen);
        layout_eraser_size.setVisibility(View.VISIBLE);
        btn_eraser.setEnabled(false);
        break;

    case R.id.btn_brush:
        layout_brush_btns.startAnimation(brush_move_from_bottom_into_screen);
        layout_brush_btns.setVisibility(View.VISIBLE);
        btn_brush.setEnabled(false);
        break;

    case R.id.btn_undo:
        Constants.custom_toast(this, "undo", "clicked");
        mv.onClickUndo();
        break;

DrawView2
public class MyDrawView2 extends View
{
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mBitmapPaint;
    Context context;

    private ArrayList<Path> paths = new ArrayList<Path>();
    private ArrayList<Path> undonePaths = new ArrayList<Path>();

    public MyDrawView2(Context c, AttributeSet attrs)
    {
        super(c, attrs);
        context = c;
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null); // for solely removing the black eraser
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, Constants.mPaint);
    }

    public void onClickUndo ()
    {
        if (paths.size()>0)
        {
           undonePaths.add(paths.remove(paths.size()-1));
           invalidate();
        }
        else
        {
            Toast.makeText(getContext(), "nothing to undo", Toast.LENGTH_SHORT).show();
        }
    }

    public void onClickRedo ()
    {
       if (undonePaths.size()>0)
       {
           paths.add(undonePaths.remove(undonePaths.size()-1)) ;
           invalidate();
       }
       else
       {
           Toast.makeText(getContext(), "nothing to redo", Toast.LENGTH_SHORT).show();
       }

    }

    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y)
    {
        undonePaths.clear();
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void touch_move(float x, float y)
    {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)
        {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

    private void touch_up()
    {
        mPath.lineTo(mX, mY);
        mCanvas.drawPath(mPath, Constants.mPaint);  // commit the path to our offscreen
        paths.add(mPath);
        Toast.makeText(getContext(), "path added" + paths.size(), Toast.LENGTH_SHORT).show();
        mPath.reset();  // kill this so we don't double draw
        Constants.mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        // mPaint.setMaskFilter(null);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction())
        {
         case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:

                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }
}

Question:
on each touch_up I have added a toast counting the number of path in the arraylist paths and that was showing correctly. But the undo function does not work after clicking btn_undo.
How could that be fixed? Thanks a lot!

A: I got the undo and redo to work by doing the following changes to onSizeChanged(), onDraw() and touch_up():
public class MyDrawView2 extends View
{

    private Canvas mCanvas;
    private Path mPath;

    Context context;

    private ArrayList<Path> paths = new ArrayList<Path>();
    private ArrayList<Path> undonePaths = new ArrayList<Path>();

    public MyDrawView2(Context c, AttributeSet attrs)
    {
        super(c, attrs);
        context = c;
        mPath = new Path();
        //added
        mCanvas = new Canvas();

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
    //removed bitmap ...

    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
         //added
           for (Path p : paths){
               canvas.drawPath(p, Constants.mPaint);
           }

        canvas.drawPath(mPath, Constants.mPaint);

      //removed bitmap ...
    }

    public void onClickUndo ()
    {
        if (paths.size()>0)
        {
           undonePaths.add(paths.remove(paths.size()-1));
           invalidate();
        }
        else
        {
            Toast.makeText(getContext(), "nothing to undo", Toast.LENGTH_SHORT).show();
        }
    }

    public void onClickRedo ()
    {
       if (undonePaths.size()>0)
       {
           paths.add(undonePaths.remove(undonePaths.size()-1)) ;
           invalidate();
       }
       else
       {
           Toast.makeText(getContext(), "nothing to redo", Toast.LENGTH_SHORT).show();
       }

    }

    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y)
    {
        undonePaths.clear();
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }

    private void touch_move(float x, float y)
    {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE)
        {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
    }

        private void touch_up()
        {
            mPath.lineTo(mX, mY);
            mCanvas.drawPath(mPath, Constants.mPaint);  // commit the path to our offscreen
            paths.add(mPath);
            Toast.makeText(getContext(), "path added" + paths.size(), Toast.LENGTH_SHORT).show();
            //added
            mPath = new Path();
            //removed reset...

        }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction())
        {
         case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:

                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }
}


text:
Q: Why won't Android 12 record travel? My app collects locations with a foreground service, and it has been working well up through Android 11. With the Android 12 beta, with all permissions that work well for previous versions granted, I'm getting very few locations, well below my update interval settings, sometimes not for several minutes at a time.
Are there some Android 12 changes for running apps with a foreground service, with the LocationManager, or anything else that might affect this?
Edit: Tried mock locations; those come in fine. Also tried adding
 android:foregroundServiceType="location"

... which didn't help. I've thought about switching to the Fused Location Provider API, but I've read that doesn't help to get more locations, just the opposite.
My next step is to use the "gps" location provider with the LocationManager; my guess is that will get more locations, but my app has been handling the types of locations from the "fused" provider, so I'd really like a better option.

A: Using FusedLocationProviderClient instead of LocationManager for Android 12 worked; it looks like using the "fused" provider with LocationManger.requestLocationUpdates with Android 12 will no longer cause new locations to be collected.


text:
Q: Multiple internet connections being used. Say, on my computer I happen to have three internet sources.

*

*USB tether from my phone

*WiFi to my home network

*Ethernet to another router different from my wifi.
I want to use 1 to brows the web. 2 to transfer files to another machine in the house and 3 to transfers other files to other machines.
The above is an overly exaggerated use case. Most likely option 3 wont exist.
Is this possible?
How?

A: (you don't say what OS so I am assuming windows for this, other OS's have similar commands)
This can easily be set up via the route command in windows.
route [-f] [-p] [Command [Destination] [mask Netmask] [Gateway] [metric Metric]] [if Interface]]

You would need to set up 3 routes

*

*Default connection that uses the USB Teather

*A route for a single computer to use the WiFi

*A route for the rest of the local connections

Assumes:

*

*192.168.0.1 is the IP of the gateway on the tether

*The interface ID of the WiFi is 11

*192.168.1.3 is the IP of the "other computer".

*The interface ID of the Ethernet is 12

*The subnet of the Ethernet is 192.168.2.0 with a netmask of 255.255.255.0
Adding the default gateway (also -f clears out any old routes already set up)
route -f -p ADD  0.0.0.0 mask 0.0.0.0 192.168.0.1

Add the route for the "other comptuer" that is connected via WiFi (as long as the subnet is different than network 3 you could just use the same command as the 3rd command for the 192.168.1.0 subnet if you wanted every computer on your home network to work instead of just one or adding them individually)
route -p ADD 192.168.1.3 if 11

Add the route so the rest of the computers in the 192.168.2.x range are all via the wired Ethernet
route -p ADD 192.168.2.0 mask 255.255.255.0 if 12


text:
Q: Uncaught (in promise) FirebaseError: Missing or insufficient permissions when trying to update collection i am createing a microblogging app using firebase firestore and im getting this error
`const handleNewPostSubmit = async (e) => {
e.preventDefault();
const createdAt = new Date().toISOString();

await firestore.collection('posts').add({
  text: newPostText,
  createdAt,
});`

this is the code i used but i get the error Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
and im also getting the warning
[2023-02-24T03:48:58.451Z]  @firebase/firestore: Firestore (9.17.1): Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficient permissions
i wanted this to create a collections posts and add the new post to it


text:
Q: GLFW - many errors is this code So my university lecturer gave us this code and it doesn't work.. it never has and no one has been able to get it to work so far.. are we being stupid or is our lecturer giving us broken material? I seriously can't figure this out and need help, i managed to get part way through in fixing many mistakes but after that the issues got harder and harder to solve despite this being '100% working' code.... side note: all the directories are formatted correctly and additional dependencies have all been set up correctly to the best of my knowledge.
//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++ gl::exts::LoadTest didLoad = gl::sys::LoadFunctions(); if (!didLoad) {
    //Load failed
    fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

    glfwTerminate();
    return 1;
}

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to //the viewer

//i.e. Enable depth testing with smaller depth value //interpreted as being closer gl::Enable(gl::DEPTH_TEST); gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points,
    gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in //separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile GLuint vs = gl::CreateShader(gl::VERTEX_SHADER); gl::ShaderSource(vs, 1, &vertex_shader, NULL); gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER); gl::ShaderSource(fs, 1, &fragment_shader, NULL); gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable //GPU shader program

//Create empty program and attach shaders GLuint shader_program = gl::CreateProgram(); gl::AttachShader(shader_program, fs); gl::AttachShader(shader_program, vs); gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display glfwSwapBuffers(window);

}

//Close GLFW and end
glfwTerminate();

return 0;

}

A: Your line endings seems to been mangled.
There are multiple lines in your code where actual code was not broken into two lines, so that code is now on the same line as a comment and therefor not being executed. This is your program with proper line endings:
//First Shader Handling Program

#include "stdafx.h"

#include "gl_core_4_3.hpp"

#include <GLFW/glfw3.h>

int _tmain(int argc, _TCHAR* argv[])
{
    //Select the 4.3 core profile
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //Start the OpenGL context and open a window using the
    //GLFW helper library

    if (!glfwInit()) {
        fprintf(stderr, "ERROR: could not start GLFW3\n");
        glfwTerminate();
        return 1;
    }

    GLFWwindow* window = glfwCreateWindow(640, 480, "First GLSL Triangle", NULL, NULL);

    if (!window) {
        fprintf(stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Load the OpenGL functions for C++
    gl::exts::LoadTest didLoad = gl::sys::LoadFunctions();
    if (!didLoad) {
        //Load failed
        fprintf(stderr, "ERROR: GLLoadGen failed to load functions\n");

        glfwTerminate();
        return 1;
    }

printf("Number of functions that failed to load : %i.\n", didLoad.GetNumMissing());

//Tell OpenGL to only draw a pixel if its shape is closer to
//the viewer

//i.e. Enable depth testing with smaller depth value
//interpreted as being closer
gl::Enable(gl::DEPTH_TEST);
gl::DepthFunc(gl::LESS);

//Set up the vertices for a triangle
float points[] = {
    0.0f, 0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f
};

//Create a vertex buffer object to hold this data
GLuint vbo=0;

gl::GenBuffers(1, &vbo);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::BufferData(gl::ARRAY_BUFFER, 9 * sizeof(float), points, gl::STATIC_DRAW);

//Create a vertex array object
GLuint vao = 0;
gl::GenVertexArrays(1, &vao);
gl::BindVertexArray(vao);
gl::EnableVertexAttribArray(0);
gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
gl::VertexAttribPointer(0, 3, gl::FLOAT, FALSE, 0, NULL);

//The shader code strings which later we will put in
//separate files

//The Vertex Shader
const char* vertex_shader =
"#version 400\n"
"in vec3 vp;"
"void main() {"
        " gl_Position = vec4(vp, 1.0);"
"}";

//The Fragment Shader
const char* fragment_shader =
"#version 400\n"
"out vec4 frag_colour;"

"void main() {"
        " frag_colour = vec4(1.0, 0.5, 0.0, 1.0);"
"}";

//Load the strings into shader objects and compile
GLuint vs = gl::CreateShader(gl::VERTEX_SHADER);
gl::ShaderSource(vs, 1, &vertex_shader, NULL);
gl::CompileShader(vs);

GLuint fs = gl::CreateShader(gl::FRAGMENT_SHADER);
gl::ShaderSource(fs, 1, &fragment_shader, NULL);
gl::CompileShader(fs);

//Compiled shaders must be compiled into a single executable
//GPU shader program

//Create empty program and attach shaders
GLuint shader_program = gl::CreateProgram();
gl::AttachShader(shader_program, fs);
gl::AttachShader(shader_program, vs);
gl::LinkProgram(shader_program);

//Now draw
while (!glfwWindowShouldClose(window)) {
    //Clear the drawing surface
    gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    gl::UseProgram(shader_program);
    gl::BindVertexArray(vao);

    //Draw point 0 to 3 from the currently bound VAO with
    //current in-use shader
    gl::DrawArrays(gl::TRIANGLES, 0, 3);

    //update GLFW event handling
    glfwPollEvents();

    //Put the stuff we have been drawing onto the display
    glfwSwapBuffers(window);
}

//Close GLFW and end
glfwTerminate();

return 0;
}


text:
Q: How can I get a LAMP stack application in docker to send an HTTP POST to another service running on my local host? I have a simple web application that uses HTML and PHP to capture information via a HTML form. It take this information and uses HTML-POST to sent it to a service, also running on my local host on port 8400, as application XML. I have this application running in a LAMP stack on macOS and it works perfectly. The XML gets to the service without any issues.
When I moved this app into a containerized LAMP stack using Docker, the application runs, but when my PHP tries to post it to the other service running on port 8400, it cannot get there.
I am confident that this is an issue with Docker networking, but I am not sure what the problem is. Here is my docker-compose.yml file:
version: "1.0"
services:
  php:
    build: "./php/"
    networks:
      - backend
      - frontend
    volumes:
      - ./public_html/:/var/www/html/
  apache:
    build: "./apache/"
    depends_on:
      - php
      - mysql
    networks:
      - frontend
      - backend
    ports:
      - "8080:80"
    volumes:
      - ./public_html/:/var/www/html/
  mysql:
    image: mysql:5.6.40
    networks:
      - backend
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
networks:
  frontend:
  backend:

I think the answer probably lies in the allowing the container to reach my localhost network, but being relatively new to Docker, I am unsure.
How can I configure Docker networking to allow posting to services outside of Dockernet on specific ports?


text:
Q: Выдает ошибку функция fopen HTTP request failed! HTTP/1.1 400 Bad Request <?php

$name = $_POST['user_name'];

$phone = $_POST['user_phone'];

$email = $_POST['user_email'];

$token = "1516441406:AAEi30721lyOLlc7bKgni-FWJDGzPrAPP0o";

$chat_id = "-592602248";

$txt = "";

$arr = array(
  'Имя пользователя: ' => $name,
  'Телефон: ' => $phone,
  'Email' => $email
);

foreach($arr as $key => $value) {
  $txt .= "<b>".$key."</b> ".$value."%0A";
};

$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");

if ($sendToTelegram) {
  header('Location: thank-you.html');
} else {
  echo "Error";
}
?>

A: Основная проблема здесь в том, что вам нужно кодировать кириллические символы в объекты URL. Попробуйте использовать rawurlencode для $txt: $txt = rawurlencode($txt).
Оригинал ответа: https://stackoverflow.com/a/63667704/4772782


text:
Q: How to animate drawable in Android Motion Layout I am trying out the motion layout and I would like to have a floating action button with animated icon on it. I got all the motion layout stuff down and working. But I can't find a way to get the animated FAB icon to work.
// ic_menu_toggle_arrow_down is my Animated Vector Drawable
<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/menuToggle"
        android:clickable="true"
        android:src="@drawable/ic_menu_toggle_arrow_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

Basically, I want to animate the FAB icon alongside the motion layout animation (back and forth). And I would like to do this in the motion layout scene preferably.
Thanks for any ideas guys


text:
Q: How can i print information from one main file txt or php to all content on a website Thanks for taking the time to look at this.
Okay I am looking for a way that I can use one file to edit all content on my website.
So if I am using a file in my header saying:
<?php include("content.php");?>
<?php include("content.txt");?>

in content.php or conntent.txt you have:
<?php
$SayHello = "Hello, How are you I am john";
$SayNo = "No, Try this";

?>

in index.php you have something like this

 print $SayHello

print $SayNo

I know i am doing my code wrong i would like to know the right way to do this thank you

A: If you want to run PHP code, you need to tell PHP that you're writing PHP code:
<?php print $SayHello ?>


text:
Q: Can we make the link formatting more obvious in the suggested edits queue? Link in a suggested edit show up as such:

You can't even tell that it is a link. It isn't obvious until you mouseover the text and even then, you can miss it really easily:

I've rejected a couple edits because it wasn't apparent that the user had added a link. Can we make this more obvious in the queue? Maybe make the text blue and add a highlight? Like this:


text:
Q: How can I target the same player that was previously targeted randomly? I am making a Minecraft commands map and need to give a random player two effects and one item.
I understand that each effect/item needs to be given in a separate command. The problem is, @r targets a random player each time, but I need the effects and items to be given to the same randomly targeted player.
How can I give these effects/items to the same player?

A: *

*Tag the random player.
/tag @r add RandomSelection

Note, your tag name should not contain spaces!

*Give them the effects and item by targeting the player with the tag.
/effect @a[tag=RandomSelection] fire_resistance
/give @a[tag=RandomSelection] stone

*Remove the tag.
/tag @a[tag=RandomSelection] remove RandomSelection


text:
Q: Given a non planar graph, find a planar cycle basis Having a nonplanar Graph, is there a theorem that tells me if I can always find a cycle basis that forms a planar graph or the opposite, that I cannot find it?
Can I add vertices in the nonplanar graph to find such a planar cycle basis?
So to say as an approximated (in terms of solution quality) valid planar cycle basis

A: The graph you're forming from the cycle basis is obtained from the original graph just by deleting edges that are not part of any cycle. This is exactly the bridges: edges whose removal disconnects the graph.
If deleting these would produce a planar graph, then the original graph must also have been planar. That's because we can put the bridges back, one at a time, without destroying planarity. Whenever we put back a bridge, we are joining two different components (which, by assumption, are planar). We can always turn the plane embeddings of those components "inside out" if necessary so that the endpoint of the bridge lies on the outside face; then, we can just draw the edge through the outside face of both components. This produces a plane embedding of the graph with the bridge.
Therefore you'll never get a planar graph this way if the original graph was not planar.


text:
Q: Display image from array of pathnames My goal is to display an image on the page from the one of the folders, for example ~/Content/Images/img_1.jpg.
The image paths are saved inside an array that I successfully fetch from a DB. What I am struggling with is the fact that there are special characters in the passed command.
So I'd have something like @Url.Content("~/Content/Images/img_1.jpg")
to pass in the DB field and when it gets passed to JQuery .html() it doesn't work properly and gives a 404. I looked into escaping the characters but I don't think that works. This might be a bad way of doing the whole thing though, so I am open to ideas on how to facilitate that dynamic image loading...
EDIT: I have figured a bit out. The DB will hold only the image name, not the full path. So only the escaping the pathname characters in JS in HTML context are left.
"";

A: I escaped the string inside using the mapping from this answer.
So I got:
"";
With the image being placed in the respective directory.


text:
Q: Why is "undefined" illegal as a request header value of Node's lib/http.js? The following code
const http = require('http')

const req = http.request('http://localhost:8080')
req.setHeader('x-api-key', undefined)
req.end()

gives a ERR_HTTP_INVALID_HEADER_VALUE error.
What might be the reason why this behavior is chosen?
Getting an unset header key with req.getHeader results in undefined, too. So from  a security standpoint how can just silently not setting the value become dangerous? Or is there any other reason?

A: Nothing about the error message mentions security in any way.
Header values have to be strings. If you pass undefined then it is probably because you are passing a variable and it is undefined by mistake. An error alerts you to that so you can fix it.
Use the removeHeader method to unset a header.


text:
Q: Set of vertices of graph $G$ is power set of $\{0,1,2,3,4,5,6,7,8,9\}$. Two vertices $A,B$ are connected iff $|A \Delta B |\le 2$. Then $|E(G)|=?$
Let the set of vertices of graph $G$ be the power set of $\{0,1,2,3,4,5,6,7,8,9\}$ and two (different) vertices $A,B$ are connected iff $|A \Delta B |\le 2$. How many edges does $G$ have?

I just need proof verification:

*

*If $|A\Delta B|=0$ then there is no edges.

*If $|A\Delta B|=1$ then there is ${10\choose 1}$ choises for $A\setminus B$ and $2^9$ for $A\cap B$ so we have $10\cdot 2^9$ edges.

*If $|A\Delta B|=2$ then we have 2 subcases:

*

*If $|A\setminus B| =2$ then there is ${10\choose 2}$ choises for $A\setminus B$ and $2^8$ for $A\cap B$ so we have $45\cdot 2^8$ edges.

*If $|A\setminus B| =1$ and $|B\setminus A| =1$ then there is ${10\choose 2}$ choises for $A\Delta B$ and $2^8$ for $A\cap B$ so we have again $45\cdot 2^8$ edges.

So we have overall $110\cdot 2^8$ edges?

A: This looks right. I would add the preliminary statement for clarity:
For ensuring edges are only counted once, assume $|A|\geq|B|$
Then the rest follows

*

*If $|A\triangle B|=0$ then $A=B$ and there is no edge.

*If $|A\triangle B|=1$ then there are ${10\choose 1}$ choices for $A\setminus B$ and $2^9$ for $A\cap B$ so we have $10\cdot 2^9$ edges.

*If $|A\triangle B|=2$ then there are $2^8$ choices for $A\cap B$ and either:

*

*the ${10\choose 2}=45 $ choices for $A\triangle B$ are in $A$, giving $45\cdot 2^8$ edges or

*the ${10\choose 2}$ choices for $A\triangle B$ are split between $A$ and $B$ (at each end of an edge)  giving another $45\cdot 2^8$ edges

So a total of $55\cdot 2^9$ edes as you found.

A: Another method. First, note the number of ordered pairs $(A,B)$, where $A,B\subseteq [0,9]\cap \mathbb Z$ and $|A\Delta B|=k$, is $2^{10}\binom{n}k$. You choose the elements of $|A\cap B|$ in $\binom{n}k$ ways, and independently choose the subset $A$ in $2^{10}$ ways. The choice of $A\Delta B$ and $A$ determines $B$. Adding up $k=1$ and $k=2$, and dividing by two to get unordered pairs, you get $\frac12(2^{10}\binom{10}1+2^{10}\binom{10}2)$, agreeing with your answer.


text:
Q: What type of documentation does WordPress code follow? I am trying to begin using some sort of standard for documenting my PHP code.  Most of my code is in the form of WordPress plugins, some are getting quite complex, and I need to document it.
So my question is simple, what system does WordPress use to document their code?

A: I think it uses phpDoc.
There is also a guide for WordPress inline documentation.


text:
Q: Get file path from Uri showing exception in android 10 this is my code to get a real file path from Uri. It is working fine below all devices except Android 10. Please help me out. Thanks in Advance
enter code here

fun getPathFromUri(
        context: Conteenter code herext,
        Uri: Uri
    ): String? {
        val isKitKat: Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            val docId: String = DocumentsContract.getDocumentId(uri)
            val split = docId.split(":").toTypedArray()
            val type = split[0]
            if ("primary".equals(type, ignoreCase = true)) {

                return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
            }

            // TODO handle non-primary volumes
        } else if (isDownloadsDocument(uri)) {
            val id: String = DocumentsContract.getDocumentId(uri)
            val contentUri: Uri = ContentUris.withAppendedId(
                Uri.parse("content://downloads/public_downloads"),
                java.lang.Long.valueOf(id)
            )
            return getDataColumn(context, contentUri, null, null)
        } else if (isMediaDocument(uri)) {
            val docId: String = DocumentsContract.getDocumentId(uri)
            val split = docId.split(":").toTypedArray()
            val type = split[0]
            var contentUri: Uri? = null
            if ("image" == type) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            } else if ("video" == type) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            } else if ("audio" == type) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            }
            val selection = "_id=?"
            val selectionArgs = arrayOf(
                split[1]
            )
            return getDataColumn(context, contentUri, selection, selectionArgs)
        }
    } else if ("content".equals(uri.scheme, ignoreCase = true)) {

        // Return the remote address
        return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(
            context,
            uri,
            null,
            null
        )
    } else if ("file".equals(uri.scheme, ignoreCase = true)) {
        return uri.path
    }
    return null
}

fun getDataColumn(
    context: Context, uri: Uri?, selection: String?,
    selectionArgs: Array<String>?
): String? {
    var cursor: Cursor? = null
    val column = "_data"
    val projection = arrayOf(
        column
    )
    try {
        cursor = context.contentResolver.query(
            uri!!, projection, selection, selectionArgs,
            null
        )
        if (cursor != null && cursor.moveToFirst()) {
            val index: Int = cursor.getColumnIndexOrThrow(column)
            return cursor.getString(index)
        }
    } finally {
        if (cursor != null) cursor.close()
    }
    return null
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
fun isExternalStorageDocument(uri: Uri): Boolean {
    return "com.android.externalstorage.documents" == uri.authority
}

/**
 * @param Uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
fun isDownloadsDocument(uri: Uri): Boolean {
    return "com.android.providers.downloads.documents" == uri.authority
}

/**
 * @param Uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
fun isMediaDocument(uri: Uri): Boolean {
    return "com.android.providers.media.documents" == uri.authority
}

/**
 * @param Uri The Uri to check.
 * @return Whether the Uri authority is Google Photos.
 */
fun isGooglePhotosUri(uri: Uri): Boolean {
    return "com.google.android.apps.photos.content" == uri.authority
}`enter code here`


text:
Q: Not able to get to Web API end point? I'm taking over a what is supposed to be a Web API project and I'm having a problem getting to an endpoint to test and I'm not understanding why.
There is a HomeController.cs in the project but it is of type Controller. If I go to http://localhost:64650/api/ I can get to that View.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }
}

In order to test things out and try to determine why I can't get to some of the listed endpoints I decided to create a TestController that is of type ApiController. This is just the default code when you create a new Web API controller.
public class TestController : ApiController
{
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
}

My understanding is that I should be able to go to http://localhost:64650/api/Test and have it return "Value1" and "Value2".
Instead what I get
Runtime Error
Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

I even put a break point on the return of the Get() on the TestController and it never gets there.
This is the same error I get when I try to hit any of the other endpoints. Any suggestions on what I can look at to get it to work?
UPDATE
I turned off the custom errors in the web.config file and now I see this error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /api/Test

This is the web.config
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Validation-20161122025514.mdf;Initial Catalog=aspnet-OnBoardingValidation-20161122025514;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="DataContext" connectionString="DATA SOURCE=TSTAFF;PASSWORD=*****;USER ID=*****" providerName="Oracle.ManagedDataAccess.Client" />
    <add name="IDMEntities" connectionString="DATA SOURCE=TSTAFF;PASSWORD=*****;PERSIST SECURITY INFO=True;USER ID=*****" providerName="Oracle.ManagedDataAccess.Client" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <remove invariant="Oracle.ManagedDataAccess.Client" />
      <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
  </system.data>
  <system.web>

    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <customErrors mode="Off"></customErrors>
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <publisherPolicy apply="no" />
        <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <oracle.manageddataaccess.client>
    <version number="*">
      <dataSources>
        <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
      </dataSources>
    </version>
  </oracle.manageddataaccess.client>
  <entityFramework>
    <defaultConnectionFactory type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess" />
    <providers>

      <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

Route.config
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

WebApiConfig
public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    // Configure Web API to use only bearer token authentication.
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}


text:
Q: Restrict only 1 file to use sendmail I want to restrict access to sendmail process, to only 1 php file /var/www/mysite/contact.php
How can I do this? Maybe there is a trick with Iptables or sendmail configuration?
I want to secure sendmail on my Debian Server, to avoid spam/hacking.
Thanks for your help

A: If you are using Debian then your sendmail process is likely to be exim4 or postfix.  These programs have significantly different configuration processes, both of which are simpler than the process for the original sendmail program.
Sendmail tends to be used by multiple system processes, so restricting local access to only one process may cause problems.  (Many system monitoring processes will use email to notify you of issues.)
You can restrict outgoing connections to port 25 to only your email process with iptables.  This will prevent any malicious processes from sending email directly.
You can to rate limit outgoing emails with either iptables or your sendmail program (exim4 has this capability, postfix may have it).
You can restrict the valid sending user-ids to prevent random senders.  You could require the apache user to authenticate before sending email.  This will make it more difficult from code injected to your site to send email.
If you do your contact.php correctly, you can (and should) limit the sending domain to your domain.  Don't allow use of random domains on outgoing email. Use a Reply-To address if you want to reply to a name provided to contact.php.
Make sure you do the rest of the setup for your mail server to prevent your server from being classified as Spam.


text:
Q: AJAX live search returning HTTP 500 error I get a 500 Internal Server Error when I use live search.
Html code:

         <input type="text" name="search" id="search"
                placeholder="@lang('index.Type here to search')">
         <button>@lang('index.Search')</button>

         results is here

Ajax code:

My controller:
public function search(\Illuminate\Http\Request $request) {

    $currentLangKey = session()->get('language') ?? App::getLocale();
    $languageId = Language::whereNull('deleted_at')->where('name', $currentLangKey)->first()->id ?? 0;

    $search = mb_strtolower($request->get('search'));
    $bookSearch = DB::table('books')->select('id', 'name', 'category_id', 'collection_id', 'price',
        'cover', 'seller', 'publisher',
        DB::raw("(SELECT name FROM categories WHERE id = category_id) as category_name"),
        DB::raw("COALESCE((SELECT AVG(star) FROM comments WHERE book_id = books.id), 5) as star_average"),
        DB::raw("(SELECT name FROM collections WHERE id = collection_id) as collection_name"))
        ->where(DB::raw('lower(name)'), 'like', '%' . $search . '%')
        ->where('language_id', $languageId)
        ->paginate(16);

    return response()->json($bookSearch);

}

A:
The search string is sent to your server through value attribute

//...
$("input[name=search]").keyup(function () {
            var value = $(this).val();
            var data = "value=" + value;
//...

Fix
$search = mb_strtolower($request->get('value'));

A: You can try a couple of things. First is change you post type in ajax from get to post. Second is change the value of $search to $request->value which you are sending using Ajax


text:
Q: Average 2 hex colors together in javascript Alright thought I would throw this one out there for the crowd to think over.
Given a function (written in javascript) that expects two strings formated like a hex color (ex #FF0000)
return a hex color that is the average of both of the colors passed.
function averageColors(firstColor,secondColor)
{
  ...
  return avgColor;
}

--edit--
average would be defined as
if the color passed was yellow and the second was light purple the returned color would be a medium orange

A: Smells like homework to me, but here's my clue.
Take each hex value for R, G, and B, and average each of them.  If necessary convert to Decimal to do the math.

function d2h(d) {return d.toString(16).padStart(2,'0');}
function h2d(h) {return parseInt(h,16);}

Then return a string containing the concatenated values of the three elements.

A: I hate sounding like the oh-so-broken jQuery record, but there is a jQuery plugin for this already.

A: A quick/dirty/convenient/ES6 way to blend two hex colors by a specified perecentage:

// blend two hex colors together by an amount
function blendColors(colorA, colorB, amount) {
  const [rA, gA, bA] = colorA.match(/\w\w/g).map((c) => parseInt(c, 16));
  const [rB, gB, bB] = colorB.match(/\w\w/g).map((c) => parseInt(c, 16));
  const r = Math.round(rA + (rB - rA) * amount).toString(16).padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount).toString(16).padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount).toString(16).padStart(2, '0');
  return '#' + r + g + b;
}

console.log(blendColors('#00FF66', '#443456', 0.5));

Where amount should be 0 to 1, with 0 being exactly colorA, 1 being exactly colorB, and 0.5 being the "midpoint".

A: Only requires a few lines of POJS if you don't want to bother with lots of unnecessary stuff:
// Expects input as 'nnnnnn' where each nn is a
// 2 character hex number for an RGB color value
// e.g. #3f33c6
// Returns the average as a hex number without leading #
var averageRGB = (function () {

  // Keep helper stuff in closures
  var reSegment = /[\da-z]{2}/gi;

  // If speed matters, put these in for loop below
  function dec2hex(v) {return v.toString(16);}
  function hex2dec(v) {return parseInt(v,16);}

  return function (c1, c2) {

    // Split into parts
    var b1 = c1.match(reSegment);
    var b2 = c2.match(reSegment);
    var t, c = [];

    // Average each set of hex numbers going via dec
    // always rounds down
    for (var i=b1.length; i;) {
      t = dec2hex( (hex2dec(b1[--i]) + hex2dec(b2[i])) >> 1 );

      // Add leading zero if only one character
      c[i] = t.length == 2? '' + t : '0' + t;
    }
    return  c.join('');
  }
}());

A: Here's a compact set of relevant (interdependent) functions:
Hex ⟷ RGB Color Conversion:
function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}

Calculate Average of 2 Hex Colors: Requires conversion functions (above)
function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2); return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}

Generate Random Hex Color:
function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}

Run snippet for demo:

// color functions (average/random/conversion)
function hexToRgb(h){return['0x'+h[1]+h[2]|0,'0x'+h[3]+h[4]|0,'0x'+h[5]+h[6]|0]}
function rgbToHex(r,g,b){return"#"+((1<<24)+(r<<16)+(g<<8)+ b).toString(16).slice(1);}
function rndHex(){return'#'+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);}
function avgHex(h1,h2){a=hexToRgb(h1);b=hexToRgb(h2);return rgbToHex(~~((a[0]+b[0])/2),~~((a[1]+b[1])/2),~~((a[2]+b[2])/2));}

//code below is just for the demo
function auto(){if(chk.checked){tmr=setInterval(rnd,1000)}else{clearTimeout(tmr)}}auto();
function rnd(go){for(h of[h1,h2]){h.value=rndHex();}avgInput();}
addEventListener('input',avgInput);
function avgInput(){ // get avg & colorize
 ha.value=avgHex(h1.value,h2.value);
 for(h of [h1,h2,ha])h.style.background=h.value;
}
*{font-family:monospace;font-size:5vw; }
Color 1 → <input id='h1'>

Average → <input id='ha'>

Color 2 → <input id='h2'>

Type hex colors or <input type='checkbox' id='chk' onclick='auto()' style=' transform: scale(1.5)'checked>Autorandom

A: Here is my function, hope it helps.
function averageColors( colorArray ){
    var red = 0, green = 0, blue = 0;

    for ( var i = 0; i < colorArray.length; i++ ){
        red += hexToR( "" + colorArray[ i ] + "" );
        green += hexToG( "" + colorArray[ i ] + "" );
        blue += hexToB( "" + colorArray[ i ] + "" );
    }

    //Average RGB
    red = (red/colorArray.length);
    green = (green/colorArray.length);
    blue = (blue/colorArray.length);

    console.log(red + ", " + green + ", " + blue);
    return new THREE.Color( "rgb("+ red +","+ green +","+ blue +")" );
}

//get the red of RGB from a hex value
function hexToR(h) {return parseInt((cutHex( h )).substring( 0, 2 ), 16 )}

//get the green of RGB from a hex value
function hexToG(h) {return parseInt((cutHex( h )).substring( 2, 4 ), 16 )}

//get the blue of RGB from a hex value
function hexToB(h) {return parseInt((cutHex( h )).substring( 4, 6 ), 16 )}

//cut the hex into pieces
function cutHex(h) {if(h.charAt(1) == "x"){return h.substring( 2, 8 );} else {return h.substring(1,7);}}

A: Very late to this party, but I was personally looking for a way to average an undefined amount of HEX values. Based on the answer  @RobG, I came up with this. Granted, the more colors you add the more brown/greyish they get, but, perhaps it helps!

/**
 * Averages an array of hex colors. Returns one hex value (with leading #)
 *
 * @param {Array} colors - An array of hex strings, e.g. ["#001122", "#001133", ...]
 */
function averageHex(colors) {

  // transform all hex codes to integer arrays, e.g. [[R, G, B], [R,G,B], ...]
  let numbers = colors.map(function(hex) {
    // split in seperate R, G and B
    let split = hex.match(/[\da-z]{2}/gi);

    // transform to integer values
    return split.map(function(toInt) {
      return parseInt(toInt, 16);
    });
  });

  // reduce the array by averaging all values, resulting in an average [R, G, B]
  let averages = numbers.reduce(function(total, amount, index, array) {
    return total.map(function(subtotal, subindex) {

      // if we reached the last color, average it out and return the hex value
      if (index == array.length - 1) {

        let result = Math.round((subtotal + amount[subindex]) / array.length).toString(16);

        // add a leading 0 if it is only one character
        return result.length == 2 ? '' + result : '0' + result;

      } else {
        return subtotal + amount[subindex];
      }
    });
  });

  // return them as a single hex string
  return "#" + averages.join('');
}

console.log(averageHex(["#FF110C", "#0000AA", "#55063d", "#06551e"]));
// expected: #571b44, see also https://www.colorhexa.com/ and enter "#FF110C+#0000AA+#55063d+#06551e"

A: Here is the function
function avgColor(color1, color2) {
  //separate each color alone (red, green, blue) from the first parameter (color1)
  //then convert to decimal
  let color1Decimal = {
    red: parseInt(color1.slice(0, 2), 16),
    green: parseInt(color1.slice(2, 4), 16),
    blue: parseInt(color1.slice(4, 6), 16)
  }
  //separate each color alone (red, green, blue) from the second parameter (color2)
  //then convert to decimal
  let color2Decimal = {
    red: parseInt(color2.slice(0, 2), 16),
    green: parseInt(color2.slice(2, 4), 16),
    blue: parseInt(color2.slice(4, 6), 16),
  }
  // calculate the average of each color (red, green, blue) from each parameter (color1,color2)
  let color3Decimal = {
    red: Math.ceil((color1Decimal.red + color2Decimal.red) / 2),
    green: Math.ceil((color1Decimal.green + color2Decimal.green) / 2),
    blue: Math.ceil((color1Decimal.blue + color2Decimal.blue) / 2)
  }
  //convert the result to hexadecimal and don't forget if the result is one character
  //then convert it to uppercase
  let color3Hex = {
    red: color3Decimal.red.toString(16).padStart(2, '0').toUpperCase(),
    green: color3Decimal.green.toString(16).padStart(2, '0').toUpperCase(),
    blue: color3Decimal.blue.toString(16).padStart(2, '0').toUpperCase()
  }
  //put the colors (red, green, blue) together to have the output
  let color3 = color3Hex.red + color3Hex.green + color3Hex.blue
  return color3
}
console.log(avgColor("FF33CC", "3300FF"))
// avgColor("FF33CC", "3300FF") => "991AE6"

console.log(avgColor("991AE6", "FF0000"))
// avgColor("991AE6", "FF0000") => "CC0D73"

console.log(avgColor("CC0D73", "0000FF"))
// avgColor("CC0D73", "0000FF") => "6607B9"

To check you can use this link and midpoint 1 then blend
https://meyerweb.com/eric/tools/color-blend/#CC0D73:0000FF:1:hex