text:
Q: Are passwords on modern Unix/Linux systems still limited to 8 characters? Years ago it used to be the case that Unix passwords were limited to 8 characters, or that if you made the password longer than 8 characters the extra wouldn't make any difference.
Is that still the case on most modern Unix/Linux systems?
If so, around when did longer passwords become possible on most systems?
Is there an easy way to tell if a given system supports longer passwords and if so, what the effective maximum (if any) would be?
I've done some web searching on this topic and couldn't really find anything definitive; much of what came up was from the early 2000s when I think the 8 character limit was still common (or common enough to warrant sticking to that limit).

A: Not for Linux.  It's only 8 if you disable MD5 Hashing.
http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/security-guide/s1-wstation-pass.html
You can administer policies enforcing longer and more complex passwords as well.
The full lengths are discussed here:
http://www.ratliff.net/blog/2007/09/20/password-length/

A: Are you asking about the crypt algorithm?
http://linux.die.net/man/3/crypt
"By taking the lowest 7 bits of each of the first eight characters of the key..."
"The glibc2 version of this function has the following additional features. ... The entire key is significant here (instead of only the first 8 bytes)."
Here's a hint as to how long ago this change happened.
Glibc 2 HOWTO
  Eric Green, ejg3@cornell.edu
  v1.6, 22 June 1998

A: Although the original DES-based algorithm only used the first 8 characters of the password, Linux, Solaris, and other newer systems now additionally support other password hash algorithms such as MD5 which do not have this limit.  Sometimes it is necessary to continue using the old algorithm if your network contains older systems and if NIS is used.  You can tell that the old DES-based algorithm is still being used if the system will log you in when you enter only the first 8 characters of your >8-character password.
Because it is a hash algorithm, MD5 does not have an intrinsic limit.  However various interfaces do generally impose some limit of at least 72 characters.
Although originally the encrypted password was stored in a world-readable file (/etc/passwd), it is now usually stored in a separate shadow database (e.g. /etc/shadow) which is only readable by root.  Therefore, the strength of the algorithm is no longer as important as it once was.  However if MD5 is inadequate, Blowfish or SHA can be used instead on some systems.  And Solaris supports pluggable password encryption modules, allowing you to use any crazy scheme.  Of course if you are using LDAP or some other shared user database then you will need to select an algorithm that is supported on all of your systems.

A: In glibc2 (any modern Linux distribution) the password encryption function can use MD5/SHA-xxx (provoked by a magic salt prefix) which then treats as significant all the input characters (see man 3 crypt). For a simple test on your system, you could try something like:
#!/bin/perl -w
my $oldsalt = '@@';
my $md5salt = '$1$@@$';
print crypt("12345678",  $oldsalt) . "\n";
print crypt("123456789", $oldsalt) . "\n";
print crypt("12345678",  $md5salt) . "\n";
print crypt("12345678extend-this-as-long-as-you-like-0", $md5salt) . "\n";
print crypt("12345678extend-this-as-long-as-you-like-1", $md5salt) . "\n";

(which on my system gives)
@@nDzfhV1wWVg
@@nDzfhV1wWVg
$1$@@$PrkF53HP.ZP4NXNyBr/kF.
$1$@@$4fnlt5pOxTblqQm3M1HK10
$1$@@$D3J3hluAY8pf2.AssyXzn0

Other *ix variants support similar - e.g. crypt(3) since at least Solaris 10.
However, it's a non-standard extension - POSIX does not define it.

A: You will find this article of interest.  There is something called PAM (Password Authentication Module) which runs your password through a series of modules (configured in /etc/pam.d/passwd or /etc/pam.conf) to determine whether the password is valid or not.

A: I think around the time when actual passwords were moved from /etc/passwd to shadow, on Linux . I am guessing around 2000, Red Hat 6.x had long passwords IIRC.  Around 2000 there were still a lot of old SUN, and they had password and username limits.


text:
Q: Storybook does not render Stories, Error: "useContext(...) is undefined" If I create a Story for the following Component I only get a couple of messages in a red frame, which do not contain any information I can gain any insight from:
import React, { useState, useContext } from "react";
import { FormGroup, FormControl, Col } from "react-bootstrap";
import Button from "../button/Button";
import AuthContext from "../../AuthContext";
import { useHistory } from "react-router-dom";
import LoginWarning from "./LoginWarning";

export function Login(props) {
  const [email, setEmail2] = useState("");
  const [password, setPassword] = useState("");
  const [showAlert, setShowAlert] = useState(false);
  const {
    setRole,
    setName,
    setEmail,
    setSessionId,
    setLocalStorage
  } = useContext(AuthContext);
  let history = useHistory();

  function validateForm() {
    return email.length > 0 && password.length > 0;
  }

  const loginPost = {
    email: email,
    password: password
  };

  function handleSubmit(event) {
    event.preventDefault();

    const fetchUserInfo = async () => {
      const result = await fetch(`/account`, {
        method: "GET"
      });
      const body = await result.json();

      console.log(body);
      setRole(body.role);
      setName(body.name);
      setEmail(body.email);
      history.push("/home");
    };

    const fetchAuth = async () => {
      const result = await fetch(`/login`, {
        method: "POST",
        body: JSON.stringify(loginPost),
        headers: {
          "Content-Type": "application/json"
        }
      });
      const body = await result.json();

      console.log(body);
      if (body.isUser === true) {
        setSessionId(body.sessionId);
        setLocalStorage(body.sessionId);
        fetchUserInfo();
      } else {
        setShowAlert(true);
      }
    };
    fetchAuth();
  }

  return (

      {showAlert ? <LoginWarning /> : null}
      <form onSubmit={handleSubmit}>
        <Col lg={6}>
          <FormGroup controlId="email" bsSize="large">
            Email

            <FormControl
              autoFocus
              type="email"
              value={email}
              onChange={e => setEmail2(e.target.value)}
            />
          </FormGroup>
        </Col>
        <Col lg={6}>
          <FormGroup controlId="password" bsSize="large">
            Passwort
            <FormControl
              value={password}
              onChange={e => setPassword(e.target.value)}
              type="password"
            />
          </FormGroup>
          <Button disabled={!validateForm()} type="submit" text="Login" />
        </Col>
      </form>

  );
}

export default Login;

The Story looks like this:
import React from "react";
import { Login } from "./Login";
import { storiesOf } from "@storybook/react";

export default {
  title: "Login Form"
};

storiesOf("Login Form", module).add("default", () => <Login />);

And this is what Storybook is showing. Since my Component is showing in the App without any problems, I can't figure out what causes the problem for Storybook:
useHistory@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:100829:10
Login@http://localhost:6006/main.e31f087434cfd38286ae.bundle.js:763:84
renderWithHooks@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:84742:27
mountIndeterminateComponent@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:87276:13
beginWork$1@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:88638:16
callCallback@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:68837:14
invokeGuardedCallbackDev@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:68886:16
invokeGuardedCallback@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:68941:31
beginWork$$1@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:94239:28
performUnitOfWork@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:93166:12
workLoopSync@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:93139:22
performSyncWorkOnRoot@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:92738:11
scheduleUpdateOnFiber@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:92166:28
updateContainer@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:95562:15
legacyRenderSubtreeIntoContainer/<@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:95986:22
unbatchedUpdates@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:92901:12
legacyRenderSubtreeIntoContainer@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:95985:21
render@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:96073:12
render/<@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:20472:26
render@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:20471:10
_callee$@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:20563:20
tryCatch@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:19561:40
invoke@http://localhost:6006/vendors~main.e31f087434cfd38286ae.bundle.js:19787:30
defineIteratorMethods/

The browsers console shows the following:
The above error occurred in the <Login> component:
    in Login (at Login.stories.js:10)
    in AuthProvider (at Login.stories.js:10)
    in storyFn
    in ErrorBoundary

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary. react-dom.development.js:21810
    React 18
    render render.js:70
    render render.js:69
    _callee$ render.js:161
    Babel 8
    _callee$ start.js:408
    Babel 8
    renderUI start.js:453
    emit index.js:180
    setSelection story_store.js:325
TypeError: "useContext(...) is undefined"
    useHistory react-router.js:706
    Login Login.js:19
    React 16
    render render.js:70
    render render.js:69
    _callee$ render.js:161
    Babel 8
    _callee$ start.js:408
    Babel 8
    renderUI start.js:453
    emit index.js:180
    setSelection story_store.js:325

A: If your component uses useContext(), you actually have to initialize the context.  Storybook has a different entry point from your app so all your normal app initialization won't happen unless you do it yourself.
The easiest way to do so is with a decorator.  See https://storybook.js.org/docs/react/writing-stories/decorators#global-decorators for details on how to do this from 5.0+.
From 5.0 onwards, to do this globally, add something like this to .storybook/preview.js
export const decorators = [
  (Story) => (
    <YourContextProvider>
      <Story />
    </YourContextProvider>
  ),
];

Before 5.0, to do this globally, add something like this to your .storybook/config.js:
const StorybookWrapper = (storyFn) => (
  <YourContextProvider>
    {storyFn()}
  </YourContextProvider>
);
addDecorator(StorybookWrapper);

Updated: distinguish between pre-5.0 and 5.0+

A: You can create custom context decorator as follows
----- Button.js -----
export const Button = (props) => {
  const { state, dispatch } = useContext(BoxContext);
  return <button>{state.name}</button>
}
/*I had useContext in Button.js so need to
 create ContextDecorator*/

----- ContextDecorator.js -----
import React, { useReducer, createContext } from 'react';
import { initialState } from '../../App';
import { reducer } from '../../Context/Reducer';

export const BoxContext = createContext();

export const ContextDecorator = (props) => {
const [state, dispatch] = useReducer(reducer, initialState);
  return <BoxContext.Provider value={{state,dispatch}}>
     {props.children}
     </BoxContext.Provider>
}

----- AddButton.stories.js -----
import React from 'react';
import {Button} from './Button';
import { ContextDecorator } from './ContextDecorator';
export default {
  title: 'Example/AddButton',
  component: Button,
  decorators:[(Story) => {
      return <ContextDecorator><Story /></ContextDecorator>
  }],
  argTypes: {
      onClick: {
          action:'clicked'
      },
    backgroundColor: { control: 'color' },

  },
};

export const SampleAddButton = (args) => <Button {...args} />

A: I had the same issue: I wrapped my component in my .stories.tsx file <BrowserRouter> tags and BOOM, problem was gone. ¯_(ツ)_/¯
The culprit here is useHistory().
Damn, did that take a while.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to pass args containing & char in python I was trying to do something like this
python something.py ThisIs&TheKindOfThing=4Input

import sys
a = sys.argv[1]
b = sys.argv[2]

This throws an exception, and we can inspect the values and see that
a = 'ThisIs'

and it appears the rest is rejected. I had a bit of a google search around that, but didn't find any match. Can anyone explain to me how I can pass in a parameter like this, or just tell me where the relevant documentation is. I can't imagine that there isn't an easy way to handle this.


text:
Q: Make a user enter an array I am new to coding and I need to plot an array but I could not modify my code to ask the user to enter the array.
passengersByQueue = [5,4,6,1,7,7]
I need to make the user to input 6 numbers instead of the numbers in the code

A: You could use input() with a loop:
arr = []
count = 6
while count > 0:
  arr.append(input('Enter a number: '))
  count = count - 1

or use split():
userInput = input('Enter a comma-separated list of numbers')
arr = userInput.split(',')

Edit to add parsing of integers:
The returned array is an array of strings, so you need to convert them back to integers:
newArr = list(map(int, arr))

map(int, arr) returns an iterator of the array after the function int() is applied to all members of the array, you have to use list() in order for it to return an actual array. Alternatively, if you use the loop to have the user enter each value one by one, you can use int() before appending to the array.

A: If you are looking to use pythons inbuilt function input(), then you can set a loop like this to read your input list
    li = []
    for i in range(n):
      x = input() #get input
      li.append(int(x)) # append to list


text:
Q: In ruby, how do you mess with the back button? Redirect user somewhere if they click back button? In otherform.erb I have
<%= link_to "Back", redirect "/" %>

But then I can't even view the front page when I start my server, even without pressing anything. It gives me syntax error, unexpected keyword_end, expecting ')' ...k_to "Back", do erb :index end ).to_s); @_out_buf.concat "... ... ^
So what's the proper way to control the back button in ruby, in the erb documents?

A: Just use
redirect_to :back
# is a shorthand for:
redirect_to request.env["HTTP_REFERER"]

Going back to root it's a "homepage" link, not a "back" link.


text:
Q: Why is the proxy not changed in Selenium Python? I wrote a python code and in this python code I feel that my proxy does not change
My code:
from selenium import webdriver
from time import sleep

#input proxy list
print("=======================================")
proxy = input("*\n-- please enter PROXY LIST: ")
print("*\n=======================================\n\n\n\n")

#open file list proxy
file_proxy = open(proxy,"r")

#loop proxy
for proxy in file_proxy:

    #set proxy
    PROXY = "<" + proxy + ">"
    webdriver.DesiredCapabilities.CHROME['proxy'] = {
        "httpProxy": PROXY,
        "ftpProxy": PROXY,
        "sslProxy": PROXY,
        "proxyType": "MANUAL",
    }

    #sleep
    sleep(20)

example file list proxy:
91.98.80.2:8080
183.221.221.149:9091
103.134.177.182:8888
103.110.162.210:80
103.151.226.46:8080
165.154.235.178:80
120.196.186.248:9091

I am using Selenium library
And of course I know my code has an error, but I can't find it :/
Thank you for helping me

A: DesiredCapabilities is deprecated. You can replace your code under #set proxy with:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy)
chrome = webdriver.Chrome(chrome_options=chrome_options)


text:
Q: How to use node8 in dialogflow inline fullfillment editor? I want to use node 8 to use async/await in dialogflow fullfillment using the inline editor (!).
I added "engines": { "node": "8" } in package.json (and used high enough versions of firebase-admin/firebase-functions there) however during deployment async still gives a syntax error and the firebase funtions dashboard still says node 6.
Does anybody have an idea how to solve this?


text:
Q: HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace I'm a beginner in WCF, but trying to improve my experience. And on the first step I faced the problem. I created the simplest WCF service. The listing of code: (all the code in one file)
using System;
using System.ServiceModel;

namespace EssentialWCF
{
    [ServiceContract]
    public interface IStockService
    {
        [OperationContract]
        double GetPrice(string ticker);
    }

    public class StockService : IStockService
    {
        public double GetPrice(string ticker)
        {
            return 94.85;
        }
    }

    class Service
    {
        static void Main(string[] args)
        {
            ServiceHost serviceHost = new ServiceHost(typeof(StockService),
                                                        new Uri("http://localhost:8000/HelloWCF"));

            serviceHost.AddServiceEndpoint(typeof(IStockService), new BasicHttpBinding());
            serviceHost.Open();

            Console.WriteLine("To continue press ENTER");

            serviceHost.Close();
        }
    }
}

That would be the service that give me a number via console. But debug give me the exception: (instead of number :) )

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace.

Have you ever faced the same situation? I will be glad to see every advice.

A: In Windows Vista and later the HTTP WCF service stuff would cause the exception you mentioned because a restricted account does not have right for that. That is the reason why it worked when you ran it as administrator.
Every sensible developer must use a RESTRICTED account rather than as an Administrator, yet many people go the wrong way and that is precisely why there are so many applications out there that DEMAND admin permissions when they are not really required. Working the lazy way results in lazy solutions. I hope you still work in a restricted account (my congratulations).
There is a tool out there (from 2008 or so) called NamespaceManagerTool if I remember correctly that is supposed to grant the restricted user permissions on these service URLs that you define for WCF. I haven't used that though...

A: Right Click on Visual Studio > Run as Administrator > Open your project and run the service.
This is a privilege related issue.

A: Unfortunately the link in the exception text, http://go.microsoft.com/fwlink/?LinkId=70353, is broken. However, it used to lead to http://msdn.microsoft.com/en-us/library/ms733768.aspx which explains how to set the permissions.
It basically informs you to use the following command:
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
You can get more help on the details using the help of netsh
For example: netsh http add ?
Gives help on the http add command.

A: I closed Visual studio IDE and reopened it by right clicking on the Visual Studio icon and saying "Run as Administrator", Then when I ran the host , It worked!!!

A: The simple thing you need to do is to close your Visual Studio environment and open it again by using 'Run as administrator'. It should now run successfully.

A: You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...

A: You must give permission to your app for listening http requests. You can use this command in cmd for this purpose (open cmd Run As Administrator mode)
netsh http add urlacl url=http://+:8000/ user=Everyone

If your app is working other port, for example 9095, this command must be like as below:
netsh http add urlacl url=http://+:9095/ user=Everyone

And re-run your app, it should work.
This way working for me.

A: Your sample code won't work as shown because you forgot to include a Console.ReadLine() before the serviceHost.Close() line. That means the host is opened and then immediately closed.
Other than that, it seems you have a permission problem on your machine. Ensure you are logged-in as an administrator account on your machine. If you are an administrator then it may be that you don't have the World Wide Web Publishing Service (W3SVC) running to handle HTTP requests.

A: While I was able to solve this problem in one computer following the other users solutions, the command netsh didn't solve the issue in one of my machines and even though the current user had administrator rights I was still getting the "HTTP could not register URL.... Your process does not have access rights to this namespace". So I'm sharing my solution in case you still don't get it to work with the other solutions too.
After also trying to give write permissions to the user in the physical directory of my website and getting no success, I finally decided trying to change IIS settings.
As the images below show, I configured the Physical Path Credentials of my website to connect as an specifc user, which was an admin account with DOMAIN\username and password, and this was enough to make the error disapear.

A: Close iis express and all the browsers (if the url was opened in any of the browser). Also open the visual studio IDE in admin mode. This has resolved my issue.

A: I was getting the same error in a for a domain using a different port (2130). The process was a service. I was able to fix the issue by changin the user running the service from NetworkSystem to Local System Account.

A: Another thing I might add: If this just for local testing purposes you could try to change the port from 8000 to something else such as 8080 and not get this error. That worked for me at least.


text:
Q: Convergent series and its sum Can anyone solve for the alternating sum of $$\sum_{n=1}^\infty \frac{(-1)^{n+1}}{\sqrt{1+n^2}
}=\frac{1}{\sqrt{2}}-\frac{1}{\sqrt{5}}+\frac{1}{\sqrt{10}}\ ...$$ I know that the sum is convergent by the leibniz test but i cannot seem to find it.

A: Since $\mathcal{L}^{-1}\left(\frac{1}{\sqrt{x^2+1}}\right)(s) = J_0(s)$ (a Bessel function of the first kind) the given series equals
$$\begin{eqnarray*} \int_{0}^{+\infty}\frac{J_0(s)}{e^s+1}\,ds &=& \sum_{n\geq 0}\frac{(-1)^n}{4^n n!^2}\int_{0}^{+\infty}\frac{s^{2n}}{e^s+1}\,ds\\&=&\color{blue}{\log 2+\sum_{n\geq 1}\left(-\frac{1}{16}\right)^n\binom{2n}{n} (4^n-1)\,\zeta(2n+1)}\\&=&\log 2+\frac{5\sqrt{2}-4\sqrt{5}}{10}+\sum_{n\geq 1}\left(-\frac{1}{16}\right)^n\binom{2n}{n} (4^n-1)\,\left(\zeta(2n+1)-1\right)\end{eqnarray*}$$
where the leftmost integral is simple to approximate numerically by exploiting $J_0(x)\approx \sqrt{\frac{2}{\pi x}}\cos\left(x-\frac{\pi}{4}\right)$ for $|x|\gg 1$ or
$$ \int_{0}^{+\infty}\frac{J_0(s)}{e^s+1}\,ds \approx \int_{0}^{+\infty}\frac{J_0(s)}{s+2}\,ds = \frac{\pi}{2}\left(H_0(2)-Y_0(2)\right) \approx 0.44.$$

A: Note that:
$$\sum_{n=0}^\infty\frac{(-1)^n}{\sqrt{1+n^2}}=\sum_{n=0}^\infty\frac1{(2n+i)^{1/2}(2n-i)^{1/2}}-\frac1{((2n+1)+i)^{1/2}((2n+1)-i)^{1/2}}$$
Thus, a closed form may be found in terms of the Shintani zeta function, not that I'd find this especially helpful.


text:
Q: Why do some people in The Sarah Jane Adventures not know about aliens? Of course in the Doctor Who Universe the people of the world became aware of the existence of aliens due to the repeated failed invasions.
But I noticed while watching The Sarah Jane Adventures was that every new character they introduce in the series is very surprised to hear about aliens existing, like they have never heard anything about any previous invasions (except the invasions that occurred in this spin-off series).
How do they not remember these past invasions?

A: I can provide 1 explanation which relates to the Slithereen, having just rewatched the episode.
At the end, Rose's friend shows the  Doctor a newspaper headline reading "Alien Hoax".  People are much happier NOT having their horizons expanded.

A: They are so self-involved as to not notice the aliens. Head down on their phones, gabbing with their friends, etc etc. This was the explanation given for Donna's obliviousness.


text:
Q: Prevent TinyMCE prompting onbeforeunload with save from custom button I couldn't find any post regarding this issue, so this was my last way out. I'd like to somehow tell TinyMCE that I've taken care of the saving process (reset the isdirty I guess), but to keep checking for further changes without reloading the page. Ofcourse, if I do a location.reload it works, but that takes a bit of elegance out of it.
I have a custom save-button with the following method:
$("#saveAbout").click(function(){

tinymce.activeEditor.getBody().setAttribute('contenteditable', false);
$("#outerWrapper").animate({opacity:0.3});
$("#bigloader").fadeIn();

var currentData = tinyMCE.activeEditor.getContent();
var currentLanguage = $("#currentLang").val();

$.post("src/actions/pup_about.php", { text: currentData, lang: currentLanguage })
.done(function(data) {
$("#bigloader").fadeOut();
$("#outerWrapper").animate({opacity:1});

// What to do here?

});

});

This basically gets the contents and saves it through a PHP file. A neat ajax loader shows up and fades out during the process. The #outerWrapper div is a div around the TinyMCE in order to fade it slightly out during the save process.
Is there any smart way to tell TinyMCE that saving is done, but to keep looking for further changes?

A: You could issue in your function
tinymce.get('your_editor_id').save();

this should then take care of setting everything else.


text:
Q: React Native RCTFatal + 448 crash when testing via iOS TestFlight I have released my React Native App on IOS TestFlight for few weeks, everything looks good except the App will crash sometimes (Launch screen will show up about 1 sec, then App crashes). And once the crash starts, reopen the App will crash it again.
I looked up my crashes log in Xcode, the error is RCTFatal + 448 (RCTAssert.m:132) caused by main + 88 (main.m:14)See screenshot.
I'm certain the App is in Release mode; I can't replicate the crash on Simulator; I installed Bugsnag, No error was reported; I have the componentDidCatch Error Boundary in my index.js, No error was caught, so I guess the error in not from my JavaScript code?
Has anyone experienced the similar issue and figured it out? Here's my crash log and package.json in case it helps
Date/Time:           2019-03-11 19:39:06.1522 +1000
Launch Time:         2019-03-11 19:39:05.6004 +1000
OS Version:          iPhone OS 12.1.4 (16D57)
Baseband Version:    3.31.00
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                  0x211811ea4 __exceptionPreprocess + 228 (NSException.m:172)
1   libobjc.A.dylib                 0x2109e1a50 objc_exception_throw + 56 (objc-exception.mm:557)
2   App                             0x104b475f8 RCTFatal + 448 (RCTAssert.m:132)
3   App                             0x104ba2da0 facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 712 (RCTNativeModule.mm:116)
4   App                             0x104ba292c invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dy... + 88 (RCTNativeModule.mm:71)
5   libdispatch.dylib               0x2112496c8 _dispatch_call_block_and_release + 24 (init.c:1372)
6   libdispatch.dylib               0x21124a484 _dispatch_client_callout + 16 (object.m:511)
7   libdispatch.dylib               0x211229b34 _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 1012 (inline_internal.h:2441)
8   CoreFoundation                  0x2117a1ce4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12 (CFRunLoop.c:1813)
9   CoreFoundation                  0x21179cbac __CFRunLoopRun + 1964 (CFRunLoop.c:3113)
10  CoreFoundation                  0x21179c0e0 CFRunLoopRunSpecific + 436 (CFRunLoop.c:3247)
11  GraphicsServices                0x213a15584 GSEventRunModal + 100 (GSEvent.c:2245)
12  UIKitCore                       0x23eb30c00 UIApplicationMain + 212 (UIApplication.m:4347)
13  App                             0x104aed3b4 main + 88 (main.m:14)
14  libdyld.dylib                   0x21125abb4 start + 4

Thread 0 name:
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x00000002113a7104 __pthread_kill + 8
1   libsystem_pthread.dylib         0x0000000211427948 pthread_kill$VARIANT$armv81 + 296 (pthread.c:1492)
2   libsystem_c.dylib               0x00000002112fed78 abort + 140 (abort.c:94)
3   libc++abi.dylib                 0x00000002109c8f78 abort_message + 132 (abort_message.cpp:75)
4   libc++abi.dylib                 0x00000002109c9120 default_terminate_handler() + 304 (cxa_default_handlers.cpp:68)
5   libobjc.A.dylib                 0x00000002109e1e58 _objc_terminate() + 124 (objc-exception.mm:693)
6   App                             0x0000000104d37470 CPPExceptionTerminate() + 520 (BSG_KSCrashSentry_CPPException.mm:193)
7   libc++abi.dylib                 0x00000002109d50fc std::__terminate(void (*)()) + 16 (cxa_handlers.cpp:66)
8   libc++abi.dylib                 0x00000002109d5188 std::terminate() + 84 (cxa_handlers.cpp:97)
9   libdispatch.dylib               0x000000021124a498 _dispatch_client_callout + 36 (object.m:514)
10  libdispatch.dylib               0x0000000211229b34 _dispatch_main_queue_callback_4CF$VARIANT$armv81 + 1012 (inline_internal.h:2441)
11  CoreFoundation                  0x00000002117a1ce4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12 (CFRunLoop.c:1813)
12  CoreFoundation                  0x000000021179cbac __CFRunLoopRun + 1964 (CFRunLoop.c:3113)
13  CoreFoundation                  0x000000021179c0e0 CFRunLoopRunSpecific + 436 (CFRunLoop.c:3247)
14  GraphicsServices                0x0000000213a15584 GSEventRunModal + 100 (GSEvent.c:2245)
15  UIKitCore                       0x000000023eb30c00 UIApplicationMain + 212 (UIApplication.m:4347)
16  App                             0x0000000104aed3b4 main + 88 (main.m:14)
17  libdyld.dylib                   0x000000021125abb4 start + 4

  "dependencies": {
    "@turf/boolean-point-in-polygon": "^6.0.1",
    "@turf/helpers": "^6.1.4",
    "@types/react-navigation": "^2.0.24",
    "amazon-cognito-identity-js": "^3.0.3",
    "apollo-boost": "^0.1.16",
    "apollo-cache-inmemory": "^1.3.5",
    "apollo-cache-persist": "^0.1.1",
    "apollo-link": "^1.2.3",
    "apollo-link-http-common": "^0.2.5",
    "apollo-link-state": "^0.4.2",
    "aws-amplify": "^1.1.17",
    "aws-amplify-react-native": "^2.0.5",
    "aws-appsync": "^1.3.4",
    "aws-appsync-react": "^1.1.4",
    "axios": "^0.18.0",
    "buffer": "^5.2.1",
    "bugsnag-react-native": "^2.15.0",
    "date-fns": "^1.29.0",
    "graphql": "^14.0.2",
    "lodash": "^4.17.11",
    "react": "16.5.0",
    "react-apollo": "^2.2.4",
    "react-native": "0.57.0",
    "react-native-camera": "^1.3.1",
    "react-native-device-info": "^0.24.3",
    "react-native-dotenv": "^0.2.0",
    "react-native-fbsdk": "^0.8.0",
    "react-native-google-signin": "^1.0.2",
    "react-native-heic-converter": "^1.2.0",
    "react-native-maps": "^0.22.0",
    "react-native-open-settings": "^1.0.1",
    "react-native-push-notification": "^3.1.2",
    "react-native-quick-actions": "^0.3.7",
    "react-native-splash-screen": "^3.2.0",
    "react-native-vector-icons": "^6.1.0",
    "react-navigation": "^2.17.0",
    "rn-fetch-blob": "^0.10.13",
    "subscriptions-transport-ws": "^0.9.15",
    "tslint": "^5.11.0",
    "uuid": "^3.3.2"
  },

A: It seems odd that Bugsnag is not reporting the error when the app crashes so I suspect Bugsnag may be misconfigured.
Have you followed the instructions here to ensure that native crashes are captured?
https://docs.bugsnag.com/platforms/react-native/enhanced-native-integration/
If you reach out to us directly at Bugsnag Support we can take a closer look.


text:
Q: Two language site in wordpress what i can do I want to create 2 language site in word press. I am pretty new in word press. so what can i do. I will have 2 different theme for each language or do something else. The English is for left to right while Arabic is for right to left. So what can i do. Please help me.

A: You want to look into the WPML plugin. Also, any time you emit a string from your own PHP code, you'll want to use the PHP gettext() method, which makes the string localizeable and will allow you to localize it using WPML.
You may also want to modify your WordPress theme to emit the appropriate dir tag depending on the language.


text:
Q: Как делать, чтобы с помощью JRadiobutton вывести тексе вопрос такой. Есть название несколько песен. Надо делать так, что если выбрал первую песню и запустил то вывел текст какой-то песни.
В этом деле еще новичок и не знаю как делать. Я вставлю текст и программа выводит этот текст для всех песен, а надо, чтобы для отдельных песен был отдельный текст.
Прошу не сказать "Да что тут сложного все просто и т.д.". Я только вчера начал изучать GUI.
Ладно вот код։
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Grafika extends JFrame {
    JButton button = new JButton("Запустить");
    JTextField text = new JTextField("Выберите песню");
    JLabel input = new JLabel("Все песни");
    JRadioButton radio1 = new JRadioButton("Песня 1");
    JRadioButton radio2 = new JRadioButton("Песня 2");
    JRadioButton radio3 = new JRadioButton("Песня 3");
    JRadioButton radio4 = new JRadioButton("Песня 4");
    JRadioButton radio5 = new JRadioButton("Песня 5");
    JRadioButton radio6 = new JRadioButton("Песня 6");
    JRadioButton radio7 = new JRadioButton("Песня 7");

    public Grafika(){
        super("Lyrics");
        this.setBounds(200, 200, 450, 500);
        this.setDefaultCloseOperation(Grafika.EXIT_ON_CLOSE);
    Container container = this.getContentPane();
    container.setLayout(new GridLayout(5,5, 7, 7 ));

    container.add(input);
    container.add(text);
    ButtonGroup group = new ButtonGroup();
    group.add(radio1);
    group.add(radio2);
    group.add(radio3);
    group.add(radio4);
    group.add(radio5);
    group.add(radio6);
    group.add(radio7);
    container.add(radio1);
    radio1.setSelected(true);
    container.add(radio2);
    container.add(radio3);
    container.add(radio4);
    container.add(radio5);
    container.add(radio6);
    container.add(radio7);
    text.setEditable(false);

    button.addActionListener(new ButtonEventListener());
    container.add(button);
    }

    class ButtonEventListener implements  ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "Текст какой-то песни", "Текст",
        JOptionPane.PLAIN_MESSAGE);
        }

A: Создайте мапу (радио-кнопка, текст). Занесите туда все кнопки (можно ограничиться номерами).
В ButtonEventListener при нажатии на кнопку проверяйте какая радио-точка выбрана и берите из мапы текст для неё и показывайте.


text:
Q: How to unit test a function that has a condition for the state of something? I'm trying to write a unit test for a function that has a condition for wifi state. When the wifi state is disconnected, the function returns with false, but I want to simulate a scenario when the wifi state is connected. How do I go about it? Should I make a setter for the state variable? Isn't that a bad approach?
The function I want to test:
public boolean performSomething() {
    if (WIFI_STATE != "connected") {
        return false;
    }else{
          ....
    }
}

I want to test the else part of the function above, but as you may have guessed, the function executes the if condition, and returns false because WIFI_STATE is "disconnected"

A: Without seeing any of your code, make sure your class uses a WifiState constructor parameter or injection (or something similar).  In your test you can then provide a mock for this object and set the state accordingly to your testing needs.

A: Two approaches that I can think of:
1: Define a sensor's state capturing class say WifiStatus, which your production code initializes automatically through a static initializer.
For testing, you can load a dummy WifiStatus class though a test initializer or change the value of WifiStatus through instrumentation.
2: Use WifiStatus as a interface and then mock it for dependency injection. This approach is more common.
public interface WifiStatus{
    boolean isConnected();//
}

public class Performer{
    WifiStatus wifiStatusProvider;
    public Performer(WifiStatus stateProvider){
        this.wifiStatusProvider = stateProvider;
    }

    public boolean performSomething() {
        //if (WIFI_STATE != "connected") {
        if (wifiStatusProvider.isConnected() != true) {
            return false;
        }else{
            ....
        }
    }
}

For test class, you use as follows:
public class PerformerTest{
    @Test
    public void verifyPerformSomething(){
        WifiStatus dummyWifiStatus = mock(WifiStatus.class);
        doReturn(true).when(dummyWifiStatus).isConnected();

        new Performer(dummyWifiStatus).performSomething();
    }
}

A: Assuming you are talking about "Local Unit Tests" and not "Instrumented Unit Tests", you can use Robolectric:  http://robolectric.org
http://robolectric.org/javadoc/3.0/org/robolectric/shadows/ShadowWifiManager.html
https://github.com/robolectric/robolectric/blob/master/robolectric/src/test/java/org/robolectric/shadows/ShadowWifiManagerTest.java
Local Unit Tests:
https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html
Instrumented Unit Tests:
https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html

A: Well, for testing, you must be sure for your input how your output looks like because you need to compare them. Make the boolean value of wifi state is injected from outside, so you can mock it how you like. For example:
public boolean method(boolean wifiState){
   return !wifiState;
}

So now you can be sure that if your parameter is false you will got true and vice versa so you can mock that param and make your tests.

A: Chiming in with a code-based answer based on john16384's answer. You mention that the state is set with other functions within the same class, assuming those methods are public I propose something like this (assuming WifiChecker is your class):
private WifiChecker wifiChecker;

@Before public void setUp() {
    wifiChecker = new WifiChecker();
}

@Test public void testWifiConnected() {
    wifiChecker.setConnected()
    assertTrue(wifiChecker.performSomething());
}

@Test public void testWifiDisconnected() {
    wifiChecker.setDisconnected()
    assertFalse(wifiChecker.performSomething());
}


text:
Q: React initial state delay I have a React project and I am fetching data from firebase directly on the client side.
For the components that are using an initial state (which is usually set from firestore data), there is like 1 second delay on the component until the data is visible.
For example, I have a paragraph "Welcome {username}". Username is being set in the useEffect by calling a function that fetches data from firestore. At first it appears blank and after 1 second, let's say, the username is visible.
Is there anything I can do to fix this? I know it is due to the setState, but I am wondering if there is any fix.

A: I think that what you are looking for is not a fix, but a way to display things once they've been loaded.
What I would suggest is a conditional display.
Something like :
  const [username, setUsername] = useState(null);

  useEffect(() => {
    yourMethodThatSetUsername();
  }, [])

  return (
    {
      username ? <YourComponent /> : null
    }
  )

A: Usually you set a state in the component from which you are calling useEffect, like this:
[loading, setLoading] = useState(true);
You can then  conditionally render your component like this:
loading ? //some progress component
: Welcome ${username};


text:
Q: What can be the issue for the following error: invalid character '-' after top-level value? I am using the golang library go-jmespath to query a json file. My code looks like the following:
package main

import (
    "encoding/json"
    "log"

    "github.com/jmespath/go-jmespath"
)

func main() {
    var jsonBlob = []byte(`[
    {
        "oeeId": 3162396,
        "oeeDate": "2019-03-06T00:00:00",
        "oee": 21.2
    }]`)

    var d interface{}

    err := json.Unmarshal(jsonBlob, &d)
    if err != nil {
        log.Printf("1: %s", err)
    }

    res, err := jmespath.Search("{ labels: ['example'], datasets: [{label: 'Verfügbarkeit', data: [?oeeDate == `2019-03-06T00:00:00`].oee}]}", d)
    if err != nil {
        log.Printf("2: %s", err)
    }
    log.Println(res)
}

Here is also a link to an example in the Playground.
When I execute this code I get the following error:
invalid character '-' after top-level value

I am wondering what's my issue with this code since this example works with other Jmespath implementations like the javascript jmespath.js library.
The error seems to be in the query rather than the input data. Can anybody help me on this one?

A: Replacing the backticks in the search string with single quote removes the error.
Use this instead: "{ labels: ['example'], datasets: [{label: 'Verfügbarkeit', data: [?oeeDate == '2019-03-06T00:00:00'].oee}]}".
No more error.


text:
Q: SQL "group by" algorithm in object-c? I have array with title, author.
------------------------
title      author
------------------------
A        a
B        a
C        b
D        c
E        c
F        d
G        d
------------------------

if I select * group by author
-----------------
a        A, B
b        C
c        D, E
d        F,G

How to implement by object-C for "GROUP BY" of SQL?

A: Create a class Book
@interface Book : NSObject
@property(strong)NSString *title;
@property(strong)NSString *author;
@end

Now implement as :
//Create objects, title and author
Book *b1=[Book new];
[b1 setTitle:@"A"];[b1 setAuthor:@"a"];

Book *b2=[Book new];
[b2 setTitle:@"B"];[b2 setAuthor:@"a"];

Book *b3=[Book new];
[b3 setTitle:@"C"];[b3 setAuthor:@"b"];

Book *b4=[Book new];
[b4 setTitle:@"D"];[b4 setAuthor:@"c"];

Book *b5=[Book new];
[b5 setTitle:@"E"];[b5 setAuthor:@"c"];

Book *b6=[Book new];
[b6 setTitle:@"F"];[b6 setAuthor:@"d"];

Book *b7=[Book new];
[b7 setTitle:@"G"];[b7 setAuthor:@"d"];

NSArray *books=@[b1,b2,b3,b4,b5,b6,b7];

//your manipulation starts here
NSMutableArray *groupByAuthors=[NSMutableArray new];
for (Book *book in books) {
    if (![groupByAuthors containsObject:book.author]) {
        [groupByAuthors addObject:book.author];
    }
}

for (NSString *author in groupByAuthors) {
    NSMutableArray *titles=[NSMutableArray new];
    for (Book *book in books) {
        if ([book.author isEqualToString:author]) {
            [titles addObject:book.title];
        }
    }
    NSLog(@"Author: %@, Books: %@",author,titles);
}

A: Here is a simple algorithm to do what you are asking and loops only once through your data set.
int main (int argc, const char * argv[])
{
    @autoreleasepool {

        NSArray *booksAndTitles = @[
            @[@"Book A1", @"Author A"],
            @[@"Book B" , @"Author B"],
            @[@"Book C" , @"Author C"],
            @[@"Book A2", @"Author A"],
            @[@"Book A3", @"Author A"],
            @[@"Book C" , @"Author C"],
            @[@"Book B" , @"Author B"]
        ];

        NSMutableDictionary *titlesByAuthor = [NSMutableDictionary dictionary];

        for (NSArray *pair in booksAndTitles) {

            NSString *title  = pair[0];
            NSString *author = pair[1];

            NSMutableArray *titles = titlesByAuthor[author];
            if (titles == nil) {
                titles = [NSMutableArray array];
                titlesByAuthor[author] = titles;
            }

            [titles addObject:title];
        }

        NSLog(@"%@",titlesByAuthor);
    }
    return 0;
}

The output is the following:
 {
    "Author A" =     (
        "Book A1",
        "Book A2",
        "Book A3"
    );
    "Author B" =     (
        "Book B",
        "Book B"
    );
    "Author C" =     (
        "Book C",
        "Book C"
    );
}


text:
Q: I want to use Widget.Button.Transparent style with my button
error: Error: Resource is not public. (at 'style' with value '@android:style/Widget.Button.Transparent').,style="@android:style/Widget.Button.Transparent"

A: I have bad news.  The Android API is white-listed.  Only object that are listed in $ANDROID_SRC/frameworks/base/api/NN.txt are visible to client applications running on API level NN.
While the three other button styles found in styles.xml are all exposed, Widget_Button_Transparent is not.  You can't use it.


text:
Q: Delphi Firemonkey TLayout mousedown not firing I am creating a button array in Firemonkey and each of the buttons are created by loading a style from a resource.
FButtons[r,c] := TLayout( TStyleManager.LoadFromResource(HInstance, BUTTON_STYLE, RT_RCDATA) );
FButtons[r,c].Parent := Self;
FButtons[r,c].Stored := false;
FButtons[r,c].HitTest := true;
FButtons[r,c].OnMouseDown := OnButtonMouseDown;

The contents of the resource is just copied from a TButton (dark style).
The problem I am having is that the button does not animate a pressed state. So I am trying to capture the OnMouseDown event to fire the "IsPressed" animation but the OnMouseDown is never triggered.
Any ideas why OnMouseDown is not happening?
Thanks in advance.
Martin

A: If you are using custom FM style, then ensure HitTest property of style's elements (containers probably) is set to False.
If HitTest is True the style itself will "swallow" the event.
You may find more information here:

*

*"Beware the HitTest"

*"Glyphs on buttons"

A: Dont know why but setting
Locked := true

fixed my problem.


text:
Q: How to justify text on an RDLC report on C# I'm trying to justify the text inside a RLDC report text-box in C#.
I tried this solution but couldn't make it work.
This is what I've got inside the expression:

="
La empresa " +First(Fields!name.Value, "CompanyCertificate")+ " identificada con el Nit. " +First(Fields!documentNumber.Value, "CompanyCertificate")+ " se encuentra afiliada en la Caja de Compensación Familiar del Valle del Cauca - Comfamiliar Andi - Comfandi.
"

See screenshot
This is the PDF it generates, but the main text is left aligned, and I need it justified:
See pdf screenshot
Is that html code wrong? How could I make this work?


text:
Q: How to mock a deeply nested function with TypeScript and Jest I want to test my modules and mock axios external dependencies. The problem is that the methods I directly test do not (directly) import axios. It it rather "hidden" behind an intermediate call.
Like this, A and B are my custom modules: A calls B, B uses axios
So, A does not import axios, only B.
Since B is a very thin layer around axios, I do not want to test it directly. I would rather just test A, and have axios being mocked.
How to do this?
If instead of axios, I have a custom module C, does it make any difference?

A: Yes you can mock a module - see https://jestjs.io/docs/en/manual-mocks . To mock axios, just use jest.mock('axios'), then anything imported from 'axios' will be a mock (and you can configure it by standard Jest mock API). Just note that it will be mocked for the whole test case, so e.g. if you test a module that uses two other modules each using axios, you can't mock axios for only one of them.


text:
Q: How to rember $_POST var from previous ? if ($_SERVER['REQUEST_METHOD'] != 'POST'){

    echo    '<form method="post" action="">
                <select name="class_name">
                    <option value="class_id">name</option>
                </select>
                <input type="submit" value="Proceed">
            </form>';
}
else{
    $_SESSION['var_name'] = $_POST['class_name'];
    $sql = "SELECT (...) students.class_id = " . $_SESSION['var_name'];
    $que = mysqli_query($conn, $sql);

    echo    '

Last	Name	Add
';

                while ($row = mysqli_fetch_array($que)){ //<-HERE I GOT A ERROR
                    echo    '
' . $row['user_last'] . '	' . $row['user_name'] . '
                                    <form method="post" action="">
                                            <input type="hidden" name="usr_id" value = "' . $row['user_id'] . '"/>
                                            <input type="submit" name="button" value="+" />
                                        </form>

';
                }
    echo    '
';

    if (isset($_POST['button'])){
        //DOESEN'T MATTER
    }
}

Ok, so my problem is that after clicking on my button from the second  i got the error mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given on line I've commented above. I know that after clicking the value of _SESSION var is lost. My question is how to store this thing. I've tried session management but nothing.
I forgot to add, that I'm opening a session in included file.

A: Use Sessions, and make sure you have a
session_start();

on each page.


text:
Q: Picture syncing on Multiple Macs, iPhones, and iPad together so each device can update them all One of the owners of my company has put me to task to sync his pictures between the following devices together.
(2) iPhones
(2) iMacs
(1) Macbook Air
(1) iPad
Here is what is happening:

*

*He has a camera that can upload pictures into iPhoto in either (1) of his iMacs, or Macbook Air.

*He has (2) different iPhones. And here are how they are paired up
iPhone -> iMac Home
iPhone -> Macbook Air

*He has MobileMe syncing Calendar, Contacts, and Notes across all devices

*Currently we are using MobileMe web galleries to sync all photos, by having ME create each album and upload them to the MobileMe web gallery.
Now, the problem is he wants to just take pictures, and once he does that it syncs with all his devices, he'll even dock the iPad. Is there a better way to sync photos between all devices?

A: Will Dropbox work? It won't sync them to the mobile devices immediately but they'll be available. He'll have to do a manual sync to iTunes to push them down to the mobile devices to get them into the Photos app.

A: With iOS 5.0 and OS X 10.7 plus the latest iPhoto, you can do this using iCloud. iCloud is basically the next-gen MobileMe.


text:
Q: How do I get the Xorg folder so I edit my mouse? Okay so I'm new to Xubuntu and I'm trying to get rid of the mouse acceleration like windows has it but I've been told that I need to edit files in xorg first. But the folder is not there and I can't right-click and make it because of permissions. I've tried doing
sudo -X configure

but i get:
Fatal server error:
Server is already active for display 0
If this server is no longer running, remove /tmp/.X0-lock
and start again.

Is there anyway to get the folder back?

A: Just simply kill Xorg server for this session? :)
sudo xkill -a
to start Xorg server after configuring Your mouse acceleration:
sudo xinit.


text:
Q: Restart Script from Beginning if Failures encountered in Jmeter I have around 20 transactions in my jmeter script, I need to run a load test for 2000 Users.
I have added test checks and Assertions to validate if the transactions are passing
I want to introduce error handling , where the script start from the beginning if any of the assertions/transactions fail

A: I am not sure if I have understood your question correctly. If your aim is to stop the workflow for the current user and start from the beginning, then you could use until controller.
More information on this can be found here.


text:
Q: PyFMI FMU-module method get_variable_unit() on constants PyFMI FMU-module method get_variable_unit() does not work on constants.
It seems to me that the PyFMI method for FMU-mouldes get_variable_unit()  and _variable_description also handles constants and parameters.
I have made a package M that contains declaration of constants. Try to make it neat and declare both unit and description. When i try to get_model_variable_unit('model.variable') then I get the error message "No unit was found for the variable…". However it works as expected for get_model_variable_description().
It looks to me as a small bug.
I run JModelica 2.4 installed in the fall, i.e. the recent upgrade of PyFMI to 2.5 that came in December I do not use.

A: This is indeed a bug in JModelica.org - see https://trac.jmodelica.org/ticket/5729.


text:
Q: Visual Studio 2010 and XNA game studio crashes while debugging code Now, this is a problem I've been having for a while now. I've tried googling it, asking people I know, and have searched this site for ages, but have not been able to find a solution.
I am running XNA Game Studio 4.0 and Microsoft Visual Studio 2010. While trying some of the basic tutorials with XNA (Available on the Microsoft website), I encountered several errors:
First off, I had set up a basic Kernel32.dll console, to calculate and display FPS. For some odd reason, after a seemingly random amount of time had elapsed it started updating the FPS several times a second. As the program ran fine, I presumed it was an error with my code, and so removed it.
But, when I did this, the program just seemed to crash. The only code in the program so far is simple draw calls, basic movement, and the foundations of a rudimentary inventory system. There is no complex code happening. I have tried several things, including placing break points on every line of code and spending hours attempting to sort this out.
So, my question is: Is this an entirely random occurrence, or is it most likely a problem with my code? And more importantly, is there a way to prevent such a bug from happening?
Any help will be greatly appreciated.
Code:
http://pastebin.com/3sRiVnwe


text:
Q: Is it possible to only include a header once per project? On top of simpler syntax, Go claims that it largely achieves it's fast compilation speed by only importing dependencies once:

Go imports dependencies once for all files, so the import time doesn't
increase exponentially with project size.

Is it possible to accomplish the same thing with C++ if you are careful with your design?
Say adding all includes to a single include file (that uses pragma once) that is included in all files? Or would it slow it down a lot as any change to any header would recompile everything instead of incremental?
I'm using LLVM. Still architecting the project.

A: Usually a project consists of many .cpp files. A .cpp file with all it includes is a Translation Unit (TU). They are compiled separately and then linked into an executable or a dll.
Your solution would force every single TU despite however small its dependencies might be to include that huge header file. It will be included once, but once for every .cpp file in your project.
Most probably, it will make compilation slower. To let alone all the problems of such architecture - maintaining sanity of this codebase would be pain.
There is an insight in your question - probably what you want is precompiled headers. Carefully used in some cases they can shorten compilation time.

A: Yes it is possible to greatly reduce build time in C++ by carefully manage code structure.
One way to achieve that is to extensively use forward declarations.
There is a tool which helps to achieve that: Include What You Use.
To make this more effective you have to also prevent compiler to generate default implementations of constructors, destructors and assignment operators in header file. So declaring them in header and then default define them in respective cpp can help to keep some classes forward declared in header file.
Other way to have build time speed up is to extensively use dependency inversion. But this is general rule for any language.

Happily the C++20 is coming with modules support, which should make this stuff much much easier (no more header files).

A: Many compilers support "Precompiled Headers".  So, even if a given header is used in multiple Translation Units, the compiler will compile it only the first time and cache the result for use in subsequent units.  Check your compiler's documentation if this feature is supported and how to use it.


text:
Q: Sort List based on character count Example:
List<string> folders = new List<string>();
folders.Add("folder1/folder2/folder3/");
folders.Add("folder1/");
folders.Add("folder1/folder2/");

I want to sort this list based on character i.e '/'
so my output will be
folder1/
folder1/folder2/
folder1/folder2/folder3

A: LINQ:
folders = folders.OrderBy(f => f.Length).ToList(); // consider null strings

or List.Sort
folders.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

a safe approach if the list could contain null's:
folders = folders.OrderBy(f => f?.Length ?? int.MinValue).ToList();

If you actually want to sort by the folder-depth not string length:
folders = folders.OrderBy(f => f.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Length).ToList();

A: It's likely you actually want to sort by name:
folders = folders.OrderBy(f => f).ToList();

Or simply:
folders.Sort();

This will work correctly for cases like this:
folder1/
folder1/subfolder1
folder1/subfolder1/subsubfolder
folder2
folder2/subfolder2

Sorting by length alone will consider "folder1" and "folder2" equal.


text:
Q: Why are no CMB experiments able to measure the whole range of multipole moments? Have a look at the following diagram:

This shows measurements of the CMB by various experiments, with multipole moment $l$ on the x-axis and the temperature of the corresponding moment on the y-axis. (Please correct me if I have that wrong.)
Looking at the plot, I can see that WMAP's results extend to about $l=1000$, and they become poor as we go to higher values of $l$. Meanwhile, the other experiments can't measure the CMB at lower values of $l$ around $l < 500$. I'm guessing that a ground-based approach with a large collector is required to get the high resolutions needed to measure the power of the component at high values of $l$. Is this correct?
What I don't understand is, why can't the other experiments get measurements in the lower part of the plot?

A:
What I don't understand is, why can't the other experiments get measurements in the lower part of the plot?

Firstly, you are assuming that graph shows all the data from all the listed experiments.
Secondly, the full sky needs to be observed to obtain data for very small multipole moments.
As can be seen in the case of the Boomerang data, both of the above reasons apply.
The data do go down to multipole moments much lower than in the plot of the question, and only 1% of the sky was observed.
In the case of ACBAR, as the name Arcminute Cosmology Bolometer Array Receiver implies, the experiment was designed to obtain very high spacial resolution from small patches of the sky.  But again, the plot in the question does not show the full range of the ACBAR data, which is from about l=450 to l=2500.


text:
Q: Unification not providing me user password and username When I am using Instagram sharing then how can I get username and password from Instagram (current login user).
$app = new UEApp(self::APP_SECRET, self::APP_SECRET);
$user = new UEUser($this->currentUser->unification_userkey, $this->currentUser->unification_usersecret);
$con = $access_token."@instagram.com/?username=rajneesh49&password=test&@instagram.com";

Now I am using static password and username then its working fine but How can I get current username and password(required filed by unification engine)
username and password both are required fields by unification engine.
How can I get this password and username in php code for unification engine sharing.
Authentication only provide this information
Array
(
    [access_token] => 4544942713.7da612b.4de7a5a78fba2b27a60dc1749d
    [user] => Array
        (
            [id] => 45434542713
            [username] => rajneesh8469
            [profile_picture] => https://scontent.cdninstagram.com/t51.2885-19/s150x150/16229522_1877141895853233_7596497588304478208_a
.jpg
            [full_name] => Rajneesh
            [bio] => Testing website
            [website] => http://localhost:3000/
  ))

But only password is missing so how can I get current user password.

A: We could see that you can now specify optional parameters while you add a connection, with the updated version of SDK (https://github.com/unifiedinbox/ue-php-sdk).
The optional params for each connections are specified in documentation under 'Add connection' section https://developer.unificationengine.com/ In case of instagram, the optional params are "username" and "password".

A: This problem not related with any code or unification its only related with Security validation. I have fixed same issue in same sharing but I have fixed this problem by authentication please do below some changes as per application

*

*Create Instagram authentication

*Get username (only username authentication not providing password)

*Open User validation popup in exiting application (then show username and and asking to user please enter password)

*Please do not save user password in you database (its related with security)

*Then use same parameters for sharing

Only change this according to password:
$con = $access_token."@instagram.com/?username=".$username.'&password='.$password&@instagram.com";

please do this as per security social networking proving good security as per application(Instagram is good as per security) .


text: Q: Laravel multi tenancy creating first User in tenant database I am following this documentation Hyn/Multitenant for creating a new user in tenant database from main app but as if i changes the User Model to use TenantConnection it would produce error that tenancy database is not configured. What i would like to ask is if there is any other solution beside creating new Model. Any help would be appreciated.


text:
Q: Ehcache Default values I am using ehcache in my project and am facing some performance issue. Few question which exact answer I am not able to find on internet.

*

*If sizeOfPolicy is not defined in ehcache.xml file- Is there any default value of this.

*If writeToDisk is true and maxElementInDisk is not defined - Is there any limit on writing to disk then

A: Looking at the decompiled sources for Ehcache 2.6:

*

*The default sizeOfPolicy is maxDepth=1000 and maxDepthExceededBehavior="continue".

*The default value of maxElementsOnDisk is 0, which translates to no limit. Hope you have a lot of disk space! :)


text:
Q: Globally Available Azure App Architecture / Design? I am fairly new to Azure architecture and hope someone can point me in the right direction.
I have an app that is currently available only in the Southeast Asia region; All my Azure Services (App Service, Azure SQL, etc.) are in the Southeast Asia region.
If I were to make the app available to other regions (ex. US or Europe), how do I scale my current Azure Setup? Because if it still points to the same region, there might be issues with latency/data location? Will I need to create Resource Groups for each region and perform replication?
I am trying to search for reference architectures by Microsoft but am having a hard time finding, or maybe I just don't know the correct terminology for it.

A: If you check the Azure Reference Architecture page, there's a section for Web applications:
https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/
and inside of it, a template for high availability web apps:
https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/app-service-web-app/multi-region
In case Azure Front Door does not meet your requirements, take a look on Azure Traffic Manager.
Trafic Manager
https://learn.microsoft.com/en-us/azure/traffic-manager/
LB with Azure Front Door
https://learn.microsoft.com/en-us/azure/frontdoor/front-door-lb-with-azure-app-delivery-suite


text:
Q: How to extract the shape value of a placeholder Tensor in Tensorflow? I defined a x = tf.placeholder("float", shape=[None, 784]) for input data. Later on, I need to know the first value of the shape of x as batch size. And I extract the value by x.get_shape().as_list()[0] but I got None. Could you please tell me how should I extract it properly? Thanks a lot!
Edit:
I have used tf.get_shape() now but it cause another bug. In my code, I have defined a deconv funciton:
def deconv(X, W, b, output_shape):
    X += b
    return tf.nn.conv2d_transpose(X, W, output_shape, strides=[1, 1, 1, 1])

If I set the batch_size to a int in such way: batch_size = 50, the calling of the deconv functions works well as following:
W_conv2_T = tf.ones([5, 5, 32, 64])
pool1_tr = deconv(conv2_tr, W_conv2_T, tf.zeros([64]), [batch_size, 14, 14, 32])

The shape of conv2_tr is [50, 14, 14, 64]. And the resulting shape of pool1_tr is [50, 14, 14, 32]. But if I set batch_size = tf.get_shape(x)[0], shape of conv2_tr is [None, 14, 14, 64] and the resulting shape of pool1_tr becomes [None, None, None, None]. This bug is so strange. Could you please help me with this issue? Thanks in advance!

A: A value of None for the number of rows in your placeholder means that it can vary at runtime, so you must use tf.shape(x) to get the shape as a tf.Tensor. The following code should work:
batch_size = tf.shape(x)[0]


text:
Q: Using WFS Vector layers in OpenLayers? I have some code in loop:
var vector =   new ol.layer.Vector({
                                title: name,
                                style: styleFunction
                            });
                             function getFeatures(geoJson) {
                                // If response is valid
                                var format = new ol.format.GeoJSON({
                                    featureProjection: "EPSG:3857"
                                });
                                vector.setSource(
                                        new ol.source.Vector({
                                            format: new ol.format.GeoJSON(),
                                            features: format.readFeatures(geoJson),

                                        }));
                            }

                            $.ajax({
                                type: "GET",
                                url: urlAjax,
                                dataType: 'jsonp',
                                jsonpCallback: 'getJson',
                                success:getFeatures
                            });

                            overlays.push(vector)

After push vector to overlay array I add that array of vectors to map:
 var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Group({
                title: 'Base maps',
                layers: basemaps
            }),
            new ol.layer.Group({
                title: 'Overlays',
                layers: overlays
            })

        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([31.4, 48.9]),
            zoom: 6
        })
    });

And create switcher controls... And all vectors are reset sources last layer and only last layer visible in map, others don`t work...why?

A: I found a solution. I had problem because I used ajax. Requests was asynchronized and source created asynchronized too... now I use this code to get sources:
 var vector = new ol.layer.Vector({
                        title: bean.name,
                        style: styleFunction,
                        source:new ol.source.Vector({
                                format:new ol.format.GeoJSON({
                                    featureProjection: "EPSG:3857"}),
                                url:bean.urlAjax
                        })


text:
Q: What would prevent ESRI JSAPI AMD modules from being cached? I am using AMD style in the ESRI Javascript API (along with the esri application boilerplate: https://github.com/Esri/application-boilerplate-js).
For some reason, the AMD modules from the js.arcgis.com CDN do not appear to be cached and I've been unable to determine why.  Local AMD modules are caching fine:

Request headers:

Remote Address:54.230.50.98:80
Request URL:http://js.arcgis.com/3.10/js/esri/dijit/InfoView.js
Request Method:GET
Status Code:200 OK
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:rclg0=en; __unam=f220af1-14499213906-3dc5afe-11; esri_auth=[removed by author]
Host:js.arcgis.com
Referer: [removed by author]
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36

I would suspect this is from the Cache-Control: max-age=0 header, but I have no idea what would be setting that and why.

A: *******Solution Below is Deprecated******
Use the HTML5 App Cache. To your HTML element add the manifest attribute like this
<html manifest="offline.appcache">

Then in the offline.appcache file list the resources you would like to cache. Updating the appcache file will force the browser to make the http request for the resource.
Fore more details see:
https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_application_cache


text:
Q: Handling a space in a get parameter I am using a command like
 $page = file_get_contents($url);

where
$url = "http://www.site.com/search/index.cfm?tab=names&workername=firstname lastname";

When the url is typed directly in the browser chrome adds a %20 in between firstname and lastname and the website handles things properly.
However when I use $url with a space, file_get_contents grabs only results that match the firstname and isn't aware that workername = "firstname lastname"
When I explicitly add "%20" in between it returns NULL...
What's the work around?
Thanks guys!

A: A few problems:

*

*I hope this is just because you quick-typed it here, but you need to have the string in single quotes.

*There is no query string for the URL because you never start it with the ?, so no, neither of those variables will exist in $_GET.

*You do have to redefine spaces as %20 for URLs.

$url = 'http://www.site.com/search/?tab=names&workername=firstname%20lastname';
       ^                           ^                              ^^^        ^

Edit:
It is possible that the website you're trying to query is ignoring them as GET variables. Have you tried adding this code to explicitly say it is a GET request?
$options = array(
  'http' => array('method' => "GET", 'header' => "Accept-language: en\r\n")
);
$context = stream_context_create($options);
file_get_contents($url, false, $context);

A: You need to urlencode your text:
$fixed= urlencode($workername);
$url = 'http://www.example.com/search/?tab=names&workername='.$fixed;


text:
Q: jqgrid colnames (href) links in the header Please tell me how you can make a column name in jqgrid working reference.
jQuery(document).ready(function(){
    jQuery("#table").jqGrid({
            url: 'test.php',
        imgpath: 'css/flick/images',
            datatype: 'json',
        height: 'auto',
        width: 1050,
        sortname: 'id',
            sortorder: "asc",
            mtype: 'POST',
            colNames: ['id', 'INDEX LINK', 'notes'],
            colModel: [{name:'id', index:'id', width:320, align:'left', sortable:false, search:false},
                        {name:'data', index:'data', width:320, align:'left', sortable:false, search:false},
                        {name:'notes', index:'notes', width:320, align:'left', sortable:false, search:false}],
        rowNum: 50,
        viewrecords: false,
        shrinkToFit: false,
        hidegrid: false,
        loadonce: true
    });
});

The tooltip shows that the reference is to move on but it does not come out – not active

A: Not sure if this is the right solution, but this works,
jQuery(document).ready(function() {
    $("#th_id").click(function() {
      window.open('http://www.google.com');
    });
});

Here is a Fiddle. Hope this helps.


text:
Q: Unable to boot ubuntu in virtual box after "dd" command usage I was trying to copy a cross-compile of uboot .img to the sdcard file attached in the ubuntu(running on virtual-box under windows 10 host) but ended leaving the working ubuntu into some undefined state which I want to recover from. In the ubuntu I could see /dev/sda1 that was created using the cmd
createrawvmdk -filename"D:\Virtual_Machines_Hard_Drive_Area\image_linux\sdcard_attachment_file\sdcard.vmdk" -rawdisk "\\.\PHYSICALDRIVE1"

correctly mapping to the 8GB sdcard as attached to laptop. But the command
sudo dd if=sdcard.img of=/dev/sda1 bs=2048

corrupted my working copy of ubuntu that its not booting with an error of unknown file system.
I have lots of dev tools configured in the version of Linux. Please help me to recover the same if possible.

A: Usually, sda1 is the first partition on your first hard-disk.
So, you have overwritten the initial sectors of that partition with the img image.
If you are using uefi and you have the efi system on sda1,  you can recover by booting with a live-cd and reinstall grub.
But if you are using the legacy boot inside virtualbox and sda1 is the partition with your linux... there is no way to recover the system.


text:
Q: Python writing to file errors expected string/buffer I have a code which will replace specific text from keywords iteratively,
Problem:When i provide a file as input i get error
Coding:(works good when text is provided within code)
import re, itertools
car = ['skoda', 'audi', 'benz']
text = """
I have a car="mycar"
My friend has a vehicle="myvehicle"
       My uncle have a car="mycar"
Second verse same as the first
"""
it = itertools.cycle(car)
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)
print newtext

Coding: when file as input
import re, itertools
car = ['skoda', 'audi', 'benz']

with open('ckili.txt','r') as text:
    text1=text.readlines()
    it = itertools.cycle(keywords2)
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text1)

with open('ckili.txt','w') as f:
    f.write(newtext)

I get error as:
File "C:\Python27\replmay.py", line 8, in <module>
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)
  File "C:\Python27\lib\re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
>>>

Please help me to write output into a file!

A: Your traceback doesn't match your code. In your traceback, text is used, which is a file object.
Not that your code works with text1 either; that is a list, not a str. Instead of using readlines(), use read():
with open('ckili.txt','r') as fileob:
    text = fileob.read()
    it = itertools.cycle(keywords2)
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text)

or process each line separately. Note that I took the liberty to change the names a little; text isn't the best name for a file object.
You appear to be importing the module into your interactive interpreter. Know that module imports are cached, you'll need to explicitly restart your interpreter or reload the module after changes.


text:
Q: I get an error creating a react-360 project I get this error when I start a new react-360 project using react-360 init myProject.It creates the folder but when I npm start it gives me more errors.
react-360 init MyProject
(node:17583) ExperimentalWarning: The fs.promises API is experimental
Creating new React 360 project...
Project directory created at MyProject

Copying assets...

Installing dependencies...
(node:17584) ExperimentalWarning: The fs.promises API is experimental
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: MyProject@0.0.1
npm ERR! Found: react@16.3.2
npm ERR! node_modules/react
npm ERR!   react@"16.3.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"16.3.1" from react-native@0.55.4
npm ERR! node_modules/react-native
npm ERR!   react-native@"~0.55.4" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/scylla/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/scylla/.npm/_logs/2021-03-17T10_50_46_670Z-debug.log
`npm` exited with code 1. Try fixing the errors above and run `npm` from within MyProject again.

When I run npm start
npm start
(node:17675) ExperimentalWarning: The fs.promises API is experimental

> MyProject@0.0.1 start
> node node_modules/react-360/scripts/packager.js

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module '/Users/scylla/Documents/cs/react360test/MyProject/node_modules/react-360/scripts/packager.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Any Ideas on how to solve it? Thanks.

A: ok, I just ran npm install --force and it fixed everything!!


text:
Q: What is Dynamic Optimization in compilers People are talking about dynamic optimization in compilers.What does it mean? Can anyone give me a fair idea about it?

A: Static optimization is based on the program code itself. Alternatively, dynamic optimization is based on code execution results. For example, having a long switch statement in C/C++, it would be possible to optimize it by changing case operators order. To do this, it is necessary to run the program many times and keep this switch operator statistics.
Some modern compilers contain such optimization framework, which allows to run the program and save its runtime statistics. Then the program code is optimized by using this statistics.
See, for example, VC++ Profile-Guided Optimizations:
http://msdn.microsoft.com/en-us/library/e7k32f4k.aspx


text:
Q: Docker Restart Policy for PostgreSQL is a good idea to set "restart: always" in a PostgresSQL container? Perhaps to use "restart: unless-stopped" is a better idea to prevent outdated containers?

A: If with "outdated containers" you mean "containers created from old images" you don't have to worry because in both cases if you modify your docker-compose.yml with a new version of postgres and perform a docker-compose up -d you will get new container running.
The difference on the behavior is what happens if you stop a container and then the machine restarts (for any reason). If you have restart: always the container will be restarted, if you used restart: unless-stopped it will not spin-up.


text:
Q: General Generics c# So I have this test program:
namespace ConsoleApplication1TEST{

class Program
{
    static void Main(string[] args)
    {
        new derp<int,int>(5,4);
    }
}

class derp<T,V>
{
    public T top;
    public V vop;

    public derp(T to, V vo)
    {
        top = to;
        vop = vo;
        top.ToString();
    }
}

}
top.ToString is allowed. As are GetHashCode, GetType, and Equals. However, ToUpper is not allowed, and neither are other string-specific methods.  Can this be changed?
When I place a method that is not allowed, this is the error I get:

Error 1   'ConnectionServiceT' does not contain a definition for
  'connect' and no extension method 'connect' accepting a first argument
  of type 'ConnectionServiceT' could be found (are you missing a using
  directive or an assembly reference?)

A: It is reasonable that the method ToUpper() is not allowed, since this is a method specific for string types. If your type isn't a string then you can't use the ToUpper() method, because this method is specific to string types.
On the other hand, since all types inherrit the object type, they  inherit it's methods,  which are ToString(), GetHashCode(), GetType() and Equals().
This is a good link regarding the inheritance in C#, in where you can see more thoroughly what I am talking about.
Also here is stated that:

In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

A:
top.ToString is allowed. GetHashCode, GetType, Equals is also allowed.
However, ToUpper is not allowed, and other string-specific methods are not allowed. Can this be changed?

That's perfectly normal. The compiler knows nothing about the actual type of T, so it can't assume that it has a ToUpper method. However, since all types (except pointers) inherit from Object, calling methods of the Object class is allowed.
Now, if there was a constraint on T to force it to inherit a type that has a ToUpper method, your code would work:
class derp<T,V> where T : String

It's a bad example, because String is sealed, so this code wouldn't compile, but it's just to illustrate the idea.
Anyway, if you want to be able to call the String.ToUpper method on top, then the type of top cannot be generic: it has to be String.
To learn more about generic constraints, see MSDN: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

A: .ToString() works on every type. If the type is not a string the type's name will be returned.
.ToUpper() is a string specific, won't work on types other than string.

A:
Can this be changed?

You don't know what T and V are, so the only assumption the compiler can make is that they inherit from object, which is why ToString, GetHashCode, GetType, and Equals are allowed (since they're methods on object which every class inherits from).
If ConnectionServiceT (and other similar classes) inherit from a base class you can constrain T and V to be subclasses of a given type:
class derp<T,V> where T:BaseService
                where V:MyOtherClass
{
    public T top;
    public V vop;

    public derp(T to, V vo)
    {
        top = to;
        vop = vo;
        top.ToString();
    }
}

Then you can call methods specific to BaseService on instances of T (since you know that T must derive from BaseService.
But you can't constrain to string because it's sealed - the only possible class would be derp<string, string> so there's no reason to use generics.

A: It is a good thing you cant use ToUpper(). You are sending in integers, those certainly do not have a ToUpper method. ToUpper is a method that belongs to string objects. You could do this:
string myUpperCaseString = top.ToString().ToUpper();

//or

if(top.GetType() == typeof(string)
{
    string myUpperCaseString = (top as string).ToUpper();
}

What you may have been mistaken about, is that ToString() does not change the string... it instead returns a new string representation of that object, you then have to store this object somewhere. Above I stored it in a variable called myUpperCaseString with the type of string.
ToString, GetHashCode, GetType are all methods that belong to the object class and anything that inherits from it.


text:
Q: Loop Error including strings and variables I keep getting an error like when I have string, it says it cannot convert 'byte[]' to string. And when I have it as var it says the same thing but gives me an error to the data next to Results.txt.
if (Lock.Contains("Mode: Data Grabber"))
{
    Console.WriteLine("Loading Data Grabber 2.0! Mode = Data Grabber!\n");
    Console.WriteLine("Enter the websites url!\n");
    Console.WriteLine("(\n) " + "(\n)");
    if (Option == Option)
    {
        WebClient wc = new WebClient();
        string data = wc.DownloadData(Option);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Downloading data from " + data);
        Thread.Sleep(3000);
        Console.WriteLine("\n");

        if (!File.Exists(Directory.GetCurrentDirectory() + @"/Results.txt"))
        {
            File.Create(Directory.GetCurrentDirectory() + @"/Results.txt");
        }

        File.WriteAllText(Directory.GetCurrentDirectory() + @"/Results.txt", data);
        Console.WriteLine("All data has been sent to the path");
    }
}

A: You are trying to write string when you have a byte[], i.e., data
string data = wc.DownloadData(Option);

WebClient.DownloadData returns a byte[]
public byte[] DownloadData (string address);

Try out:
string data = wc.DownloadString (address);

A: Here you go:
Replace this code string data = wc.DownloadData(Option); with System.Text.Encoding.UTF8.GetString(wc.DownloadData(Option))
The premise is that the encoding of the corresponding text is UTF-8.
Hope this would be helpful.

A: You should use the 'DownloadString' method of WebClient to get a string:
string data = wc.DownloadString (Option);

Now the content will a string.


text:
Q: Spring Remoting with Camel and HTTP REST seems to be a big work for me right now as I'm migrating an existing "Big" monolithic application into small "micro-services" and there are a lot Interface wiring inside.
Based on my research, A camel based spring remoting is a great idea.
I tried it using ActiveMQ/JMS as the transport mechanism. Because the app required to access a lot of data stored in spring-session based web sessions, this approach has many issues for me.
So, the transport should use an HTTP based transport.
Do you recommend Spring remoting with Camel and HTTP ? Or should I stick with HttpInvoker mechanism ? Or REST itself ?


text:
Q: Converting multiple PDF's to Text files with PDFminer3 Hopefully this is a pretty easy one, but I am brand new to using python 3 for a small project and would like some guidance. I have a folder of over 1000 pdf documents with some data I would like to extract. I can successfully convert a PDF to a text file and save it in the scripts directory, however I cant figure out how to have this run for all of the PDFs at once and create an output file for each in a new folder. The code I have so far is below.
from pdfminer3.layout import LAParams, LTTextBox
from pdfminer3.pdfpage import PDFPage
from pdfminer3.pdfinterp import PDFResourceManager
from pdfminer3.pdfinterp import PDFPageInterpreter
from pdfminer3.converter import PDFPageAggregator
from pdfminer3.converter import TextConverter
import io

resource_manager = PDFResourceManager()
fake_file_handle = io.StringIO()
converter = TextConverter(resource_manager, fake_file_handle)
page_interpreter = PDFPageInterpreter(resource_manager, converter)

with open('/sample/mypdf.pdf', 'rb') as fh:

    for page in PDFPage.get_pages(fh,
                                  caching=True,
                                  check_extractable=True):
        page_interpreter.process_page(page)

    text = fake_file_handle.getvalue()

# close open handles
converter.close()
fake_file_handle.close()

print(text, file=open("Output.txt","a"))

I would appreciate any help or direction as how I can move forward. Thank you!

A: There are two ways I can think of. If you wish to do it for a few files. You can append all your file paths into a list as follows. and iterate through it. Same function but just iterate it from a list. For example,
list = ["C:\\Users\\blabla\\Desktop\\.pdf\\test.pdf"
        ,"C:\\Users\\blabla\\Desktop\\.pdf\\testmore.pdf"
        ,"C:\\Users\\blabla\\Desktop\\.pdf\\writingtoxml.pdf"
        ,"C:\\Users\\blabla\Desktop\\.pdf\\2Data.pdf"]
for pathname in list:
    #your code goes here

Or else, you could iterate from a given directory. Place all your documents in one folder, specify the directory as follows and iterate through. If you wish for a different output name for every file, rename them.
import os
directory = "C:\\Users\\blabla\\Desktop\\.pdf"
for filename in os.listdir(directory):
    if filename.endswith(".pdf"):
        pathname = os.path.join(directory, filename)
        #Your code goes here
        continue
    else:
        continue

The only part you have to change in your code is replacing this part:
with open('/sample/mypdf.pdf', 'rb') as fh:

with this:
with open(pathname, 'rb') as fh:

Because pathname itself prints out the paths that you want as follows:
C:\Users\blabla\Desktop\.pdf\test.pdf
C:\Users\blabla\Desktop\.pdf\testmore.pdf
C:\Users\blabla\Desktop\.pdf\writingtoxml.pdf
C:\Users\blabla\Desktop\.pdf\2Data.pdf

A: This post was so helpful! I know it's from a few years ago, but just in case someone else out there is trying to figure out how to do this, I'm adding a bit to Han's code.
Below is how I figured out how to extract and then append the text to new files in a directory. This is my first time posting, so sorry if I've missed some etiquette!
from pdfminer3.layout import LAParams, LTTextBox
from pdfminer3.pdfpage import PDFPage
from pdfminer3.pdfinterp import PDFResourceManager
from pdfminer3.pdfinterp import PDFPageInterpreter
from pdfminer3.converter import PDFPageAggregator
from pdfminer3.converter import TextConverter
import io
from io import StringIO
import glob
import os

rsrcmgr = PDFResourceManager()
sio = StringIO()
codec = "utf-8"
laparams = LAParams()
converter = TextConverter(rsrcmgr, sio, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, converter)

directory_path = "D:/User/ToyDir"
directory = directory = glob.glob(f"{directory_path}/**/*.pdf", recursive=True)
outputDir = "D:/User/NewToyDir"

for pathname in directory:
    with open(pathname, 'rb') as fh:
        for page in PDFPage.get_pages(fh,
                                    caching=True,
                                    check_extractable=True):
            interpreter.process_page(page)
        text = sio.getvalue()
        #print(text)
        bareName = os.path.split(pathname)[1]
        bareName = bareName[:-3] +".txt"
        newName = os.path.join(outputDir, bareName)
        with open(newName, "a") as o:
            o.write(text)


text:
Q: Un-nesting lists within a tibble list column I have a tibble with a list column where each element contains a list of length 2.  I have tried to use unlist(), unnest() and flatten() and various other combinations but no luck getting my desired outcome.
A minimal working example is below:
df <- tibble(x = c('A', 'B'),
         preds = list(list(Phi = data.frame(time = 1:2, estimate = c('y1', 'y2')),
                           p = data.frame(time = 1:2, estimate = c('y3', 'y4'))),
                      list(Phi = data.frame(time = 1:2, estimate = c('y5', 'y6')),
                           p = data.frame(time = 1:2, estimate = c('y7', 'y8')))))

with an expected outcome:
output <- tibble(x = rep(c('A', 'B'), each = 4),
             grp = c(rep(c('Phi', 'p'), each = 2 ), rep(c('Phi', 'p'), each = 2 )),
             time = rep(1:2, 4),
             estimate = c('y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7', 'y8'))

The following code gets me part way and I could easily include the other columns, but its not correct.
df$preds %>% flatten_df()

After a day of googling I'm still stuck.  Please point me in some direction.......many thanks!!!

A: Building on akrun's already good answer, I offer the following.
library(tidyr)
library(dplyr)

df %>%
  mutate(
    preds = lapply(
      preds, lapply, mutate, estimate = as.character(estimate)
    ) %>%
    lapply(bind_rows, .id = "grp")
  ) %>%
  unnest

# # A tibble: 8 x 4
#       x   grp  time estimate
#   <chr> <chr> <int>    <chr>
# 1     A   Phi     1       y1
# 2     A   Phi     2       y2
# 3     A     p     1       y3
# 4     A     p     2       y4
# 5     B   Phi     1       y5
# 6     B   Phi     2       y6
# 7     B     p     1       y7
# 8     B     p     2       y8

N.B. The only improvement is the conversion of estimate from factor to character. Otherwise, and if this could be addressed in the source data, the map solution by akrun is more concise and easier to reason about.


text:
Q: Getting error of non-object property Here, I am getting error like,

Notice: Trying to get property of non-object

in last two lines while fetching record.
what does it say?
My code:
$Id = $_REQUEST['id'];

        $sql = "Select * From ".CHANNEL_MASTER."
                    Where sam_status = '".ACTIVE_STATUS."' And user_id = '".$_SESSION['user_id']."' And sam_id = '".$Id."'";

        $db->query($sql);
        $row = $db->fetch_object(MYSQL_FETCH_SINGLE);

        $siteID = array_search($row->sam_site_id, $site_id_array);
        $ebay_token = $row->sam_ebay_token;

A: You need to store query result into a variable then fetch data from it.
So instead of
 $db->query($sql);
 $row = $db->fetch_object(MYSQL_FETCH_SINGLE);

use
 $result=$db->query($sql);// store query result into $result
 $row = $result->fetch_object(MYSQL_FETCH_SINGLE);// fetch data from $result

A: $Id = $_REQUEST['id'];

        $sql = "Select * From ".CHANNEL_MASTER."
                    Where sam_status = '".ACTIVE_STATUS."' And user_id = '".$_SESSION['user_id']."' And sam_id = '".$Id."'";

        $result = $db->query($sql);
        $row = $result->fetch_object(MYSQL_FETCH_SINGLE);

        $siteID = array_search($row->sam_site_id, $site_id_array);
        $ebay_token = $row->sam_ebay_token;


text:
Q: Problem with obtaining GET all athlete activities in Strava API v3 I would like to access my own activities using the Strava API in Python. I've researched the responses to the question below, but am still bumping into errors. Who can help me retrieve the data?
Problem with access token in Strava API v3 GET all athlete activities
I have tried the suggested answer, but am still getting an error. I've gone through steps 1-3 suggested, obtaining an access_token when I've set scope=activity:read_all in step 1. When trying to obtain all my activities, I get thrown the following error: {'message': 'Authorization Error', 'errors': [{'resource': 'Athlete', 'field': 'access_token', 'code': 'invalid'}]}
The code I'm using after step 3 is:
activities_url = "https://www.strava.com/api/v3/athlete/activities"
access_token = res.json()['access_token']
header = {'access_token': access_token}
activities = requests.get(activities_url, headers=header).json()

A: Give a look at the official documentation, section C. How to Make a cURL request.
For every request you have to send an authorization header of this type:
Bearer YOURACCESSTOKEN


text:
Q: C# Add external user control to project I'm working on a windows form application in C# VS2010.
I found on the internet an implementation of a User-Control that I want to use in my project.
Problem: how can I import or include it so I will be able to see it in my Toolbox ?
I copied the UserControl directory into my project directory(see attached photo)
and then build the project and got this warning:
Error  1   Unable to create a manifest resource name for "RecessEditorControl.resx". Could not find file 'C:\Users\bassam\Desktop\comm\Projects\Thunder Archive\Thunder Archive\RecessEditorControl.cs'.   Thunder Archive

any idea how it should be done?

A: Open the user control project separately (outside of your solution) and attempt to build it.
If the build fails, search for help from the control author(s) on what dependencies are needed and how you can build the control.
After you get it sucesfully built, there will be a .dll file in the bin/ folder (where config is most likely debug or release, depending on what configuration you used to build the project)
Reference this .dll from the windows desktop solution you are working on. Add it to the references section of your UI project.
It should automatically show up in the toolbox if it is properly coded as a user control.
There is the option of including the entire source project of your control in your win app solution, you can try this later if you verify that you are able to build the control on it's own.
Although I would not recommend this approach unless you intent to actively continue developing the user control.

A: You separately build user control to create a dll. After that include the dll in your app executable folder. When you switch to designer, you will see the control appears on the toolbox with the control name. Just drag n drop...


text:
Q: How to handle the sequelize unique constraint error? I am new to javascript and I need to handle constraint error in sequelize. I searched related to this topic everywhere, but still, I couldn't get a proper workable answer. My attempt it as follows.
app.post('/api/users', (req, res) => {
  try {
    console.log(req.body);
    User.create(req.body)
        .then(user=> res.json(user));
  } catch (error) {
    console.log("Error: "+error);
  }});

Here couldn't catch the exception yet. For a valid user input it is able to post the request. So I just need to know a way to handle the exception.

A: Was looking around for an answer for this, but was not really satisfied with the two given. If you are looking to return a correct response such as a 403 this is the solution I have came up with.
app.post('/api/users', async (req, res) => {
    try {
        console.log(req.body);
        var user = await User.create(req.body)
        return res.status(200).json({ status: 'success', result: res.json(user) })
    } catch (error) {
        if (error.name === 'SequelizeUniqueConstraintError') {
            res.status(403)
            res.send({ status: 'error', message: "User already exists"});
        } else {
            res.status(500)
            res.send({ status: 'error', message: "Something went wrong"});
        }
    }
});

A: You can use Promise with .then().catch(), or use async/await with try/catch
This is Promise
app.post('/api/users', (req, res) => {
    console.log(req.body);
    User.create(req.body)
        .then(user=> res.json(user))
        .catch(err => console.log(err))
});

This is async/await
app.post('/api/users', async (req, res) => {
    try {
      console.log(req.body);
      const user = await User.create(req.body);
      res.json(user);
    } catch (error) {
      console.log("Error: "+error);
    }
});

A: Looks like you're mixing two different styles. If you're using then(), then the try catch block is unnecessary:
app.post('/api/users', (req, res) => {
  console.log(req.body)
  User.create(req.body)
    .then(user => res.json(user))
    .catch(error => console.log('Error: ' + error))
})

The other style would be using the async package. With async, your code would look like this:
app.post('/api/users', async (req, res) => {
  console.log(req.body)
  try {
    const user = await User.create(req.body)
    res.json(user)
  }
  catch (error) { console.log('Error: ' + error) }
})

Both methods have their advantages and disadvantages that go beyond this snippet and lot of people use both as appropriate, for example the await approach works only inside a function declared with async like in the second example :async (req, res). In such cases, using then() style promise handling is a better approach