text:
Q: Why can't NestJS resolve the dynamic module options parameter I added as a provider? I made a dynamic module named AuthModule copied from Nest's documentation. I changed it so I could supply different Auth0 tenant credentials to the Auth0Service for every module that imports it. The configuration parameter in the provider array of the Auth. module is unresolved in the importing/calling module. The error appears when I run npm run start. I called Auth0's register method in the calling module (Users) imports array. I have added Auth's options parameter to its array of providers. When I run npm start, I get an error saying Nest cannot resolve the dependency AUTH0_CONFIG.
Nest can't resolve dependencies of the Auth0Service (?)...Please make sure that the argument AUTH0_CONFIG at index [0] is available in the UsersModule context.
Exporting the options parameter from Auth0 allows my app to run. The problem is that when I make any Axios request in the Auth0Service thru UsersModule, I get a 409 error. I get the 409 error even from Auth0 API endpoints that do not return a 409 error according to Auth0 documentation.
The Auth0 module is globally scoped and imported by UsersModule. Auth0's register method returns itself dynamic module:
@Global()
@Module({})
export class AuthModule {
  public static register(auth0Params: Auth0Params): DynamicModule {
    return {
      module: AuthModule,
      providers: [
        { provide: AUTH0_CONFIG, useValue: auth0Params },
        Auth0Service,
      ],
      exports: [AuthService],
    };
  }
}

This is how I imported the AuthModule into UsersModule:
@Module({
  imports: [
    TypeOrmModule.forFeature([User, UserRepository]),
    HttpModule,
    AuthModule.register({
      domain: process.env.DOMAIN,
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
    }),
  ],
  providers: [UserService, UserResolver, Auth0Service],
  exports: [UserService],
})
export class UserModule {}

How do I solve this? What should I check?

A: as you're importing the dynamic module AuthModule.register into UserModule, which exports the provider Auth0Service, I don't see any reason to register that provider again in UserModule.
When you do so, you must have to register all the dependencies of Auth0Service again into UserModule, but you can't do that as that AUTH0_CONFIG is private to AuthModule.
To solve this, just drop the Auth0Service from providers array of UserModule.
When we import some module, we're importing all the providers that that module registers and exports.


text:
Q: Crear listas de una lista general tengo una lista la cual ordené por elementos que quisiera obtener. Se trata de nombre de empresas, la idea que quiero es que cuando los objetos de la lista general sean iguales se agrupen en una lista y así sucesivamente. En este ejemplo tengo 1 lista general y resultarían 3 listas al final
var companiesf = [
    Directory(directoryId: 1, fullname: "Jose Luis", company: "A"),
    Directory(directoryId: 2, fullname: "Fernando", company: "A"),
    Directory(directoryId: 3, fullname: "Maria", company: "B"),
    Directory(directoryId: 4, fullname: "Rodrigo", company: "B"),
    Directory(directoryId: 5, fullname: "Miguel", company: "C")
]

de modo que obtendría 3 listas
 var litaA = [
    Directory(directoryId: 1, fullname: "Jose Luis", company: "A"),
    Directory(directoryId: 2, fullname: "Fernando", company: "A")
]

var listaB = [
    Directory(directoryId: 3, fullname: "Maria", company: "B"),
    Directory(directoryId: 4, fullname: "Rodrigo", company: "B")
]

var listaC = [
    Directory(directoryId: 5, fullname: "Miguel", company: "C")
]

¿Cómo podría lograr eso?
Muchas gracias

A: Puedes plantearte 2 alternativas. Tendrías que evaluar cuantos elementos tendrías y la forma de trabajar con los resultados para que fuese lo mas eficiente posible.
Una primera forma seria tenerlo todo como lo tienes ahora y cuando quieras la empresa x hacer un filter sobre la empresa y obtienes un array de esa empresa
let companies = companiesf.filter({ $0.company == "A" })

Tendrías que estar haciendo filtros cada vez que quieras trabajar con una empresa. Añadir una nueva empresa seria muy fácil, solo añadiendo un elemento mas al array y eliminarlo también seria muy fácil..
Otra opción seria tener un diccionario, donde la clave sea la empresa y el valor sea un array con todos los datos de esa empresa. El acceso seria muy rápido, pero seria mas tedioso el añadir o eliminar un elemento, pero hechos unos métodos para añadir, eliminar o lo que necesites se soluciona rápido.
var empresasDict: [String: [Directory] = [:]

Para añadir, tendrías que obtener primero lo que ya tienes , añadir el elemento y volver a asignar el resultado, y similar para eliminar.
let emp = Directory(company: "com1", name: "pepe", id: 3)
var arrAux = empresasDict["com1"] ?? []
arrAux.append(emp)
empresasDict["com1"] = arrAux

redpajama_set_name: RedPajamaStackExchange


text:
Q: records count from database I have 8 tabs containing number of records in each one and a function that should count the number of records in each tab and put it in the tab's header name like the following:
public void count_records(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
        string[] commands = {
                                "SELECT * FROM myTable",
                                "SELECT * FROM myTable WHERE Status=2",
                                "SELECT * FROM myTable WHERE Status=3",
                                "SELECT * FROM myTable WHERE Status=8",
                                "SELECT * FROM myTable WHERE Status=4",
                                "SELECT * FROM myTable WHERE Status=7",
                                "SELECT * FROM myTable WHERE Status=1",
                                "SELECT * FROM myTable WHERE Status=5"
                            };
        int[] LLCount = new int[commands.Length];
        try
        {
            for (int i = 0; i < commands.Length; i++)
            {
                SqlCommand cmd = new SqlCommand(commands[i], con);
                SqlDataReader reader;
                int count = 0;
                con.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    count++;
                }
                LLCount[i] = count;
                myTab1.HeaderText += " (" + LLCount[0] + ")";
                myTab2.HeaderText += " (" + LLCount[1] + ")";
                myTab3.HeaderText += " (" + LLCount[2] + ")";
                myTab4.HeaderText += " (" + LLCount[3] + ")";
                myTab5.HeaderText += " (" + LLCount[4] + ")";
                myTab6.HeaderText += " (" + LLCount[5] + ")";
                myTab7.HeaderText += " (" + LLCount[6] + ")";
                myTab8.HeaderText += " (" + LLCount[7] + ")";
            }
        }
        catch (Exception ex) { string ee = ex.Message; }
        finally { con.Close(); }
    }

Now, the problem I'm facing is that the reader gets the number of records of the first command string correctly "LLCount[0]" but the rest of them are zeros.
EDIT:

I added reader.Close(); and moved the assignment outside the loop but
  it didn't even show the zeros or anything as before.  So, I think it
  dosen't matter whether you put reader.Close(); or not.

A: Look for //* in the code to find the differences. The main chnage was that I put con.Open(); before the for loop. Opening the same connection again is throwing error when the connection is not closed. this error was getting caught in catch block,
public void count_records(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ConnectionString);
    //*** See Count(*) in the sql
    string[] commands = {
                       "SELECT count(*) FROM myTable",
                        "SELECT count(*) FROM myTable WHERE Status=2",
                        "SELECT count(*) FROM myTable WHERE Status=3",
                        "SELECT count(*) FROM myTable WHERE Status=8",
                        "SELECT count(*) FROM myTable WHERE Status=4",
                        "SELECT count(*) FROM myTable WHERE Status=7",
                        "SELECT count(*) FROM myTable WHERE Status=1",
                        "SELECT count(*) FROM myTable WHERE Status=5"

                    };
    int[] LLCount = new int[commands.Length];
    try
    {
        //*****This is the change I made
        con.Open();

        for (int i = 0; i < commands.Length; i++)
        {
            SqlCommand cmd = new SqlCommand(commands[i], con);

            int count = 0;
            //*** Se the use of ExecuteScalar
            count =Convert.ToInt32(  cmd.ExecuteScalar());
            LLCount[i] = count;
        }

        //***Now Assign the Tab Headers

    }
    catch (Exception ex) { string ee = ex.Message; }
    finally { con.Close(); }
}

}


text:
Q: What determines how many times map() will get called? I have a text file and a parser that will parse each line(s) and store into my customSplitInput, I do the parsing in my custom FileInputFormat phase so my splits are custom. Right now, I have 2 splits and within each split contains a list of my data.
But right now, my mapper function is getting called repeatedly on the same split. I thought the mapper function will only get called based on the number of splits you have?
I don't know if this applies but my custom InputSplit returns a fixed number for getLength() and an empty string array for getLocation(). I am unsure of what to put in for these.
@Override
    public RecordReader<LongWritable, ArrayWritable> createRecordReader(
            InputSplit input, TaskAttemptContext taskContext)
            throws IOException, InterruptedException {
        logger.info(">>> Creating Record Reader");
        CustomRecordReader recordReader = new CustomRecordReader(
                (EntryInputSplit) input);
        return recordReader;
    }

A: map() is called once for every record from the RecordReader in (or referenced by) your InputFormat. For example, TextInputFormat calls map() for every line in the input, even though there are usually many lines in a split.


text:
Q: Garbage collector in c for variables inside a loop I am mainly a Java person recently working on some projects involving C so please bear with me if it's a basic C question.
So inside my main I have a while loop and I declare a variable each iteration.
int main()
{
  int done = 0;
  while(!done)
  {
    char input[1024];
    scanf("%s", input);
    //parse the input string
    ...
  }
}

Now since the input variable will change every time depending on what the user wants I have to use a "new" variable each time. However, I think the above declaration will be causing memory leak ultimately(or will it?). I would like to know if gcc takes care of garbage collection.
Is there any better approach without allocating and freeing after every iteration?

A:
I think the above declaration will be causing memory leak ultimately(or will it?).

No, it wouldn't: input is an automatic (AKA "Stack") variable, it will get "deallocated" as soon as it goes out of scope (i.e. after the closing brace).

Is there any better approach without allocating and freeing after every iteration?

There is no actual allocation or deallocation going on: the space in the automatic memory (AKA "on the stack") is allocated by some compile-time bookkeeping around the stack pointer. The access of automatic variables is a very fast operation heavily assisted by hardware, so there is no loss of efficiency there.
Dynamic memory allocation (Java-style) is done with malloc/calloc/realloc in C. These are not garbage collected - you need to explicitly free every pointer that you allocated.

A:
However, I think the above declaration will be causing memory leak ultimately(or will it?)

It will not. The inputobject is discarded every time the trailing } of the loop is encountered.

A: As other have already said, stack variables are automatically freed when they go out of scope and are usually overwritten soon.
That being said, the reason I'm writing this answer is to stress this: there is no garbage collector in C, at least not by default. This means that heap allocated memory (usually initialized with malloc, calloc and others) must be manually freed by you (using free).


text:
Q: Python script to remove all comments from XML file I am trying to build a python script that will take in an XML document and remove all of the comment blocks from it.
I tried something along the lines of:
tree = ElementTree()
tree.parse(file)
commentElements = tree.findall('//comment()')

for element in commentElements:
    element.parentNode.remove(element)

Doing this yields a weird error from python: "KeyError: '()'
I know there are ways to easily edit the file using other methods ( like sed ), but I have to do it in a python script.

A: Use strip_tags() from lxml.etree
from lxml import etree
XML = """<root>
  <!-- COMMENT 1 -->
  <x>TEXT 1</x>
  <y>TEXT 2 <!-- COMMENT 2 --></y>
  </root>"""

tree = etree.fromstring(XML)
print etree.tostring(tree)
etree.strip_tags(tree,etree.Comment)
print etree.tostring(tree)

Output:
<root>
<!-- COMMENT 1 -->
<x>TEXT 1</x>
<y>TEXT 2 <!-- COMMENT 2 --></y>
</root>
<root>

<x>TEXT 1</x>
<y>TEXT 2 </y>
</root>

A: The same as
https://stackoverflow.com/a/3317008/1458574
from lxml import etree
import sys

XML = open(sys.argv[1]).read()
parser =  etree.XMLParser(remove_comments=True)
tree= etree.fromstring(XML, parser = parser)
print etree.tostring(tree)

A: This is the solution I implemented using minidom:
 def removeCommentNodes(self):
        for tag in self.dom.getElementsByTagName("*"):
            for n in tag.childNodes:
                if n.nodeType is dom.Node.COMMENT_NODE:
                    n.parentNode.removeChild(n)

In practice I first retrieve all the tags in the xml, then for each tag I look for comment nodes and if found I remove them. (self.dom is a reference to the parsed xml)

A: comment() is an XPath node test that is not supported by ElementTree.
You can use comment() with lxml. This library is quite similar to ElementTree and it has full support for XPath 1.0.
Here is how you can remove comments with lxml:
from lxml import etree

XML = """<root>
  <!-- COMMENT 1 -->
  <x>TEXT 1</x>
  <y>TEXT 2 <!-- COMMENT 2 --></y>
</root>"""

tree = etree.fromstring(XML)

comments = tree.xpath('//comment()')

for c in comments:
    p = c.getparent()
    p.remove(c)

print etree.tostring(tree)

Output:
<root>
  <x>TEXT 1</x>
  <y>TEXT 2 </y>
</root>


text:
Q: Как полностью убрать углы у RoundedCornerShape в Jetpack compose? Мне нужно создать прямоугольник с двумя закругленными сверху углами, пробовал убрать 2 угла у RoundedCornerShape:
        Card(
            modifier = Modifier
                .fillMaxSize()
                .clip(
                    RoundedCornerShape(
                        topStart = 30.dp,
                        topEnd = 30.dp,
                        bottomEnd = 0.dp,
                        bottomStart = 0.dp,
                    )
                ),
            backgroundColor = light
            ){

            //***
        }

Но в итоге скругление убирается не полностью и остаются такие засечки:

Как я могу их убрать?

A: Вы убираете углы у маски, но у самого компонента Card остаются собственные закругления углов.
Будет правильнее задать компоненту кастомную форму и отказаться от обрезки по контуру:
        Card(
            shape = RoundedCornerShape(
                topStart = 30.dp,
                topEnd = 30.dp,
                bottomEnd = 0.dp,
                bottomStart = 0.dp,
            ),
            modifier = Modifier.fillMaxSize(),
            backgroundColor = light
            ){

            //***
        }


text:
Q: Does MySql also need to be installed on computers that access the database? I am making a GUI and using MySql, if I send the executable to another computer will the computer on which the app is executed also require MySql or is it just required to be connected to the internet?

A: Second option is right theres only a need of internet connection.
You see in your code for example in java you defined IP adress(in other worlds path) to database server(e.g 110.0.2.1 or even localhost).
When other computer takes your executable it only tries to connect to database server and sends whatever you programmed on it(request) in the form of SQL Query and waits for a response.
Other computers with your executables do not process queries just seds requests and recieve replies therefore they do not need to have installed mysql

A: You need a server and a client to communicate. Kind of like you need a mouth and an ear to make a conversation.
For example, browsing a website takes a web server and a web browser.
It's essentially the same with MySQL - you need a server and a client. They both can come in the same installation package, so you may be under the impression it takes the same thing on both ends, but in fact you'll be running something else on your server and something else on your client machine.
Now, depending on your application, you may or you may not to install a MySQL client on the client machines. You can have a built-in client in your application, or your application can assume there is a client library on the machine, in which you case you will need to install it separately or have your application's installer do it on top of installing your application.
TL;DR
You may need to install a MySQL client on your client machine unless your application has a built-in client.


text:
Q: Providing compiler flags to Rust build for the MSVC toolchain I am looking to enable compiler options for Rust applications built on Windows using the MSVC toolchain. I see that rustc provides the option "-C llvm-args" to provide flags to the LLVM toolchain but I don't see such an option for MSVC. Does this support currently exist for rustc or cargo?

A: Rustc is the Rust compiler and it relies on the LLVM backends for actual code generation on all platforms. So if you need to pass arguments to the backend, you can use -C llvm-args on Windows like in other platforms.
The distinction between the MSVC toolchain or the MINGW toolchain mostly concerns the linker. Options can be passed to the linker with -C link-arg or -C link-args on all platforms, although of course in this case the available options will depend on the targeted toolchain.


text:
Q: DynamoDB - Reducing number of queries After my users log in the app makes too many requests to DynamoDB and I am thinking about different ways to reduce the number of calls.
The app allows user to trigger certain alerts that get sent to other users. For instance: "Shipment received, come to the deck", "Shipment completed", etc.
These are the calls made:

*

*Get company's software license expiration date.

*Get the computer's location in the building (i.e. "Office A").

*Get the kinds of alerts that can be triggered (i.e. "Shipment received, come to the deck", "Shipment completed", etc).

*Get information about the user (i.e. company teams the user belongs to, and admin level the user has (which can be 0, 1, 2, or 3).

Potential solutions I have though about:

*

*Put the company's license expiration date as an attribute of each computer (This would reduce the number of queries by 1). However, if I need to update the company's license expiration date, then I need to update it for EVERY SINGLE computer I have in the system, which sounds impractical to me since I may have 200, 300 or perhaps even more computers in the database.

*Add the company's license expiration date as an attribute of the alerts (This would reduce the number of queries by 1); which seems more reasonable because there are only about 15 different kinds of alerts, so if I need to change the license expiration date later on, it is not too bad.

*Cache information on the user's device; however, I can't seem to find a good strategy to keep the information stored locally as updated as possible.
I still think these 3 options do not sound too good, so I am hoping someone can point me in the right direction. Is there a good way to reduce the number of calls? I am retrieving information about 4 different entities (license, computer, alert, user), should I leave those 4 calls after users log in?

A: here are few things that can be done wrt each component.

*

*Get information about the user
keep it in session store and whenever details changes update the store. session stores are usually implemented using cache like redis.

*Computer location
Keep it in a distributed cache like redis. lazily initialise it. and whenever new write happens to computer location (rare IMO) remove the entry from redis using dynamodb streams and aws lambda.

*Kind of alerts
Same as Computer location

*License expiration date
If possible don't allow license expiry date (issue a new one for these cases, so that traceability is maintained.) and cache licence expiry forever. OR same as Computer location.


text:
Q: Dynamically re-route specific traffic on NIC failure in Linux This is my first question on this forum. Hope I will be able to help others in the future.
I have two boxes with two NICs each. I know that using bonding I can have some degree of fault tolerance but I feel I need something else. What I want is different traffic (PING, LOGIN, etc..) following one path and the other traffic (DRBD, web, etc..) following the other one.
Just in the case that one of the links fail, I want part of the other traffic (in my case, just IP for a heartbeat mechanism) following the same path as DRBD and web do. Is this possible?, what do I need to monitor links status and acct accordingly?. I would know how to do this statically (iproute and so on), but need it dynamically...

A: You do not want what you're asking for in the Question. Use a single bond interface. Bonding has several different modes to accommodate various balances of throughput and fault tolerance. Be sure to put the time into configuring it correctly for your networks capability's and your application's requirements.
That said, you could create two bonding devices Bond0 and Bond1 which both have members Eth0 and Eth1, with Bond0 having Eth0 as primary and vice versa for Bond1, and configure the Bond interfaces for failover only. Then assign IPs to each of the Bond interfaces. And finally assign services to a particular IP. This would create a situation where traffic prefers one NIC or the other, but is an administrative nightmare and likely to cause many more problems than you perceive it to solve.

A: This tutorial on load-balancing links shows how to mark packets and dynamically choose a route. Instead of marking every nth packet, mark the packets based on port instead.
It's also my instinct that you don't need to use the conditional tagging, but rather just enter redundant routes in each table and set the route priority correctly. Example:
Default:
default via 10.0.0.1 dev eth0 metric 100
default via 10.0.0.1 dev eth1 metric 110

DRBD tagged:
default via 10.0.0.1 dev eth0 metric 110
default via 10.0.0.1 dev eth1 metric 100


text:
Q: What Regex would I use to match file names with the format 'number-text-text'? I have code that searches a folder that contains SQL patch files. I want to add file names to an array if they match the following name format:
number-text-text.sql
What Regex would I use to match number-text-text.sql?
Would it be possible to make the Regex match file names where the number part of the file name is between two numbers? If so what would be the Regex syntax for this?

A: This should work:
select '4-dfsg-asdfg.sql' ~ E'^[0-9]+-[a-zA-Z]+-[a-zA-Z]+\\.sql$'

This restricts the TEXT to simple ASCII characters. May or may not be what you want.
This is tested in PostgreSQL. Regular expression flavors differ a lot between implementations. You probably know that?
Anchors at begin ^ and end $ are optional, depending how you are going to do it.

A: The following regex make it halfway there:
\d+-[a-zA-Z]+-[a-zA-Z]+\.sql

Regarding to match in a specific range it gets trickier as regex doesn't have a simple way to handle ranges. To limit the match to a filename with a number between 2 and 13 this is the regex:
([2-9]|1[0-3])-[a-zA-Z]+-[a-zA-Z]+\.sql

A: How about:
\d+-[^-]+-[^-]+\.sql
Edit: You want just letters, so here it is without specific ranges.
\d+-[a-z]+-[a-z]+\.sql - You'll also want to use the i flag, not sure how that's done in c#, but here it is in js/perl:
/\d+-[a-z]+-[a-z]+\.sql/i
Ranges are more difficult. Here's an example of how to match 0-255:
([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])
So to match (0-255)-text-text.sql, you'd have this:
/^(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])-[a-z]+-[a-z]+\.sql/i
(I put the digits in a non-capturing group and matched from the beginning of the string to prevent partial matches on the number and in case you're expecting numbered groups or something).
Basically every time you need another digit of possibility, you'll need to add a new condition inside this case. The smaller the digit you'd like to match, the more cases you'll need as well. What is your desired min/max? AFAIK there's not a simple way to do this dynamically (although I'd love for someone to show me I'm wrong about that).
The simplest way to get around this would be to simply capture the digits, and use native syntax to see if it's in your range. Example in js:
var match = filename.match(/(\d+)-[a-z]+-[a-z]+\.sql/i);
if(match && match[1] < maximumNumber && match[1] > minimumNumber){
    doStuff();
}

A: Your regular expression should be:
(\d+)-[a-zA-Z]+-[a-zA-Z]+\.sql

You would then use the first captured group to check if your number is between the two numbers you desire. Don't try to check if a number is within a range with a regular expression; do it in two steps. Your code will be much clearer for it.


text:
Q: How can I create a persisted state hook that uses cookies and server side rendering? I am trying to setup a hook that stores the selected state on cookies and I wan't it to be able to access cookies via server side rendering. Problem is that the only way I can think of accessing cookies from server side is via the getServerSideProps method exported from pages, and I don't have this method available on this hook. Here is the code:
// src/hooks/persistedState.tsx
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { useCookies } from 'react-cookie';

type Response<T> = [T, Dispatch<SetStateAction<T>>];

export default function usePersistedState<T = any>(key: string, initialState: T): Response<T> {
  const [cookies, setCookie] = useCookies([key]);

  const [state, setState] = useState<T>(() => {
    if (cookies[key]) return cookies[key];

    return initialState;
  });

  useEffect(() => {
    setCookie(key, state);
  }, [key, setCookie, state]);

  return [state, setState];
}

When this hook is executed on the server, "cookies[key]" will always be null even if there is a cookie set. This means that server side rendering will get the "initialState", whilst client side rendering the cookie is present. This leads to inconsistencies when rendering the page.
Here is a working example. Try selecting dark theme and then reloading the page.
Here is my _app.tsx
// src/pages/_app.tsx
import { AppProps } from 'next/app';
import { ThemeProvider } from 'styled-components';
import { Provider as AuthProvider } from 'next-auth/client';
import { CookiesProvider } from 'react-cookie';

import DialogContainer from '../components/shared/DialogContainer';
import { ToastsContainer } from '../components/shared/ToastsContainer';

import { ThemeContextProvider, useTheme } from '../hooks/theme';
import { DialogContextProvider } from '../hooks/dialog';
import { NormalTimerContextProvider } from '../hooks/timer/normal';
import { ToastContextProvider, useToast } from '../hooks/toast';
import { SoundContextProvider } from '../hooks/sound';

import GlobalStyle from '../styles/global';

const AppWithProviders: React.FC<AppProps> = ({ Component, pageProps }) => {
  const { theme } = useTheme();
  const { messages } = useToast();

  return (
    <AuthProvider session={pageProps.session}>
      <CookiesProvider>
        <SoundContextProvider>
          <ThemeProvider theme={theme}>
            <DialogContextProvider>
              <NormalTimerContextProvider>
                <Component {...pageProps} />
                <GlobalStyle />
                <DialogContainer />
                <ToastsContainer messages={messages} />
              </NormalTimerContextProvider>
            </DialogContextProvider>
          </ThemeProvider>
        </SoundContextProvider>
      </CookiesProvider>
    </AuthProvider>
  );
};

const MyApp: React.FC<AppProps> = (props) => (
  <ThemeContextProvider>
    <ToastContextProvider>
      <AppWithProviders {...props} />
    </ToastContextProvider>
  </ThemeContextProvider>
);

export default MyApp;

And here is where I'm trying to access this hook:

// src/hooks/theme.tsx

import { createContext, useCallback, useContext, useState } from 'react';
import { DefaultTheme } from 'styled-components';
import { dark, light } from '../styles/themes';
import usePersistedState from './persistedState';

export type Theme = 'dark' | 'light';

interface ThemeContextProps {
  theme: DefaultTheme;
  toggleTheme: () => void;
  currentTheme: Theme;
}

const ThemeContext = createContext({} as ThemeContextProps);

export const ThemeContextProvider: React.FC = ({ children }) => {
  const [storedTheme, setStoredTheme] = usePersistedState<Theme>('theme', 'light');
  const [theme, setTheme] = useState<DefaultTheme>(storedTheme === 'light' ? light : dark);

  const toggleTheme = useCallback(() => {
    if (storedTheme === 'dark') {
      setTheme(light);
      setStoredTheme('light');
    } else {
      setTheme(dark);
      setStoredTheme('dark');
    }
  }, [setStoredTheme, storedTheme]);

  return (
    <ThemeContext.Provider
      value={{
        theme,
        toggleTheme,
        currentTheme: storedTheme,
      }}
    >
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const themeContext = useContext(ThemeContext);

  if (!themeContext) {
    throw new Error('useTheme must be used within a ThemeContext.Provider');
  }

  return themeContext;
};


text:
Q: How to create a sound map using ArcGIS? I have locations of the points which produce sound. I want to create a sound map based of those points, topography, and the distance at which a sound can travel. On this picture you can see the red dot indicating the source of the sound; yellow dots indicate location which would be impacted by the the sound coming from the source; purple points indicate location where you won't hear the sound coming from the source location, because there is a major ridge blocking it. Is there a way to do this in ArcGIS?

A: Well, I don't know if there are any standard out of the box ArcGIS tools set up for sound modelling, and I know sound-waves do have different properties than light waves that may affect your modelling (ex: echo/reflected sound), but there are out of the box tools for modelling line of sight from given point(s) that may work for what you need.
Take a look at Viewshed modelling in ArcMap or ArcGIS Pro  (you can also look at the Viewshed 2 tool for either software and determine which would best meet your needs).
Anyway, I would suggest reading up on the tools before just going forward with it, but the basic principle is you feed the tool an input point with specific fields containing values for maximum distance, elevation off the ground, angle, etc. and you give an input raster elevation dataset like a DEM.  The result is a raster showing which spots have direct line of site with the input location given your parameters.
There may be other tools out there specific to sound modelling, but if line of sight modelling would get you close enough, looking up Viewshed analysis will get you at least pointed in the right direction.

A: Look up the Sound Mapping Tools, there is a google+ group about it. I'm using it to model sound from tornado sirens, it may be what you are looking for, though it will likely require some troubleshooting on your part to make it work with your data.


text:
Q: Using Pentaho PDI, unable to connect to MariaDB database with SSL enabled in Azure environment From Pentaho PDI, PDI is unable to connect to MariaDB database with SSL enabled in Azure environment. Someone please send me steps to be followed for this.
Here is the error while connecting:

Connection failed. Verify all connection parameters and confirm that the appropriate driver is installed.
SSL connection is required. Please specify SSL options and retry


text:
Q: Rundeck pass common parameters/variable to the flow Consider I have one main flow execution job, I will have many more like this in the future.
I will have few backend flow jobs which will be used as reference jobs in the main flow execution job which I mentioned above.
Things I need to accomplish:

*

*Pass a few command-line arguments in the main flow job for later reference jobs to use

*Also, if reference jobs generate few more variables that should be available for later reference steps to use.

I did not find some very clear documents with the example on the Rundeck site, I would really appreciate it if someone could help on this.
#Update:
After making the text option with the list as plain text, which I able to use in any new step which I add like inline script or command.
But when I wanted to use the same options in Job reference from workflow steps, even after passing the command line argument I could able to get that in my python script.

I passed the argument both way but could not able to get the value of the option in the reference job. As mentioned like this: -source_details ${option.source_details}
and like this as well ${option.source_details}
The child job which I and referring to here is calling the one python script whereas I was checking the command line argument with sys.argv, which is not giving anything extra except the actual python filename.
Correct me if I am missing something here.

A: To do that, you need to pass options as arguments, for example, the child job uses its own options to use as arguments.
I leave an example:
<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='age' value='32' />
        <option name='name' value='Alice' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>bf45b9bd-f8f4-4f00-8aaf-86572b637e05</id>
    <loglevel>INFO</loglevel>
    <name>ChildJob</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <fileExtension>.sh</fileExtension>
        <script><![CDATA[echo "Username: @option.name@";
echo "Age: @option.age@";]]></script>
        <scriptargs />
        <scriptinterpreter>/bin/bash</scriptinterpreter>
      </command>
    </sequence>
    <uuid>bf45b9bd-f8f4-4f00-8aaf-86572b637e05</uuid>
  </job>
</joblist>

And the parent job can pass another options to override child job options:
<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='age' value='25' />
        <option name='name' value='Bob' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>9fa68cd8-5bb0-4341-be32-f58c372cb765</id>
    <loglevel>INFO</loglevel>
    <name>Parent</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <jobref name='ChildJob' nodeStep='true'>
          <arg line='-name ${option.name} -age ${option.age}' />
          <uuid>bf45b9bd-f8f4-4f00-8aaf-86572b637e05</uuid>
        </jobref>
      </command>
    </sequence>
    <uuid>9fa68cd8-5bb0-4341-be32-f58c372cb765</uuid>
  </job>
</joblist>

In few words: you can use options in your jobs (to "receive" from parent job or to use itself), and keep your values across your workflows.
Update with a python3 example
The concept is the same, in the child job you can create some options to receive the values from the parent job, take a look.
Child Job:
<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='arg1' value='one' />
        <option name='arg2' value='two' />
        <option name='arg3' value='three' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>159e14d6-29e2-4fe9-b9b3-b1621d59843d</id>
    <loglevel>INFO</loglevel>
    <name>PythonChildJob</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <fileExtension>.py</fileExtension>
        <script><![CDATA[#!/usr/bin/python3

import sys

print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))]]></script>
        <scriptargs>${option.arg1} ${option.arg2} ${option.arg3}</scriptargs>
        <scriptinterpreter>/usr/bin/python3.8</scriptinterpreter>
      </command>
    </sequence>
    <uuid>159e14d6-29e2-4fe9-b9b3-b1621d59843d</uuid>
  </job>
</joblist>

And the parent job, you can pass options or just strings like -arg1 hello -arg2 from -arg3 mars
<joblist>
  <job>
    <context>
      <options preserveOrder='true'>
        <option name='opt1' value='hello' />
        <option name='opt2' value='entire' />
        <option name='opt3' value='world' />
      </options>
    </context>
    <defaultTab>nodes</defaultTab>
    <description></description>
    <executionEnabled>true</executionEnabled>
    <id>1442dbb7-55e3-45c0-af4b-a58ce5c07582</id>
    <loglevel>INFO</loglevel>
    <name>ParentJob</name>
    <nodeFilterEditable>false</nodeFilterEditable>
    <plugins />
    <scheduleEnabled>true</scheduleEnabled>
    <sequence keepgoing='false' strategy='node-first'>
      <command>
        <jobref name='PythonChildJob' nodeStep='true'>
          <arg line='-arg1 ${option.opt1} -arg2 ${option.opt2} -arg3 ${option.opt3}' />
          <uuid>159e14d6-29e2-4fe9-b9b3-b1621d59843d</uuid>
        </jobref>
      </command>
    </sequence>
    <uuid>1442dbb7-55e3-45c0-af4b-a58ce5c07582</uuid>
  </job>
</joblist>


text:
Q: Swift crash with nil coalescing operator EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000 I'm getting a crash EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000 on the following line and am not sure why.
let personManager = PersonManager.shared ?? PersonManager(user: firebaseUser)

...in this code block...
AppUtils.getFirebaseUser { firebaseUser in
    let personManager = PersonManager.shared ?? PersonManager(user: firebaseUser)
    if personManager.peopleHaveLoaded() {
        ...
    } else {
        ...
    }
}

PersonManager.swift
class PersonManager: NSObject {
    public static var shared: PersonManager?
    init(user: User) {
        ...
        super.init()
        PersonManager.shared = self
    }

    ...
}

What I assumed would happen is the if PersonManager.shared is nil then the nil coalescing operator would call the init function, so either way it was guaranteed to have an instance.
I know that you generally see that crash when you have a dangling pointer, but I thought the nil coalescing operator ?? would take care of that. Any ideas on why it's crashing?

A: it could be the race condition issue. The PersonManager.shared is accessed on two thread at the same time.


text:
Q: Perl - Win32::Gui - Determin text content of text field which has focus I have defined a main window $mw on which I placed several text fields in which an user can provide information.
As soon as the user presses RETURN I want to determin the field which had the focus at that time and read out its text content to process it further.
Here is the code how I defined the text fields:
$mw->AddLabel (
    -name   => "lblSAP",
    -top    => 5,
    -left   => 10,
    -width  => 80,
    -text   => "identity no.",
);

$mw->AddTextfield (               # text field 1
    -name   => "txtSAP",
    -pos    => [ 5, 20 ],
    -size   => [ 80, 20 ],
    -tabstop    => 1,
);

$mw->AddLabel (
    -name   => "lblDokar",
    -top    => 5,
    -left   => 95,
    -width  => 40,
    -text   => "dokar",
);

$mw->AddTextfield (               # text field 2 (there are more)
    -name   => "txtDokar",
    -pos    => [ 90, 20 ],
    -size   => [ 40, 20 ],
    -tabstop    => 1,
    -text   => 'DRW',
);

I have tried method GetFocus() which returns a handle but I don't know how to use this handle to get the text from the textfield (I even don't know whether the method returned the handle of the main window or the control which got the focust :-(.
I tried it like so:
my $handle = $mw->GetFocus();    # get handle of the focusse control
my $txt_text = $handle->Text();   # get text of the focussed control

That didn't work.
Have I overlooked a method which returns the name instead of the handle or how can one access the controls by their handle?


text:
Q: Use PVlib in 1-axis [vertical] and 2-axis PV arrays I would like to know if it is possible to use PVlib to make predictions for 1-axis (vertical) and 2-axis PV arrays. Despite not very common, these PV plants have a big presence in some countries and it would be great to make use of PVlib to make the predictions.
I have been able to get the POA Irradiances for both cases:

*

*1-axis (vertical): I obtained the irradiance multiplying the direct normal irradiance by the angle of incidence projection. Method pvlib.irradiance.aoi_projection.

*2-axis: The PV array surface is always perpendicular to the sun beam. Therefore the irradiance on the plane of array is the direct normal irradiance (dni).

But I got stuck when trying to convert these irradiances into PV power! Since this type of tracking systems are not taken into account in PVlib, I'm not sure of which would be the best approach to get the PV power. So any help in which steps would you recommend me will be appreciated!
Many thanks in advance.

A: The pvlib.tracking.singleaxis function allows you to specify axis tilt. Presumably you can set the axis tilt to 90 degrees and get reasonable results for vertical systems, but you'd have to follow the referenced literature to know if/how it's been validated at that orientation. I've never compared it to data in that orientation.
I'm a bit confused by your question, though. If you already have the POA irradiance and AOI then you're ready to move on to calculating power using the standard PV models (single diode, SAPM, PVWatts): http://pvlib-python.readthedocs.io/en/latest/api.html#pv-modeling


text:
Q: WebAPP Quiz html - read data from google spreadsheet - select sheet What I am trying is to have a little web app published that has a selector to choose one of the sheets in a spreadsheet.
Then, fetch the data in that sheet to build a Quiz.
INDEX.HTML
<!-- Build select options from spreadsheet sheets -->
<?  var ss = SpreadsheetApp.openById('id_key'); ?>
  <select id="select_sheet" onchange="showQuestion(this.value);">
  <option value="" disabled selected style="display:none;">Choose unit</option>
    <? for (var i = 0; i < ss.getSheets().length; ++i) { ?>
      <option><?!= ss.getSheets()[i].getSheetName() ?></option>
    <? } ?>
  </select>

SCRIPT
<script>
function showQuestion(name){

  <? var data = SpreadsheetApp.openById('id_key').getSheetByName(name).getDataRange().getValues; ?>

    document.getElementById("question").innerHTML = <?= data[0][0] ?>;
    document.getElementById("btn0").innerHTML = <?= data[0][1] ?>;
    document.getElementById("btn1").innerHTML = <?= data[0][2] ?>;
    document.getElementById("btn2").innerHTML = <?= data[0][3] ?>;
    document.getElementById("btn3").innerHTML = <?= data[0][4] ?>;
}
</script>

The selector menu is built correctly, however, I can't manage to trigger a function onchange that can read the data from the sheet selected (select_sheet)
How could I achieve this?

A: Your option tag should have value attribute set.
Change:

<option><?!= ss.getSheets()[i].getSheetName() ?></option>

to:
<option value="<?= ss.getSheets()[i].getSheetName() ?>"><?!= ss.getSheets()[i].getSheetName() ?></option>


text:
Q: Given a record of functions, and a record of data of the types acted on by the functions, how to generically apply the function record? The title is slightly inaccurate as my particular case is a bit more involved: rather than the functions in the first record acting directly on values in the second record, they act on a list (or other traversable) of the values. The result of an application for a particular field returns a value of the same type as was in the field, we can assume, if that buys us anything.
An example would be something like:
data Foo = Foo {
  v1 :: Int
, v2 :: Double
}

data FooFuns = FooFuns {
  v1 :: [Int] -> Int
, v2 :: [Double] -> Double
}

So the goal now is to automatically construct e.g.
result = Foo {
  v1 = (v1 FooFuns) (v1 <$> listOfFoos)
, v2 = (v2 FooFuns) (v2 <$> listOfFoos)
}

Currently I'm wrapping up the function on a list of values as a newtype (so it can be used by Higgledy's HKD) and a GADT for the Traversable constraint, but this latter part may be unnecessary, or perhaps better modeled as a typeclass:
data TraversableFun a t where
  TraversableFun :: Traversable t => (t a -> a) -> TraversableFun t a
newtype ListFun a = ListFun {unTravFun :: TraversableFun [] a}

type RecSummaryFuns a = HKD a ListFun

Now RecSummaryFuns a should have the same "field names" (constructor arguments) as a. Ideally there would be a way to easily apply sFuns to recs below to get a single record out.
applyStatFuns :: Traversable t => RecSummaryFuns r -> t r -> r
applyStatFuns sFuns recs = ???

I'm also curious if this is the best way to model the situation: basically I'm applying summary statistics to values held in records, but I need a way to encapsulate those summary statistics for each type of record.

A:
Now RecSummaryFuns a should have the same "field names" (constructor
  arguments) as a

This answer uses red-black-record to construct "generalized records" that have the same field names as the original Foo record. First we must auto-derive some supporting typeclasses:
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wno-partial-type-signatures #-} -- hide some scary types

import Data.RBR (FromRecord (..), Record, ToRecord (..), fromNP, insert, toNP, unit)
import Data.SOP (I (I), NP) -- from sop-core
import Data.SOP.NP (liftA2_NP, liftA_NP) --   useful functions for n-ary products
import GHC.Generics

data Foo
  = Foo
      { v1 :: Int,
        v2 :: Double
      }
  deriving (Show, Generic, FromRecord, ToRecord)

Now we can define a value of our generalized record, whose fields will hold functions. Sadly, we can't employ the usual record syntax:
newtype Func a = Func ([a] -> a) -- helper newtype encapsulating the function

type FooFunc = Record Func (RecordCode Foo) -- wrap every field in Func

exampleFunc :: FooFunc
exampleFunc =
      insert @"v1" (Func head) -- field names give with TypeApplications
    . insert @"v2" (Func last) -- same order as in the original record
    $ unit -- unit is the empty record

The next step is defining this generic apply function with the help of the n-ary product datatype provided by sop-core:
applyFunc ::  _ => Record Func _ -> [r] -> r
applyFunc func foos =
  let foos_NP :: [NP I _] -- a list of n-ary products. I is an identity functor
      foos_NP = toNP . toRecord <$> foos
      listfoos_NP :: [NP [] _] -- turn every component into a singleton list
      listfoos_NP = liftA_NP (\(I x) -> [x]) <$> foos_NP
      listfoo_NP :: NP [] _ -- a single n-ary product where each component is a list
      listfoo_NP = mconcat listfoos_NP
      func_NP :: NP Func _ -- turn the function record into a n-ary prod
      func_NP = toNP func
      resultFoo_NP_I :: NP I _ -- apply the functions to each list component
      resultFoo_NP_I = liftA2_NP (\(Func f) vs -> I (f vs)) func_NP listfoo_NP
   in fromRecord . fromNP $ resultFoo_NP_I -- go back to the nominal record Foo

Putting it all together:
main :: IO ()
main =
  print $
    applyFunc exampleFunc [Foo 0 0.0, Foo 1 1.0]
-- result: Foo {v1 = 0, v2 = 1.0}

Possible disadvantages of this solution are longer compilation times, and also the fact that turning the list-of-Foos into a Foo-with-list-fields inside applyFunc might be inefficient for long lists.
We could ditch red-black-record—we are only using it to preserve field names in the generalized records—and rely on sop-core / generics-sop directly; in that case field names would be handled differently—or we could simply rely on positional matching.


text:
Q: HTML Form Validation make sure the last 2 characters in input field are alphabets I would like to make sure that HTML input field contains the last 2 characters as Alphabets and not any other characters. Is there a way to do it from the HTML pattern itself?
For example:
´Allowed values are:´
123554BA
1248848585GH
8484884rd

So basically the last 2  characters have to be alphabets if not then an error message is displayed and form is not submitted. Is there a way to do it from the HTML side itself using some patter or regex? Any help would be appreciated.

A:

<form>
  <input name="x" type="text" size="10" pattern=".*[a-zA-Z]{2}" required>
  <input name="submit" type="submit" value="Submit">
</form>


text:
Q: Quickly finding array element by pointer I have an array of strings where each string can also be clearly identified by a unique pointer assigned to it. The order of the elements in that array often changes, for example because of sorting.
I want to be able to quickly find the numeric index of an array item just from its accompanying pointer. For example, after sorting the array in the code below, I'd like to have 0 for 0xfeedface, 1 for 0xc0decafe and 2 for 0xdeadbeef. Of course, I don't want to iterate over all elements and manually compare the pointer values because that would be too slow in the real life application. So how can I do that please?
I need a solution that still allows me to use std::sort to sort the items and I also don't have C++11 on my target platform so the solution should not require C++11 or higher. Thanks for your help!
#include <iostream>
#include <string>
#include <vector>
#include <array>

class RowItem
{
public:
   RowItem(std::string text, void *ptr) : m_text(text), m_ptr(ptr) {}
   std::string GetText() {return m_text;}
private:
   std::string m_text;
   void *m_ptr;
};

class RowCmp
{
public:
   RowCmp() {}

   bool operator()(RowItem &first, RowItem &second) const
   {
    return first.GetText().compare(second.GetText()) < 0;
   }
};

int main()
{
    std::vector<RowItem> v;
    RowItem one("C\n", (void *) 0xdeadbeef), two("B\n", (void *) 0xc0decafe), three("A\n", (void *) 0xfeedface);

    v.push_back(one);
    v.push_back(two);
    v.push_back(three);

    std::sort(v.begin(), v.end(), RowCmp());

    for(size_t k = 0; k < v.size(); k++) std::cout << v[k].GetText();

    return 0;
}

A: This is what I came up with after Paul's explanations in the comments. It seems to do the trick. As suggested by Paul, it doesn't sort the original vector but keeps that as it is. Since the positions in the original vector now stay the same, we can use a simple map to map the pointer values to the corresponding index.
All that's left to do now is to merely sort an array of indices referencing the strings in the original vector. After that is done we can easily find the new position of an item using its pointer value by just peeking into the sorted indices vector.
In code, it looks like this:
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <algorithm>

class RowItem
{
public:
   RowItem(std::string text, void *ptr) : m_text(text), m_ptr(ptr) {}
   std::string GetText() const {return m_text;}
private:
   std::string m_text;
   void *m_ptr;
};

class RowCmp
{
public:
   RowCmp(std::vector<RowItem> &v) : m_v(v) {}

   bool operator()(int first, int second) const
   {
    return m_v[first].GetText().compare(m_v[second].GetText()) < 0;
   }

private:
   std::vector<RowItem> m_v;
};

int main()
{
    std::vector<RowItem> v;
    std::vector<int> index;
    RowItem one("C\n", (void *) 0xdeadbeef), two("B\n", (void *) 0xc0decafe), three("A\n", (void *) 0xfeedface);

    index.push_back(0);
    index.push_back(1);
    index.push_back(2);

    v.push_back(one);
    v.push_back(two);
    v.push_back(three);

    std::map<unsigned __int64, int> pmap;
    pmap[0xdeadbeef] = 0;
    pmap[0xc0decafe] = 1;
    pmap[0xfeedface] = 2;

    std::sort(index.begin(), index.end(), RowCmp(v));

    for(size_t k = 0; k < v.size(); k++) std::cout << v[index[k]].GetText();

    std::cout << "Deadbeef at: " << index[pmap[0xdeadbeef]] << "\n";
    std::cout << "Codecafe at: " << index[pmap[0xc0decafe]] << "\n";
    std::cout << "Feedface at: " << index[pmap[0xfeedface]] << "\n";

    return 0;
}


text:
Q: Thinking in angularJS with a javascript background I have worked with javascript before but now I'm getting into angularjs but I am confused about how to do basic stuff.
For example:
In Javascript:
 //here is how i create a constructor
   function createUser(name, age, address)
   {
      this.name = name;
      this.age = age;
      this.address = address;

      this.sayName = function()
      {
        return this.name;
      }
   };

NOTE: the data to the constructor is being provided by user input through a form.
But in AngularJS I would create a module with a controller in it. And the controller will get user input by using the "ng-model" to bind data and $scope to transfer data to the controller. My question is that, do I create the constructor the same way within my angular module as I did in pure javascript and if yes then how do I create (an example would be great). I want to keep my angular module and controller thin and no too much in it.
An example would be very help. And any advice on how to think in angularjs would be great.
Thanks in advance.

A: The cool thing about angular.js is that it allows you to bind POJO on the scope.
You can create it as you already know and just put it on the scope.
I tend to register constructor functions as services, inject them into a controller and then instantiate an object per use.
For example here is the service:
app.factory('User', function() {

  function User(name, age, address) {
    this.name = name;
    this.age = age;
    this.address = address;
  }

  User.prototype.sayName = function() {
    return this.name;
  };

  return User;
});

And a controller:
app.controller('UserCtrl', ['$scope', 'User', function($scope, User) {
  $scope.user = new User('ilan', 30, 'Nahariya');
}]);

And a template:

{{ user.sayName() }}

A: angular is very good client side javascript framework.
you can register a constructor function for your service object using the
"service(name, constructor)" method:
(function() {
  var MyService = function(magicNumber) { // "magicNumber" is injected
    this.getMagicNumber = function() {
      return magicNumber;
    };
  };

  app.service('magicNumberService', MyService);
}());

(function() {
  var MyService = function(magicNumber) { // "magicNumber" is injected
    this.getMagicNumber = function() {
      return magicNumber;
    };
  };

  app.service('magicNumberService', MyService);
}());


text:
Q: Where to put a class on the f.select in Ruby? I am trying to apply a class to a select form element that is built with Ruby.
Here is the f.select:
<%= f.select :within, ["5km", "50km", "100km", "250km", "500km", "1000km"], { :include_blank => 'Anywhere', :selected => (params[:listing][:within] unless params[:listing].nil? || !params[:listing].has_key?(:within)) } %>

Where does the class go? My class is:
:class => 'input-medium'

Thanks!

A: See the documentation, specifically the html_options argument.
Add yet another argument onto the end of what you've posted in your question with:
{ class: "input-medium" }

Altogether that's
<%= f.select :within, ["5km", "50km", "100km", "250km", "500km", "1000km"], { :include_blank => 'Anywhere', :selected => (params[:listing][:within] unless params[:listing].nil? || !params[:listing].has_key?(:within)) }, { class: "input-medium" } %>


text:
Q: Getting the precision of a string number I'm reading values from a text file and converting them to doubles,
then, I'll need to print these values on screen,
and they should look exactly the same as in the text file.
Currently, I'm using max precision when printing,
and I might get results like this:
text value:    8.994279313857e-317
printed value: 8.99427931385706e-317
Each text file may have different precision,
or even different precision for different values (in the same text file),
and I can't store these values as strings for memory concern.
My thought is to store them as doubles with another unsigned int for precision,
is there a way to get the precision out of a string number?

A: You can't have your cake and eat it too! :)
I mean, you want the exact representation of a string in a number, without having to pay the cost in terms of memory (by just storing the string*).
So in that case the best thing you could do is to use a long double, you know the L we append at the end of numeric constants. However, of course this also has its limits (..since our computer also has limits). Moreover, what a waste of space (and processing time) would it be to use a long double for numbers that do not need, since you say that the precisions that you will meet are not fixed. So, you could do that with that code (kindly assembled by this and this answers and the std::numeric limits):
#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>
#include <limits>

typedef std::numeric_limits< double > dbl;

int main() {
    std::ifstream ifile("example.txt", std::ios::in);
    std::vector<long double> scores;

    //check to see that the file was opened correctly:
    if (!ifile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);//exit or do additional error checking
    }

    long double num = 0.0;
    //keep storing values from the text file so long as data exists:
    while (ifile >> num) {
        scores.push_back(num);
    }

    std::cout.precision(dbl::max_digits10); // you can print more digits if you like, you won't the exact representation obviously
    //verify that the scores were stored correctly:
    for (int i = 0; i < scores.size(); ++i) {
        std::cout << std::fixed << scores[i] << std::endl;
    }

    return 0;
}

which gives on my machine:
C02QT2UBFVH6-lm:~ gsamaras$ cat example.txt
3.12345678912345678912345678 2.79
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
3.12345678912345679
2.79000000000000000

If you want to go even further, then use GMP, which is "a free library for arbitrary precision arithmetic". Of course, this will won't come for free in terms of memory usage and processing time, so you should really think twice before using it!

*I feel that you are a victim of premature optimization. If I were you, I would just store the strings and see how this is going, or better yet use a numeric data type, thus losing some precision, making your life far easier. When the project is ready see what results you are getting and if the precision achieved pleases "your boss". If not, use strings (or gmp).

A: The right way is to use some class represents any numeric value faithfully. To represent such values you can use the arbitrary precision integer class with scale factor. For example, it can be defined like the following:
#include <boost/multiprecision/cpp_int.hpp>

// numeric = value/pow(10, scale)
struct numeric {
  /// arbitrary precision integer
  boost::multiprecision::cpp_int value;
  /// point position
  int scale;
};
// for example, 10.1 can be represented with the numeric class exactlty in difference to double :
numeric n{101, 1}; // 101/pow(10, 1)

To print such number you can use helper function which convert objects of the numeric class to std::string:
std::string to_string(const numeric& n)  const
{
  if (n.value.is_zero() && n.scale <= 0)
    return "0";
  bool neg = n.value < 0;
  std::string r;
  {
    std::ostringstream s;
    s << (neg ? -n.value : n.value);
    s.str().swap(r);
  }
  if (n.scale > 0) {
    if (n.scale >= r.length()) {
      r = std::string(n.scale - r.length() + 1, '0') + r;
    }
    r.insert(r.length() - n.scale, 1, '.');
    if (neg)
      r = '-' + r;
  }
  else if (n.scale < 0) {
    if (neg)
      r = '-' + r;
    r += std::string(-n.scale, '0');
  }
  else {
    if (neg)
      r = '-' + r;
  }
  return std::move(r);
}

To construct the numeric object from std::string you can find point position (that is scale of the numeric), remove point and init cpp_int with the cleared from a point string.


text:
Q: OOP-Design: Interface-Methods with implementation-dependent parameters The subject says it already:
I am thinking right now about following design-problem: I define an interface for a specific type of object that contains various methods.
Now i have the problem, that different implementations of this interface, need additional/different method-parameters (because the way they are implemented makes this necessary), which i cannot incorporate into the interface because they are not common to all interface-implementations.
Now i realize that interface implementations could come with their own property-files, loading their additional parameters from there, but what if these parameters need to be passed in at runtime?
Currently i can only think of passing in a Map<String, Object> parameters to overcome this problem - since JDK-Classes like DocumentBuilderFactory are doing something very similar by providing methods like setAttribute(String attName, Object attValue) this
seems like a feasible approach to solve this problem.
Nevertheless i would be interested in how others solve issues like this, alternative ideas?
I dont want to derive from the interface and add additional methods, since in my case i would then have to throw NotImplementException from the methods of the base interface.
UPDATE:
What could be eventual problems of the Map-approach? Implementing classes are free to ignore it completely if they cant make use of additional parameters.
Others might check if the Map contains the desired parameter-names, check the type of their values and use them if valid, throw an exception if not.
I have also seen this being used for the abstract class JAXBContext, so it seems to be a common approach..
UPDATE:
I decided to go for the map-approach, since i dont see any obvious disadvantages and it is being used in the JDK as well (yes, i know this does not necessarily mean much :)
Since i cannot accept an answer on this question, i will just upvote. Thanks for your input!
regards,
--qu

A: You should just initialize each inheritor with its own specific required parameters and let the interface method remain parameter-less, as in:
Interface Runnable:
public interface Runnable {
    public abstract void run();
}

Implementation:
public class MyRunnable {

    private final String myConcreteString;

    public MyRunnable(String myConcreteString) {
        this.myConcreteString = myConcreteString;
    }

    public void run() {
        // do something with myConcreteString
    }
}

A: couldn't you design subinterfaces that extend your (super)interface?
anyhow I see a design problem if you need a method with different parameters depending on the implementation!
edit: code to clarify
interface CommonBehaviour
{
    void methodA(int aParam);
}

interface SpecificBehaviour extends CommonBehaviour
{
    void methodB(int aParam, int anotherParam);
}

class SpecificBehaviourImpl implements SpecificBehaviour
{
   void methodA(int aParam)
   {
      //do something common
   }

   void methodB(int aParam, int anotherParam)
   {
      //do something specific
   }
}

CommonBehaviour myObj = new SpecificBehaviourImpl();

EDIT: You may benefit from the Command pattern:
"Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters."
(source: wikipedia)
I don't think the Map approach to be any good, I may accept it as a fix of existing code that would allow you to have any parameter number and type, but without formal checks! You're trying to define a common behavior (interface methods) given a variable, runtime, state.

A: The point of the interfaces is to have something that is common to all implementations. By trying to do this you destroy the whole reason why interfaces exists.
If you absolutely must do that there is a simple enough way that I have used before.
My answer is in C++ because I'm just not that fluent in other languages. I'm sure there are ways to implement this in java as well.
SomeMethod(void* parameterData);
void* parameterData is a pointer to a struct containing your data. In each implementation you know what you are receiving. You can even have a enum to tell you what kind of data you are receiving.
SSomeData* data = (SSomeData)parameterData
EDIT:
Another approach would be to create a new interface for the parameters: IParameterData.
Inside that interface you have 2 methods: GetParameter(name) and SetParameter(name).
For each implementation of your primary interface you create a implementation of IParameterData.
I hope it helps

A: Can you invert the problem, and implement an interface on the user of these objects which they can query for the additional parameters?
So, when you instantiate these objects implementing the common interface, you also pass in (e.g. to their constructor) an object which provides a way of accessing the additional parameters they might require.
Say your interface has a method 'doSomething' taking parameter 'a', but you have an implementation that needs to know what 'b' is inside this 'doSomething' method. It would call 'getB' on the object you provided to it's constructor to get this information.

A: You should introduce parameter object representing a super-set of possible arguments.

A: In your place, I would consider finding appropriate design pattern to your problem, rather then try to bend the interface methods to suit your needs. Look into Strategy Pattern for starters.


text: Q: How to mask countor plot over basemap python? I want to draw a contour map with basemap-python. I used contour and contourf functions I have data over the land but ı want to mask these datas. Contourf is self masked with basemap but contour is not ? How can ı mask contour plot like contourf ?  Here the image link : https://pasteboard.co/Iegz6ql.png


text:
Q: Add new colums with regex I have a data frame and I want to create a new column of specific words that are in a particular column using pandas.
In this example:
I have a certain text and a list of words
I would like to locate those specific words in a new column.
enter image description here
import re

txt = df['text']
x = re.findall(("apple|banana|orange"), txt)
print(x)

TypeError: expected string or bytes-like object

It is important to note that there are empty cells in the text column

A: You could use pandas Series.str.contains to filter the df and pass the results to a new columns:
import pandas as pd

df = pd.DataFrame([["a"], ["applea"], ["bana"], ["bananak"], ["banana"], ["orange"]],columns=["fruits"])
df["new"] = df[df["fruits"].str.contains(pat=r"banana|apple|orange", na=True)]

>>> df
    fruits      new
0        a      NaN
1   applea   applea
2     bana      NaN
3  bananak  bananak
4   banana   banana
5   orange   orange

A: In your case do
df['text'].str.findall("apple|banana|orange")

A: Assuming you have a list:
lst = ['Apple', 'Orange', 'Banana']
I would do:
    for i, row in df.iterrows():
        for item in lst:
            if item in row['txt']:
                df.loc[i, 'newcol'] = item

Maybe a little convoluted, but that works!


text:
Q: Vue 2 / Typescript, how to cast a prop inline? I have a Vue 2 NuxtJS project setup with Typescript and I'd like to take advantage of the unknown keyword in Typescript.
In my component, I receive a prop declared like so
props: {
  items: {
    type: Array as () => LabelValuePair[],
    required: true,
  },
},

LabelValuePair is declared here
interface LabelValuePair {
  label: string;
  value: unknown;
}

And inside my template, I'd like to use something like this

    {{ item.label }}: {{ item.value }}

The thing is, as well as the ternary operator, the as Typescript keyword is not recognize as valid syntax by the vue compiler.
Is there a solution or a workaround at least to avoid doing something silly like the following?
setup(props) {
  const castItems = props.items.map((item) => ({
    ...item,
    value: item.value as string,
  }));

  return { castItems };
},

A: If LabelValuePair is supposed to be reused and is expected to have string value in a prop, this is the case for generic type:
interface LabelValuePair<T = unknown> {
  label: string;
  value: T;
}

and
  items: {
    type: Array as PropType<LabelValuePair<string>[]>,
    required: true,
  },


text:
Q: python string split only by `/` but not `//` For example, I have a string as:
str = 's3://files.production/object/Image/110/image.jpg'
and I would like to split it into:
's3://files.production' and 'object/Image/110/image.jpg'.
I am wondering if there is any convenient way to do it.


text:
Q: Why won't my JQuery (Kendo) Popup windows update the form controls? I have a KendoGrid/details setup that I am trying to get working. A button in the grid opens a popup window where edits are made, and saved. The window is opening, and the template is getting the data, but the "click" event that I have wired up to the [Update] link isn't working. Looking around on the interwebs, I see that there is a problem with the popup (JQuery) not opening within the form, but I don't know how to attach the "form.append" to it, since it's a KendoWindow (I am new to both).

Update

/*Popup code*/
function showDetails(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    wnd.content(detailsTemplate(dataItem));

    wnd.center().open();
}

/*Code to wire up the onClick event to the "update" link*/
function lnkUpdate_0858_OnClick() {
    return $("#lnkUpdate_0858").click(function() {
        alert("lnkUpdate_0858_OnClick");
    });
}

To add a little background, I am researching the problem. Looking at the KG page on Telerik's site
[http://docs.telerik.com/kendo-ui/getting-started/web/window/overview], I can see that I should be able to add a custom click to the [.data("kendoWindow")]. I have taken a look at this code. While it does work for the demo, it does NOT for my page. I think that it is failing on my page because I am using a template, and the ID of the link is not something that the ".wrapper.find" method can locate.
Also, the page suggests making use of ".appendto" to attach it (the kendoWindow) to the current form, which I have also done.
I am able to connect to the link click, and retrieve the values from the form fields on the popup window using the following code.
function ClickButton(ButtonID) {
    var x = $("[id$='tbAlertID']").val;
    $("[id$='" + ButtonID + "']").click();
}

function PopulateASPDotNetForm() {
    $("[id$='tbAlertID']").val(tbAlertID);
        ClickButton("btnUpdateAlert2");
    alert("PopulateASPDotNetForm" + tbAlertID);
}

function LoadDataFromPopupForm(PopupForm) {
    tbAlertID = PopupForm.find('.tbAlertID').val();
}

$(document).on('mousedown', ".LinkButton", function() {
    PopupForm = $(this).parent().parent();
    LoadDataFromPopupForm(PopupForm);
    PopulateASPDotNetForm();
    return;
});

I am running into a problem with the click of the ASP.net button from JQuery. The click event fires, and I can catch it in the Visual Studio debugger. When I do, the value of the fields changed in the JQuery popup window are not visible to ASP.net, but the values of fields changed outside of the JQuery popup window are visible.

A: It wouldn't update because I wasn't doing it right. The KendoGrid control comes with the ability to attach commands, like "edit", "update", and "destroy". Using these, can attach managed buttons that will automatically update what the user sees in the grid. You still have to attach methods to the save event to update it in the database, but it was a lot easier than what I was trying to do.


text:
Q: Cannot use numbers with commas in Google Charts I have loads of big data that I pull from a database and into an array where I really need commas for usability. So, in SQL I Format the numbers and they're really nice. When I use them in Google Charts, the charts break. So I remove the Format in SQL and display raw numbers and Google Charts is happy. What a dilemma. Usability of both would be splendid.
Here's my current beautiful chart code.
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart'],
callback: drawChart});

function drawChart() {
var tableRows = [];
var results = document.getElementById('allstage');
Array.prototype.forEach.call(results.rows, function(row) {
var tableColumns = [];
Array.prototype.forEach.call(row.cells, function(cell) {
var cellText = cell.textContent || cell.innerText;
switch (cell.cellIndex) {
case 0:
tableColumns.push(cellText.trim());
break;

default:
switch (row.rowIndex) {
case 0:
tableColumns.push(cellText.trim());
break;

default:
tableColumns.push(parseFloat(cellText));
    }
  }
});
tableRows.push(tableColumns);
});

var data = google.visualization.arrayToDataTable(tableRows);
var formatter = new google.visualization.NumberFormat(
     {negativeColor: 'red', negativeParens: true, pattern: '###,###'});
    formatter.format(data, 1);

var options = {

title: 'All Stages In Percent',
titleTextStyle: {color: 'black', fontSize: 28},
 bar: {groupWidth: '70%'},
    chartArea: { backgroundColor: { fill: '#F0F8FC', opacity: 100 }},
    fontSize:12,
    legend:  { position: 'right', textStyle: { color: 'black', fontSize: 12}},
     tooltip: {isHtml: true},
      is3D: true,
    };

var chart = new google.visualization.PieChart(document.getElementById('allstage_div'));

chart.draw(data, options);
}

Any ideas? I tried to post a image of my problem but this thing says "You need at least 10 reputation to post images!" Wonderful... What's a reputation among friends? The simple image is at  HTTP : // i.ibb.co/DYZWbkc/Capture.jpg


text:
Q: android: how to save login credentials from server to phone cache I have web services and I want to create a class that should takes an email and password from server after authentication in hash table, and then saves email and password in shared preferences.

A: Try this class to call webservice in your app, i am sharing get and post both methods you can use any one as per your need.
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;

public Context getContext() {
    return context;
}

public void setContext(Context context) {
    this.context = context;
}

public CallService(String url1) {
    this.url = url1;

}

public String getResponceWithPost() {

    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
        HttpConnectionParams.setSoTimeout(httpParameters,500000);
        HttpConnectionParams.setTcpNoDelay(httpParameters,true);

        HttpClient hc = new DefaultHttpClient(httpParameters);
        HttpPost post= new HttpPost (url);

        HttpResponse rp = hc.execute(post);

        // //////////////
        if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            str = EntityUtils.toString(rp.getEntity());
               Log.e("Calling service", str);
                return str;
        }
    } catch (IOException e) {

        e.printStackTrace();
    }

    return str;
}

public int getResponceWithGet() {
      int code = 0;

    try {
        HttpClient hc = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);

        HttpResponse rp = hc.execute(get);

     code=  rp.getStatusLine().getStatusCode();
            return code;

    } catch (IOException e) {
        Log.e("calling service", e.toString());
        e.printStackTrace();
    }
    catch(Exception e)
    {
        Log.e("calling service", e.toString());
    }

    return code;
}}

this will return response from server like email password or other details.
and you can save these details in sharedpreference .
for shared preference follow this -
http://developer.android.com/guide/topics/data/data-storage.html#pref
and in your activity call your url using my call service class like this-
declare your hashTable in activity like this
Hashtable hashtable = new Hashtable();

call this method
new checkForLogin().execute();

and your async class
class checkForLogin extends AsyncTask<Void, Void,String>
{

    @Override
    protected void onPreExecute() {
        progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");

    }
    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub

Parse your json data here that will be in data

CallService  cl2=new CallService("your server url here");
        Log.e("login url is",""+Urls.loginurl);

        data=cl2.getResponceWithPost();

        Log.e("server response data","data = "+data);

hashtable.put("email″, data.getString("email"));
hashtable.put("pass″, data.getString("pass"));

        return null;

    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        progress.dismiss();

    }

i hope this ll help you.


text:
Q: How can I extract and pair the values of an array based object I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
  [{ name: 'cookie1', value: 'false' },
  { name: 'cookie2', value: '123' },
  { name: 'cookie3',value: 'abc'}]

What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc

I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
  return {
    "name": d.name,
    "value": d.value,
  }
})

A: One way to do this is to map the array of objects into name: value strings and then join them with , :

const data =   [{ name: 'cookie1', value: 'false' },
  { name: 'cookie2', value: '123' },
  { name: 'cookie3',value: 'abc'}]

const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')

console.log(result)


text:
Q: Cannot find symbol error bufferedreader THIS IS MY CODE
 import java.IO.*;
 class jed {
    public static void main (String args[]){

    BufferedReader datain = new BufferedReader(new InputStreamReader(System.in));
    String name =" ";
    System.out.print("What is your name?:");
    try{
       name = datain.readline();
    } catch(IOException e) {
      System.out.print("Error");
    }

    System.out.print("Your name is" + name); } }

THIS IS THE ERROR
 D:\>javac jed.java jed.java:1: error: package java.IO does not exist
 import java.IO.*; ^ jed.java:4: error: cannot find symbol
 BufferedReader datain = new BufferedReader(new
 InputStreamReader(System.in)); ^   symbol:   class BufferedReader
 location: class jed jed.java:4: error: cannot find symbol
 BufferedReader datain = new BufferedReader(new
 InputStreamReader(System.in)); ^   symbol:   class BufferedReader
 location: class jed jed.java:4: error: cannot find symbol
 BufferedReader datain = new BufferedReader(new
 InputStreamReader(System.in));^   symbol:   class InputStreamReader
 location: class jed jed.java:10: error: cannot
 find symbol catch(IOException e){^   symbol:  class IOException                                                      location: class jed 5 errors

I will appreciate any help I can get to fix this issue. Thank you

A: Java is case sensitive. You should import java.io.*, instead of java.IO.*.

A: Java is case sensitive.
Your import is wrong. Change
import java.IO.*;

to
import java.io.*;

In defence of the compiler it does actually tell you the problem clearly:

error: package java.IO does not exist import java.IO.*;

A: You have to change .readline()
to .readLine(), because java is case sensitive.


text:
Q: Jhipster upgrade In our organization we have several JHipster generated projects, they were done with version 3.0.0 and we haven't upgraded them since.
I've been working on upgrading one of them for the past 5 days, please find breakdown below:
I have tried three different approaches:
1.- Use the jhipster:upgrade tool
Steps:
This process could break down into several steps such as:
1.- Creating local npm folder to be able to install generators for different jhipster versions with no persmission issues
2.- Erasing all old installations of yo and jhipster
3.- Cloning project and creating dev branches
4.- Erase .jhipster folder so entities are not affected by upgrade
5.- Once the upgrade code runs, we need to tweak several files/dependencies so the mvn clean/install works
Complications
After applying all these steps, I find that the 2nd level cache from Hibernate refuses to work, asking me to include all classes in cache, I try several fixes/workarounds such as:
1.-  Deleting liquibase from project
2.-  Configuring DatabaseConfiguration.java with old settings and downloading old versions of libraries for this
3.-  Configuring dev.yml file to start as in old version
4.-  Disable 2nd level cache
After doing this the cache and liquibase do not represent a problem, however, we go to another complication, this time involving the RememberMe services, the JhipsterProperties parameter for the constructor comes in empty, I debugged for a while, finding no relevant information on this and decided to drop this and try with method 2
2.- Re-create the upgrade steps manually.
For this method I follow the script found in github:  https://github.com/jhipster/generator-jhipster/issues/3761
I installed locally the 3.4.0 version of Jhipster to try and make a smooth transition and I do not erase the entities as in method 1, however now the project files just won't load, the upgrade_branch becomes resilient and whatever I do, I end up needing to erase the project and re-clone it
3.- Use the jhipster command in the project root folder
I use version 3.4.0 for this too
The upgrade process runs smooth, changes the version in the package.json file and links fine to the database first attempt (except for having to delete liquibase again, which recreates itself during upgrade)
However we face a new issue with the RememberMe tokens:  Custom Persistence RememberMeServices]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: key cannot be empty or null
A little bit of research:
There are a number of reports and git-hub tickets stating that jhipster upgrade doesn't work properly and, in fact, at this time, on the latest version, users are told that they may need to upgrade in a manual way as per this ticket: https://github.com/jhipster/generator-jhipster/issues/5883
I also consulted an ex-colleague who tried this and reckoned that it was much easier to make a new project and copy the necessary code rather than trying to manually migrate the conflicting pieces of code that arouse after doing an upgrade
Now, I also read in the git hub tickets that plenty of users seem to upgrade their projects seamlessly, so the questions I have would be:
1.- Am I facing the same issues as other developers but fail to know the technologies enough as to be able to solve them?
2.- Is there a solution at all to these kind of issues (2nd level cache and JhipsterProperties not holding key/not being passed as variable to constuctor)?
EDIT
I have found answer to the missing key in JHipsterProperties.  When running yo jhipster it asks you if you want to overwrite a series of files, I just marked yes for all and so it overwrote the application.yml where the key is stored for the properties, not restoring it or creating a new one.  I tried running it again after cloning the project from master and it worked fine by choosing not to overwrite application.yml (but overwriting the rest of the files)
EDIT 2
I finally managed to sort the hibernate cache issue by:
1.-  Manually adding the cache for all entities in the CacheConfiguration.java file, such as this:
cm.createCache(org.wwarn.drugquality.domain.AntiretroviralSurveyData.class.getName(), jcacheConfiguration);
            cm.createCache(org.wwarn.drugquality.domain.Country.class.getName(), jcacheConfiguration);

And so on with all (48) entities
2.- Jhipster team now defaults cache region to the jhipster config properties looking like this:
hibernate.cache.region.factory_class: io.github.jhipster.config.jcache.NoDefaultJCacheRegionFactory

I had to change it to this:
hibernate.cache.region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory

And now it works just fine
Front end is broken and many customized code will need to be modified/replaced, but I finally managed to upgrade my project from v3.0.0 to v4.0.8 (using the yo jhipster command, as the upgrade tool just doesn't work for me) Now the application is rolling smooth on the backend, and ready for a slow migration to Angular 2-4

A: Most of the issues of the upgrade were related to Windows and yarn. If you use Linux or OSX and npm < 5, you're in a better shape.
Also, if you run it often, issues will be easier to solve than a big version leap as you experienced.
This tool is very useful but it's still relatively new, things will get better over time.
You can run manually the steps from upgrade by just reading its code, it's quite easy to follow and read its documentation.


text:
Q: comparison between two floating value in python I am new to python programming.
I have written some simple python code as shown below:
#!/usr/bin/python
import sys

def reducer():
    bigSale = 0
    oldKey = None
    for line in sys.stdin:
        data = line.strip().split("\t")
        if len(data) != 2:
                continue
        thisKey, thisSale = data
        print oldKey,bigSale,thisKey,thisSale
        if not oldKey:
                oldKey = thisKey
                bigSale = thisSale
                print "This is first if and value of oldKey and bigSale are ",oldKey," ",bigSale
        elif oldKey and oldKey != thisKey:
                print "{0}\t{1}".format(oldKey, bigSale)
                oldKey = thisKey
                bigSale = 0
        elif(oldKey and oldKey == thisKey and thisSale > bigSale):
                print "Observe the expression : ", thisSale, " > " , bigSale , " has a boolean value of ", thisSale > bigSale
                print "This is the second elif construct and value of bigSale before assignment is ",bigSale
                bigSale = thisSale
                print "This is the second elif construct and value of bigSale after assignment is ",bigSale
                print "Now the new value of oldKey and bigSale are: ",oldKey," ",bigSale
    if oldKey != None and thisSale > bigSale:
        print "{0}\t{1}".format(oldKey, bigSale)

def main():
        reducer()

main()

I am passing below data as input:
Anchorage       22.36
Anchorage       298.86
Anchorage       6.38
Aurora  117.81
Austin  327.75
Austin  379.6
Austin  469.63
Boston  418.94
Buffalo 483.82
Chandler        344.09
Chandler        414.08
Chicago 31.08
Corpus Christi  25.38
Fort Wayne      370.55
Fort Worth      153.57
Fort Worth      213.88
Fremont 222.61
Fresno  466.64
Greensboro      290.82
Honolulu        345.18
Houston 309.16
Indianapolis    135.96
Las Vegas       53.26
Las Vegas       93.39
Lincoln 136.9
Madison 16.78
Minneapolis     182.05
Newark  39.75
New York        296.8
Norfolk 189.01
Omaha   235.63
Omaha   255.68
Philadelphia    351.31
Pittsburgh      475.26
Pittsburgh      493.51
Portland        108.69
Reno    80.46
Reno    88.25
Riverside       15.41
Riverside       252.88
San Bernardino  170.2
San Diego       66.08
San Francisco   260.65
San Jose        214.05
San Jose        215.82
Spokane 287.65
Spokane 3.85
Stockton        247.18
Tulsa   205.06
Virginia Beach  376.11

When I see the output with the help of debugging statements, I found that float comparison is not happening as expected
Please find below snippet of the output i got when i run the code on sample data:
None 0 Anchorage 22.36
This is first if and value of oldKey and bigSale are  Anchorage   22.36
Anchorage 22.36 Anchorage 298.86
Observe the expression :  298.86  >  22.36  has a Boolean value of  True
This is the second elif construct and value of bigSale before assignment is  22.36
This is the second elif construct and value of bigSale after assignment is  298.86
Now the new value of oldKey and bigSale are:  Anchorage   298.86
Anchorage 298.86 Anchorage 6.38
Observe the expression :  6.38  >  298.86  has a Boolean value of  True
This is the second elif construct and value of bigSale before assignment is  298.86
This is the second elif construct and value of bigSale after assignment is  6.38
Now the new value of oldKey and bigSale are:  Anchorage   6.38
Could anyone please help me where i am doing it wrong?

A: It seems like the problem you are facing is that you compare string to string instead of float to float
When comparing strings indeed 6.38 > 298.86 has a Boolean value of True since 6 is greater than 2.
In order to compare float to float, you'll need to cast the string to a float, using float(str)
e.g.
>>> float('1.99')
1.99

For example, you can change your code (in all cases when you compare float values) in the following style:
    elif(oldKey and oldKey == thisKey and float(thisSale) > float(bigSale)):

Also, you can assign the values to the variables as float, instead of as string. Again using casting to float using float(str_number)
More info about python data type conversion:

*

*https://docs.python.org/2.7/library/functions.html?highlight=float#float

*http://www.pitt.edu/~naraehan/python2/data_types_conversion.html


text:
Q: FFMPEG Audio Issues Youtube Live This issue may have more to do with youtube than ffmpeg, but hopefully someone can help anyway.
I am having the exact issue described in this post https://productforums.google.com/forum/#!topic/youtube/nHTb7ilKvrw. I would have added to it, but it is locked for some reason.
I create a stream from a local webm file on my computer using ffmpeg. This file sounds perfectly fine, and still sounds fine when it is sent to platforms other than youtube live (twitch/facebook). On youtube live, however, the audio has static and crackles during the live feed, but the archive of the video on youtube (after processing) sounds perfectly fine. The ffmpeg command is
ffmpeg -re -i test.webm -acodec aac -vcodec libx264 -ar 44100 -f flv rtmp://a.rtmp.youtube.com/live2/${your_key}
Webm files from this fiddle (https://jsfiddle.net/2rgv7pgj/) will have the issue.
If someone could offer advice it would be greatly appreciated.

A: I managed to fix this on the client side using the DynamicsCompressorNode in the Web Audio API. For some reason the audio was clipping on youtube exclusively. This filter stopped the clipping and fixed the poor quality on youtube.


text:
Q: How can I download large files from Google Drive? I uploaded a file on Google Drive, which is 1.3 GB in size.
Now when I try to download it through the browser (Firefox), it only downloads 1 GB,
and then downloading fails.
I tried to copy the downloading link and paste it into a download manager,
but then Google redirects to an HTML page "ServiceLogin" and downloads it instead.
I also tried to install Google Drive for PC, but it proved to be a piece of malware,
messed up things on my computer, caused me a lot of troubles.
How can I download this large file from Google Drive without this Google Drive for PC?
Thank you.

A: Google Drive Sync helped me with this. Either you can install the sync and download or sync all files to local pc.
Or
Create a new drive and share the files required to this drive, then sync this drive to local pc using google drive sync.

A: You can use Python & GDown
It takes care of the large file warning by Google and should download your file without a problem.


text:
Q: javascript get elements inside other elements I'm trying to use less an less jQuery, but I find it hard for dom elements selection or manipulation.
I don't know well how to ask this question, but I'm trying to loop over elements inside an element coming from a forEach loop.
this might be clearer with code:
const sections = document.querySelectorAll('.section')
sections.forEach(section => {
    // now get an array of boxes elements INSIDE this section (and only this one)
})

In jQuery I would do it this way:
$('.section').each((key, section) => {
    $('.box', $(section)).each((key2, item) => {
        console.log($(item))
    })
})

A: querySelectorAll can be called not only on the document to find descendants of the document, but also on nodes to find descendants of that node that match the selector.
document.querySelectorAll('.section').forEach(section => {
  section.querySelectorAll('.box').forEach((box) => {
    // ...
  });
});

If the situation warrants, you can also combine the selectors and use only a single querySelectorAll.
document.querySelectorAll('.section .box').forEach((box) => {
  // ...
});


text:
Q: Support multiple screens for android and libgdx I was starting with game development for android and i have one question or i need suggestion. At the moment i have problem if the same picture i use for all screen (mobile tablets itd itd), in one screens look cool but other strange. How can i slove this problem.
Yes i know i must suport for other widths. But the main problem is what i must support,

*

*denisty,

*size?

*resolution

or maybe small/normal/large etc..screens?
What is the bast way to support,

A: If you use sprite batch then you can use batch.setprojectionmatrix(yourOrthographicCamera.combined) in this way the sprites will resize automatically  . if you use stage and actors then search in google about libGDX stage viewports .

A: If you are using latest version of libgdx. The stage.setViewPOrt changed.
stage = new Stage(new StretchViewport(width, height)); // OR
stage.setViewport(new StretchViewport(width, height));

or
stage = new Stage(new ExtendViewport(width, height)); // OR
stage.setViewport(new ExtendViewport(width, height));

to fit your difference ratio of screen.


text:
Q: Finding the right file path for a Perl file on a windows server? Using Cygwin on my local machine, the following Perl code works:
system "cmd /c start 'c:\\cygwin\\home\\fl\\CSmtp_prac.exe'";

when I try to move the Perl file on to Windows SQL server 2008, I can't get it to run.
It says it can't find it on the server even though it is indeed there and I have updated the path to do so. The icon of the perl file is of perl so I know the server has perl on it.  I'm wondering what is wrong with my syntax.
Here's what I have on the perl file that is on the server: system "cmd /c start 'c:\PDAutomation\CSmtp_prac.exe'";

A: Lose the single quotes inside the system call. They are fine in Cygwin and the bash shell, but in the Windows shell it will look for filenames with a literal ' character in them.
Try one of these instead, which should work in both Cygwin and MSWin32:
system 'cmd /c start c:\cygwin\home\fl\CSmtp_prac.exe';
system q(cmd /c start c:\cygwin\home\fl\CSmtp_prac.exe);
system "cmd /c start c:\\cygwin\\home\\fl\\CSmtp_prac.exe";
system qq(cmd /c start c:\\cygwin\\home\\fl\\CSmtp_prac.exe);


text:
Q: iOS - Copy specific images from bundle resource path to Documents Dir I am trying to get selected files from bundle resourcePath on application launch. I am able to get all the files at resource path but when i try to get files with name stored in BGImage.plist i get error "cocoa 260" (item not found at specified path).
But images are present at the path and I can get all the images by doing [fileManager copyItemAtPath:bundlePath toPath:BGImagePath error:nil];
code below doesnt work.. (reference : iPhone (iOS): copying files from main bundle to documents folder error )
NSString* BGImagePath =[[[AppDelegate applicationDocumentsDirectory]
                         URLByAppendingPathComponent:@"BGImages" isDirectory:YES]
                        path];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:BGImagePath error:&error];
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSString *BundleImagePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"BGImages.plist"];          //has file names
bgImagesArray = [[NSArray arrayWithContentsOfFile:BundleImagePath] retain];

if (folderContents.count == 0) {
    for (id obj in bgImagesArray) {
            NSError* error;
            if ([fileManager
                  copyItemAtPath:[bundlePath :obj]
                  toPath:[BGImagePath stringByAppendingPathComponent:obj]
                  error:&error])
                NSLog(@" *-> %@", [bundlePath stringByAppendingPathComponent:obj]);
       }
    }
}

Is there any other elegant way to get specific files without storing names in plist?

A: This following code fixed the issue:
 NSFileManager* fileManager = [NSFileManager defaultManager];
 NSString* bgImagePath =[[[AppDelegate applicationDocumentsDirectory]
                         URLByAppendingPathComponent:@"BGImages" isDirectory:YES]
                        path];
 [fileManager createDirectoryAtPath:bgImagePath withIntermediateDirectories:NO   attributes:nil error:nil];
  NSArray * folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bgImagePath error:nil];
 NSString * bundlePath = [[NSBundle mainBundle] resourcePath];
 NSString * bundleImagePath = [[NSBundle mainBundle] pathForResource:@"BGImages" ofType:@"plist"];
 NSArray* bgImagesArray = [NSArray arrayWithContentsOfFile:bundleImagePath];
 if (folderContents.count == 0) {
    [bgImagesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSString * sourcePath = [bundlePath stringByAppendingPathComponent:obj];
        NSString * destinationPath = [bgImagePath stringByAppendingPathComponent:obj];
        [fileManager copyItemAtPath:sourcePath toPath:destinationPath error:nil];
    }];
}