text:
Q: How to avoid update checks with CMake FetchContent? all.
I decided to use the new cmake macro to download external dependencies.
I took the sample code from the documentation for the Catch2 library.
include(FetchContent)

FetchContent_Declare(
    Catch2
    GIT_REPOSITORY https://github.com/catchorg/Catch2.git
    GIT_TAG        v2.13.4
)
FetchContent_GetProperties(Catch2)
if(NOT Catch2_POPULATED)
    FetchContent_Populate(Catch2)
    add_subdirectory(${catch2_SOURCE_DIR} ${catch2_BINARY_DIR})
endif()

The solution works great, except for the ability to restart the cmake when I am offline (no wifi and mobile network only me and my laptop).
I get the following error:
[0/7] Performing update step for 'catch2-populate'
fatal: «https://github.com/catchorg/Catch2.git/» недоступно: Could not resolve host: github.com
CMake Error at /Users/evgeny.proydakov/repository/ihft/build/_deps/catch2-subbuild/catch2-populate-prefix/tmp/catch2-populate-gitupdate.cmake:97 (execute_process):
  execute_process failed command indexes:

    1: "Child return code: 128"

FAILED: catch2-populate-prefix/src/catch2-populate-stamp/catch2-populate-update
cd /Users/evgeny.proydakov/repository/ihft/build/_deps/catch2-src && /usr/local/Cellar/cmake/3.20.1/bin/cmake -P /Users/evgeny.proydakov/repository/ihft/build/_deps/catch2-subbuild/catch2-populate-prefix/tmp/catch2-populate-gitupdate.cmake
ninja: build stopped: subcommand failed.

CMake Error at /usr/local/Cellar/cmake/3.20.1/share/cmake/Modules/FetchContent.cmake:1012 (message):
  Build step for catch2 failed: 1
Call Stack (most recent call first):
  /usr/local/Cellar/cmake/3.20.1/share/cmake/Modules/FetchContent.cmake:1141:EVAL:2 (__FetchContent_directPopulate)
  /usr/local/Cellar/cmake/3.20.1/share/cmake/Modules/FetchContent.cmake:1141 (cmake_language)
  /usr/local/Cellar/cmake/3.20.1/share/cmake/Modules/FetchContent.cmake:1184 (FetchContent_Populate)
  .cmake/icmake.cmake:46 (FetchContent_MakeAvailable)
  CMakeLists.txt:10 (include)

-- Configuring incomplete, errors occurred!

Is it possible to download dependency one time, check revision and don't try to connect each time to remote server?

A: The documentation for FetchContent_Populate says you can get exactly what you want with the FETCHCONTENT_UPDATES_DISCONNECTED cache variable:

FETCHCONTENT_UPDATES_DISCONNECTED
... This ... disables the
update stage. Therefore, if content has not been downloaded
previously, it will still be downloaded when this option is enabled.
This can speed up the configure stage... It is OFF by default.

So set this one to ON globally, or for Catch2 only, set the variable FETCHCONTENT_UPDATES_DISCONNECTED_Catch2 to ON.


text:
Q: IndexError when trying to get output of layer in Keras model I am trying to see what my data looks like after going through a convolutional layer in my Keras model. I am using the Theano backend. The code I have has been cobbled together from the Keras Github:
def get_layer0_outputs(model, test_data):
    output = model.layers[0].output
    inputs = [K.learning_phase()] + model.inputs
    func = K.function(inputs, [output])
    return func([0] + [test_data])

What I'm trying to do here is compile a function for the first layer (a Conv2D layer) in my network. The test_data argument is an np.ndarray. My model is loaded correctly, and I have already trained it with decent accuracy.
However, when I call this function, I get a cryptic stacktrace:
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/theano/compile/function_module.py", line 884, in __call__
    self.fn() if output_subset is None else\
  File "/usr/local/lib/python3.5/dist-packages/theano/gof/op.py", line 872, in rval
    r = p(n, [x[0] for x in i], o)
  File "/usr/local/lib/python3.5/dist-packages/theano/tensor/nnet/abstract_conv.py", line 1626, in perform
    conv_out = self.conv(img, kern, mode="valid", dilation=self.filter_dilation)
  File "/usr/local/lib/python3.5/dist-packages/theano/tensor/nnet/abstract_conv.py", line 1531, in conv
    dilated_kern[n, im0, ...],
IndexError: index 1 is out of bounds for axis 1 with size 1

What does this mean? Am I calling my function incorrectly?

A: Your function works for me using the following model:
a = Input(shape=(224,224,3))
b = Conv2D(8, 3, strides=(2,2))(a)
model = Model(inputs=a, outputs=b)
model.compile(optimizer='sgd', loss='mse')

def get_layer0_outputs(model, test_data):
    output = model.layers[0].output
    inputs = [K.learning_phase()] + model.inputs
    func = K.function(inputs, [output])
    return func([0] + [test_data])

print get_layer0_outputs(model, np.zeros((1, 224, 224, 3)))[0].shape

Note that layer 0 is an Input layer not a Conv2D, but the code also works for layer 1. I'm using the tensorflow backend so I don't know if the difference is your model or the theano backend.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use history.push( ) and call a function at the same time? I want to implement a button, in the AppBar provided by Material UI, that when clicked, it redirects me to a new page (from '/' to '/login'). So, I used history.push( ) and it works. But, the page does not render another component that it should display. The component is a function. How can I make this work?
I'm new to ReactJS and I'm using stuff from Material-UI so I don't how to tweak things to my favor.
It's a lot of code, so I made a working example for those who want to see what I mean:
https://codesandbox.io/embed/6jmlxlj3wz?fontsize=14

A: Use react-router-dom to manage your routes and for history.push functionality. Its support for React is built in so it will be a much more declarative coding experience for you.

A: A few things:
In your App.js you are passing history to Router but you haven't imported it...
import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import Login from './components/Login';
import history from './history'; // import it to use it

class App extends Component {
  render() {
    return (
      <Router history={history}>

          <Switch>
            <Route exact path="/" component={Home} /> // notice I also added exact
            <Route path="/login" component={Login} />
          </Switch>

      </Router>
    );
  }
}

export default App;

And here is your Home.js cleaned up... (no need for the handleClick function...)
function gotoLogin() {
  history.push('/login');
}

function ContainedButtons(props) {
  const { classes } = props;
  return (

      <Button
        variant="contained"
        color="secondary"
        className={classes.button}
        onClick={gotoLogin}
      >
        Login
      </Button>

  );
}

See a working demo here: https://codesandbox.io/s/ovwrm11wl5


text:
Q: TSQL Transpose FROM Rows to Colums No Aggregration I have the following style data from a csv file I have imported
Appt_ID,Sched_ID,Person_ID,Order_Field_Name,Order_Field Value
10001,2002,123456,Name,Fred Jones
10001,2002,123456,Address,"123 ABC St, Seasame Town"
10001,2002,123456,Appt_type,Consultation
10001,2002,123456,Sched_Start_time,12:00PM
10001,2002,123456,Sched_End_time,02:00PM
10001,2002,123456,Appt_With,Larry Smithe,
10002,2000,987654,Name,Mary Mags
10002,2000,987654,Address,"258 Street Ave, Neverland"
10002,2000,987654,Appt_type,Procedure
10002,2000,987654,Sched_Start_time,10:00AM
10002,2000,987654,Sched_End_time,4:00PM
10002,2000,987654,Appt_With,Larry Smithe

I need to transform it to look like this. I have tried using a pivot function but not coming out right.
Appt_ID,Sched_ID,Person_ID,Name,Address,Appt_type,Sched_Start_time,Sched_End_time,Appt_With
10001,2002,123456,Fred Jones,"123 ABC St, Seasame Town",Consultation,12:00PM,02:00PM,Larry Smithe
10002,2000,987654,Mary Mags,"258 Street Ave, Neverland",Procedure,10:00AM,4:00PM,Larry Smithe

Any help would be great.
Thanks in advance.

A: You can do this with conditional aggregation:
select appt_id, sched_id, person_id,
       max(case when order_field = 'Name' then order_value end) as name,
       max(case when order_field = 'Address' then order_value end) as address,
       max(case when order_field = 'Appt_type' then order_value end) as appt_type,
       . . .
from table t
group by appt_id, sched_id, person_id;


text:
Q: What should i do to apply datepicker to this code?

    @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })

A: Add attributes to your property
[DataType(DataType.Date)]
 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
 public DateTime StartDate {get; set;}
and in your view
@Html.EditorFor(model => model.StartDate)


text:
Q: How to customise the tag format of the Maven release plugin? In our SVN repo, we store tags like this:
trunk
    project_a
    project_b
branches
    project_a
        branch_x
        branch_y
    project_b
tags
    project_a
        1.0
        1.1
    project_b
        1.0

When I run the Maven release plugin's "prepare" goal on project A, by default it creates the tag as "tags/project_a-x.x", which does not match my tag naming scheme above. I am thus depending upon whoever does the release (i.e. a fallible human) to spot this and change the tag to "tags/project_a/x.x". How can I tell the release plugin to use the correct format by default?
The "prepare" goal has a "tag" configuration option that claims to do this, but if I set it as follows:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-release-plugin</artifactId>
    <version>2.1</version>
    <configuration>
        <tag>${project.artifactId}/${project.version}</tag>
    </configuration>
</plugin>

... then the created tag is "tags/project_a/x.x-SNAPSHOT", i.e. it uses the pre-release version number instead of the release version number. Hardcoding the tag name into the POM seems wrong too.
How can I ensure that the tag is correct by default?

A: It looks like this is not possible until one of these bugs is fixed:

*

*MRELEASE-150: Can't add prefix to tags without affecting version (not scheduled)

*MRELEASE-159: Support a pattern to generate the release tag (scheduled for 2.2)

*MRELEASE-259: Provide a configuration settings for default tag/label to use when releasing (not scheduled)

A: The release plugin now supports the tagNameFormat configuration option, which defaults to @{project.artifactId}-@{project.version}. In your case, you could do something like:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-release-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
        <tagNameFormat>@{project.artifactId}/@{project.version}</tagNameFormat>
    </configuration>
</plugin>

A: If you are passing in the releaseVersion, you can do this:
<tag>${project.artifactId}/${releaseVersion}</tag>


text:
Q: Resume Activity I have 3 activities let's say MainActivity, Activity 2, and Activity 3.
In the MainActivity I have a button (start/stop) when I click on this button an animation start but when I go to activity 2 or activity 3 and I comeback to MainActivity the animation stopped by itself.
But me I want that the animation of the MainActivity never stop until I click the button stop.
I tried this code in AndroidManifest.xml but it doesn't work.
android:launchMode="singleInstance"

A: If you go back from MainActivity then your Activity will be Destroyed if you do not fire an Intent in onbackPressed() regardless of launchMode.
launchMode are  instruction for how the activity should be launched. On stack pop it will destroy anyway. Read launchModes .
Solution:-  Solution to your problem SharedPreference. Save the current state of animation and restart it with previous state when Activity relaunched.


text:
Q: Flutter: FAILURE: Build failed with an exception on Could not create task ':app:compileFlutterBuildDebug'. Must provide Flutter source directory Recently I immigrated my project to a new system and rectified all the errors but I got an exception that says provide flutter source directory.
I added the flutter SDK path and checked but I still couldn't solve the
problem.
FAILURE: Build failed with an exception.

* Where:
Script 'C:\src\flutterSDK\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 572

* What went wrong:
A problem occurred evaluating root project 'android'.
> A problem occurred configuring project ':app'.
   > Could not create task ':app:compileFlutterBuildDebug'.
      > Must provide Flutter source directory

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

I have run the Flutter doctor cmd and everything is fine
flutter doctor -v
[√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [Version 10.0.19043.1165], locale en-IN)
    • Flutter version 2.5.0 at C:\src\flutterSDK\flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 4cc385b4b8 (6 days ago), 2021-09-07 23:01:49 -0700
    • Engine revision f0826da7ef
    • Dart version 2.14.0

[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at C:\Users\Barfi Nandeti\AppData\Local\Android\sdk
    • Platform android-31, build-tools 31.0.0
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[√] Android Studio (version 2020.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[√] VS Code (version 1.60.0)
    • VS Code at C:\Users\Barfi Nandeti\AppData\Local\Programs\Microsoft VS Code
    • Flutter extension can be installed from:
       https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (2 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 93.0.4577.63
    • Edge (web)   • edge   • web-javascript • Microsoft Edge 93.0.961.47

• No issues found!

A: This is probably because the flutter SDK is in a different directory than your old machine. Checkout this answer.


text:
Q: My breadcrumb does not align with the search bar using Bootstrap As you can see in this example, my breadcrumb does not align like my search bar, I want it to be at the left-middle of the red background (just like the search bar). I'm using Bootstrap to do so.
Here is my code :

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Test1

Test2

Test3

                <form class="d-flex">
                    <input class="form-control mr-1" type="search" placeholder="Search..." aria-label="Search">
                    <button class="btn btn_rechercher" type="submit">Search</button>
                </form>

Cordially

A: Just apdate your HTML with following code

Test1

Test2

Test3


text:
Q: Recursive function that sums the first n recriprocals The function below accepts an integer n and returns the sum of the first n reciprocals.
sum(2) should return 1.5
Here is what I have:
 public double sum(int n) {

     if (n < 0) {
       throw new IllegalArgumentException("Illegal Power Argument");
    }

    double zero = 0.0;

    if(n == 0)
       return zero;

    else
       return (1/n) + sum(n-1);
 }

I am almost certain that this should work but instead it's returning 1.0 for basically everything.

A: You are using integer division. Cast it to a double:
return (1/(double)n) + sum(n-1);

Alternatively, use:
return (1.0/n) + sum(n-1);

A: (1/n) is integer division - use (1.0/n) instead.

A: Try this change:
return (1.0/n) + sum(n-1);


text:
Q: Screen upside down after upgrade to 18.04.01 After upgrading to 18.04 my screen suddendly switched upside down, since my Laptop apparently has a rotation sensor. I temporarily fixed it with xrandr -o normal and disabled the gnome rotation sensor, because I could not fix the problem by physically holding my laptop upside down.
The problem is, that the rotation switches back to inverted with every restart.
I tried to write a script, which executes the xrandr command with every restart and added a xrandr --output eDP-1 --rotate normal in the gdm3 file, but none of that works.
Is there any way to set the default orientation back to normal or write a working script, which fixes the problem at a restart (including stand-by).

A: You can use xrandr -o normal from the command prompt and it will fix it.

A: *

*Remove the iio-sensor-proxy which is what triggers the orientation changes to happen.
sudo apt-get remove --purge iio-sensor-proxy

*Restart your computer

*Go into "Settings > Displays" (gnome-control-center). Change the "Orientation" setting for your monitor to landscape.

*Restart again to ensure that orientation is correct
Why this works is that even after you disable the orientation changes, gnome holds onto a previous orientation that was active and treats it as a sort of default even though it is no longer actively using the sensor to determine orientation. By manually changing the orientation, you are resetting the default.

A: I had been facing with this problem so I searched for the solution and found this. But unfortunately, I didn't found the solution from here but I found it by myself. Let me share my solution.

*

*Go to the search box

*Search "Lock Orientation"

*Click it

The problem is solved.


text:
Q: Bootstrap form labels in mobile decrease in size when input text gets focus I have a form in a web page that uses Bootstrap class, sample is below:
<form>

        Username
        <input type="text" name="username class="form-control" />

        Password
        <input type="password" name="passwordclass="form-control" />

    <input type="submit" class="btn btn-primary" value="submit" name="submit" />
</form>

On mobile, the form initially displays as I hoped it would. The form elements are stacked vertically.
But when I tap on the username or password input boxes, the labels would decrease in size. How do I keep the label text size as is?
Thanks

A: Here is working fiddle that work nice
http://jsfiddle.net/52VtD/9094/
<form class="form-horizontal" role="form">

      First Name

         <input type="text" class="form-control" id="firstname"
            placeholder="Enter First Name">

      Last Name

         <input type="text" class="form-control" id="lastname"
            placeholder="Enter Last Name">

         <input type="submit" class="btn btn-primary" value="submit" name="submit" />

</form>

A: On the viewport of the meta tag, the attribute/ value content="width=device-width, initial-scale=1" was added. The complete meta tag is now:
<meta name="viewport" content="width=device-width, initial-scale=1">

This seems to have solved the problem. On mobile, when I tap on on input entry, all label font sizes are retained


text:
Q: Is it possible to get NuGet.exe running disconnected from Visual Studio? I've been wrestling with NuGet for a few days now and I'm turning to StackOverflow in frustration - hopefully someone here can be kind enough to point me in the right direction.
I've used NuGet several times for simple one-man pet projects, but this is the first time I've used it for something I really care about and want to have fully continuous builds, etc.  I'm trying to create a simple NAnt build script to get the source for Git, ensure the external dependencies have been brought down, compile, and run tests - vanilla CI.
I originally went down the path of trying to get solution restore working, but it just didn't work or I didn't how it worked.  Visual Studio is not on the build server and will not be installed there - that is not an option.  As an aside, I couldn't get solution restore to work just with two developers (one trying to bring down the source fresh and build cleanly).  I'm assuming it's because "allow solution restore" must be turned on everywhere (and is not by default).  I punted on that approach before I got to the bottom of it - frankly, having my package manager so tightly coupled to the IDE makes me uncomfortable and was hoping I could do it another way.  The package managers I'm used to using are simple command line tools - the CI build script invokes it on build, and developers do it on demand.  I've spent the last two hours trying to get this working with the last 30 minutes in the NuGet source code.  I feel like I'm fighting the tool and need to reboot.
Does anyone have any examples of the best to use NuGet in a multi-developer + CI scenario?  This is what I want:

*

*Any and all developers can get the source and run the tests in 3 or
less clicks (preferably 1).  If the binaries are not present locally, that will be JIT fetched.  If they are there, they will be updated if necessary, etc.  This would ideally not even require NuGet to be installed (i.e. NuGet.exe would need to be in my repo).

*Do #1 via a CI server like Jenkins, TeamCity, etc. (preferably using the same script)

*If its not overly fighting the tool, I would like to have all this disconnected from Visual Studio with a single packages.config file and all binaries dumped into a single Lib folder in the root of the repo.

Any pointers would be very much appreciated.

A: TeamCity has a build step for that, called "NuGet Installer", it fetch required packages from .sln file and download the locally. It does not require Visual Studio to run.
Read more about it here: http://confluence.jetbrains.com/display/TCD7/NuGet+Installer

A: Below, how I think you can achieve each your requisites:

*

*You need to "Enable NuGet Package Restore" in your solution: http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages

*As @alexander-doroshenko mentioned for TeamCity you can use Nuget Installer: http://confluence.jetbrains.com/display/TCD7/NuGet+Installer, but if you want a script to run in Jenkins, try this (works at TC too, as a command line step) for each project:
nuget.exe install "[Project folder]/packages.config" -source "" -solutionDir "" -OutputDirectory "packages"

*This requisite will be done by item 1 and 2.

A: There are several different solutions for integrating NuGet into your build process depending on how much integration you require. In our case we wanted to use NuGet as package manager and allow developers to build their solutions even if they haven't got NuGet installed on their machine. For that to work we enabled package restore which adds the NuGet binaries to your solution folder and updates the project files. Note that NuGet doesn't always do the update of the project files correctly. In our case we found that some project files got updated but others didn't. To verify that the project was updated you will need to open the project file as XML file. To achieve this load the solution and right click the project in question and select unload project. Then right click the project again and select edit [PROJECT_NAME]. In the project file you should see

*

*A RestorePackages property in the first propertygroup. This property should have the value true

*An import statement at the very end of the project file. This import statement should point to the 'NuGet.targets file that accompanies the NuGet binary.

Below is an example of one of our project files (heavily edited)
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <SolutionDir Condition="'$(SolutionDir)' == '' or '$(SolutionDir)' == '*undefined*'">$(MSBuildProjectDirectory)\..</SolutionDir>
    <ProjectGuid>{8B467882-7574-41B2-B3A8-2F34DA84BE82}</ProjectGuid>
    <OutputType>Library</OutputType>
    <RootNamespace>MyCompany.MyNamespace</RootNamespace>
    <AssemblyName>MyCompany.MyNamespace</AssemblyName>

    <!-- Allow NuGet to restore the packages if they are missing -->
    <RestorePackages>true</RestorePackages>
  </PropertyGroup>
  <Import Project="$(SolutionDir)\BaseConfiguration.targets" />
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="MyClass.cs" />
    <!--
        .... MANY MORE FILES HERE
    -->
  </ItemGroup>

  <!-- Import the Nuget.targets file which integrates NuGet in the build process -->
  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

The next step you'll need to take is to provide a solution level NuGet configuration file in which you'll indicate where the packages need to be 'installed' and what the URL of the package repository is. In our case the solution directory structure looks like:
(D) root
    (D) build
    (D) packages
    (D) source
        (D) .nuget
            NuGet.config
            NuGet.exe
            NuGet.targets
        (D) MyCoolProject
            MyCoolProject.csproj
        MyCoolProject.sln
    (D) templates
    NuGet.Config

Where (D) indicates a directory.
The NuGet.config file contains the following configuration settings.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageRestore>
    <add key="enabled" value="True" />
  </packageRestore>
  <config>
    <add key="repositorypath" value="packages" />
  </config>
  <packageSources>
    <add key="OurPackageServer" value="PACKAGE_SERVER_ADDRESS" />
  </packageSources>
  <activePackageSource>
    <add key="All" value="(Aggregate source)" />
  </activePackageSource>
</configuration>

This configuration file indicates that package restore is enabled, that the repository path (where the packages are placed) is the packages directory and which package sources are active.
By placing a NuGet.config file in the root directory we can use the hierarchical configuration option with NuGet.  This allows the individual solutions to override computer specific configurations. The other benefit is that this way we don't need to have NuGet installed on the build server (because the executable and the configurations are in the repository).
With this setup developers can build the solution from Visual Studio. The build should work fine on developers machines even if they don't have NuGet installed. Note however that they won't be able to add packages to a project without having NuGet installed in visual studio.
On the build server you can simply use MsBuild to build the solution which will automatically download the packages from your package repository. Visual Studio is not required to be installed on the build machine for that (just the .NET framework of your choice).


text:
Q: Cannot customize default Ext.Price decimal length on screen SOOrder I created new Project and customized it.
-ExtPrice (Customized Existing Field)
 [PXDBDecimal(5)]
 [PXDefault(TypeCode.Decimal,"0.0")]

-SQL Server
 ALTER TABLE dbo.SOLine
 ALTER COLUMN CuryLineAmt decimal(19, 5) NULL

After then I publish that project but I see no changing on screen SOOrder that default still Ext.Price decimal length 4.

A: In acumatica 5.3, there is an option to set the price/cost decimal places. Did you try that?

Organization > Organization structure > Configure > branches


text:
Q: PHP Array only get those elements/values whose keys match a particular pattern I have a multi-dimensional & nested array like below:
Array
(
    [_edit_lock] => Array
        (
            [0] => 1504299434:6
        )

    [_edit_last] => Array
        (
            [0] => 6
        )
    [additional_photos_0_gallery_image_1] => Array
        (
            [0] => 77556
        )
    [additional_photos_0_gallery_image_2] => Array
        (
            [0] => 77567
        )
    [additional_photos_0_gallery_image_3] => Array
        (
            [0] => 73768
        )
    ....
)

Now I need to get only those elements of the given array(in a separate array without changing current array), whose keys match a particular pattern like below:
additional_photos_[any_number]_gallery_image_[any_number]

How can I get using one of the array functions and avoiding foreach loops ?

A: Just use array_filter and preg_match.
return array_filter($data, function($key) {
    return preg_match('~^additional_photos_[0-9]+_gallery_image_[0-9]+$~', $key);
}, ARRAY_FILTER_USE_KEY);


text:
Q: IIS PHP include files stopped working unless I delete old & create new Include files won't work on a Win 7 Pro machine unless I...

*

*Copy include file contents

*delete old include file

*paste and save contents in a new include file with same name

Switched to a Win 7 Pro machine I had with
IIS Version 6.1
and PHP Version 5.6.31
Example of a couple of dozen files that are included in the application:
<?php
include "inc_header_public.php";
?>

This application was working on my former Win 10 machine running the same version of iis and php. That machine crashed and I moved to my backup machine running Win 7 Pro.
For some reason I have to replace each of the include files in order to make the darn thing work.
Old files give me this error..

PHP Warning:  include(C:\mySite\inc_header_public.php): failed to open stream: Permission denied in C:\mySite\inc_header.php on line 23
PHP Warning:  include(): Failed opening 'inc_header_public.php' for inclusion (include_path='.;C:\php\pear') in C:\mySite\inc_header.php on line 23

Old & new include file  properties look the same.


text:
Q: NoSuchMethodException when using SpringRestPactRunner I am using SpringRestPactRunner for the pact provider test.
In the build.gradlew, I have put
testImplementation 'au.com.dius:pact-jvm-provider-spring:4.0.10'

In the test file,
@RunWith(SpringRestPactRunner.class)

Test failed message:
Verifying a pact between
  [consumer and provider]
  Given agency id 1 exist
  a get request for Report

au.com.dius.pact.provider.spring.SpringInteractionRunner.surrogateTestMethod()
java.lang.NoSuchMethodException: au.com.dius.pact.provider.spring.SpringInteractionRunner.surrogateTestMethod()
    at java.base/java.lang.Class.getMethod(Class.java:2108)
    at au.com.dius.pact.provider.spring.SpringInteractionRunner.withBefores(SpringInteractionRunner.kt:82)
    at au.com.dius.pact.provider.junit.InteractionRunner.interactionBlock(InteractionRunner.kt:231)
    at au.com.dius.pact.provider.junit.InteractionRunner.run(InteractionRunner.kt:162)
    at au.com.dius.pact.provider.junit.PactRunner.runChild(PactRunner.kt:150)
    at au.com.dius.pact.provider.junit.PactRunner.runChild(PactRunner.kt:56)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:220)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:188)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:202)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:181)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:412)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)

A: This dependency is an old one. In order not to analyze I'd advice to use the latest libraries. For instance for Spring + Junit5 and Spring + Junit4
It is published from https://github.com/pact-foundation/pact-jvm/tree/master/provider to https://mvnrepository.com/artifact/au.com.dius.pact.provider/ now


text:
Q: WebMatrix 3 deploying to IIS on the the local machine I'm trying to deploy a WebMatrix 3 application to my local IIS. What values do I enter for the settings? I do not have a host server as I'm trying to put this on the local IIS on my laptop, what do I enter for server. What values do I use for the site name and Destination URL? I have published in Visual C#, no problem. All I had to do was choose the Publish option. Everything was set up. Not the case with WebMatrix.

A: If you want to deploy to your local machine, it needs to be set up as a Web Deploy server:
http://www.iis.net/downloads/microsoft/web-deploy
After you set that up, you can use the publish dialog to publish to localhost.


text:
Q: ViewPager goes below the display? So I'm trying to make an app have a Tabbed Activity and I'm using this code for the ViewPager.
activity_result_screen_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.proyo.wshindsight.ResultScreenTab">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:layout_width = "wrap_content"
                android:layout_height = "wrap_content"
                android:id = "@+id/toolbartext"
                android:text = "Results"
                android:textColor="@color/white"
                android:textSize="20sp"
                android:layout_gravity="center"
                android:fontFamily="sans-serif-medium"
                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>

The code below is one of the tabs in that Activity.
fragment_text.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="layout.TextFragment"
    android:id="@+id/framelayout">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:orientation="vertical"
            android:id="@+id/vlayout">

        </LinearLayout>
    </ScrollView>
</FrameLayout>

And in fragment_text.xml TextViews are dynamically added to the LinearLayout.
Now here's the problem. When enough TextViews are added, so that we reach the bottom of the display, it will not show a few of them. The ScrollView works just normally, but I think the ViewPager is not working correctly.
Here's a picture of how it it looks like. It should continue till 15, like the one above it, but for some reason it stops at 10.
Here's a picture of the same page, with scrollbar. If you look at the scrollbar, it is already at the bottom of the screen, while it still scrolls on till 10.
Finally, when checking out the Preview option in Android Studio on the ViewPager component, it also showed that it's going below the screen.
So I highly suspect the fault being in activity_result_screen_tab.xml, but I really wouldn't know what could be wrong there.
EDIT: Still don't have an answer, someone answered to change the layout_heights of fragment_text, but that didn't help either.


text:
Q: Facebook Android SDK No Email even after permission I'm trying to get the user  email through a Facebook app. but it always return it empty. I've even given the permissions required. app also shows the message the app will get the email etc to the user.
public class MainActivity extends AppCompatActivity {

private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (BuildConfig.DEBUG) {
        FacebookSdk.setIsDebugEnabled(true);
        FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    }
    callbackManager = CallbackManager.Factory.create();
    setContentView(R.layout.activity_main);
    info = (TextView)findViewById(R.id.info);
    loginButton = (LoginButton)findViewById(R.id.login_button);
    loginButton.setReadPermissions(Arrays.asList("email","user_friends"));
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
        final AccessToken accessToken= loginResult.getAccessToken();
            GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject user, GraphResponse graphResponse) {
                    info.setText(
                            "User ID: "
                                    + user.optString("email")
                                    + "\n"
                                    + user.optString("name")
                                    + "\n" +
                                    "Auth Token: "
                                    + accessToken.getToken()
                    );

                }
            }).executeAsync();

        }

        @Override
        public void onCancel() {
            info.setText("Login attempt canceled.");
        }

        @Override
        public void onError(FacebookException e) {

            info.setText("Login attempt failed.");
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
}

}
Any idea what i'm i doing wrong here?

A: Instead of:
executeAsync();

use:
the bundle parameter to Request:
 Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();

in your Code:
final AccessToken accessToken= loginResult.getAccessToken();
        GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject user, GraphResponse graphResponse) {
                info.setText(
                        "User ID: "
                                + user.optString("email")
                                + "\n"
                                + user.optString("name")
                                + "\n" +
                                "Auth Token: "
                                + accessToken.getToken()
                );

            }
         });

Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();

Also make sure the Email is public in your Facebook Account.


text:
Q: Property of non-Gorenstein algebras In the article http://www.sciencedirect.com/science/article/pii/S0021869301991306?via%3Dihub (see also the MO thread Why does there exist a non-split sequence with the condition that $\mathrm{pd} M=\infty$?  ) the authors proved the following:

Theorem: In case $A$ (every algebra is an Artin algebra in the following) has infinite global dimension, there exists an indecomposable module $M$ with infinite projective and infinite injective dimension.

Now I looked at the following, which I formulate as a conjecture in the following:

Conjecture: In case $A$ has infinite Gorenstein dimension, there exists an indecomposable module $M$ with infinite Gorenstein projective and infinite Gorenstein injective dimension.

There are two motivations to conjecture this (appart from being the natural Gorenstein homological version of the first result):

*

*My computer found no counterexample.

*A proof of the conjecture would give a new proof of the theorem and thus a generalisation of the theorem.
Proof of the theorem using the conjecture: Assume $A$ has infinite global dimension. We have 2 cases:
Case a) A is Gorenstein. In this case there is an indecomposable non-projective Gorenstein projective module. But such modules have infinite projective and infinite injective dimensions.
Case b) A is not Gorenstein. If the conjecture is true, there exists indecomposable M of infinite Gorenstein projective and infinite Gorenstein injective dimension. But then also the projective and injective dimension of $M$ are infinite. $\blacksquare$
Now I try to give a proof of the conjecture, which imitates the proof in the paper (expect that I take $D(A)$ instead of the simple module $S$ as in the paper). One just hast to find a short exact sequence of the form:
$$0 \rightarrow T \rightarrow E \rightarrow M \rightarrow 0 $$
as in the paper but with projective and injective dimension replaced by Gorenstein projective dimension (Gpd) and Gorenstein injective dimension (Gid) everywhere.
Since $A$ is not Gorenstein, the Gorenstein projective dimension of $D(A)$ is infinite (why???). Let $n:= \sup \{ Y | Y $ simple and $Gid(Y) < \infty \}$.
There is a summand $M'$ of $\Omega^n(D(A))$ of infinite Gorenstein projective dimension. Since $M'$ also has infinite projective dimension, there exists a simple module T with $Ext^l(M',T) \neq 0$ for infinitely many $l$.
Let $r$ be such that $Ext^r(M',T) \neq 0$ and $M$ an indecomposable summand of $\Omega^{r-1}(M')$ (which is a summand of $\Omega^{n+r-1}(D(A))$) of infinite Gorenstein projective dimension such that $Ext^1(M,T) \neq 0$.
Then $M$ has infinite Gorenstein projective dimension and $Ext^1(M,T) \neq 0$.
$Ext^l(M',T) \neq 0$ for infinitely many $l$ implies that $Ext^q(D(A),T) \neq 0$ for infinitely many $q$ and thus $T$ has infinite Gorenstein injective dimension. (here I use that the Gorenstein injective dimension of a module $X$ is larger than or equal to $\sup \{ t \geq 1 | Ext^t(D(A),X) \neq 0 \}$, see for example the dual of proposition 3.2.2. in http://home.ustc.edu.cn/~xwchen/Personal%20Papers/postdoc-Xiao-Wu%20Chen%202010.pdf .)
This gives the desired short exact sequence and one can finish the proof now exactly as in the rest of the paper, in case I made no mistake.
Questions:

*

*I had to assume that for a non-Gorenstein algebra $A$ one has that the Gorenstein projective dimension of $D(A)$ is infinite. Is that correct? I see no proof at the moment (but it is late...). So in short: Does $pd(D(A))= \infty$ imply that $Gpd(D(A))= \infty $?

*Is there maybe another proof of the conjecture (in case 1. fails)?

A: I think I found a proof that in a general Artin algebra one has that the projective dimension of $D(A)$ is equal to the Gorenstein projective dimension of $D(A)$. The proof is simple in case I made no mistake. But it relies on something which I expected to be wrong so I have not thought about this at the beginning.
A complex $X^{\bullet}=(X^n,d^n)$ is called right GP-acyclic in case $Hom(G,X^{\bullet})$ is acyclic for each Gorenstein projective module $G$.
A Gorenstein projective resolution of a module $M$ is an acyclic complex $....G_2 \rightarrow G_1 \rightarrow G_0 \rightarrow M \rightarrow 0$ that is also right GP-acyclic.
Now a module $M$ has Gorenstein projective dimension at most $n$ iff for every right GP-acyclic complex $0 \rightarrow K \rightarrow G^{n-1} \rightarrow .. \rightarrow G^0 \rightarrow M \rightarrow 0$ with $G^i$ Gorenstein projective has the property that $K$ is Gorenstein projective.
Now I show that a minimal projective resolution $(P_i)$ of an indecomposable injective module $I$ of infinite projective dimension is right GP-acyclic and $\Omega^{i}(I)$ is never Gorenstein projective, which shows that $I$ also has infinite Gorenstein projective dimension. That the minimal projective resolution is GP-acyclic is a direct consequence that $Hom(G,P_i) \rightarrow Hom(G, \Omega^i(I))$ is surjective for each Gorenstien projective module $G$, since $Ext^1(G,\Omega^i(I))=0$ for each $i \geq 0$ (see proposition 2.2. in https://arxiv.org/pdf/1710.03066.pdf ). But also by proposition 2.2. of https://arxiv.org/pdf/1710.03066.pdf , $\Omega^i(I)$ is never Gorenstein projective and thus the Gorenstein projective dimension of $I$ has to be infinite.


text:
Q: Using Open CL with AMD Radeon R9390 not possible - why? (QGIS 3.4) I recently found out that you can activate OpenCL acceleration in QGIS 3.4. But QGIS can't find any device which is compatible. I checked my GPU, which is a Radeon R9 390 (16GB) and in the GPU's sofware menu it sais "OpenCL™ Version 22.19.677.257".
So shouldn't it actually support OpenCL? If yes - why can I not find and activate it in QGIS?


text:
Q: Select2 Ajax call failing with Uncaught ReferenceError: require is not defined Does Select2 now have a prerequisite requirement for require.js or something as from the 4.0.0-rc.2 version from cdnjs.cloudfare.com I keep getting an error in select2.js on line 4582-

Uncaught ReferenceError: require is not defined.

My code is fairly straightforward:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Test Select2</title>
  <link href="/css/normalize.css" rel="stylesheet">
  <link media="all" type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.css">

    <form method="POST" action="http://test.local/test" accept-charset="UTF-8" role="form">

     Test:

      <input type="hidden"
                 id="test_select2"
                 class="input-xlarge form-control minimal select2"
                 data-placeholder="Search ACME"
                 data-minimumInputLength=3
                 data-width="copy"
                 data-containterCssClass="form-control minimal"
                 data-dropdownCssClass="alert-danger"
                 data-allowClear="true"
                 data-delay=250>

 <//body>

A: This is a known issue in Select2 4.0.0-rc.2 that only affects people using Select2 with an <input /> element.
https://github.com/select2/select2/pull/3192
The problem is that the internal require calls were moved to a namespace in 4.0.0-rc.2 and we missed one call.
You can either stick with 4.0.0-rc.1 until Select2 4.0.0 is released (soon) or start converting your pages to use a <select> instead.


text:
Q: Wrap text inside align environment I have a bunch of text in an align environment which is overflowing to the margin. I would like to wrap it. Note I'm using a different document class than the one state below.
\documentclass[11pt]{article}

\usepackage{amsmath}

\begin{document}

\begin{align}
    e_i &= \varepsilon(d_i, y_i) + \lambda\frac{1}{2} \vert w \vert ^2\label{eq:regularisation} \\
    \textnormal{where:} & \nonumber \\
    \varepsilon(\cdot) &= \textnormal{cost function} \nonumber \\
    w &= \textnormal{weights matrix of connection from immediate right layer (towards output layer)} \nonumber
\end{align}

\end{document}

Only solution I can think of is:
    w &= \textnormal{weights matrix of connection from immediate right} \nonumber \\
      &= \textnormal{layer (towards output layer)} \nonumber

Was hoping for a better solution as I don't want to have to change this every time the length of sentence changes.

A:
\documentclass[11pt]{article}

\usepackage{amsmath}

\begin{document}

\begin{align}
    e_i &= \varepsilon(d_i, y_i) + \lambda\frac{1}{2} \vert w \vert ^2\label{eq:regularisation} \\
    \textnormal{where:} & \nonumber \\
    \varepsilon(\cdot) &= \parbox[t]{5cm}{\raggedright cost function} \nonumber \\
    w &= \parbox[t]{5cm}{\raggedright weights matrix of connection from immediate right layer (towards output layer)} \nonumber
\end{align}

\end{document}

A: You can use a tabular environment to have full control, and \shortintertext from mathtools:
\documentclass[11pt]{article}
\usepackage{mathtools}

\begin{document}

\begin{align}
    e_i &= \varepsilon(d_i, y_i) + \lambda\frac{1}{2} \vert w \vert ^2\label{eq:regularisation} \\
    \shortintertext{where:}
    \varepsilon(\cdot) &= \textnormal{cost function} \nonumber \\
    w &= \begin{tabular}[t]{@{}l@{}}weights matrix of connection from immediate right layer\\ (towards output layer)\end{tabular} \nonumber
\end{align}

\end{document}


text:
Q: multiple website hosted on single Apache web hosting with exact .htaccess code, one show gzip enabled while other website says gzip not enabled I have multiple website hosted on single Apache web server and when trying to resolve for gzip one website shows no error while the other website says compression not enabled in PageSpeed test. In .htaccess I have exact same code
Suggestion from this thread did not  helped.
How can I get Apache gzip compression to work? and .htacess file contain exact same code as mentioned by Umut D.


text:
Q: Win10,Goland. protoc -I . --go_out=plugins=grpc: . proto/hello/hello.proto .: Permission denied software environment:Win10, Goland.
go version :
go1.9.1 windows/amd64.
protoc --version:
libprotoc 3.5.1
When i Executive Command.
The results are as follows
protoc -I . --go_out=plugins=grpc: . proto/hello/hello.proto
.: Permission denied

I tried to run as an administrator.And I have full control over all the files.now how can i do.

A: I had the same issue.
What I found was that the error message was misleading.
Here's what worked for me:
Change this:
protoc -I . --go_out=plugins=grpc: . proto/hello/hello.proto

to this:
protoc ./proto/hello/hello.proto --go_out=plugins=grpc:./outputDirectory -I ./proto/hello/hello.proto

Parts of the command obviously look redundant, but this was what I had to do to get it working.  I recommend trying this, and see if it runs.  If it does then you can see if you're able to tweak it, but I don't think so.
You definitely should not have "proto/hello/hello.proto" as the output, since that's actually your input file. if "." is your output, then do this:
protoc ./proto/hello/hello.proto --go_out=plugins=grpc:. -I ./proto/hello/hello.proto

Notice that you don't need the space.

A: The command does not seem to be well formatted.
As mentioned on https://grpc.io/docs/tutorials/basic/go.html, the format is as so -

protoc -I routeguide/ routeguide/route_guide.proto --go_out=plugins=grpc:routeguide

A: I really dont know why permission is denied but I have a solution for this problem. My solution may take time but it will work. Try to convert each protoc file one by one to py files like
protoc object_detection/protos/model.proto --python_out=.

I solve my problem like this

A: I also received permission denied with protoc in Windows.  I was also able to generate individual files based on a note by @sohaib-anwaar
This batch script saved a lot of typing by iterating over the files one by one and issuing the protoc command.
for %i in (object_detection\protos\*.proto) do protoc object_detection\protos\%~nxi --python_out=.

After execution matching *_pb2.py files will be found in the object_detection\protos folder.

A: Worked for me: Actually the already present hello.pg.go has to be deleted bcoz it wasn't being allowed to be overwritten even when full access was given... after deleting the hello.pb.go and the compiling the .protoc file again, a new .pb.go file appeared and this is now able to be overwritten multiple times by
command: protoc -I proto/ hello/hello.proto --go_out=plugins=grpc:hello


text:
Q: Bug in the ListenOrderService (notifications) in my app I'm testing a delivery android app, and I've got a bug in the Notifications System. When it had only one restaurant, it was all working good, but when I changed to multiple restaurants, it stopped appearing the notifications, either for server side when a client makes a new order, also for the client when the server updates the order. Look at my Order Status Service (Server Side):
public class OrderStatusService extends Service {

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    public OrderStatusService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Restaurants").child(Common.restaurantSelected)
                .child("Request");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        databaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Request request = dataSnapshot.getValue(Request.class);
                assert request != null;
                if(request.getPhone().equals(Common.currentUser.getPhone()))
                    showNotification(dataSnapshot.getKey(), request);
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    //Helper method
    private void showNotification(String key, Request request) {
        Intent intent = new Intent(getBaseContext(), OrderStatusActivity.class);
        intent.putExtra("phone", request.getPhone());
        PendingIntent pendingIntent = PendingIntent.getActivity
                (getBaseContext(), 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        builder.setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setTicker("ParisCart")
                .setContentTitle("Pedido Atualizado")
                .setContentText("Pedido #" + key + " foi atualizado para " + Common.getStatus(request.getStatus()))
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_access_time_black_24dp);

        NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(NOTIFICATION_SERVICE);
        assert notificationManager != null;
        notificationManager.notify(1, builder.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        firebaseDatabase = null;
        databaseReference = null;
    }
}

Same thing for client at the Order Listen Service:
public class OrderListenService extends Service {

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    public OrderListenService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Restaurants").child(Common.restaurantSelected)
                .child("Request");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        databaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Request request = dataSnapshot.getValue(Request.class);
                assert request != null;
                if(request.getStatus().equals("0") && request.getPhone().equals(Common.currentUser.getPhone()))
                    showNotification(dataSnapshot.getKey(), request);
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    //Helper method
    private void showNotification(String key, Request request) {
        Intent intent = new Intent(getBaseContext(), OrderStatusActivityServer.class);
        intent.putExtra("phone", request.getPhone());
        PendingIntent pendingIntent = PendingIntent.getActivity
                (getBaseContext(), 0,  intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
        builder.setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setTicker("ParisCart")
                .setContentTitle("Pedido Novo")
                .setContentText("Pedido #" + key + " adicionado")
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_access_time_black_24dp);

        NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(NOTIFICATION_SERVICE);
        assert notificationManager != null;
        notificationManager.notify(2, builder.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        firebaseDatabase = null;
        databaseReference = null;
    }
}

I don't know if it's something at Firebase, or one little thing, like currentUser, restaurantSelected, etc...


text:
Q: How to do resolve the 'jQuery not defined' error in Google Chrome? Ok, sometimes the jQuery is defined and sometimes it is not. Here is the following jQuery code I am using on this page.
If it is defined, the columns are all the same width, else the two-side columns are 200 pixels and the middle is 100% width. I am trying to get jQuery defined at all times here, but can't figure out what the problem is exactly…
Any help would greatly be appreciated!

All of this code is inserted into the body of the HTML, as it is inserted into a Module on that page, and needs to be that way. What am I doing wrong here? Is there a better way to define jQuery so that it is always defined?
Chrome errors are almost all of the time on the line jQuery(document).ready(function($) { saying that jQuery is not defined.

A: Try this one: If jQuery is undefined, add it to the , and when completed, call resizeColumns. On resizeColumns, I added noConflict as well.
With this, the undefined will stop, since we will always wait the script gets fully downloaded before trying to use it.

A: Can't you just wrap everything?:
// asynchronous function depending on jQuery
(function($){
    // define your shizzle
    var project = this,
        resizeColumns = function(){/**/};
})(jQuery);

This will also secure the $ variable inside this function.
The same can be achieved by adding asynchronous functions to the DOM tree.
window.project = (function($){
    var resizeColumns = function(){/**/};
})(jQuery);

or
window.project = (function(){
    var $ = window.jQuery || {},
        resizeColumns = function(){/**/};
});


text:
Q: Fragment recreated after popBackStack I have 3 fragments: A, B, C.
If I go A -> B and press back. Fragment B just disappears and you see fragment A exactly like it was before transaction.
If I go A -> C and press back (in exactly same manner) - fragment A is recreated! (calling onAttachFragment, onCreate, onCreateView etc). No "onDetach called ever".
I can't find out what the difference and why is that happens.
I use ".add" only (no replaces, no removes).
    getSupportFragmentManager().beginTransaction()
            .setCustomAnimations(R.anim.slide_enter_left, R.anim.slide_exit_left, R.anim.slide_enter_right, R.anim.slide_exit_right)
            .add(R.id.fragment_holder, newFrag)
            .addToBackStack(backName).commit();

How to prevent recreating of fragment A? It should be under B and just reappear when B goes out?
Any ideas?

A: Ok, I found a solution.
It has nothing to do with fragments at all.
Posting here for sake of someone faces same problem.
I was creating fragment A in activity's onCreateOptionsMenu.
That called every time there is a change in appbar's menu.
Fragment C not dealed with menus, so onCreateOptionsMenu was not called when entering/exiting this fragment, but fragment B added button on appbar, so called activity's onCreateOptionsMenu and that recrated the A fragment.

A: Use null in addToBackStack(null) method of your fragment transaction
getSupportFragmentManager().beginTransaction()
            .setCustomAnimations(R.anim.slide_enter_left, R.anim.slide_exit_left, R.anim.slide_enter_right, R.anim.slide_exit_right)
            .add(R.id.fragment_holder, newFrag)
            .addToBackStack(null).commit();


text:
Q: What should i use Nginx html app or/and load balancing? i have a index.html application who execute js application with nginx.
https://github.com/daleharvey/pacman
I would like to dockerize this application with 3 containers of app and a load balancing who chose with round robin algorithms 1 of 3 containers.
But my html app is with nginx, my load balancing it's nginx too ?
my docker-compose.yml:
version: '3'

services:
  pacman1:
    build: ./pacman
  pacman2:
    build: ./pacman
  pacman3:
    build: ./pacman

   nginx:
    image: nginx:latest
    container_name: production_nginx
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    ports: ['8000:80']

  redis:
    image: redis
    ports: ['6379']

my Dockerfile of html app:
#Start with current nginx
FROM nginx:latest
#Update package manager and install git
RUN apt-get update && apt-get install -y \
        git
#Clean the html root dir
RUN rm -R /usr/share/nginx/html/
#Clone pacman app from git
RUN git clone https://github.com/daleharvey/pacman.git /usr/share/nginx/html/
#Modify files for web serving
RUN chmod -R 755 /usr/share/nginx/html/*
RUN chown -R www-data /usr/share/nginx/html/*

EXPOSE 3000

#USAGE:
# docker run --name pacman -d -p 8080:80 pacman

my nginx.conf
worker_processes 4;

events { worker_connections 1024; }

http {

        upstream mysite {
              least_conn;
              server pacman1:3000;
              server pacman2:3000;
              server pacman3:3000;
        }

        server {
          listen 8080;
              server_name _;
          root /usr/share/nginx/html;
          index index.html;
              location / {
                proxy_pass http://mysite;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
              }
        }
}

Please, why it's doesn't work ? because nginx have default port 80 ? How can i run my html app without nginx ? thanks.

A: Nginx is what is running your HTML app. You will need Nginx (good choice) or some other web server such as Apache to run the HTML app.
You could build your app with NodeJS or something which includes a server however using Nginx is probably the best solution.


text:
Q: Request read through websocket getting garbled I am attempting to create a minimal Websocket implementation using Cramp framework.
Where as Cramp successfully renders normal web content, I run into trouble when I try to use HTML5 websockets.
My action class is as follows :

Cramp::Websocket.backend = :thin

class HomeAction < Cramp::Action
  self.transport = :websocket
  keep_connection_alive

  on_data :recv_data

  def recv_data data
    puts "got message"
    puts "#{data}"
    render "Hello world"
  end

end

My javascript code is as follows :

$(function(){

    window.socket = new WebSocket("ws://localhost:3000/game");
    socket.onmessage = function(evt){
        console.log(evt.data);
        socket.close();
    }
    socket.onclose = function(evt) {
        console.log("end");
    }
    socket.onopen = function() {
        console.log("Now open!");
        socket.send("Hello");
    }

})

The server (thin) detects when data is sent but the text that is read is garbled.
the encoding of the data is ASCII-8BIT (puts data.encoding prints "ASCII-8BIT"). However forcing UTF encoding through data.force_encoding('UTF-8') does not resolve the issue. In addition after forcing encoding - data.valid_encoding? returns false where as it was true before forcing.
I have tested the app in ruby-1.8.7 as well as ruby-1.9.3 . The output is same in both scenarios.
Another weird thing is that in client side the onmessage event is never fired.
Also, if I remove keep_connection_alive call from HomeAction the connection immediately terminates after the data is received and still the client does not receive the data being sent by server ("Hello world").
I have tested the app in Google chrome (latest version) and Mozilla firefox (latest version). The problem remains exactly the same in both of them. My operating system is Ubuntu 12.04 LTS (Precise Pangolin).
Any help in this regard would be strongly appreciated.

A: I have been running into the same thing, and it seems to be an issue with the released version of the cramp 0.15.1 gem versus what you get from the github repo (https://github.com/lifo/cramp) thought is still marked as 0.15.1.
Try this experiment which works for me:

*

*Clone the GH repo locally

*Copy in the bin/ and lib/ folders, as well as the cramp.gemspec file from the repo to your test cramp project

*Change your gemfile, instead of just
gem 'cramp'

Include the local copy of code:
gemspec
gem 'cramp', :path => File.dirname(__FILE__)

*Erase your Gemfile.lock and re-bundle, see that bundler now reports it will use the local copy of the cramp gem

*Try your app again, in my scenario, this now works exactly as expected.

It would appear there is either a fix in github they have not released yet (but have not incremented the working version in their gemspec) or some other version snafu, but either way the code in GH works whereas a "gem install cramp" doesn't give you working code for websockets.


text:
Q: Angular (10) material touchUi datepicker - can't select anything Good morning,
I've recently updated a fairly old Angular project from ~6 to 10. After all the other parts of it that I've had to fix, I'm left with just the material date picker that I can't get working again.
In short: It works, it comes up, I can flick the months and hit the year dropdown, but anything within the main content area, I can't click (both dates and years). Well, I can click but doesn't do anything. No console output.
My basic datepicker wrapper component:
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'date-picker-component',
  templateUrl: './date-picker.component.html',
  styleUrls: ['./date-picker.component.css']
})
export class DatePickerComponent {

  @Input() public disabled: boolean;
  @Input() public placeholder: string;
  @Input() public value: Date;
  @Input() public minDate: Date;
  @Input() public maxDate: Date;
  @Input() public filter: Function;
  @Output() public onSelect = new EventEmitter<Date>();

  public onDateChange(date: Date): void {
    this.onSelect.emit(date);
  }
}

<mat-form-field fxFlexFill>
  <input matInput
    [value]="value"
    [min]="minDate"
    [max]="maxDate"
    [matDatepicker]="picker"
    [placeholder]="placeholder"
    (dateChange)="onDateChange($event.value)"
    (click)="picker.open()"
    [matDatepickerFilter]="filter"
    [disabled]="disabled">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker touchUi #picker></mat-datepicker>
</mat-form-field>

Example usage:
<date-picker-component
    [disabled]="!availableDates || loading"
    [minDate]="today"
    [filter]="dateFilter()"
    placeholder="Select trial date"
    (onSelect)="onDateSelected($event)">
</date-picker-component>

Opening the picker works:

Showing the picker:

Frantically clicking a date does nothing:

Showing the year selection:

Frantically clicking a year does nothing:

Month switching works fine:

And for final details, the relevant packages:
    "@angular/animations": "10.1.3",
    "@angular/cdk": "10.2.2",
    "@angular/common": "10.1.3",
    "@angular/compiler": "10.1.3",
    "@angular/core": "10.1.3",
    "@angular/flex-layout": "10.0.0-beta.32",
    "@angular/forms": "10.1.3",
    "@angular/material": "10.2.2",
    "@angular/platform-browser": "10.1.3",
    "@angular/platform-browser-dynamic": "10.1.3",
    "@angular/router": "10.1.3",
    "buffer": "5.6.0",
    "classlist.js": "1.1.20150312",
    "core-js": "3.6.5",
    "hammerjs": "2.0.8",
    "intl": "1.2.5",
    "moment": "2.29.0",
    "rxjs": "6.6.3",
    "tslib": "2.0.0",
    "web-animations-js": "2.3.2",
    "zone.js": "0.10.3"

Oh, also useful I suppose is proving setup details (in app.module.ts providers):
{
  provide: MAT_DATE_LOCALE,
  useValue: 'en-GB'
}

And also importing MatNativeDateModule somewhere or other...
Edit: Initial cause found to be the filter. It doesn't like the filter. Take the filter off and I can select the dates and things again.
Doesn't help much, but it's a start.
Filter is working - can see that with the filtered dates, but won't allow the selection thereof.
Here's the filter for the above:
public dateFilter(): (dt: Date) => boolean {
    const fn = (dt: Date): boolean => {
      const day = DateExtensions.toStringFormat(dt, 'dddd');
      return ArrayExtensions.firstOrDefault(this._availableDates, x => x.day === day) != undefined;
    };

    return fn;
}

A: Fix found by this glorious individual on my GitHub post.
Seems Angular 11 doesn't like the original way of evaluating the filter:
public dateFilter(): (dt: Date) => boolean { ... }

<date-picker-component
    [filter]="dateFilter()"
    ...>
</date-picker-component>

Instead, it's now happy with:
public dateFilter = (dt: Date): boolean => { ... }

<date-picker-component
    [filter]="dateFilter"
    ...>
</date-picker-component>


text:
Q: How to send email with laravel? The application has no problem, I do not change the configuration.
A month later i tried the program gets an error.
Error messages :

Swift_TransportException in StreamBuffer.php line 269: Connection
  could not be established with host smtp.gmail.com [ #0]

This configuration of the env:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mr.xxxxxxx@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=ssl

This configuration of mail.php :
<?php
return [

'driver' => env('MAIL_DRIVER', 'smtp'),

'host' => env('MAIL_HOST', 'smtp.gmail.com'),

'port' => env('MAIL_PORT', 465),

'from' => ['address' => 'muhamadramadhan95@gmail.com', 'name' => 'Ramadhan'],

'encryption' => env('MAIL_ENCRYPTION', 'ssl'),

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

'sendmail' => '/usr/sbin/sendmail -bs',

];

Please help, thanks a lot.

A: You can use sendgrid. Its very simple.
step-1:
Add SendGrid to your composer.json
"require":
{
"sendgrid/sendgrid": "~6.0"
}

step-2:
in .env file set your sendgrid api key
SENDGRID_API_KEY= Your Sendgrid API key

step-3:
Add following code in your controller
$from = new \SendGrid\Email(null, "your email id");//place senders email id
                        $subject = "checking Email service"; //*your subject goes here*
                        $to = new \SendGrid\Email("Example User", 'example@gmail.com');  //*place reciever email id*
                        $content = new \SendGrid\Content("text/html", $otp);
                        $mail = new \SendGrid\Mail($from, $subject, $to, $content);

                        $apiKey = env('SENDGRID_API_KEY');// set in .env file
                        $sg = new \SendGrid($apiKey);

                        $response = $sg->client->mail()->send()->post($mail);
                        return json_encode(['code' => 200, 'status' => 'Success', 'message' => 'mail sent Sucessfully]);

for better understanding follow below link
https://github.com/sendgrid/sendgrid-php

A: Try changing encryption and port in your .env file:
MAIL_ENCRYPTION=tls
MAIL_PORT=587

and then run:
$php artisan config:clear

Or, If that doesn't work either then try the hack below:
Add the following lines to _establishSocketConnection() method in Swift/Transport/StreamBuffer.php on line 263:
$options['ssl']['verify_peer'] = FALSE;

$options['ssl']['verify_peer_name'] = FALSE;

Note: The hack specified above is just a workaround and could be overwritten anytime the Swift package updates. So keep that in mind if you try to use this method.

A: Try using mailgun. Here i've post the steps to use it:
Step 1:
Get the Mailgun API, Sign up to Mailgun, Add Your Domain
Step 2: Configure Laravel Application
In your config/services.php file, add the following:
'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

Next, you will need to go to your .env file, and replace the "MAIL_USERNAME", "MAIL_PASSWORD", "MAILGUN_DOMAIN" AND "MAILGUN_SECRET" with your own.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=2525
MAIL_USERNAME=postmaster@yourdomain.com
MAIL_PASSWORD=yourmailgunpassword
MAIL_ENCRYPTION=null

MAILGUN_DOMAIN=yourdomain.com
MAILGUN_SECRET=key-YourMailGunSecret

Last step, in the same file, you will need to also add, and replace the value with your own:
MAIL_FROM_ADDRESS: hello@yourdomain.com
MAIL_FROM_NAME: John

That's it! Hope this will helps you!


text:
Q: Browser not recognizing struts2 tag I am designing a simple html page. I am using struts2 tags. The code is as follows

   <a class="imageLink grow" href="<s:url action="uploadLink"/>">
   <acronym title="Upload"></acronym>

The resultant output is

I don't understand why "> is being printed. If I remove that strut2 tag in 'href' then the problem is not there. Can anyone tell me what is happening?

A: because you are using " " for href you need to use ' ' to wrap the action. Otherwise you will escape the command
<a class="imageLink grow" href="<s:url action='uploadLink'/>">

A: EDIT:
Try this instead:

There's an error in your code, extra html "> after the a class

   <a class="imageLink grow" href="<s:url action="uploadLink"/>">
   <acronym title="Upload"></acronym>


text:
Q: Avoid UI buttons to run function twice after fast click How do I avoid my UI buttons to run functions twice if clicked (accidentally) twice or more in a short time?
I have a UI button that calls a StartGame function in my game script. I attached the script to the button in the inspector. The function sets a few variables in order for the game to start.
If I accidentally click the button twice really quickly, the start function is executed twice and thus it screws up my variables. How do I avoid that?
I am thinking of splitting up the function so that it checks if it's already started, but that seems like a bit complex. Isn't there a standard setting in Unity UI or some standard code I missed? Tried to google but not much luck.
Simplified example of my code:
public void StartGame() {

MenuAnimator.SetBool ("Startbutton", false); // animates my start game panel off the screen.
lives = lives - 1;
Do Rest of Code();
}

In this case, clicking the UI menu Start Game button multiple times causes two or more lives to be deducted.

A: There's no need for a lock, just have a boolean that flips each click and the button only triggers a response when the bool is true.
first click -> true -> response.
second click -> false -> return.

A: What about something like this? This will prevent double clicks that happen within 1 second (or however many you want)
bool buttonLocked;
System.Timers.Timer t = new System.Timers.Timer(1000); //however many milliseconds
t.Elapsed += new EventHandler(resetFlag);

private void button_clicked(object sender, EventArgs e){
    if(!buttonLocked){
       // Handle Click
       buttonLocked= true;
       t.Enabled = true;
    }
}

private void resetFlag(){
    buttonLocked = false;
    t.Enabled = false;
}

Or you could probably just use whether or not the timer is enabled as a flag assuming the timer is properly initialized. I like having a separate flag though for readability.
Full disclosure- I'm at a bar typing this on my phone so it's untested but I think that should work

A: Due the fact that I canno't comment, here is my answer.
You can lock the variable.
First create a lock
private readonly object _locker = new object();

In your lock property set/get
get { lock (_locker) { return this.myVar; } }
set { lock (_locker) { this.myVar = value; } }

Now you can lock this MyVar variable using
public void MethodA()
{
    lock(_locker)
    {
        if(myVar == 1)
          myVar = 0;
    }
}

This is mostly used with multi-threading but It should do the job for you.


text:
Q: SQL COUNT(*) returning the wrong answer The following script should return the name of the departments and the number of employees that are in those departments, the Marketing,Executive and Sales departments have '0' employees but instead of '0' , the returned value is '1'. How can I correct it?
select Department, Departments.DepartmentID, count(*) as 'NumOfEmps'
from Departments
left join Employees
on   Employees.DepartmentID = Departments.DepartmentID
group by Departments.DepartmentID,Department

A: You can't do that all in one query.  You need a sub-query to get the employee counts first, then get the related department information (name, etc.) using the aggregated results:
SELECT Department, Departments.DepartmentID, t.NumOfEmps
FROM Departments
LEFT JOIN (SELECT DepartmentID, count(*) as 'NumOfEmps'
           FROM Employees
           GROUP BY DepartmentID) t
  ON t.DepartmentID = Departments.DepartmentID

I'm making some assumptions about your schema since it's not listed. Column names may be off a bit, but this is the general idea.  Hope it helps.

A: Don't use Count(*) count the thing you want to count  namely the employees.
Count(*) counts the whole row. Since there's always going to be at least one record for each Department in Departments when you do count(*) you'll always get at least 1
SELECT d.Department, d.DepartmentID, count(e.EmployeeID)
FROM Departments d
    LEFT JOIN employees e
    ON d.DepartmentID = e.DepartmentID
GROUP BY
 d.Department, d.DepartmentID

DEMO


text:
Q: log4j can't locate the database where to put the log messages I am trying out log4j to do log some information to a persistent datastore. I tried to use java db.
I already created the database, named firstdb with the table named logging_data.
but when I try to run my mini application, it throws java.sql.SQLException: Database 'firstdb' not found.
I don't know why but I can seem to play with the database, query some rows and other stuff using the ij tool.
any suggestions please.?
my properties file named log4jDB.properties
log4j.logger.LoggerClass=DEBUG,DB

log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.DB.driver=org.apache.derby.jdbc.EmbeddedDriver
log4j.appender.DB.URL=jdbc:derby:firstdb
log4j.appender.DB.user=app
log4j.appender.DB.password=

log4j.appender.DB.sql=INSERT INTO LOGGING_DATA VALUES('%x','%d{yyyy-MM-dd}','%C','%p','%m')
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
log4j.appender.DB.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

my test class
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class LoggerClass {
    public static void main(String[] args) {
        Logger logger = Logger.getLogger(LoggerClass.class);
        PropertyConfigurator.configure("log4jDB.properties");
        logger.info("Hello this is a info message");
    }
}

also added the embedded driver for java db on my classpath if that would help.
cheers!
simon

A: You must specify database location more precisely. In your log4j file for jdbc connection properteis put path, for example:
log4j.appender.DB.URL=jdbc:derby:C:/Temp/firstdb

or
log4j.appender.DB.URL=jdbc:derby:./firstdb


text:
Q: chain or nested variable in terraform I want to create a chained/nested variable for multiple attributes.
For example, I have this resource block:
resource "aws_rds_cluster" "default" {
  cluster_identifier      = "aurora-cluster-demo"
  engine                  = var.db_engine
  engine_version          = var.db_engine_version
  availability_zones      = ["us-west-2a", "us-west-2b", "us-west-2c"]
  database_name           = "pgdb"
  master_username         = "foo"
  master_password         = "bar"
  backup_retention_period = 5
  preferred_backup_window = "07:00-09:00"
  db_cluster_parameter_group_name     = "rds-cluster-pg"
}
resource "aws_rds_cluster_parameter_group" "default" {
  name        = "rds-cluster-pg"
  family      = var.db_engine_family
  description = "RDS default cluster parameter group"

  parameter {
    name  = "character_set_server"
    value = "utf8"
  }

  parameter {
    name  = "character_set_client"
    value = "utf8"
  }
}

I have three variables related to each other: db_engine, db_engine_family and db_engine_version.
I would like to know if and how it is possible to chain the three, so if I set db_engine=postgresql, the other variables will match it.
For example:
db_engine = PostgreSQL, db_engine_version= 13.6 and db_engine_family=aurora-postgresql9.6.
If db_engine=mysql, db_engine_version=5.7.mysql_aurora.2.03.2 and db_engine_family=aurora-mysql5.7.
Thank you

A: The best way would be to create map:
variable "db" {
    default = {
        PostgreSQL = {
            db_engine_version = 13.6
            db_engine_family = "aurora-postgresql9.6"
        },
        mysql = {
            db_engine_version = "5.7.mysql_aurora.2.03.2"
            db_engine_family = "aurora-mysql5.7"
        }
    }
}

then
resource "aws_rds_cluster" "default" {
  cluster_identifier      = "aurora-cluster-demo"
  engine                  = var.db_engine
  engine_version          = var.db[var.db_engine].db_engine_version
  availability_zones      = ["us-west-2a", "us-west-2b", "us-west-2c"]
  database_name           = "pgdb"
  master_username         = "foo"
  master_password         = "bar"
  backup_retention_period = 5
  preferred_backup_window = "07:00-09:00"
  db_cluster_parameter_group_name     = "rds-cluster-pg"
}
resource "aws_rds_cluster_parameter_group" "default" {
  name        = "rds-cluster-pg"
  family      = var.db[var.db_engine].db_engine_family
  description = "RDS default cluster parameter group"

  parameter {
    name  = "character_set_server"
    value = "utf8"
  }

  parameter {
    name  = "character_set_client"
    value = "utf8"
  }
}


text:
Q: jQuery check if object element is inside another I am trying to create a simple jQuery popup menu, but cant seem to figure out the script to check if an element is in a predefined element.
Clicking on the popup trigger launches the jQuery function. The function saves the following variables:
The element that was clicked (js_popup-trigger), its main parent (js_popup-container), and the actual menu with the menu items (js_popup-menu).
Once the trigger is clicked, the menu fades in/out, and an event listener is added to the document to check if the user clicked outside of the menu, in which case it should close, nothing should happen to the menu if the user clicks inside of it.
This is the part i cant figure out - how do i detect if the user has clicked inside the popup element or outside of it?
I have tried this:
if(!$(e.target).parent('.js_popup-container').length){
But this does not work well when you have multiple popups on the page, because if you click anywhere else, including another popup, the current one should close, but since if you click on another popup with the same class of js_popup-container, then it will remain open because it technically is inside of an element with that class.
/*  Popup menu toggle
===========================================*/
$(document).on("click",".js_popup-trigger", function(e){
    e.preventDefault();

    //Set variables
    var element     = $(e.currentTarget),
        container   = element.parent('.js_popup-container'),
        menu        = element.next('.js_popup-menu');

    //Toggle the menu
    menu.fadeToggle(200);

    /*  Create a click listener for the document
    *   This is to close the menu if clicked outside of it */
    $(document).click(function closePopup(e){

        //If the clicked item is not in the popup, close it
        if(!$(e.target).parent(container).length){
            menu.fadeToggle(200);
            $(document).unbind('click',closePopup);
        }
    });
});

In the end, what i want to achieve is a function that can be applied to any popup menu just by adding the 3 classes.
There should be the option to have multiple popup menus on the same page, and when clicking anywhere outside of the menu, it should close.
Of course i am open to suggestions on improving the code, but i don't want to use a preexisting plugins at this point.
EDIT:
I know that there are already other questions and solutions very similar to this one, but the difference is that the solutions given in other questions is to check if the target that was clicked is inside of another element with a specific class name/id/selector.
I need something a little bit different, i already have the parent element (the popup container) saved in a variable. I need to know if the clicked element is inside of that saved element.
Using the solutions already found, i run in to a problem because i will have multiple popups on the page, so if i have one popup open, and i click on another, the first popup will remain open instead of closing, that's because using the other solutions, i am checking for an element with the popups container class, which they both have, which means that the first popup wont close.

A: It depends on how performant you want your method to be, but here's one concise option assuming element and container are both jQuery objects.
if(element.parents().find(container).length == 1){
   // do work
}

A: I came up with a solution that is working for my current app at the moment.
$(document).on("click",".js_popup-trigger", function(e){
    e.preventDefault();

    //Set variables
    var element     = $(e.currentTarget).closest('.js_popup-trigger'),
        container   = element.parent('.js_popup-container'),
        menu        = element.next('.js_popup-menu');

    //Toggle the menu
    menu.fadeToggle(200);

    //Add the open classes to the container and trigger
    container.toggleClass('js_popup-container--open');
    element.toggleClass('js_popup-trigger--open');

    /*  Create a click listener for the document
    *   This is to close the menu if clicked outside of it */
    $(document).click(function closePopup(e){

        //If the clicked item is not in the popup, close it
        if(!$(e.target).closest(container[0]).length && element.is(":visible")){

            //Close the popup
            menu.fadeOut(200);

            //Remove the added classes
            container.removeClass('js_popup-container--open');
            element.removeClass('js_popup-trigger--open');

            //Unbind the closePopup function from the document
            $(document).unbind('click',closePopup);
        }
    });
});

This makes it so that you can add as many popups as you want to the same page, and they will all work independently of others - all other solutions i found used a general class to check if the popup is open instead of an actual element/object, which meant that if you had another popup open with the same class, then clicking on a new popup would not close the first one. This approach fixes that problem.
Hope this is helpful to others, if anyone has better ideas then i would love to hear them!


text:
Q: Invalid Syntax on variables in python May I know why there be a invalid syntax on my f variable on the first elif loop?
def bsd():
if price_of_properties <= 180000:
    price = 180000*0.1
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 180000 <= 360000:
    price = (((180000*0.1) + (price_of_properties - 180000 + (180000* 0.2)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 360000 <= 100000:
    price = (((180000*0.1) + (180000*0.2) +(price_of_properties - 180000 + (640000* 0.3)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))

A: Your second and third assignments to  the price variable have unbalaned parentheses ((more opens than closes).
This will cause an error on the following lines though I think Python 3.11 may fix that, reporting errors more accurately. You can probably fix this by adding a closing parenthesis on each of those two lines. Or removing the first. But check the formulae after you do so, in case you make the wrong choice.
And, yes, the extra opening parenthesis in that first paragraph was intended :-)


text:
Q: How to deal with reference data-members in the assignment operator, and copy constructor? I have following class
class TVData
{
  private:
  int ID;
  Monitor& monitor;
  string pName;

}

I need to implement the assignment operator, and a copy-constructor usable with this class.

*

*How do I handle reference members, in this case TVData::monitor, in such scenario?

A: You can't reassign a reference, so if you need it to change in the assignment operator then you should make it a pointer - assignment can then be done as usual with =, although it's still encouraged to use an initialiser list in the copy constructor...
TVData(const TVData& rhs)
  : ID(rhs.ID), p_monitor(rhs.p_monitor), pNmae(rhs.pName)
{ }

A: INTRODUCTION
To correctly assign a data member variabled declares as being a reference you will need to make use of a member initialization list in your constructor (both in your default-, and your copy-constructor).
The problem with an overload assignment operator is that since a reference cannot be bound to a new entity after it has been initialized (and it must be initialized) you cannot change what this reference is referring to after you have created your TVData.
If you'd want to be able to change what the reference refers to consider using pointers instead of references.

SAMPLE IMPLEMENTATION
#include <iostream>

struct Obj {
  Obj (int& r)
    : ref (r)
  { }

  Obj (Obj const& src)
    : ref (src.ref)
  { }

  Obj& operator= (Obj const& src) {
    // we cannot reassign what `ref` is refering to,
    // but we can at least assign the value of `src.ref`
    // to `this->ref`

    ref = src.ref; // note: does not make `ref` refer to `src.ref`
  }

  int& ref;
};

int
main (int argc, char *argv[])
{
  int some_val = 0, some_other_val = 100;

  Obj a (some_val);
  Obj b (a); // copy `a`
  Obj c (some_other_val);

  b = c;

  b.ref += 23;

  std::cout << "some_val: " << some_val << std::endl;
}

some_val: 123

A: reference are not copiable nor movable, you have to fallback to pointer or reference_wrapper

A: First of all, using (non-const) references as class members is fairly dangerous because in that case you have to guarantee somehow that the referenced object will outlive the class's instance referencing it.
Secondly, you can implement the copy constructor for such a class but you can't make assignment because C++ references are not rebindable.
In order to manage this, you might prefer using shared_ptr/unique_ptr depending on the assignment semantics of your class (whether it should share the owned Monitor or pass the ownership). If you're not owning it, then weak_ptr (std:: or boost::) is your best bet.


text:
Q: How does Github takes screenshots from the clipboard? On Github it is possible in the comment textarea to copy paste a screenshot on at least OSX.
How does they do that with javascript?
How is the image received? Base64?