text:
Q: The solution of Poisson equation and the distance function from the boundary Let $D$ be a domain in $\mathbb{R}^n$, and let $u$ be the solution to the Poisson equation, that is
$$   \begin{cases}
                                   \Delta u = f &   \text{in} ~ D, \\
                                   u=0 & \text {on} ~ \partial D,
  \end{cases}
$$
for some function $f \in C(D)$ (the function which is identically $1$ on $D$ could be a good candidate for $f$). Is the values of $u(x)$ comparable to the distance function to the boundary, that is $ \delta (x)= \mathrm{dist} (x , \partial D) $? I think of an inequality of (boundary) Harnack type. I have not made any regularity assumption (on $\partial D$, or the function $f$), such assumptions can be applied if necessary.

A: Let us assume some regularity on $\partial D$ (bounded and $C^2$ suffices). Then the problem above has a unique solution $u \in W^{2,p}(\Omega) \cap W^{1,p}_0(\Omega)$ for every $p<\infty$ and taking $p>n$ we get $\|\nabla u\|_\infty \le C\|f\|_\infty$. Therefore the upper estimate $|u(x)| \le C\|f\|_\infty \delta (x)$ always holds. The lower estimate does not hold for every $f$ (take $u$ with support far away from $\partial D$ and $f=\Delta u$). However it holds if $-\Delta u=f$ (note the minus sign) and $f \geq c >0$. In fact, by the regularity assumption on $D$, $\Delta \delta \geq -\kappa$ in $D$ and then $-\Delta (u-\epsilon \delta)=f+\epsilon \Delta \delta \geq c-\epsilon \kappa \geq 0$ for small $\epsilon$. By the maximum principle $u-\epsilon \delta \geq 0$, which gives the lower estimate.
EDIT: The lower estimate holds assuming only that $-\Delta u= f \geq 0$ and $u\neq 0$. In fact, $u(x)>0$ for every $x \in D$, by the strong maximum principle and then $\frac{\partial u}{\partial \nu}(x_0)<0$ for every $x_0 \in \partial D$, by Hopf Lemma ($\nu$ is the unit exterior normal). The minimum of $\frac{\partial u}{\partial \nu}$ on $\partial D$ is then strictly negative and form this one obtains the lower bound.

A: You can use Feynman-Kac formula:
$$ u(x) = -\mathbb{E}_x\int_0^T f(X_t)dt$$where $X_t$ is a Brownian process starting at $x$ and $T$ the stopping time  $T=\inf\{t\geq 0:X(t)\in \partial D\}$.  So $u(x)$ is essentially given by the expected time for the process to get out of $D$. For example if $\epsilon \leq f\leq M$ we get $$ \epsilon\mathbb{E}_x(T)\leq -u(x) \leq M \mathbb{E}_x(T).$$
Consider the case $\partial D$  smooth around a point $x_0$. As a simplification we suppose that locally $D=\mathbb{R}_+\times\mathbb{R}^{n-1}$, $x_0 = (0,\cdots,0)$ and $x=(\delta,0,\cdots,0)$ with $\delta>0$ and $X_s = (x+B_s^{(1)},B_s^{(2)},\cdots,B_s^{(n)})$, where $B^{(i)}$ are iid Brownian motion. In that case it is easy to gives the escape time of $X$: we have $$\mathbb{P}_x(T>t)=\mathbb{P}_x(\inf_{0\leq s\leq t} B_s^{(1)} > - \delta) = 1-2\mathbb{P}_x(B_t^{(1)}<-\delta) \approx \frac{2\delta}{\sqrt{2\pi t}} $$ (see reflection) and then
$$ \mathbb{E}_x(T)= \mathbb{E}_x(\int_0^\infty 1_{t< T}dt)=\mathbb{E}_x(\int_0^1 1_{t< T}dt)+\mathbb{E}_x(1_{T>1}\int_1^\infty 1_{t\leq T}dt) \\ = \int_0^1 \mathbb{P}_x(t< T)dt+\mathbb{P}_x(T>1) \mathbb{E}_x\left( \int_1^\infty 1_{t\leq T}dt|T>1\right)
\approx \delta C$$
for some $C>0$.
If the boundary is not regular at $x_0$, it can be possible for the process to avoid $\partial D$ such that $\mathbb{P}(T>1)$ is bounded away from $0$ (or decay very slowly) as $x\rightarrow x_0$ and then $u(x)$ is no more comparable with $d(x,\partial D)$. This lead to a nice physical phenomena call " Effet de pointe" that  occures in Lightning rod.


text:
Q: ASP.NET Core custom route not working with web api 2.1 I'm new to ASP.NET Core Web API and trying to implement a custom route.
Here is my controller:
using ...

namespace FoodDeliveryServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MenusController : ControllerBase
{
    private readonly FoodDeliveryContext _context;

    public MenusController(FoodDeliveryContext context)
    {
        _context = context;
    }

    // GET: api/Menus
    [HttpGet]
    public IEnumerable<Menu> GetMenu_1()
    {
        return _context.Menu;
    }

    // rest of the methods

    // POST: api/Menus
    [HttpPost]
    public async Task<IActionResult> PostMenu([FromBody] Menu menu)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Menu.Add(menu);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetMenu", new { id = menu.Id }, menu);
    }

    // POST: api/Menus/filter
    [HttpPost("filter", Name = "Filtermenu")]
    public async Task<IActionResult> FilterMenu([FromBody] bool isActive)
    {
        return Ok(_context.Menu.Where(m => m.IsActive == isActive));
    }

    private bool MenuExists(long id)
    {
        return _context.Menu.Any(e => e.Id == id);
    }
}
}

Now, I'm trying to hit the filter route from POSTMAN and getting 404. Other standard routes are working fine.
POST
http://localhost:5000/api/Menus/filter

Body -> raw -> JSON

{
    "isActive": true
}

Headers -> Accept -> application/json
Headers -> Content-Type -> application/json

What am I doing wrong here?
I looked at this link also but still having problems:
ASP.Net Core Web API custom route not working

A: You can use the [Route("")] decorator on your actions too. Otherwise it will create routes upon what you defined in StartUp.Configure.
// POST: api/Menus/filter
[Route("filter")]
[HttpPost("filter", Name = "Filtermenu")]
public async Task<IActionResult> FilterMenu([FromBody] bool isActive)
{
    return Ok(_context.Menu.Where(m => m.IsActive == isActive));
}

Should work for you.
The '/api/Menus/' part will be inherited from your [Route("api/[controller]")] definition on controller level

A: I resolved the issue with the help of @Marius. Here is what I did:
    // POST: api/Menus/filter
    [HttpPost]
    [Route("filter", Name = "Filtermenu")]
    public async Task<IActionResult> FilterMenu([FromBody] Menu menu)
    {
        return Ok(_context.Menu.Where(m => m.IsActive == menu.IsActive));
    }

Looks like, we need to provide a class to read FromBody

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing stageWebView in GestureWorks TouchSprite I am attempting to create a component in a GestureWorks AIR application that renders a stageWebView in a touchsprite container. Given the stageWebView is not a display object is this possible?
Below is the code:
package view
{
import com.gestureworks.core.GestureWorks;
import com.gestureworks.core.TouchSprite;
import com.gestureworks.events.GWGestureEvent;
import com.modestmaps.Map;
import com.modestmaps.events.MapEvent;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.geom.Rectangle;
import flash.media.StageWebView;
import flash.net.URLLoader;
import flash.net.URLRequest;

public class webView extends TouchSprite
{

    private var urlAddress:String = "http://google.com";

    public var stageWebView:StageWebView = new StageWebView();

    private var ts:TouchSprite;

    public function webView()
    {
        super();
        init();

    }

    private function init():void
    {

        ts = new TouchSprite();
        ts.width = 500;
        ts.height = 500;
        ts.x = 200;
        ts.y = 100;
        ts.rotation = 45;
        ts.scaleX = 0.5;
        ts.scaleY = 0.5;

        ts.gestureEvents = true;
        ts.disableAffineTransform = false;
        ts.gestureList = { "n-drag":true, "n-scale":true, "n-rotate":true };
        ts.addEventListener(GWGestureEvent.DRAG, gestureDragHandler);
        ts.addEventListener(GWGestureEvent.ROTATE, gestureRotateHandler);
        ts.addEventListener(GWGestureEvent.SCALE, gestureScaleHandler);

        if(StageWebView.isSupported == true)
        {

            stageWebView.stage = this.stage;
            stageWebView.viewPort = new Rectangle(0,0, 500, 500);
            //stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangedHandler);
            //stage.scaleMode = StageScaleMode.EXACT_FIT;
            //this.stage.addEventListener(Event.RESIZE, resizeEvent);

            getURL();
        }
        else
        {
            urlAddress = "StageWebView not supported";
        }
        ts.addChild(stageWebView as DisplayObject);
        addChild(ts);
    }

    protected function getURL():void
    {
        stageWebView.loadURL(urlAddress);

        //stageWebView.addEventListener(Event.COMPLETE,handleLoad);

    }

A: No.  Since StageWebView is not a display object, you can't add it to another object to be managed automatically.
You can manage it manually from the sprite--when the sprite is displayed, show the web view, when the sprite is resized, resize the web view, etc.
If your web view is covering up the entire TouchSprite once it's rendered, I'm fairly certain that your sprite won't receive gesture events--those would be handled by the native component.


text:
Q: How can I check if an object has a time value? a = '12'

I want to check if this object has a time value. Let's say I do a.try(:to_time). This returns an ArgumentError. Can I check if a value is a time value receiving a true or false response?

A: You could use respond_to? to check if the object responds to the method.
a.respond_to?(:to_time)

EDIT
It raised ArgumentError which I missed before. respond_to? helps NoMethodError, but not ArgumentError.
You should take a look of the to_time's definition in order to know how many arguments and what the arguments are for that method.

A: a = "12"
p a.is_a?(Time)      #false
p a.class  == String #true
p a.is_a?(Object)    #true (a's class or superclass)

A: It doesn't appear that there is a built in method to do this.  But you can always overload the String model. Something like -
    class String
       def to_time
          begin
             Time.parse(self)
          rescue Exception => exception
             return false
          end
          return true
       end
    end

A: To parse a time try using Time.parse:
irb(main):002:0> Time.parse('12:00')
=> 2012-10-04 12:00:00 -0700
irb(main):003:0> Time.parse('the time is 12:00')
=> 2012-10-04 12:00:00 -0700
irb(main):005:0> Time.parse('jan 1, 1970 11:11')
=> 1970-01-01 11:11:00 -0700

Notice that this fails silently:
irb(main):004:0> Time.parse('12 noon')
=> 2012-10-12 00:00:00 -0700


text:
Q: How to import path to php interpreter from docker container to $PATH Linux? It is possible? It need because editor Atom gives error "Error running PHP Error: Failed to spawn command php. Make sure php is installed and on your PATH".
And I don't want install PHP on my host machine.


text:
Q: Compare between strings in query statement in Oracle I have this table:
id         value
AA000001   500
AA000002   1000
AA000003   1500
AA000004   2000
AA000005   2500
AA000006   3000
AA000007   3500

The type of id is a string and I use below sql statement to query my record:
SELECT sum(value), max(value), min(value) FROM my_table WHERE id BETWEEN 'AA000001' AND 'AA000007'

And it's works as expected. But I wonder if there are any exceptions in this query?
I'm using Oracle 10g Release 2 and 11g Release 2.
Thanks in advances.

A: I'm not exactly sure what you mean by "exceptions".  Your query is:
SELECT sum(value), max(value), min(value)
FROM my_table
WHERE id BETWEEN 'AA000001' AND 'AA000007';

It will match anything between these values.  In addition to what is in your table, it will match, say, 'AA000003ZYW243'.  You are safe that all matches will start with 'AA00000'.  The next character will be between '1' and '7', and then anything can follow that (unless that character is a '7').


text:
Q: SAPI5 voices / using 32bit voices After spending a whole lot of time on searching the web I think it's time to ask.
I'm trying to implement some text to speech with SAPI5 in C++.
The only available 64bit voice is Anna. With Anna everything is fine, but I also need a german voice. So I found Hedda(Microsoft) and Steffi(Realspeak).
I already feel like implementing some dating service.
Neither Hedda nor Steffi are added to the registry. So both of them are not detected by SAPI while it checks "HKLM\SOFTWARE\Microsoft\Speech\Voices" to get the required tokens to select voices.
I also tried to change the registry paths to ...\SOFTWARE\Wow6432Node... to use the 32bit voices, but no success.
Does anybody know how to use Hedda or Steffi with Sapi?
Is there any way to use the 32bit voices?
Hope anyone can help.
Thanks in advance.

A: You can use 32 bit voices if you build a 32 bit program, and have 32 bit voices installed to the registry correctly. I describe how to do this registry hack over here. Basically, you just move things around in the registry. The quickest way to accomplish this is to install all of the voices that you want, and then use RegEdit to export those specific registries for where your speech platform voices are.
Then open the registry files with a text editor and replace "Speech Server\v11.0\Voices" with "Speech\Voices"
and replace "Speech Server\v11.0\Voices" with "Speech\Voices". Save off the registry files and then run them to add to your registry.
You should be able to test your new voices in your normal text to speech dialog that windows provides. If however you're on a 64 bit system and you want to test 32 bit voices (because you're building a 32 bit program) you'll have to open the windows speech to text dialog with either
C:\Windows\SysWOW64\Speech\SpeechUX\sapi.cpl
for 32 bit voices I believe and
C:\Windows\System32\Speech\SpeechUX\sapi.cpl
for 64 bit systems voices.
As contradictory as that seems.

A: Well, editing the registry did the job.
After copying the registry entrys from "\Speech Server\v11.0..." to "\Speech..." (see Lesley Gushurst) and reinstalling SDK, Runtime and voice, voice-"Hedda" can be used on 64bit system with 64 bit application.
Thanks for your help.


text:
Q: Using query string to redirect/rewrite to different internal IIS sites I have an Azure VM that is hosting a web application.
The application will be accessible via the VM's IP address:
http://191.238.112.62

I want to be able to use query strings to redirect to completely different sites that are within the local IIS. For example:
http://191.238.112.62/?site=1

would redirect to
www.site1.com

The way I have structured IIS can be seen below:

Each site has an entry in the systems host file.
127.0.0.1 wwww.site1.com
127.0.0.1 wwww.site2.com
127.0.0.1 wwww.site3.com

There is likely a better way to achieve what I am going for here so any pointers would be greatly appreciated.
Thanks.

A: Here is what i would do :
First, you need to download and install the URL Rewrite extension for IIS (A reboot, so a downtime, may be required to activate the extention).
You will need to update your DNS creating A or CNAME records for other web Sites, e.g :
www.site1.com. IN A 191.238.112.62
www.site2.com. IN A 191.238.112.62
www.site3.com. IN A 191.238.112.62

You will need a main entry site that will respond to http://191.238.112.62. Let use the "Default Web Site" for this.
Configure the Bindings for this "Default Web Site" so that its Host Header is set to 191.238.112.62 :

You need to set the appropriate Host Header within the Binding for site1.com :

Enter the URL Rewrite module for "Default Web Site" and create a new rule :

You will need to uncheck "Append query string" to remove ?site=1 once redirected.
Then "Apply".
Proceed the same way for other sites wwww.site2.com and wwww.site3.com


text:
Q: Selenium - How to automatically Download PDF Files of Web Page if there is no Download Button? 1.) I'am trying to Download the Article PDF Files from multiple web pages to a local folder on the computer. But there is now "Download PDF" button on the web pages. What would be the Quickest and Best way to do this with Selenium ?
2.) One way I have thought of is to use the Keyboard Keys for Print, "Control"- "P", but inside Selenium, none of the Keyboard Keys are working when i run the program. The Code is below,
from selenium import webdriver
import chromedriver_binary  # Adds chromedriver binary to path
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time

driver = webdriver.Chrome()
driver.maximize_window() # Makes Full Screen of the Window Browser
time.sleep(4)

url = 'https://finance.yahoo.com/news/why-warren-buffett-doesnt-buy 152303112.html'
driver.get(url)
time.sleep(10)

a = ActionChains(driver)
a.key_down(Keys.CONTROL).send_keys('P').key_up(Keys.CONTROL).perform()

A: You can do that by using ChromeOptions() and have a setting id, origin etc.
Also you can give savefile.default_directory to save the PDF file.
Code:
import time

from selenium import webdriver
import json

Options = webdriver.ChromeOptions()
settings = {
       "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "selectedDestinationId": "Save as PDF",
        "version": 2
    }
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings), 'savefile.default_directory': 'C:\\Users\\****\\path\\'}
Options.add_experimental_option('prefs', prefs)
Options.add_argument('--kiosk-printing')
driver_path = r'C:\\Users\\***\\***\\chromedriver.exe'
driver = webdriver.Chrome(options=Options, executable_path=driver_path)

driver.maximize_window() # Makes Full Screen of the Window Browser
time.sleep(4)

url = 'https://finance.yahoo.com/'
driver.get(url)
time.sleep(2)

driver.execute_script('window.print();')

Output:
You should see a PDF file in the directory like this:

Update:
driver_path = r'C:\\Users\\***\***\\chromedriver.exe'
driver = webdriver.Chrome(options=Options, executable_path=driver_path)


text:
Q: Css and js files do not load into production When doing the deploy of my application on a tomcat8.5 server the imported css and js files are not loaded angular.json. locally works correctly
Comments:
This server has a link to external access when it is accessing an application for the server's IP or to a remote access server, but with the external access link the Css and js are not loaded.
I use the base href = "/ Project", not angular.json I define the paths as follows:
"node_modules / primeicons / primeicons.css",
"src / styles.css",
"node_modules / owl.carousel / dist / assets / owl.carousel.min.css",
"node_modules / owl.carousel / dist / assets / owl.theme.default.min.css",
"node_modules / bootstrap / dist / css / bootstrap.min.css",
"src / bootstrap3 / bootstrap3.min.css",
"node_modules / font-awesome / css / font-awesome.css",
"node_modules / primeng / resources / primeng.css",
"node_modules / primeng / resources / themes / nova-light / theme.css"

I've already tried:
do the project build with config --extract-css = false
and I've already changed this attribute to false in angular.json
Comments :
When you inspected a page it was possible that the file happens to be an error
Failed to load resource: net :: ERR_CONNECTION_RESET

and this error indicates that it was in styles.e7efefb7ef5355459826.js: 1
I did a production build

A: You should try ng build --prod in src folder?

A: Build with base href ng build --prod --base-href /Project/
Your index HTML is unable to find relative paths to your js bundles


text:
Q: What is the word for "swallow a word"? Consider this fictional situation which I made up to let you feel the sense:

Brad and Brett was chatting about recent thefts where cheats were making hoax and decieved the victims. While Brett was talking about a particular case of this kind of theft, Brad remembered he himself was duped in a similar way and almost went to tell Brett but swallowed his word thinking Brett might use this fact against him later in future to mock him.

So what is the word for the italicized phrase? I thought about "choke". But something tells me it isn't.

A: The idiomatic expression used for cases like that is bite your tongue, which means to stop yourself from saying something that might upset somebody or cause an argument, although you want to speak.

I was going to tell her the truth, but I bit my tongue.

Choke could be used if you meant to be unable to speak normally especially because of strong emotion. It would not mean somebody avoided saying something he was going to say.

A: "Kept his silence" might be a better expression in this case.  Also, I wouldn't run this sentence together with "but":

...almost went to tell Brett.  However, he kept his silence, thinking Brett might use this fact...

A: Brad kept his mouth shut would be quite literal.


text:
Q: bootstrap как сделать отступ между блоками Здравствуйте. Сайт сверстан на bootstrap.
На lg экранах смотрится прекрасно, с отступом между картинками. На мониторах типа md смотрится отвратно - сливаются блоки без отступов. Вот тут можно проверить.
@model Site.Models.MebelModel

@{
    ViewBag.Title = Model.Title;
}

@if (Model.Id!=0)
{

Вся мебель

        @if (Model.Level>=2)
        {

@Model.Name

        }

@ViewBag.Title

}

    @if (Model.Id != 0)
    {

@ViewBag.Title

    }

        @foreach (var item in Model.CatalogList)
        {

@item.Caption

@item.UnderLine

                                    Смотреть

@item.Title

        }

A: Надо bootstrap лучше было изучить. нужно для отступов использовать класс offset с соответствующими col_md (в случае для верстки под ноутбуки). А так же правильно выбирать контейнер.


text:
Q: Hiding a react component in nested routes in react I am trying to hide a component in nested routes using pathname but could not achieve it. The global Navbar component is only hiding in my "/freelancer/freelancer-dashboard" but I want it to hide in nested components inside my freelancer-dashboard.
Here is my code:
In Navbar.js which contains
import React from "react";
import GlobalNavbar from "../DashBoard/Navigation/GlobalNavbar";
import { Outlet, useLocation } from "react-router-dom";

const Navbar = () => {
  const { pathname } = useLocation();
  return (
    <div>
      {pathname === "/freelancer/freelancer-dashboard"
        ? null
        : <GlobalNavbar />
      }
      <Outlet />
    </div>
  );
};

export default Navbar;

My app.js file which contains my routes:
 <Route path="/freelancer" element={<Navbar />}>
   <Route
     path="freelancer-dashboard"
     element={<FreelancerDashBoard />}
   >
     <Route path="home-feed" element={<MyHome />} />
     <Route path="my-gigs" element={<MyGigs />} />
   </Route>
 </Route>


text:
Q: UPPER_CASE_WITH_UNDERSCORES in Django in Django,
almost all the variables' naming style is UPPER_CASE_WITH_UNDERSCORES,
for instance:
INSTALLED_APPS = [
    ]
MIDDLEWARE_CLASSES = [

]

and so on...
what's the conventions it follows?

A: In addition to being constants and following PEP8, these constants are Django settings. Settings are defined in a settings module, and Django exposes an object, django.conf.settings, that proxies attributes in this module. The proxy object only exposes settings that are all uppercase.
So if you want your settings to be available on django.conf.settings, using uppercase variable names is not just a convention, it's required.

A: Pep8, its common across most python and PyCharm helps to enforce it.
In particular, this is the rule for constants

Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.

A: It follows PEP 8.
The letters are upper case because they are constants. And the underscore is a usual python naming convention.
UPPER_CASE_WITH_UNDERSCORES

A: Django setting required uppercase letter for custom-defined settings variables
These are certain rules in Django for creating our own settings
Creating your own settings
There's nothing stopping you from creating your own settings, for your own Django apps, but follow these guidelines:
Setting names must be all uppercase.
Don't reinvent an already-existing setting.
For settings that are sequences, Django itself uses lists, but this is only a convention.
Please have a look at Django documentation - https://docs.djangoproject.com/en/3.0/topics/settings/
Django itself follows that rules and Naming convention in python like splits with the underscores are from pep8.


text:
Q: Is there any way to open or extract a data.PACK file? i have a file with resources that i need to open, but it's in data.PACK format. tried to rename it to data.zip and extract but it gives a corruption error.
i tried to look it up on the internet and it seems no one actually does the opening of a .PACK file
i'm completely lost please help


text:
Q: Tinyurl API Example - Am i doing it right :D we use super-long Hashes for the Registration of new Users in our Application. The Problem is that these Hashes break in some Email Clients - making the Links unusable.
I tried implementing the Tinyurl - API, with a simple Call, but i think it times out sometimes ... sometimes the mail does not reach the user.
I updated the Code, but now the URL is never converted. Is Tinyurl really so slow or am i doing something wrong? (I mean hey, 5 Seconds is much in this Times)
Can anybody recommend me a more reliable service?
All my Fault, forgot a false in the fopen. But i will leave this sample of code here, because i often see this sample, wich i think does not work very reliable:
return file_get_contents('http://tinyurl.com/api-create.php?url='.$u);

This is the - i think fully working sample. I would like to hear about Improvements.
static function gettinyurl( $url ) {

    $context =
        stream_context_create(
            array(
                'http' => array(
                    'timeout' => 5  // 5 Seconds should be enough
                )
            )
        );

    // get tiny url via api-create.php
    $fp = fopen( 'http://tinyurl.com/api-create.php?url='.$url, 'r', $context); // open (read) api-create.php with long url as get parameter

    if( $fp ) { // check if open was ok
        $tinyurl = fgets( $fp ); // read response

        if( $tinyurl && !empty($tinyurl) ) // check if response is ok
            $url = $tinyurl; // set response as url

        fclose( $fp ); // close connection
    }

    // return
    return $url; // return (tiny) url

}

A: You might want to use urlencode() for the url parameter.
It is also recommendable to check fgets() against false. Then, you could save the empty() function call by just comparing the response to an empty string, like:
$line = fgets($fp);

if ($line !== false && $line !== '') {
    // ...
}

Generally, it is advisable to check everything against false first, if the function returns values of different types such as integer or boolean. This can be crucial because 0 and false mean in comparisons the same. Because of PHP's lack for type safety, it is strongly recommended to always check for type equality. There are even cases when the documentation recommends this explicitly, e.g. in the case of strpos(). Meanwhile, I've forced myself to use === over to ==, same for `!=' etc. It requires more typing but it is definitely worth the effort because you eliminate possible pitfalls.
The rest of your code looks good to me.

A: You can try bit.ly service. It supported by google as i know.
Api

A: I don't know exactly how long your hash is, but not all services (browsers, servers etc) can handle URLs longer than 255 chars. You could look into  php's Pack()

A: What is the point of using a "super-long hash", if you are immediately shortening it to a 7-8 character tinyurl?
Nobody would bother with guessing the long hash, and would crack the tinyurl instead.
Use a 10-character hash yourself and be more secure than you are now.

A: Here's another version:
function getTinyUrl($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL,'http://' . 'tinyurl.com/api-create.php?url=' . $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $tinyUrl = curl_exec($ch);
    curl_close($ch);

    if ($tinyUrl === false) {
        throw new RuntimeException("Could not create URL");
    }

    return $tinyUrl;
}

I had to split the tinyurl url because SO wouldn't let me post the answer.


text:
Q: Keycloak Environment Variables Not Working I would like to specify the database for Keycloak to use.
I've found this which specifies the parameters and environment variables that can be used. KC_DB should be available for setting the vendor. E.g. mysql.
I create a Dockerfile to create my image.
FROM  bitnami/keycloak:18

EXPOSE 80

I then run the image using this.
docker run --name keycloak -e KC_DB=mysql -p 8080:80 keycloak

Logs
PS D:\Projects\keycloak> docker run --name keycloak -e KC_DB=mysql -p 8080:80 keycloak
keycloak 23:48:07.88
keycloak 23:48:07.88 Welcome to the Bitnami keycloak container
keycloak 23:48:07.88 Subscribe to project updates by watching https://github.com/bitnami/containers
keycloak 23:48:07.89 Submit issues and feature requests at https://github.com/bitnami/containers/issues
keycloak 23:48:07.89
keycloak 23:48:07.89 INFO  ==> ** Starting keycloak setup **
keycloak 23:48:07.90 INFO  ==> Validating settings in KEYCLOAK_* env vars...
keycloak 23:48:07.91 INFO  ==> Trying to connect to PostgreSQL server postgresql...
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:51615->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:57656->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:41930->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:48347->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:43866->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:49390->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:39474->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:46428->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:59657->192.168.65.5:53: i/o timeout
cannot resolve host "postgresql": lookup postgresql on 192.168.65.5:53: read udp 172.17.0.2:56871->192.168.65.5:53: i/o timeout

I've tried using the KC_DB_HOST and multiple other environment variables but they don't seem to be picked up. I've tried this with Keycloak 19 too.
What is causing this?

A: You should consult that to the docker image creator you're are using, here is the github reference link maybe they able to create another docker image using mysql, so far the documentation from the github repository the image requires you to use postgresql database.

A: Looks like this image has a built-in default variable for the host. If you want you can just add 'postgresql' to your hosts to be recognized as some other ip. You can do it the following way:
first you might want to check which hosts you already have:
type C:\Windows\System32\Drivers\etc\hosts
it will print something like
127.0.0.1 localhost
then using any editor add new line containing
<DESIRED-HOST> postgresql
in case your postgres is running locally just put 127.0.0.1 as host


text:
Q: Am I playing easy or normal? During a game, how can I tell if the difficulty is easy or normal? I can't remember my choice.

A: There is no way to check your difficulty in-game, while you are in the middle of a round.
However, if you never touched the difficulty option, the default is Normal (Which is pretty difficult).
If you REALLY wanted to know, you could always open up the save file in a hex editing program, as all game info is stored there.


text:
Q: ! Missing $ inserted im experiencing a kind of weird error. I receive the "! Missing $ inserted." error message for line 727. The problem: the line is empty! In the error message he seems to load an R document that I tried to include before. However, I have deleted this line of code as I have spaces in the folder paths. Now, I can work with my file at all. Can you please help? My last save is 24h old...
When i open the file with TexMaker I always receive a "File not found" error message.
Even if I shorten the document to have <727 lines, I still get an error for line 727
\documentclass[12pt,a4paper,oldfontcommands,oneside]{memoir}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{microtype}
\usepackage[dvips]{graphicx}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{xcolor}
\usepackage{times}
\usepackage{amsmath}
\usepackage{blindtext}
\usepackage{fancyhdr}
\usepackage{etoolbox}
\usepackage{eurosym}
\usepackage[printonlyused]{acronym}
\usepackage{booktabs}
\usepackage[bottom]{footmisc}
\setlength{\footnotemargin}{0.0cm}

\usepackage[breaklinks=true,colorlinks=true,linkcolor=black,urlcolor=black,citecolor=black,
bookmarks=true,bookmarksopenlevel=2]{hyperref}

\usepackage[nosectionbib]{apacite}

\usepackage{epstopdf}

\usepackage{geometry}
%%% PRINTING OPTIONS
\geometry{total={210mm,297mm},
left=33mm,right=33mm,
bindingoffset=0mm, top=25mm,bottom=20mm}

\OnehalfSpacing

%%% CHAPTER'S STYLE
\chapterstyle{article}
%%% STYLE OF SECTIONS, SUBSECTIONS, AND SUBSUBSECTIONS
\setsecheadstyle{\Large\bfseries\sffamily\raggedright}
\setsubsecheadstyle{\large\bfseries\sffamily\raggedright}
\setsubsubsecheadstyle{\bfseries\sffamily\raggedright}

%%% STYLE OF PAGES NUMBERING USING THE FANCYHDR PACKAGE
\pagestyle{fancy}
\fancyhf{}
\lhead{\leftmark}   %%% Show Chapter left in Header
%\lhead{\leftmark}  %%% Show Section left in Header
\cfoot{\thepage}

\maxsecnumdepth{subsection} % chapters, sections, and subsections are numbered
\maxtocdepth{subsection} % chapters, sections, and subsections are in the Table of Contents

%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%---%%%

\begin{document}

\end{tabular}

\clearpage

\chapter{Results}

\section{Placeholder}

\appendix
\chapter{The Internal Ratings-Based Approach of the Basel II Concept}
\[Capital = \left\{45\times N \left[\frac{IN(PD)}{\sqrt{1-R}} + \frac{\sqrt{R} \times IN(0.999)}{\sqrt{1-R}}\right] - 45 \times PD \right\} \times \left[\frac{1+(M-2.5) \times b(PD)}{1-1.5 \times b(PD}\right]\]

\chapter{Second Appendix}

\clearpage
%\markboth{BIBLIOGRAPHY}{}  %%% BIBLIOGRAPHY in Header
\bibliographystyle{apacite}
\bibliography{References}
\clearpage

\end{document}

! Missing $ inserted.
<inserted text>
                $
l.727 ...is/R/Down-and-in Call/down-and-in_call.R}

I've inserted a begin-math/end-math symbol since I think
you left one out. Proceed, with fingers crossed.

! Package Listings Error: File `C:/Users/User/Documents/Master Thesis/R/Down-an
d-in Call/down-and-in_call(.R)' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: R)

Enter file name:
! Emergency stop.
<read *>

l.727 ...is/R/Down-and-in Call/down-and-in_call.R}

*** (cannot \read from terminal in nonstop modes)

A: I managed to reduce your example to the minimum working one. To avoid messing with the filecontents routine, try this most minimal example. Create an R file, name it my.R and add this line only (if dollar signs and underscores are the suspects, why not try them?):
data$var <- a_1

Then, try this LaTeX document:
\documentclass{memoir}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{document}
\lstinputlisting[language=R]{my.R}
\end{document}

You should get something like this:

Fine? Try to copy half of your down-and-in_call.R into my.R and compile it. It works? Good. Does not work? Continue bisecting till you find the problematic line (listings does not handle UTF-8 well, for example). Good? Add the packages from your preamble.
And in case of any trouble, do not forget to do the cleanup of helper files. Does this work for you?


text:
Q: Pytest stop runnig with AttributeError (module 'html' has no attribute 'td' in pytest-html) In my PyTest, I have included conftest.py for customizing the HTML report.
But I have the following error comes up while the test script tries to access the HTML report.
"C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pluggy\callers.py", line 187, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "C:\Projects\TripTickAT\conftest.py", line 14, in pytest_html_results_table_row
INTERNALERROR>     cells.insert(2, html.td(report.status_code))
INTERNALERROR> AttributeError: module 'html' has no attribute 'td'
Traceback (most recent call last):
  File "C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\Scripts\pytest-script.py", line 11, in <module>
    load_entry_point('pytest==5.2.2', 'console_scripts', 'pytest')()
  File "C:\Users\gobiraaj.anandavel\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pytest-5.2.2-py3.7.egg\_pytest\config\__init__.py", line
  File "C:\Projects\TripTickAT\conftest.py", line 8, in pytest_html_results_table_header
    cells.insert(2, html.th('Status_code'))
AttributeError: module 'html' has no attribute 'th'

conftest.py
from datetime import datetime
import html.parser
import pytest

@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Status_code'))
    cells.insert(1, html.th('Time', class_='sortable time', col='time'))
    cells.pop()

@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
    cells.insert(2, html.td(report.status_code))
    cells.insert(1, html.td(datetime.utcnow(), class_='col-time'))
    cells.pop()

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

A: Use the following html  import instead
from py.xml import html
Initially pycharm will not identify this import but this will not impact the execution. If you want you can change the pycharm settings to ignore this error


text:
Q: Why it does not access to Javascript Function? I'm developing a web app in grails and I have my gsp, and my .js file, I want to check if when I change a value of my combobox I can access to the function, but nothing happens... these are my codes:
javascript [dynamic.js]:
function cmbFilters(){
alert("Hello");
}

GSP [numberJobs.gsp]:
Filter by : <g:select id="cmbFilterBy" name="cmbFilterBy"
 onchange="cmbFilters()" from="${['None','Name', 'Owner', 'Description', 'Status',
'Cron   Expression']}"></g:select>

and in my Application Resources.groovy i have this:
numberJobs{
    resource url:'css/custom.css'
    resource url:'js/dynamic.js'
}

A: g:select doesn't accept an onchange attribute, and the g:select tag will be replaced by HTML.
If you view source on the page you should not see the onchange set on the real html select.
What you can do is attach a listener to the change event for that select.
Example using jQuery
$('#cmbFilterBy').on( "change", function(){ cmbFilters() } );

Here is a simple fiddle.


text:
Q: Replace spaces with dashes in an HTML class or id using javascript I am trying to replace the spaces of the innerHTML of an element by the following code:
<script type="text/javascript">
    var minsFix = document.getElementById("spaceX").innerHTML;
    var keepVal = minsFix.replace(/\s+/g, "-");
    document.getElementById("spaceX").innerHTML = keepVal;
</script>

But it only changes the first space to a dash(-) and other spaces are not changed respectively.
Resolved
I manage to create my solved code.
here
<script type="text/javascript">
    // create variable for collect Class : spaceX
    var keepVal = document.getElementsByClassName("spaceX");
    // loop for collect SpaceX
    for (var i = 0; i < keepVal.length; i++) {
        // turn spaceX collected to Text
        var tranText = keepVal[i].innerText;
        // create variable for replace spaceX to -
        var toSpace = tranText.replaceAll(/\s+/g, '-');
        // output to html one by one
        document.getElementsByClassName('spaceX')[i].innerHTML = toSpace;
    }
</script>

hope can help someone


text:
Q: How to disconnect specific ssh client from ssh server in linux? I wonder if i can disconnect a specific ssh client from ssh server?
Can we do that?
Thanks in advance...

A: This is answered here: https://unix.stackexchange.com/questions/615/how-do-you-kick-a-benign-user-off-your-system/622#622
A copy of the steps:
There's probably an easier way, but I do this:

*

*See who's logged into your machine -- use who or w:
 > who
 mmrozek  tty1         Aug 17 10:03
 mmrozek  pts/3        Aug 17 10:09 (:pts/2:S.0)

*Look up the process ID of the shell their TTY is connected to:
 > ps t
 PID   TTY      STAT   TIME COMMAND
 30737 pts/3    Ss     0:00 zsh

*Laugh at their impending disconnection (this step is optional, but encouraged)
 > echo "HAHAHAHAHAHAHAHA" | write mmrozek pts/3

*Kill the corresponding process:
 > kill -9 30737

I just discovered you can combine steps 1 and 2 by giving who the -u flag; the PID is the number off to the right:
> who -u
mmrozek  tty1         Aug 17 10:03 09:01        9250
mmrozek  pts/18       Aug 17 10:09 01:46       19467 (:pts/2:S.0)


text:
Q: DataFrame.from_records convert (Django) datetime to datetime64: Value Error My error relates to datetime conversion on constructing a Pandas DataFrame after I upgraded to pandas 0.81.  Specifically, the .from_records() method passing a Django Queryset with timezone aware datetimes throws a datetime64 conversion error:
type(data)
> django.db.models.query.QuerySet

dv = data.values('begin_time', 'datum')
dv[0]
> {'begin_time': datetime.datetime(2006, 4, 27, 12, 40, tzinfo=<UTC>),
   'datum': Decimal('13.3097500')}

df = pd.DataFrame.from_records( dv, index='begin_time' )
> ValueError: Tz-aware datetime.datetime cannot be converted to datetime64
  unless utc=True

The Django datetime is timezone aware and looks to me that it is set to UTC, so I find the error message a little cryptic, but that is probably my failing.   I'm relatively knew to Python.
So, I'm thinking that either I need to:
1. Somewhere set utc=true as the error says but I don't know where to exactly or
2. Switch off conversion to datetime64 in .from_records, but I also don't know where.
Thanks for your help!

A: You're encountering an bug in pandas 0.8.1 in parsing timezones: https://github.com/pydata/pandas/issues/1693
Marked as an enhancement, so maybe I'm not understanding and there could be a workaround, but I'm pretty sure it's just a bug. Already fixed but will have to wait for 0.8.2.
This works in 0.8.0 (I ran into the same error only after upgrading). You can try falling back to 0.8.0:
pip install -I pandas==0.8.0

As long as 0.8.0 still satisfies requirements of anything else that is using pandas in your app.
Or you might try to get the lastest from https://github.com/pydata/pandas and build it, but might be less stable.

A: I've created an issue here: http://github.com/pydata/pandas/issues/1825. I was just working on this stuff recently and apparently broke it (unless it works on git master now).


text:
Q: Referencing custom AMD Modules in SuiteScript 2.0 Netsuite says to include the module id when creating custom modules like so:
define(module_id, [dependencies], function)

However when I do the module is not found:
TypeError: Cannot read property "XPELPCenterModule" from undefined (/path/to/mysuitelet.js#35)

When I remove the ID, it works???
Hello Human Coder

What am I missing. Im am calling both of them the same way
function (ui, email, runtime, search, record, log, render, cache, crypto, file, pcenter) {
        var p = new pcenter.XPELPCenterModule();

.....
p.helloWorld('Human Coder');

here are the module code examples:
WORKING CODE:
define(["require", "exports"],
function (require, exports) {

    var XPELPCenterModule = /** @class */ (function () {

        function XPELPCenterModule(name) {
            this.name = name;
        }

        XPELPCenterModule.prototype.helloWorld = function (name) {
            return 'Hello ' + name;
        };

        return XPELPCenterModule;
    }());

    exports.XPELPCenterModule = XPELPCenterModule;
});

NON WORKING CODE:
define('XPELPCenterModule', ["require", "exports"],
function (require, exports) {

    var XPELPCenterModule = /** @class */ (function () {

        function XPELPCenterModule(name) {
            this.name = name;
        }

        XPELPCenterModule.prototype.helloWorld = function (name) {
            return 'Hello ' + name;
        };

        return XPELPCenterModule;
    }());

    exports.XPELPCenterModule = XPELPCenterModule;
});

A: The trick was to use @NAmdConfig and add a .json config file of your module paths:
/**
 *@NApiVersion 2.0
 *@NScriptType Suitelet
 *@NModuleScope Public
 *@NAmdConfig  /path/to/myModule.json
 */

.JSON CONFIG FILE:
{
  "paths": {
    "XPELPCenterModule": "/path/to/myModule"
  }
}


text:
Q: MingW glfw3 skipping incompatible libgdi32.a when searching for -lgdi32 I'm working on Opengl with MingW and I was testing this code.
#include <stdio.h>
#include <stdlib.h>

// OpenGL
#include <GL/glew.h>

// Window, Keyboard Manager lib
#include <GLFW/glfw3.h>

// for 3D Calculation
#include <GLM/glm.hpp>

using namespace glm;

int main()
{

  if (!glfwInit())
  {
    fprintf(stderr, "Fail to initializing GLFW!");
    return -1;
  }

  glfwWindowHint(GLFW_SAMPLES, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  GLFWwindow *window;
  window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);

  if (window == NULL)
  {
    fprintf(stderr, "Fail to OpenGLFW window");
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);
  glewExperimental = true;
  if (glewInit() != GLEW_OK)
  {
    fprintf(stderr, "Fail to initialize GLEW");
    return -1;
  }
}

this code have to show black screen and closed right away. but when i compile this code. error log is showing.
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\msys64\mingw64\lib/libgdi32.a when searching for -lgdi32

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\msys64\mingw64\lib\libgdi32.a when searching for -lgdi32

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0x10e): undefined reference to `__imp_CreateDCW'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0x148): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0x1a0): undefined reference to `__imp_DeleteDC'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0x2db): undefined reference to `__imp_GetDeviceCaps'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0x8bb): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xa0b): undefined reference to `__imp_GetDeviceCaps'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xdda): undefined reference to `__imp_CreateDCW'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xde9): undefined reference to `__imp_GetDeviceGammaRamp'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xdf2): undefined reference to `__imp_DeleteDC'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xf67): undefined reference to `__imp_CreateDCW'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xf76): undefined reference to `__imp_SetDeviceGammaRamp'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_monitor.c.obj):(.text+0xf7f): undefined reference to `__imp_DeleteDC'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x21a): undefined reference to `__imp_CreateDIBSection'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x253): undefined reference to `__imp_CreateBitmap'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x30e): undefined reference to `__imp_DeleteObject'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x3a7): undefined reference to `__imp_DeleteObject'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x43c): undefined reference to `__imp_CreateRectRgn'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(win32_window.c.obj):(.text+0x477): undefined reference to `__imp_DeleteObject'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0x182): undefined reference to `__imp_SwapBuffers'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0x42d): undefined reference to `__imp_ChoosePixelFormat'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0x43b): undefined reference to `__imp_SetPixelFormat'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0xc90): undefined reference to `__imp_DescribePixelFormat'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0xe7a): undefined reference to `__imp_DescribePixelFormat'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0xe94): undefined reference to `__imp_SetPixelFormat'

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\mingw64\lib\libglfw3.a(wgl_context.c.obj):(.text+0x1490): undefined reference to `__imp_DescribePixelFormat'

and this is a build cli
g++.exe -IC:\msys64\mingw64\include -LC:\msys64\mingw64\lib -lfreeglut -lglew32 -lglu32 -lgdi32 -lglfw3 -lopengl32 D:\Privrate\Project\OpenGL\tutorial_1.cpp C:\msys64\mingw64\lib\*.a -o D:\Privrate\Project\OpenGL\build\tutorial_1.exe

i think the problem is the library, libgdi32.a. but everytime i compile this message is showing.
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping incompatible C:\msys64\mingw64\lib/libgdi32.a when searching for -lgdi32

i find out what skipping incompatible... the problem is that it's 32bit library. but i have to use 64bit for the program. is there a any solution?


text:
Q: subtle design error in abstract factory class class Animal
{
    public:
        typedef enum{
            CAT,
            DOG,
            RABBIT,
            EAGLE,
            FOX
        } AnimalType;

        static Animal* Create(AnimalType type);

        ~Animal();

        virtual void PlayWith(Animal* other)=0;
        virtual void Eat(Animal* other) = 0;

    protected:
        Animal();
};

I was told that there is a programming error on one of the lines, but i could not find the subtle error. can anyone figure it out please?

A: You are designing an abstract base class, so you will be manipulating pointers to instances of concrete derived classes (Cat*, Dog*, Rabbit*) through a base-class pointer with type Animal*.
For such polymorphic hierarchies, your base-class destructor must always be virtual.
virtual ~Animal();

A: Usually, the default constructor of a base class would either have public scope or private if you wanted it suppressed. I see no reason why it should have protected scope.


text:
Q: How can I detect an error when searching through a property list? On the first screen of my app, you enter a 4 digit code. When you press "Done", it saves the code automatically and the app switches views to the next screen. On the new screen, it pulls up the saved code and searches through a plist trying to find the string it's associated with. It currently works perfectly except for when the user enters a code that is not in the plist.
How can I teach it to give an error alert of the code is not present in the plist?
This is the first view:
NSString *pureString = [[detectionString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:pureString forKey:@"beaverID"];
[defaults synchronize];

ViewController *Flip = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:Flip animated:YES];

Then in the second view:
- (void)viewDidLoad {
    //Loading the unique student's ID code:
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *loadstring = [defaults objectForKey:@"beaverID"];

    //Loading the user's first name from the first .plist:
    NSString *error2 = nil;
    NSPropertyListFormat format2;
    NSString *plistPath2;
    NSString *rootPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

    NSString *file2 = @"User Data.plist";
    plistPath2 = [rootPath2 stringByAppendingPathComponent:file2];

    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath2]) {
        plistPath2 = [[NSBundle mainBundle] pathForResource:@"User Data" ofType:@"plist"];
    }

    NSData *plistData2 = [[NSFileManager defaultManager] contentsAtPath:plistPath2];
    NSDictionary *tempDict2 = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistData2 mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format2 errorDescription:&error2];

    NSString *person = [@"BCDS" stringByAppendingString:loadstring];
    NSString *string = [tempDict2 objectForKey:person];
    NSString *message = [@"Hello, " stringByAppendingString:string];
    welcome.text = message;
}

A: Just check if objectForKey returns nil:
NSString *string = [tempDict2 objectForKey:person];
if (string == nil)
    [[[UIAlertView alloc]
        initWithTitle:@"Error" message:@"Cannot find item"
        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];


text:
Q: Laravel get route list by request Type methods I am using laravel 6.1 . I am trying do dynamic permission for user for add,edit ,delete and view .so trying to get route list from laravel router using following method
$routes = [];

foreach (Route::getRoutes()->getIterator() as $route){

    $routes[] = $route->uri;

}

This will return all route url list but problem here is for paramter routes list it has below
post-detail/{categoryId}/{postid}

How i can compare in middleware whether url is matching to this route .
Also is it possible to get route type along with route list.

A: The Route object has a matches method to see if the request matches the route which can also check the HTTP method:
$route->matches($request, true);

laravel/framework 6.x - Illuminate\Routing\Route@matches
You can also ask the Route Collection to find a matching route for the current Request:
$route = Route::getRoutes()->match($request);

Though this would just be the current route: $request->route()
laravel/framework 6.x - Illuminate\Routing\RouteCollection@match
Though I am not really sure what you are trying to do just by iterating through the routes.

The HTTP methods the Route responds to can be retrieved via $route->methods().
The HTTP method of the current Request can be accessed via $request->method().


text:
Q: sql server update a table with data from another table I have two tables source_table and destination_table
The source table is given below
orderid orderno invoiceno amount
 1         10       NULL    100
 2         NULL     11      200

i need to update destination_table with columns
orderid  orderno amount
  1         -      -
  2         -      -
  3         -      -

based on conditions , orderid of source matches with destination orderid
if source orderno value is not null then that value should be updated in the orderno column of destination ,  else source invoiceno should be updated in destination orderno column

A: Please try:
Update D
    SET orderno = (case when S.orderno is not null then orderno else s.invoiceno end)
FROM
    source_table S Join destination_table D
    ON S.orderid = D.orderid

A: You have several options.  One option is to use CASE:
UPDATE d
SET d.OrderNo =
   CASE
     WHEN S.OrderNo IS NOT NULL THEN s.OrderNo END ELSE S.invoiceno END
FROM Source S
    JOIN Destination D ON S.OrderId = D.OrderId

Or I personally prefer to use COALESCE:
UPDATE d
SET d.OrderNo = COALESCE(S.OrderNo, S.InvoiceNo)
FROM Source S
    JOIN Destination D ON S.OrderId = D.OrderId

Good luck.

A: Update D
SET orderno = S.orderno, amount = S.amount
FROM
source_table S Join destination_table D
ON S.orderid = D.orderid
WHERE S.orderno is not null

Update D
SET orderno = S.invoiceno, amount = S.amount
FROM
source_table S Join destination_table D
ON S.orderid = D.orderid
WHERE S.orderno is null

A: If you are using sqlserver then you can also use ISNULL function. See below sql.
UPDATE D
SET orderno = ISNULL(S.orderno, S.invoiceno),
    amount =  S.amount
FROM source_table S INNER JOIN destination_table D ON S.orderid = D.orderid
WHERE S.orderno IS NOT NULL OR S.invoiceno IS NOT NULL


text:
Q: calling sendAsynchronousRequest too many times In ios 6, I have an image downloader method that calls sendAsynchronousRequest. When number of images are too many completion blocks are never called and there are over 60 worker threads that are never destroyed(so the image downloading is never completed).  In ios 7 it seems to be working fine.  How do you make this work? code is as below
for(NSDictionary * imageDict in thumbnailJSONArray){
    NSString * thumbNailString = [imageDict objectForKey:JSON_URL];
    //other codes..
    [self downLoadThumbNails:numbertoAdd urlRequest:thumbNailString];

}
-(void)downLoadThumbNails:(NSUInteger) numberToAdd urlRequest:(NSString*)urlString {
    if(self.imageQueue == nil){
        self.imageQueue = [[NSOperationQueue alloc] init];
    }

    [NSURLConnection sendAsynchronousRequest:urlRequest queue:self.imageQueue completionHandler:^(NSURLResponse *response, NSData* data, NSError *connectionError) {
    //image setting codes
    }];
}

--EDIT--
To be more clear, image setting codes are never called, so the downloaded images are never set.


text:
Q: How to uniquely identify each cell in UITableView I have a UITableView and I am trying to make a segue to another viewcontroller, I need the row number so that I can select a string from an array so that I can display this string in the next view controller, I have this code at the moment.
let tableFrontView = segue.destination as! FCTableFrontViewController
tableFrontView.frontText = path[FlashCardsTableViewCell.init().tag].flashCardFront

the FlashCardsTableViewCell.init().tag is currently returning an int for testing purposes though I am wanting to know what I can replace it with to get me the number of the row which was selected by the user.
Thanks

A: Use TableView's delegate method  :
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 // indetify cell using indexPath.row attribute
}

A: You can try like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let tableFrontView = segue.destination as! FCTableFrontViewController
    let selectedIndexPath = tblView.indexPathForSelectedRow
    let selectedRow = (selectedIndexPath?.row)!
    print(selectedRow)
}

A: I assume you are writing the code snippet shown in prepare(for:)?
If that's the case, go to where you perform the segue, which is likely in the didSelectedRowAtIndexPath delegate method. If you don't have such a method, you should implement it.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showTableFrontVC", sender: nil)
}

Replace whatever it is that you are passing as sender now, and replace that with indexPath.row.
performSegue(withIdentifier: "showTableFrontVC", sender: indexPath.row)

Now in prepare(for:), you can unwrap sender as an Int:
let tableFrontView = segue.destination as! FCTableFrontViewController
let rowSelected = sender as! Int
tableFrontView.frontText = path[rowSelected].flashCardFront


text:
Q: AWS Elemental MediaConvert .createJob() not working in JS SDK, but working in AWS Console I'm trying to automatically create a compressed video and a thumbnail when one is uploaded to S3. The thumbnail is working how it should. For the compression, I'm trying to use AWS's mediaconvert to no avail. In my template, I've checked my Queue arn and role arn about 100 times. That exact template works when I create a job manually in AWS. But when I use
mediaConvert
.createJob(jobTemplate).promise()
.then(
   res => console.log('compress success', res),
   err => console.log('compress fail', err)
)

in my node API, it doesn't return anything. Not a compress success nor compress fail. One line above I've got console.log('starting compression job'), and that logs just fine. So I know it gets to the code.


text:
Q: No colors when running native windows shell application from mintty I have installed cygwin (i'm not very experienced with it), and try to run a native windows shell application from it, (msbuild.exe which is the build tool for the .NET framework, to be exact).
When I run the application from the normal cygwin bash shell, the output of the application appear as it should with the text colors that I would normally see in the windows command line.
But when I execute the program from a mintty terminal, there is no coloring of the output, all text is in the default foreground color. I'm puzzled, because I would have expected the color coding to be the standard ANSI color code escape characters...
Can this be fixed?

A: The application most likely uses Windows console APIs rather than ANSI color sequences. Mintty is a Unix terminal (based on Cygwin's pty implementation) rather than a Windows console wrapper though, hence those console API calls will have no effect.
There's currently no way to make this work in mintty, although there are various rather complex ideas on how the issue could be addressed at http://code.google.com/p/mintty/issues/detail?id=56. Meanwhile, the workaround is to just start the program in question in a console window. The 'cygstart' utility is a convenient way to do that.

A: Native Windows console programs often don't run well inside Cygwin terminal emulators such as mintty. See the Cygwin documentation for an explanation. Not seeing colors is one possible symptom; a worse symptom is not being able to type into the application.
There are alternative console programs that are much better than the built-in console. My current choice of terminals under Windows is mintty for cygwin or stdio programs and console2 for Windows console programs. The topic has been discussed several times on this site already:
Advanced command line editing for Windows?
https://superuser.com/questions/87441/alternative-windows-command-shell-and-console
Windows "cmd" Replacements
free cmd/powershell replacement with normal copy paste

A: You can use bash.exe instead of mintty:
Right click on the shortcut of cygwin, change it from C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico - to C:\cygwin64\bin\bash.exe --login -i


text:
Q: Failing to load static CSS from Django on Azure I followed this tutorial from DigitalOcean and have this in my settings.py.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/

However, after deploying my app, I find that the CSS file's request is canceled as seen in Chrome tools.

I still get this error even after running:
$ python manage.py collectstatic

which gives me files in staticfiles directory for admin and app. Note that I can run all this on localhost with no issue.
I tried the suggestion in this answer by switching from /static/ to static/ but ran into the same issue.
This is the directory structure I get when run ls -la on the Azure az webapp ssh immediately after running python manage.py collectstatic.
drwxr-xr-x 7 root root   4096 May 15 10:58 .
drwxrwxrwt 7 root root   4096 May 15 10:58 ..
drwxr-xr-x 2 root root   4096 May 15 10:58 .azure
-rwxr-xr-x 1 root root   2351 May 15 10:58 .gitignore
-rwxr-xr-x 1 root root    116 May 15 10:58 README.md
drwxr-xr-x 5 root root   4096 May 15 10:58 antenv
-rwxr-xr-x 1 root root 139264 May 15 10:58 db.sqlite3
drwxr-xr-x 3 root root   4096 May 15 10:58 project
-rwxr-xr-x 1 root root    665 May 15 10:58 manage.py
-rwxr-xr-x 1 root root    111 May 15 10:58 requirements.txt
drwxr-xr-x 4 root root   4096 May 15 10:58 staticfiles
drwxr-xr-x 6 root root   4096 May 15 10:58 app

Given that I want to retain this structure of static files in their respective app directories and don't have CSS files that are not tied to any app, I don't have to use STATICFILES_DIRS as the documentation says.

Your project will probably also have static assets that aren't tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.


text:
Q: Why doesn't this C++ insertion sort work? I'm learning C++ and this is one of my first programs that is going to sort a list of numbers, I found the algorithm in Kenneth H. Rosen book and wrote it in C++. when I check it on the paper it seems to be correct, but in practice it has some error. For example I enter 3(enter)2(enter)1(enter)4(enter)5(enter) and it returns 3 1 1 4 5 as the answer. I don't know what is the problem, please help.
int main()
{
    int i, j, s, n, k, a[50];
    cout << "Enter number of numbers:\n";
    cin >> n;
    cout << "Enter the numbers:\n";
    for (i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (j = 2; j < n; j++) {
        i = 1;
        while (a[j] > a[i]) {
            i = i + 1; // Here we find the proper place to(if needed) directly insert our number into the sorted part.
        }
        s = a[j];
        for (k = 0; k < j - i - 1; k++) {
            a[j - k] = a[j - k - 1];
        }
        a[i] = s;
    }
    for (i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    _getch();
    return 0;
}

I've also included the header files and namespace, not written here though. And in the case you think I have used so many variables, sorry about that, I needed them :)

A: Your index i should start from the first element which is 0 instead of 1.
Fixing line 11 should do the job:
for (j = 2; j < n; j++) {
    i = 0;
    while (a[j] > a[i]) {

Edit:
Oh, and also, your variable j should start from the second element which is index 1 instead of 2:
for (j = 1; j < n; j++) {


text:
Q: How to share same image on messenger and facebook via meta tags Angular? I am dealing with problem of sharing same image on messenger and facebook in Angular PWA app. Whole thing is done using  tags in html. The problem is in size of image, the photo is in recommended size for Facebook 1200x630px and it shows correct. While i am sharing it via messenger it is cut, maybe there should be another image or I didnt configure it correctly. I also set width and height of image using meta.
Here's code:
  <meta property="og:title" th:content="${title}">
  <meta property="og:url" th:content="${url}" />
  <meta property="og:type" content="website" />
  <meta property="og:site_name" content="here is site name" />
  <meta property="og:image" content="here is photo url" />
  <meta property="og:image:width" content="600" />
  <meta property="og:image:height" content="314" />
  <meta property="fb:app_id" content="here is facebook app id" />

I have a component with shared buttons and messenger is using function from FB docs.
shareOnMessenger() {
window.open('fb-messenger://share?link=' + encodeURIComponent(this.detailedViewURL) + '&app_id=' + encodeURIComponent(this.facebookMetaTag.content));

}


text:
Q: How to Sort arraylist of object containing Date in Reverse Order I was able to sort in ascending order but can't figure out in descending order.Here is the code that I have used.
public class RssItemComparator implements Comparator<RssItem> {
    DateFormat simpleDateFormat = new SimpleDateFormat("E, dd MMM yyyy hh:mm");
    Date date1, date2;

    @Override
    public int compare(RssItem rssItem1, RssItem rssItem2) {
        try {
            date1 = simpleDateFormat.parse(rssItem1.getPubDate());
            date2 = simpleDateFormat.parse(rssItem2.getPubDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date2.compareTo(date1);

    }
}

this created sort in an unusual manner.Eg:

*

*Fri,24 Nov 2017 05:07

*Fri,24 Nov 2017 04:34

*Fri,24 Nov 2017 02:11

*Thu,23 Nov 2017 13:55

A: try create an instance of movie when the activity is showing and delete it when you change to a new activity. that should solve the ran out of memory problem.
Activity Life Cycle - https://developer.android.com/images/activity_lifecycle.png
before an activity is going to show it runs onResume() - this could be where you create and prepare the movie to show,
and then before it disappear because a new activty come on top of it or user close an app, it runs onPause() - this could be where you delete movie to avoid running out of memory problem
// import declarations ommited

public class DetailActivity extends Activity {

 Movie aMovie;
 // other variables ommited

 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // other logics ommited
 }

 // this will run everytime an instance of DetailActivity is on a screen
 @Override
 public void onResume() {
    // create and instance of aMovie and show it
    // this will ensure the same movie of this instance of DetailActivity will show everytime when it's showing on screen
 }

 // this will run everytime an instance of DetailActivity is closed or, another instance of an activity is pushed on top of it
 @Override
 public void onPause() {
    // remove, delete or free resource of an instance of aMovie
    // so this will help about not running out of memory since we
 }

 // other methods ommited
}


text:
Q: Can not import public EC key in jwk format suptile I am using Chrome and I want to import this public EC P-256 ECDH key like so:
await crypto.subtle.importKey(
    "jwk",
    {
      kty: "EC",
      crv: "P-256",
      ext: true,
      x: "mRBuuxrvM7xy2oc4xZkw_i0JyIiIp_b0Zmnb1RYKZcg",
      y: "emhIhswnvIHICDtkWx4LLWy3HcN-is2l1oN9-r4_ChQ",
      key_ops: ["deriveKey"],
    },
    { name: "ECDH", namedCurve: "P-256" },
    true,
    ["deriveKey"]
  );

However I get the error:  Cannot create a key using the specified key usages.
Why not?

A: Ok so it turns out that when you want to import a public key to derive a key from it you should just not give any keyUssages to it. So this works:
await crypto.subtle.importKey(
    "jwk",
    {
      kty: "EC",
      crv: "P-256",
      ext: true,
      x: "mRBuuxrvM7xy2oc4xZkw_i0JyIiIp_b0Zmnb1RYKZcg",
      y: "emhIhswnvIHICDtkWx4LLWy3HcN-is2l1oN9-r4_ChQ",
    },
    { name: "ECDH", namedCurve: "P-256" },
    true,
    [] // the public key just doesn't have usages
  );


text:
Q: How to create/update environment in release definition pipeline? I am trying to dynamically create environments with a set of specific predefined tasks and steps.
Anyone ever got this working well enough to post some sample code, or a guide?
I can't add an environment, or tasks to an existing one. I keep getting an error BadRequest, but I don't know what am I doing wrong in the JSON payload.
I can get the existing definition, I can do simple things like update the name of the release definition, comments and description when I update, but once I touch the environments it all breaks.
I am using the online URIs -
https://vsrm.dev.azure.com/{acct}/{proj}/_apis/release/definitions?api-version=5.1
Is there any way to get more information on what's wrong with my payload, what's bare minimum, or required?

A: If you mean create/update environment for the specific release definition, then you can try the following steps:

*

*Get that release definition response and convert the response to JSON body:
GET https://vsrm.dev.azure.com/{organization}/{Project}/_apis/release/definitions/{definition ID}?api-version=5.1

*Add (insert) a new environment (or update the existing one) to that JSON body. You can copy from the existing environment block, then change the parameters accordingly. For example: Add a new environment with "id":0,  set a new name, the ranks of release pipeline stages need to be consecutive natural numbers, for example, the rank in previous stage is "2", then it should be "3" here. Keep others same as previous one

*Update the release definition by calling the REST API with the updated JSON body:
PUT https://vsrm.dev.azure.com/{organization}/{Project}/_apis/release/definitions?api-version=5.1
You can reference the below screenshot for details:


text:
Q: Using Indirect to Maintain Year-to-Date Sums from Another Worksheet First time poster.  I'm trying to sum cells from an earlier dated worksheet in order to maintain year-to-date counts for comparison.  The way my workbook is setup now, I have one year's worth of data on each worksheet and the data used are monthly reports.  The monthly reports are pasted into my 'Template' worksheet.  The data from these is then organized into a time series on separate worksheets, and the name for each of the worksheets is the year for which the data corresponds.  When adding new data throughout the course of a year, I was wanting to pull in year-to-date totals from the previous year in order to compare similar time frames.  This is what my formula currently looks like.
=SUM(INDIRECT("'"&LEFT($A13,4)&"'!C17:OFFSET(C$16,MONTH(RIGHT(Template!C$3,10)))"))
LEFT($A13,4) references the year I want pulled in for the current worksheet, and MONTH(RIGHT(Template!C$3,10)) identifies the number of the month for the current report.  So, for May 2015, Left($A13, 4) would return "2014" and MONTH(RIGHT(Template!C$3,10)) would return a value of 5.
As (I hope) is evident, I'm attempting to begin my summation at the beginning of the annual series found on the previous year's worksheet, and then use OFFSET to pull in only the months that end with the current report month for this year to do a year-to-date change.  This is returning #REF! in Excel when I attempt to do this.  First impressions make is seem that INDIRECT is not recognizing OFFSET as a function, and is treating it as text.  Is there any way around this?
I see something similar was posted earlier, but was unable to translate to my situation.  Any help would be greatly appreciated.

A: Hard to replicate without the data, so take this for what it's worth...
Breaking your formula down (one distinct argument per line), we have
=SUM(
  INDIRECT(
    "'"
    &
    LEFT($A13,4)
    &
    "'!C17:OFFSET(C$16,MONTH(RIGHT(Template!C$3,10)))"
  )
)

meaning the line beginning "'!C17:OFFSET(... is likely being treated as text by Excel, since it is enclosed within quotation marks. You probably want
=SUM(
  INDIRECT(
    "'"
    &
    LEFT($A13,4)
    &
    "'!"
    &
    C17
    &
    ":"
    &
    OFFSET(C$16,MONTH(RIGHT(Template!C$3,10)))
  )
)

in order to feed all the syntax (', !, :, etc.) to INDIRECT as strings and all the cell values as formula results.

A: Thank you for taking the time to post an answer to my question.  I think I figured out a much more workable solution to my problem than I had previously imagined though.  Instead of having the only the annual worksheets with just one year's worth of data, I am instead having the reports added on the end of a new worksheet with the entire time series in a sheet titled "Raw Data" with column "A" of the new worksheet containing a month-ending date.  This is what my formula looks like for adding new reports to the 'Raw Data' sheet.
=IF(AND(YEAR($A2)=YEAR(Template!$F$4), MONTH('Raw Data'!$A2)=MONTH(Template!$F$4)),Template!C$35," ")

Template!$F$4 references the date found on the report.
My annual worksheets then reference the 'Raw Data' sheet in order to eliminate the need to use the INDIRECT function.  For maintaing year-to-date sums for the data found in column "C" of "Raw Data", here is my formula.
=SUM(INDEX('Raw Data'!C:C,(MATCH(EOMONTH($A17,-12),'Raw Data'!$A:$A,0))):OFFSET(INDEX('Raw Data'!C:C,(MATCH(EOMONTH($A17,-13),'Raw Data'!$A:$A,0))),MONTH(RIGHT(Template!$F$4,10)),0))

EOMONTH($A17, -12) is set up to always reference January of the previous year.  This is then is OFFSET by the number of the month found on the report referenced by MONTH(RIGHT(Template!$F$4,10)) and summed.


text:
Q: Python - how to combine data frame by for loop? I have the following data frame:
   Tower    Floor   Unit
0   1       1.0      A
1   1       1.0      B
2   1       1.0      C
3   1       1.0      D
4   1       1.0      E
5   1       1.0      F
6   1       1.0      G

I would like to create the following dataframe from floor 1 to 10:
   Tower    Floor   Unit
0   1       1.0      A
1   1       1.0      B
2   1       1.0      C
3   1       1.0      D
4   1       1.0      E
5   1       1.0      F
6   1       1.0      G
7   1       2.0      A
8   1       2.0      B
9   1       2.0      C
10  1       2.0      D
11  1       2.0      E
12  1       2.0      F
13  1       2.0      G
....
63  1       10.0     A
64  1       10.0     B
65  1       10.0     C
66  1       10.0     D
67  1       10.0     E
68  1       10.0     F
69  1       10.0     G

What should I do?

A: import pandas as pd

df = pd.DataFrame({
    'Tower': 1,
    'Floor': 1.0,
    'Unit': list('ABCDEFG'),
})
df = pd.concat([df for _ in range(10)])
df = df.reset_index()
df['Floor'] = df.index // 7 + 1.0
print(df)

A: In a for loop you can use pd.concat:
df = pd.DataFrame()
for i in range(1, 11):
    df = pd.concat([df, pd.DataFrame({"Tower": 1, "Floor": i, "Unit": list("ABCDGEG")})])

This concatenates the DataFrames one after the other, outputting:
In [9]: df
Out[9]:     Tower  Floor Unit
        0       1      1    A
        1       1      1    B
        2       1      1    C
        3       1      1    D
        4       1      1    G
        ..    ...    ...  ...
        65      1     10    C
        66      1     10    D
        67      1     10    G
        68      1     10    E
        69      1     10    G

        [70 rows x 3 columns]


text:
Q: Giving cron permission to execute command I'm trying to get a ruby script to run via cron. The cron job looks like this:
* * * * * /usr/local/rvm/rubies/ruby-2.0.0-p353/bin/ruby /usr/share/adafruit/webide/repositories/shed_watcher/lib/shed_watcher.rb >> /tmp/cron_shed_watcher.log 2>&1

I've encountered a couple of problems. The first was that the environment cron runs in could find one of the required gems:
require "rest_client"

This was solved by setting the GEM_PATH in the crontab:
GEM_PATH=/usr/local/rvm/gems/ruby-2.0.0-p353:/usr/local/rvm/gems/ruby-2.0.0-p353@global

The second problem is that the script, running on Occidentals on a Raspberry Pi, makes use of a temperature probe and needs to call:
`modprobe w1-gpio`
`modprobe w1-therm`

i.e. modprobe commands in backticks. Cron cannot execute this, instead I get an "operation not permitted" message. modprobe is found in /sbin so I added a path entry to my crontab:
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/usr/local/rvm/gems/ruby-2.0.0-p353/bin:/usr/local/rvm/gems/ruby-2.0.0-p353@global/bin:....

But I get the same error (not surprising as it was a "not permitted" message, not a "not found" message). What do I need to do to get this working?

A: You should add your job to the root's crontab, not the user's one. User's crontabs always executed with uid/gid of the user when root crontab can contain additional field:
* * * * * username /path/to/the/command

Then command will be executed with username privileges/permissions.


text:
Q: How to check if a string contains a pattern separated by whitespace? How to check if a string contains a pattern separated by whitespace?
Examples:
"abc  ef    ds       ab  "

Now I would like to check if the given string consists only of the pattern [a-z] separated by whitespace. My try: ^\s*[a-z]*\s*$. But this checks only whitespace in the beginning and end, not if the whitespaces is used for separation of the content.

A: Try this regular expression:
/^[a-z\s]+$/

A: ^(\s|[a-z])*$

Zero or more case characters that are either whitespace, or A-Z.
If you want to make sure there's at least one thing other than white space, then:
^\s*[a-z]+(\s*|[a-z])*$

Zero or more whitespace, at least one character A-Z, then the same as above.


text:
Q: Можно ли инициализировать константу класса enum вне класса? Есть enum:
enum :int {OneCop , FiveCops, TenCops, FivtyCops, One, Two, Five, Ten, Fivty, Hundred, FiveHundereds, Tousand, FiveTousand};

Можно ли инициализировать переменные вне "enum", те как-то так:
enum :int {OneCop , FiveCops, TenCops, FivtyCops, One, Two, Five, Ten, Fivty, Hundred, FiveHundereds, Tousand, FiveTousand};
   OneCop = 0;

У меня при попытке подобного пишет: "expression must be a modificated lmalue"

A: Тут имеется фундаментальное непонимание енумераторов. Идентификаторы, перечисляемые внутри енумераторов, не являются полями, как в структурах или классах. Они существуют только во время компиляции и не присутствуют в памяти программы, нельзя получить их адрес или ссылаться на них. При их использовании получается выражение категории prvalue, аналогично встроенным литералам. И значение для них должно идти сразу и являться константным выражением.
enum Cops:int {OneCop = 0, FiveCops = 1,

A: Нельзя. Весь смысл enum-а это мапнуть константный числовой массив в какие-то человекочитаемые названия.
И ещё лучше использовать enum class


text:
Q: Trigger in Postgres DB What is the most efficient way to create this trigger in Postgres.
I'll present below a very simplified example to what I need for my purposes, but it is based on the same concept.
Consider, we have got the schema defined below:
CREATE TABLE items (
  item_id int4,
  part_no int4,
  description text);

CREATE TABLE blacklist (
  part_no int4,
  reason text);

CREATE TABLE matches (
  item_id int4,
  part_no int4,
  reason text);

Then, every time a new item is added, we check if it is on the blacklist (comparing the part_no), and if it is, we create a new entry on the matches table.

A: You'd want a before-insert or after-insert trigger on items:
create trigger blacklist_matches after insert on items
for each row execute procedure check_blacklist();

Then the check_blacklist function would look something like this:
create function check_blacklist()
    returns trigger as $$
begin
    insert into matches (item_id, part_no, reason)
    select NEW.item_id, NEW.part_no, blacklist.reason
    from blacklist
    where blacklist.part_no = NEW.part_no;
    return null;
end;
$$ language plpgsql;

The funny looking $$ is, more or less, the SQL version of a heredoc.
That wraps the "is it on the blacklist" check and the matches insertion in one simple bit of SQL. The NEW variable in a trigger is a reference to the new row that you're working with. If NEW.part_no doesn't match anything in blacklist, then the SELECT won't produce anything and the INSERT will not be executed.
Presumably you'd have an index on blacklist.part_no (which looks like a PK anyway) so the above should be quick enough.
The PostgreSQL documentation is pretty good and has a whole section on stored procedures and triggers if you need a reference.


text:
Q: Loading data during onCreate() via AsyncTask I'm trying to load data during onCreate (also tried during onStart) via AsyncTask from a Room database. The thing is, I'm passing the context to the AsyncTask via a WeakReference and, sometimes (one out of four times) the context becomes null on the onPostExecute, even though the task finishes almost instantly (it's a small database).
I don't know which is the correct approach to load data via AsyncTask on the onCreate method without risking the context to become null so quick - I know it has to be done via WeakReference in order to avoid memory leaks, but I think the activity gets recreated for some reason sometimes so quickly that the task can't post the results to the original context and the data doesn't show up in the Activity.
Any ideas what is the correct way to handle this, given the fact the task finishes almost instantly, but it's a requirement of the Room library to do it via another thread (an also improves performance and responsiveness)?
So just for the sake of clearness, I'm trying to access the context this way:
public MyTask(ActivityListener listener) {
    mWeakContext = new WeakReference(listener);
}

protected void onPostExecute(Boolean result) {
    AcitivtyListener aListener = mWeakContext.get();
    if (aListener != null) aListener.refresh(data);
}

The ActivityListener interface is implemented anonymously on the call to new MyTask(new ActivityListener() { ... });
Thanks

A: Yeah I think context becoming null means activity was re-created, but it seems unlikely to happen as I imagine its so fast you couldn't rotate the phone faster than the database operation
Indirect answer to this question would simply be: do not use AsyncTask at all, use ViewModel and LiveData - they are part of the architecture thing from google as well as Room that you are using
To put it short these two components will solve issues with lifecycle management/context leaking and also sending results to correct Activity instance
See documentation on LiveData and ViewModel: livedata viewmodel


text:
Q: Dicas de como fazer duas excerpts dentro de cada artigo do wordpress Preciso de dicas de como criar excerpts (resumos) no Wordpress, eu tenho um pouco de conhecimento na plataforma, mas ainda muito limitado e não sei por onde começar.
Tem dois resumos dentro de cada artigo do blog, uma forma padrão. Onde será limitado os caracteres a serem exibidos. Já busquei informação em diversos locais e não encontrei.
Da mesma forma da imagem abaixo. Com o texto resumido em umas 6 linhas e "VER MAIS"
Eu não tenho código ainda, porque eu realmente não sei por onde começar. Preciso de dicas, informações, links, qualquer coisa que me dê um "norte".

A: Aqui tem um modelo simples que pode te ajudar. Caso seu texto tenha menos de 6 linhas basta vc remover o "Leia mais"
A técnica é usar uma Label com um for para o checkbox que está escondido fora do .box. Quando esse checkbox for marcado clicando na label a .box aumenta e mostra o conteúdo todo. Como o .box tem altura max-height ele sempre vai ajustar com o seu conteúdo, a não ser que ele tenha mais que 1000px de altura, o que é algo bem improvável, mas se precisar tb basta mudar esse valor...
Veja funcionando para vc entender melhor. Deixei os comentários no código para te ajudar

html, body {
 width: 100%;
 height: 100%;
 margin: 0;
 padding: 0;
}
.box {
 border: 1px solid #000;
 display: flex;
 flex-direction: column;
 margin: 1rem;
/* altura inicial do box, mude aqui o suficiente para mostrar quanto quiser do conteúdo inicial */
 max-height: 200px;
 position: relative;
 padding: 0 1rem 2rem;
 box-sizing: border-box;
 overflow: hidden;
 transition: max-height 500ms;
}
input:checked + .box {
 max-height: 1000px;
 /* hake para fazer o box crescer, o tamanho máximo dele é 1000px ou menosse o conteúdo for menor */
}
.box > label {
 cursor: pointer;
 position: absolute;
 bottom: 0;
 left: 0;
 width: 100%;
 margin-left: 1rem;
 height: 3rem;
 line-height: 3rem;
 background-image: linear-gradient(to bottom, transparent, #fff 25%);
 color: red;
}
.box > label:hover {
 text-decoration: underline;
}
#ler {
 display: none;
 /* remove o checkbox da tela */
}

<input type="checkbox" name="" id="ler" hidden>

1 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

2 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

3 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

4 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

5 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

6 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

7 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

8 Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iste, aut!

  leia mais


text:
Q: How to show actual values instead of sum/average on y-axis in a plot using Power BI I have an excel sheet which I am plotting two values over time. But when I plot it in Power BI it shows the sum of those values in y-axis rather than the actual value. The plot looks like the following.
If you see the y-axis they are in billions. But if you see the actual data below its in hundred thousands range.

If I use date hierarchy instead this is how it looks like.

A: Since your data is on specific days, you should use dates on your axis rather than weekends. When you have weekends on the axis, it groups all the days within that week together, which is not what you want.

Edit:
After looking at your file, it has nothing to do with dates after all. It looks like the data is recorded at a weekly level. The reason its adding up like that though is that for each date there are a bunch of different rows that correspond to different geography (your geo column has state name abbreviations).
If you add a slicer for geo and look at the chart for a single state at a time, then I think you'll get more what you're expecting.


text:
Q: How to populate jquery data accordingly/individually to Cards? Im new to Laravel framework and im trying to develop a simple car listing web using Bootstrap Cards. I've successfully implemented AJAX Get including populating data from Controller using Jquery append() method. However it is displaying all cars in one Card. How to populate each Cards containing each car?. current result console.log result
public function GetCars(Request $request)
    {
        if ($request->ajax())
        {
            $cars = Car::all();

            return response()->json( $cars );
        }
 }

                                        View

Make:

Model:

Price: RM

    <button id="testbtn" type="submit" class="btn btn-success">AJAX</button>

A: This is what are you meaning?
I created an example, where I'm using some rows from your console.log data.
Explanation:
I am iterating throught the data array. If it is first iteration I'm adding data (one CarDetail div exists in your code.
For the next iterations I am cloning the CarDetail div and fill with next data.
Of course,there are more posibilities how to add your data to page. For example, you can fill the first item in page and then iterate from the second to the last (in that case you won't need the if/else condition) or you can add the HTML code in a JS variable. Personally, I wouldn't do that because it looks very ugly and the readability of the code could get worse.

$(document).ready(function(){
  var data = [
   {id:31,make:"Audi",model:"R8",year:2000},
   {id:32,make:"Ferrari",model:"FF",year:2000},
   {id:33,make:"Mazda",model:"Rx-7",year:2000},
   {id:34,make:"Ferrari",model:"F12",year:2012},
   {id:35,make:"Porsche",model:"911",year:2015},
   {id:36,make:"Land Rover",model:"Vogue",year:2015},
   {id:37,make:"Mercedes Benz",model:"SL350",year:2013},
   {id:38,make:"Ferrari",model:"F12",year:2013},
   {id:39,make:"Ferrari",model:"458",year:2013},
  ];

  $.each(data, function( i, car ) {
    if(i == 0) {
      $('.card').find('.car_Make').text(car.make);
      $('.card').find('.car_Model').text(car.model);
      $('.card').find('.car_Year').text(car.year);
    } else {
      var carDetailCloned = $('.card').first().clone();
      carDetailCloned.find('.car_Make').text(car.make);
      carDetailCloned.find('.car_Model').text(car.model);
      carDetailCloned.find('.car_Year').text(car.year);

      $('.card-container').append(carDetailCloned);
    }
  });
});
.CarDetail{background-color:red;margin-bottom:2em}

              View

Make:

Model:

Price: RM

  <button id="testbtn" type="submit" class="btn btn-success">AJAX</button>

Edit: I edited my code to clone <div class="card mb-3 shadow-sm" for every card and add data in there. Moreover, I add a card-container class in the parent element to use it when I append a new car. Is that enough?


text:
Q: Why does pip3 install into /usr/local/bin64 instead of my virtual env, even though it's activated? I want dependencies for a project to be installed into a virtual environment. I create it successfully, and activate it, but still installing dependencies results in them installed under /usr/local/bin64 instead of my virtual env:
[ec2-user@machine app]$ virtualenv environment
created virtual environment CPython3.7.10.final.0-64 in 392ms
  creator CPython3Posix(dest=/home/ec2-user/app/environment, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/ec2-user/.local/share/vi
rtualenv)
    added seed packages: pip==21.0.1, setuptools==54.1.2, wheel==0.36.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
[ec2-user@machine app]$ source environment/bin/activate
(environment) [ec2-user@machine app]$ pip3 install -r requirements.txt
Collecting anyio==3.4.0
  Using cached anyio-3.4.0-py3-none-any.whl (78 kB)
Collecting appdirs==1.4.4
  Using cached appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting atomicwrites==1.4.0
  Using cached atomicwrites-1.4.0-py2.py3-none-any.whl (6.8 kB)
Collecting attrs==20.3.0
  Using cached attrs-20.3.0-py2.py3-none-any.whl (49 kB)
Collecting boto3==1.20.14
...

I find packages end up here: /usr/local/lib64/python3.7/site-packages
But I expected them to be installed inside ~/app/environment, where my virtual env was created and activated.
I checked the location of pip and pip3, seems correct:
(environment) [ec2-user@machine app]$ which pip
~/app/environment/bin/pip
(environment) [ec2-user@machine app]$ which pip3
~/app/environment/bin/pip3

What am I missing?

A: You are calling pip3 which is in the other environment. Try pip. And you can validate with which pip.


text:
Q: How to store something in JavaScript temporarily? I am trying to create blackjack with JS and React.
So far I have got most of it working but my main problem is that everytime react renders it changes the cards and the order of the deck etc. I just need a simple way to store data and so even when react re renders it keeps the order of the deck (array of objects). I am use to firebase but that seems quite heavy for something like this. any ideas? i saw local storage might be an option too but wanted peoples opinions.