text:
Q: How to query firebase keys with a substring I want to query Firebase that contains an input. for example in the database structure below, I would like to query all nodes that contains "4140"
so I use this code

  var catref = Cataloguedatabase.ref("/Listing Search/");

    return catref.once('value').then(function(snapshot){
    snapshot.forEach(childSnapshot => {

    let snapdb = childSnapshot.val();
    let key = childSnapshot.key;
    //use ES6 includes function
    if(key.includes(schname)){

    console.log(childSnapshot.val());
    var searchresults = childSnapshot.val();
    var container = document.getElementById('listing_gallery');
                      // container.innerHTML = '';

    var productCard = `

                              `
         container.innerHTML += productCard;
                    }
                })
              })

This works but the problem is that it first query all the child and sort through the array.This is ok for node with few children but when it gets to thousands of children, it becomes impractical. is there a away i can only query key the contains the value in firebase and if not how else can i implement this?

A: As Doug says, there is no way to query for values that contain a certain string. But you can query for keys that start with a certain substring:
return catref.orderByKey().startAt("4140-").endAt("4140-\uf8ff").once('value').then(function(snapshot){

This will just match the child nodes whose key starts with 4140-.

A: What you're asking is not possible with Firebase Realtime Database.  There are no substring queries.
If you're only interested in the first four characters for your query, what you can do is store that string as a child inside that node, then orderByChild() on that child to find only those items that begin with a certain four character sequence.
You can read more about ordering in the documentation.


text:
Q: react-navigation nested drawer items I'm trying to create nested menu in react native drawer. I can create the menu as below but I have to find a way to group items and put them into accordion. This is how I currently create the menu:
import React from 'react';
import PropTypes from 'prop-types';
import { SafeAreaView, ScrollView, StyleSheet,View } from 'react-native';
import { DrawerItems,createDrawerNavigator  } from 'react-navigation';
import { Container, Content, Text, List, ListItem } from "native-base";
import {Image,ImageBackground} from "react-native";
import logo from '../images/logofullwhite200.png';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 20
  }
});

const DrawerComponent = props => {
  const skippedItems = Object.keys(props.drawerItems).filter(name => props.drawerItems[name].skip);
  return (
    <ScrollView style={styles.container}>
      <SafeAreaView style={styles.container} forceInset={{ top: 'always', horizontal: 'never' }}>
        <Content>
          <ImageBackground
            source={{
              uri: "https://raw.githubusercontent.com/GeekyAnts/NativeBase-KitchenSink/master/assets/drawer-cover.png"
            }}
            style={{
              height: 120,
              alignSelf: "stretch",
              justifyContent: "center",
              alignItems: "center"
            }}>
            <Image
              square
              style={{ height: 50, width: 150 }}
              source={logo}
            />
          </ImageBackground>
          <DrawerItems
            {...props}
            onItemPress={({ focused, route }) => {
              if (!skippedItems.includes(route.routeName)) {
                props.onItemPress({ focused, route });
              }
            }}
          />
        </Content>
      </SafeAreaView>
    </ScrollView>
  );
};

DrawerComponent.propTypes = {
  onItemPress: PropTypes.func,
  drawerItems: PropTypes.object
};

export default DrawerComponent;

this is the data example
"CreateSale": Object {
    "navigationOptions": Object {
      "drawerLabel": Object {
        "$$typeof": Symbol(react.element),
        "_owner": null,
        "_store": Object {},
        "key": null,
        "props": Object {
          "i18nKey": "sale.create_sale",
        },
        "ref": null,
        "type": [Function I18nextWithTranslation],
      },
    },
    "screen": [Function KeyboardAwareNavigator],
    "userInfo": Object {
      "showOnLogin": true,
    },
  },
  "Customer": Object {
    "navigationOptions": Object {
      "drawerLabel": Object {
        "$$typeof": Symbol(react.element),
        "_owner": null,
        "_store": Object {},
        "key": null,
        "props": Object {
          "i18nKey": "list.title",
        },
        "ref": null,
        "type": [Function I18nextWithTranslation],
      },
    },
    "screen": [Function KeyboardAwareNavigator],
    "userInfo": Object {
      "showOnLogin": true,
    },
  }

This is how index.tsx looks
export default new ClientModule({
  router: <MainScreenNavigator />,
  onAppCreate: [
    async (modules: ClientModule) =>
      (ref.navigator = createDrawerNavigator(
        {
          ...modules.drawerItems
        },
        {
          // eslint-disable-next-line
          contentComponent: props => <DrawerComponent {...props} drawerItems={modules.drawerItems} />
        }
      ))
  ]
});

I have to put the items in to accordion, they have to look nested such as as below:
Outlets

*

*Customers

*Customer

A: no need to make nested drawer. you can use react-native-collapsible and make custom drawerItem like accordion
yarn add react-native-collapsible

import Collapsible from 'react-native-collapsible';

() => (
  <Collapsible collapsed={isCollapsed}>
    <SomeCollapsedView />
  </Collapsible>
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 3 Type Comparisons So I am trying to override the eq operator of a custom class, but in doing so I want to check that the two objects are the same type, so that I can compare the attributes within them.
MyScript.py
class myClass:
   def __init__(val):
      self.myVar = val

   def __eq__(self, other):
      assert type(other) is type(self)
      return self.myVar == other.myVar

MyFunc.py
from MyScript import *
def myFunc(val):
   return myClass(val)

The above two are within a MyPackage package
My main looks similar to this
main.py
from MyPackage import *
if __name__ == "__main__":
   a = myClass(1)
   b = myFunc(1)

   print(a == b)

However I am getting an assertion error saying that the two objects are of different classes
type(a) == "<MyPackage.myClass>"
type(b) == "<myClass>"

I didn't write all of my code out, but is there something I am missing with Python 3 that is stopping the classes from being the same when they are created from different places?

A: The problem appears to be caused by an errant import. But there is another way to check the instances that is worth considering. Your solution doesn't work for inheritors of myClass. Instead you could do
class myClass:
    def __init__(val):
        self.myVar = val

    def __eq__(self, other):
        if isinstance(other, myClass):
            return self.myVar == other.myVar
        else:
            raise TypeError(f"'==' not supported between instances of '{self.__class__.__name__}' and '{other.__class__.__name__}'")

It would work for child classes of myClass and raises the more typical error.


text:
Q: Building jar with dependent libraries in Teamcity I am using IntelliJ and Maven for building some Java libraries and application.
The app jar depends on a library built locally within the app's pom.xml declaration:
<dependency>
<groupId>GrpID</groupId>
<artifactId>ResultsExporterLib</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

Locally building, everything works fine, as I have defined tag "<localRepository>" in maven's .m2\settings.xml.
However, when I try to build the .jar app using TeamCity build management system, I get the following error in Teamcity build log:

[Step 1/3] [ERROR] [Step 1/3] Failed to execute goal on project
  Healthcheck: Could not resolve dependencies for project
  GrpID:ResultsExporterLib:jar:1.0-SNAPSHOT: Could not find artifact
  GrpID:ResultsExporterLib:jar:1.0-SNAPSHOT [14:12:05][Step 1/3] [ERROR]
  For more information about the errors and possible solutions, please
  read the following articles: [14:12:05][Step 1/3] [ERROR] [Help 1]
  http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
  [14:12:05][Step 1/3] Process exited with code 1

Note that the library has already been configured in Teamcity's "Artifact Dependencies" (for the app) as following:
"Depend on: " => package ResultsExporterLib
"Get artifacts from:" => "Latest Successful build"
"Artifacts rules: " => "+:ResultsExporterLib-1.0-SNAPSHOT-jar-with-dependencies.jar"

Any ideas/ suggestions on how the Teamcity build error can be resolved?
Is it anything to do with repository configuration for Teamcity?

A: Artifact Dependencies in TeamCity are just files / archives you can pass from one build to another. Maven will not find them if you don't extract them to the correct folder - which isn't the idea anyway.
Maven exchanges artifacts (same word, completely different thing) via repositories. Either the local one or a repository proxy (Nexus, Artifactory and so on). You would need to publish you dependency to such a repository in order to allow maven to find it.
What will work faster is if you run the build of your dependency (mvn install) and then the dependant build on the same agent. This way the artifact will be in the local maven repository of the agent. You can define this restriction in the snapshot dependency in teamcity. The artifact dependency is not needed at all.
So: buildA -> buildB (Snapshot Dependency on buildA, on same agent)
should do for now.
This can only be a workaround for now. Artifacts for maven need to go into a repository. This repository is configured in teamcity in the settings.xml you can pass on the maven build steps so it can resolve in-house maven artifacts.
Hope it works :)


text:
Q: How can I run a function with a specific duration of time? I am new to python and I wonder how can we set a specific time for a function to run.
Considering here I have a dataframe with 891 rows called df which has a column name body_text I want to perform a function call summary(to summary the text) through the row of dataframe and store them into a new dataframe called df_summary. Here my goal is to set a function summary to run at most for 2mins it will be good if it can finish before 2mins and move to the next iteration. In case it is not, I want to call the other function name preprocess instead of the function summary that cannot finish within 120s.
Consider we already created the df_summary with 891 rows and a column name body_text. Here is my code + a bit pseudo code as I dont know how to write it exactly:
import time

for i in tqdm(range(0,891)):
  # code to detect running time here
    df_summary['body_text'][i] = summary(df['body_text'][i])# perform the summary function with at most 120s
  # when 120s is over but the summary function cannot finish than perform a preprocessing function instead and move to the next iteration
    df_summary['body_text'][i] = preprocess(df['body_text'][i])

Note that if the function summary can run in at most 120s or under that limit time, it wont run the fallback function preprocess and then move to the next iteration.
How can I achieve this? Any help will be much appreciated.

A: Here is my answer :
import sys
import threading
try:
    import thread
except ImportError:
    import _thread as thread

def exit_after(s):
    '''
    use as decorator to exit process if
    function takes longer than s seconds
    '''

    def quit_function(fn_name):
        # print to stderr, unbuffered in Python 2.
        sys.stderr.flush() # Python 3 stderr is likely buffered.
        thread.interrupt_main() # raises KeyboardInterrupt

    def outer(fn):
        def inner(*args, **kwargs):
            timer = threading.Timer(s, quit_function, args=[fn.__name__])
            timer.start()
            try:
                result = fn(*args, **kwargs)
            finally:
                timer.cancel()
            return result
        return inner
    return outer

# I DIDN'Y WRITE THE CODE ABOVE I GOT IT FROM THERE : https://stackoverflow.com/questions/492519/timeout-on-a-function-call

@exit_after(120) # the function will kill itself after 120 seconds
def process(data):
    summary(data)

for i in tqdm(range(0,891)):
    try:
        df_summary['body_text'][i] = process(df['body_text'][i])
    except KeyboardInterrupt: # took over 120 seconds
        df_summary['body_text'][i] = preprocess(df['body_text'][i])

After 120s, it will stop processing and will run the preprocess function.
Tell me if you don't understand something


text:
Q: How to resolve an incomplete svn check-out in Eclipse? I am trying to checkout my project. After 80% it not moving forward and showing just checking out.
So, I closed Eclipse and restarted because checkout process not closing even I click on terminated icon. That's ok. I tried multiple times in multiple ways.
How to check-out remaining 20% instead of starting from first?

A: These 2 steps should solve your problem:

*

*perfom svn cleanup to remove the lock, which is probably present because of interrupting the checkout

*perform svn update. This should checkout the remaining 20%


text:
Q: How to convert hex in format 00-00 to double? I am getting values in a format like this 00-C6 (Hex). It complains when I try to convert it to double (format execption). What to do?
    public void check()
    {
        double low;
        double high;
        percentageCalculator(4095, 5, out low, out high);
        Dictionary[] A_1 = {Max_1, Min_1};

        for (int i = 0; i < A_1.Length; i++)
        {
            if ((Convert.ToDouble(A_1[i].CurrentValue) <= low) || ((Convert.ToDouble(A_1[i].CurrentValue) >= high))
            {
                Fault++;
            }
        }
    }

A: Assuming the Hex 00-C6 string represents Integer value (because if it represents floating-point value like float or double, it must consists of 4-byte or 8-byte), then one way to process it is to split the Hex string:
string hexString = "00-C6";
string[] hexes = hexString.Split('-');

Then you process each element in the hexes like this:
int hex0 = Convert.ToInt32(hexes[0], 16);
int hex1 = Convert.ToInt32(hexes[1], 16);

If the hex is little endian, then your double value would be:
double d = hex0 << 8 + hex1;

And if it is big endtion, your double will be:
double d = hex1 << 8 + hex0;

The key here is to know that you can convert hex string representation to Int by using Convert.ToInt32 with second argument as 16.
You can combine all the steps above into one liner if you feel like. Here I purposely break them down for the sake of presentation clarity.

A: Take a look at this piece of code:
        string hexnumber = "00-c6";
        double doubleValue = (double)Convert.ToInt32(hexnumber.Replace("-", ""), 16);


text:
Q: Problem with outputting object properties to html and saving object properties to file People, hello everyone, I can't understand myself. Created a Car class, it has properties: model, color, etc.
There are two methods, one method displays these fields on the page, the second should write them to a file. To call these methods, I send two post requests from index to other pages, where I create new Car objects, assign values to the object's fields, then try to call its methods. But both of these methods do not work for me; where the output should be, only empty lines are displayed
My Class Car
class Car
{
    public $model_car;
    public $color_car;
    public $horserpower_car;
    public $production_year_car;
    public function show()
    {
        echo <<<HTML

Model

<?= $this->model_car?>

Color

<?= $this->color_car?>

Power

<?= $this->horserpower_car?>

Production_year

<?= $this->production_year_car?>

        HTML;
    }
    public function save()
    {
        $filename = "reports/".$this->model_car."_".$this->production_year_car."txt";
        $content = "Model - ".$this->model_car."\n, Production year - " . $this->$this->production_year_car.
        "\n, Power - " . $this->horserpower_car."\n, Production year - " . $this->production_year_car;
        if(!file_put_contents($filename,$content))
        {
            echo "Error";
        }
        else
        {
            echo "Complete";
        }
    }
}

the method that should save the object, swears that I cannot convert this object to a string. It feels like my object's fields are empty.
My show.php
<?php
require "Car.php";
$car = new Car();
$car->model_car = "Toyota";
$car->color_car = "LightGreen";
$car->horserpower_car = 110;
$car->production_year_car = 2011;
$car->show();

My save.php
<?php
require "Car.php";
$car = new Car();
$car->model_car = "Toyota";
$car->color_car = "LightGreen";
$car->horserpower_car = 110;
$car->production_year_car = 2011;
$car->save();

My index.php

<form action="show.php" method="post">

Show

    <button type="submit">Show</button>
</form>
<form action="save_file.php" method="post">

Save

    <button type="submit">Save</button>
</form>


text:
Q: FileNotFoundError: File b'tek0000ALL.csv' does not exist Estoy intentando ller un archivo .csv y me da el siguiente error:

FileNotFoundError: File b'tek0000ALL.csv' does not exist

El archivo está en el mismo dirtectorio que el programa y el nombre está bien copiado. El código es el siguiente:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats as ss

df = pd.read_csv("tek0000ALL.csv")

¿Alguna idea de qué puede estar fallando?


text:
Q: Show button whose value is present in database else hide the button I have 5 columns in database id, a1, b1, c1 and d1.
I want to show button a if the value in database for a1 is not there and if two values eg. c1 and b1 is present in database i want to show buttons for a and d.
Simple thing I want to show the button for that if there is no value in database.
I have tried the it by entering 16 conditions but it take a lot of time and space.
if(($row['a1'] == '') && ($row['b1'] != '') && ($row['c1'] != '') && ($row['d1'] != '')) {
?>
    <form action = "a1.php" method="POST">
        <input type="submit" name="a1" value="a1">
    </form>
<?php
} elseif (($row['b1'] == '') && ($row['a1'] != '') && ($row['c1'] != '') && ($row['d1'] != '')) {
?>
    <form action = "b1.php" method="POST">
        <input type="submit" name="b1" value="b1">
    </form>
<?php
} elseif (($row['c1'] == '') && ($row['a1'] != '') && ($row['d1'] != '') && ($row['b1'] != '')) {
?>
    <form action = "c1.php" method="POST">
        <input type="submit" name="c1" value="c1">
    </form>
<?php
} elseif (($row['d1'] == '') && ($row['a1'] != '') && ($row['b1'] != '') && ($row['c1'] != '')) {
?>
    <form action = "d1.php" method="POST">
        <input type="submit" name="d1" value="d1">
    </form>
<?php
}
?>

Is there any other way to do this.
Thanks in advance

A: here is the logic you can try.if you are going for specific row
step1: select the row according to id
$sql =  SELECT * FROM Customers WHERE id=xyx(your preferred id);

step2: fetch a assosiative array.
  $result=mysqli_query($con,$sql);

  // Associative array
 $row=mysqli_fetch_assoc($result);

step2: check for the condition.
 if(isset($row['a1'])){
       echo "<button></button>"
   }

A: echo "<button I'd=btn onClick=function()>call function
Doesn't work to call javascript function


text:
Q: Page changes not reflected with lighttpd I switched from apache to lighttpd. Setup was successful with fasCGI and php now running. I also have the CodeIgniter framework running.
So I scp my project to document Root. Everything works except any changes that I make in file are not reflected in the application. Looks like there's some sort of cacheing mechanism. Also, vi keeps saying "Incomplete last line" for every file (mac to debian file transfer) that I have in the application. I clreaed my browser-side cache, restarted the server, all the basic stuff... am I missing something?

A: Well.. just flushed the lighttpd cache. That worked. For some reason I had I messed up this  line while configuring
`

static-file.exclude-extensions = (  ".pl", ".fcgi" )

` (in the config file) as you can see, I forgot to put in the .php file extension.


text:
Q: How to capture a group from a absolute fill path without any slash in it using JavaScript Here is a sample file path,
/Users/X/Q/Q-doc/src/templates/demos.js
The part I would love to capture is demos.
Here is another example,
/Users/X/Q/Q-doc/src/templates/demos1.js
The target I want is demos1.
I tried to use /\/(.*).js/ to capture the filename but seems it will also capture all the things in between.

A: Your pattern is doing what it should, however your approach needs a fix you can use this approach instead:
(\w+)\.js

Working demo
Update: in case you need a match for samples like Kyle Fairns mentioned in his comment you can use
.*\/(.*?)\.js

Working demo

A: ([^\/]*?)\.js$

This will grab everything that is not a forward slash, so long as it's followed by .js, from the end of the string.
See it here


text:
Q: Report of systems with 32/64bit Office installations within a domain Our domain has a KMS activation server and a number of virtual desktops, regular desktops, and laptops which all have Office 2010 or 2013 installed. Most of them should be 32-bit Office but I know that some of them are 64-bit. Is there any way (using system center, powershell, active directory, ???) to get a readable report of which computers have which version of Office installed?
I used a typical application monitor but it gave a huge list of office related components as well including things that look like they are bridges for 64-bit office components even though those machines have 32-bit office installed.
Thank you for any help!

A: I use Get-InstalledSoftware_32_And_64.ps1. It's incredibly useful and can do what you need. You can even set it up to add extension attributes to computer objects with a bit of extra scripting, then leverage those extensions with other AD components. But that's beyond the scope of this answer.
https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Installed-70d0c0f4
Here's an easy way to get your lists.
Note: This relies on Get-InstalledSoftware_32_And_64.ps1 being setup with Import-Module prior to running the following script.
# Import AD module
Import-Module ActiveDirectory
# Setup array of computer names
$computers = Get-ADComputer -Filter 'ObjectClass -eq "Computer"' | Select -Expand DNSHostName
# foreach loop - do stuff...
foreach ( $computer in $computers ) {
    $output = Get-SoftwareList -Computername $computer | Select-String "Microsoft Office 2013"
    if ( $output -match "64" ) {
        echo "$computer >> Office2013-64_Installs.txt"
    }
    elseif ( $output -match "32" ) {
        echo "$computer >> Office2013-32_Installs.txt"
    }
    else {
        $recheck = Get-SoftwareList -Computername $computer | Select-String "Microsoft Office"
        echo "$Computer :: $recheck >> Office2013_Check_ErrorLog.txt"
    }
}

The error log will list computers that either don't have Office 2013 installed, or have the wrong version installed. You can do a lot more validation, but this will get you started.


text:
Q: Need to find a max of three numbers in java
Possible Duplicate:
Find the max of 3 numbers in Java with different data types (Basic Java)

Write a program that uses a scanner to read three integers (positive) displays the biggest number of three. (Please complete without using either of the operators && or ||. These operators will be covered in class shortly. Similarly loops are not required.)
Some sample run:

Please input 3 integers: 5 8 3
The max of three is: 8

Please input 3 integers: 5 3 1
The max of three is 5

import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        String x = keyboard.nextLine();
        String y = keyboard.nextLine();
        String z = keyboard.nextLine();
        int max = Math.max(x,y,z);
        System.out.println(x + " " + y + " "+z);
        System.out.println("The max of three is: " + max);
    }
}

I want to know what's wrong with this code and how I can find the max when I input 3 different values.

A: Two things: Change the variables x,  y,  z as int and call the method as Math.max(Math.max(x,y),z) as it accepts two parameters only.
In Summary, change below:
    String x = keyboard.nextLine();
    String y = keyboard.nextLine();
    String z = keyboard.nextLine();
    int max = Math.max(x,y,z);

to
    int x = keyboard.nextInt();
    int y = keyboard.nextInt();
    int z = keyboard.nextInt();
    int max =  Math.max(Math.max(x,y),z);

A: It would help if you provided the error you are seeing.  Look at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html and you will see that max only returns the max between two numbers, so likely you code is not even compiling.
Solve all your compilation errors first.
Then your homework will consist of finding the max of three numbers by comparing the first two together, and comparing that max result with the third value.  You should have enough to find your answer now.

A: You should know more about java.lang.Math.max:

*

*java.lang.Math.max(arg1,arg2) only accepts 2 arguments but you are
writing 3 arguments in your code.

*The 2 arguments should be double,int,long and float but your are
writing String arguments in Math.max function. You need to parse them in the required type.

You code will produce compile time error because of above mismatches.
Try following updated code, that will solve your purpose:
import java.lang.Math;
import java.util.Scanner;
public class max {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please input 3 integers: ");
        int x = Integer.parseInt(keyboard.nextLine());
        int y = Integer.parseInt(keyboard.nextLine());
        int z = Integer.parseInt(keyboard.nextLine());
        int max = Math.max(x,y);
        if(max>y){ //suppose x is max then compare x with z to find max number
            max = Math.max(x,z);
        }
        else{ //if y is max then compare y with z to find max number
            max = Math.max(y,z);
        }
        System.out.println("The max of three is: " + max);
    }
}


text:
Q: C# Vlc.DotNet Libraries - Null reference exception on setmedia I'm aware some partial answers have been offered, both on SO and most closely here:https://github.com/ZeBobo5/Vlc.DotNet/issues/217
I want to make a dynamic vlc player in my winform.
I have succesfully added a player statically:
        vlcControl2.SetMedia(new System.IO.FileInfo(file1));
        vlcControl2.Play();

But when I try and create a dynamic one, I get a null ref exception on the setmedia line:
var new_vlc = new VlcControl();
        new_vlc.Enabled = true;
        new_vlc.VlcLibDirectoryNeeded += checkdir2;
        new_vlc.Height = 300;
        new_vlc.Width = 300;
        new_vlc.SetMedia(new System.IO.FileInfo(file2));

I get that the new_vlc is somehow null, but cannot find what it is I haven't set, and I've been at this for hours.  Can anyone help?

A: As Camilo pointed out, if you are allocating a new WinForms control yourself, you are responsible for calling BeginInit/EndInit manually (granted, BeginInit does not do anything special, but it's how you're supposed to use ISupportInitialize).
We should probably throw a better message than the NullReferenceException you're having.


text:
Q: PHP mbstring doesn't work, but I set everything I set in the php.ini file the mbstring, php_mbstring.dll is on its place, but php can't load the mudule. I tried everything, what I found on stackoverflow, or anywhere else, but nothing.
-php directory is located in C:\php
-php_mbstring.dll is located in C:\php\ext\php_mbstring.dll
-;extension_dir = "ext" row is outcommented, but I tried remove the semicolon, and set it to "C:\php\ext", also tried it with / signs
-extension=mbstring row has no semicolon before tried to name it to php_mbstring.dll, tried to give the whole path (C:\php\ext\php_mbstring.dll), tried it with outcommented extension_dir = "ext", tried it all the possible ways, with \ sign and / sign, but always the same failure...
-another device of mine (notebook) runs the mbstring, I copied the dll file from it, tried with that all the possibilities above, tried to download another dll file, also tortured through the ways above, but nothing. The dll file is on its place, the path is authentical, it's enabled in the php.ini, but it doesn't work...

Warning: PHP Startup: Unable to load dynamic library 'mbstring'
(tried: C:\php\ext\mbstring (A megadott modul nem található.),
C:\php\ext\php_mbstring.dll (A megadott modul nem található.)) in
Unknown on line 0

Using Atom editor and Atom live server, it outputs the following:

Listening on http://localhost:8000 Document root is
C:\Users\ferenczi\Desktop\Saját cuccok\html
programozás\Projectek\Hander at line 0, file Unknown[Mon May 17
05:40:46 2021] PHP Warning: PHP Startup: Unable to load dynamic
library 'mbstring' (tried: C:\php\ext\mbstring (A megadott modul nem
talC!lhatC3.), C:\php\ext\php_mbstring.dll (A megadott modul nem
talC!lhatC3.)) [Mon May 17 05:40:56 2021] PHP 7.4.12 Development
Server (http://localhost:8000) started

Everything else working perfect. PHP working, SQL queries working, mysql extension working.

A: The right way is to install php-mbstring package and let it enable the mbstring extension automatically:
sudo apt-get install php-mbstring

if you want to enable or diable, please go with the below command
sudo phpdismod mbstring # disable mbstring extension
sudo phpenmod mbstring # enable mbstring extension

Try this!


text:
Q: Cutting A File into Chunks in Qt Can anybody give me a hint or initial idea how may I cut a file into chunks in Qt ? Is there any particular file like java it has built in function to split. Later on I want to calculate SHA-256 hash value of each chunks. Any idea guys ??

A: There is no built in function for that.

*

*Open the original file.

*Open a file for the first chunk.

*Read bytes from the original file.

*Write bytes to the chunk file.

*Repeat.

See QFile documentation.


text:
Q: JSF 2 - No way to do Required Inputs + Clear (Immediate) Button? This question is similar to the question here but that solution doesn't work here.
Take this simple-to-the-max example:
<h:form>
  <h:inputText required="true" value="#{mrBean.someValue}" />
  <h:inputText required="true" value="#{mrBean.someValue2}" />

  <h:commandButton value="Submit">
    <f:ajax execute="@form" />
  </h:commandButton>
  <h:commandButton immediate="true" action="#{mrBean.clearAllValues}" value="Clear">
    <f:ajax render="@form" />
  </h:commandButton>

</h:form>

And the bean Code:
public void clearAllValues() {
    setSomeValue(null);
    setSomeValue2(null);
}

Take this scenario:

*

*Enter 'X' value in first input

*Submit it using the 'Submit' Button. (failed in validation)

*Enter 'Y' into the same input.

*Click the 'Clear' button.

*Result: Inputs don't clear and value of first input returns to 'X'.

I would expect this scenario to clear the input values but it doesn't, instead, it restores 'X' which is the previously submitted value. It actually never really runs mrBean.getSomeValue() on the bean (Which would have returned null and clear the input field)
The problem is related to JSF not working well with required fields and immediate. I wonder if anyone managed to overcome this problem.
Thanks!
Ben.

A: Your code example is oversimplified. The described problem symptoms will only occur when you have multiple required inputs. Add one more required input field to the example. Fill out only one of them. A validation error will occur for the empty one. Then enter something else in both and press clear. The valid input will indeed retain the previously submitted value.
This problem is described in detail in this question and this blog article. The solution boils down to collecting all to-be-cleared input components and calling EditableValueHolder#resetValue() on each of them. This can be done with a <f:actionListener> as shown in the blog article.
Another way in your particular case since you just want to clear out the entire form is to use a <h:button> which will basically just refresh the page. If your bean is request or view scoped then it will also be recreated with all properties set to default.
<h:form>
  <h:inputText required="true" value="#{mrBean.someValue}" />

  <h:commandButton value="Submit">
    <f:ajax execute="@form" />
  </h:commandButton>
  <h:button value="Clear" />
</h:form>

A: Are you sure clearAllValues is executed? Do you get any errors in the logs or console?
Try adding execute
<f:ajax render="@form" execute="@this">


text:
Q: what's the correct understanding about index record gaps in mysql? According to mysql reference on gap locks:

A gap might span a single index value, multiple index values, or even be empty.

However, when I look into the table performance_schema.data_locks, every gap is described by the index record following it. For example: create table test(id integer primary key); insert into test values (3),(6),(9),(12);
Then in a session, do a locking read: select * from test where id>=3 and id<11 for update. According to the reference, there is a gap lock that spans index value 3,6,9. However, data_locks table displays the locks like this:

There is no GAP LOCK_TYPE, and gap is bound to a index value. LOCK_MODE X locks the gap and index record, namely next-key lock; X,REC_NOT_GAP only locks index record without gap; X,GAP only locks gap without index record.
So should I comprehend it in the following way? The reference manual says a gap might span multiple index value, it means a logical gap; but in practice, every gap is seperated by index values, and is identified by the index value following it.


text:
Q: From uic output to C++ code in Qt In the interest of better learning Qt, I would like to learn how it would be possible to use the C++ header file output of Qt's User Interface Compiler to programmatically recreate the same UI design (e.g. as the one derived by using the Designer in Qt Creator).
Should I create a new header file in my Qt project and copy the contents of that uic output? Which parts from the uic ouptut go where and how should I call them in the .cpp?
Is this best approach in terms of good programming practices; not interested in opinions, only on how to properly separate definitions and use the header and source files as they are meant to?
A minimal example of where/how to define the layouts and widgets and how to invoke/customise them (perhaps in the .cpp file?) would be a great learning tool for me.
As an example, here is an example of a GUI design created with the Qt Creator's Designer tool with several nested layouts and multiple widgets:

And this is the header file ouptut from the uic for the above GUI design:
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H

#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralWidget;
    QVBoxLayout *verticalLayout_3;
    QFrame *top_frame;
    QGridLayout *gridLayout;
    QSpacerItem *horizontalSpacer;
    QProgressBar *progressBar_2;
    QProgressBar *progressBar_4;
    QSpacerItem *verticalSpacer;
    QSpacerItem *horizontalSpacer_2;
    QPushButton *pushButton_1;
    QProgressBar *progressBar_1;
    QPushButton *pushButton_2;
    QPushButton *pushButton_3;
    QProgressBar *progressBar_3;
    QPushButton *pushButton_4;
    QFrame *bottom_frame;
    QHBoxLayout *horizontalLayout;
    QFrame *frame;
    QFormLayout *formLayout;
    QLabel *label_1;
    QLabel *label_2;
    QSpacerItem *verticalSpacer_2;
    QLineEdit *lineEdit;
    QLineEdit *lineEdit_2;
    QFrame *frame_2;
    QHBoxLayout *horizontalLayout_2;
    QLabel *label_3;
    QSpacerItem *horizontalSpacer_3;
    QLabel *label_4;

    void setupUi(QMainWindow *MainWindow)
    {
        if (MainWindow->objectName().isEmpty())
            MainWindow->setObjectName(QStringLiteral("MainWindow"));
        MainWindow->resize(878, 632);
        centralWidget = new QWidget(MainWindow);
        centralWidget->setObjectName(QStringLiteral("centralWidget"));
        verticalLayout_3 = new QVBoxLayout(centralWidget);
        verticalLayout_3->setSpacing(6);
        verticalLayout_3->setContentsMargins(11, 11, 11, 11);
        verticalLayout_3->setObjectName(QStringLiteral("verticalLayout_3"));
        top_frame = new QFrame(centralWidget);
        top_frame->setObjectName(QStringLiteral("top_frame"));
        QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(top_frame->sizePolicy().hasHeightForWidth());
        top_frame->setSizePolicy(sizePolicy);
        top_frame->setFrameShape(QFrame::StyledPanel);
        top_frame->setFrameShadow(QFrame::Raised);
        gridLayout = new QGridLayout(top_frame);
        gridLayout->setSpacing(6);
        gridLayout->setContentsMargins(11, 11, 11, 11);
        gridLayout->setObjectName(QStringLiteral("gridLayout"));
        horizontalSpacer = new QSpacerItem(30, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);

        gridLayout->addItem(horizontalSpacer, 0, 2, 1, 1);

        progressBar_2 = new QProgressBar(top_frame);
        progressBar_2->setObjectName(QStringLiteral("progressBar_2"));
        progressBar_2->setValue(24);

        gridLayout->addWidget(progressBar_2, 2, 3, 1, 1);

        progressBar_4 = new QProgressBar(top_frame);
        progressBar_4->setObjectName(QStringLiteral("progressBar_4"));
        progressBar_4->setValue(24);

        gridLayout->addWidget(progressBar_4, 2, 5, 1, 1);

        verticalSpacer = new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed);

        gridLayout->addItem(verticalSpacer, 1, 1, 1, 1);

        horizontalSpacer_2 = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);

        gridLayout->addItem(horizontalSpacer_2, 0, 4, 1, 1);

        pushButton_1 = new QPushButton(top_frame);
        pushButton_1->setObjectName(QStringLiteral("pushButton_1"));

        gridLayout->addWidget(pushButton_1, 0, 0, 1, 1);

        progressBar_1 = new QProgressBar(top_frame);
        progressBar_1->setObjectName(QStringLiteral("progressBar_1"));
        progressBar_1->setValue(24);

        gridLayout->addWidget(progressBar_1, 0, 3, 1, 1);

        pushButton_2 = new QPushButton(top_frame);
        pushButton_2->setObjectName(QStringLiteral("pushButton_2"));

        gridLayout->addWidget(pushButton_2, 0, 1, 1, 1);

        pushButton_3 = new QPushButton(top_frame);
        pushButton_3->setObjectName(QStringLiteral("pushButton_3"));

        gridLayout->addWidget(pushButton_3, 2, 0, 1, 1);

        progressBar_3 = new QProgressBar(top_frame);
        progressBar_3->setObjectName(QStringLiteral("progressBar_3"));
        progressBar_3->setValue(24);

        gridLayout->addWidget(progressBar_3, 0, 5, 1, 1);

        pushButton_4 = new QPushButton(top_frame);
        pushButton_4->setObjectName(QStringLiteral("pushButton_4"));

        gridLayout->addWidget(pushButton_4, 2, 1, 1, 1);

        verticalLayout_3->addWidget(top_frame);

        bottom_frame = new QFrame(centralWidget);
        bottom_frame->setObjectName(QStringLiteral("bottom_frame"));
        bottom_frame->setFrameShape(QFrame::StyledPanel);
        bottom_frame->setFrameShadow(QFrame::Raised);
        horizontalLayout = new QHBoxLayout(bottom_frame);
        horizontalLayout->setSpacing(6);
        horizontalLayout->setContentsMargins(11, 11, 11, 11);
        horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
        frame = new QFrame(bottom_frame);
        frame->setObjectName(QStringLiteral("frame"));
        frame->setFrameShape(QFrame::StyledPanel);
        frame->setFrameShadow(QFrame::Raised);
        formLayout = new QFormLayout(frame);
        formLayout->setSpacing(6);
        formLayout->setContentsMargins(11, 11, 11, 11);
        formLayout->setObjectName(QStringLiteral("formLayout"));
        label_1 = new QLabel(frame);
        label_1->setObjectName(QStringLiteral("label_1"));

        formLayout->setWidget(0, QFormLayout::LabelRole, label_1);

        label_2 = new QLabel(frame);
        label_2->setObjectName(QStringLiteral("label_2"));

        formLayout->setWidget(1, QFormLayout::LabelRole, label_2);

        verticalSpacer_2 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);

        formLayout->setItem(2, QFormLayout::LabelRole, verticalSpacer_2);

        lineEdit = new QLineEdit(frame);
        lineEdit->setObjectName(QStringLiteral("lineEdit"));
        QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Expanding);
        sizePolicy1.setHorizontalStretch(0);
        sizePolicy1.setVerticalStretch(0);
        sizePolicy1.setHeightForWidth(lineEdit->sizePolicy().hasHeightForWidth());
        lineEdit->setSizePolicy(sizePolicy1);

        formLayout->setWidget(3, QFormLayout::SpanningRole, lineEdit);

        lineEdit_2 = new QLineEdit(frame);
        lineEdit_2->setObjectName(QStringLiteral("lineEdit_2"));
        sizePolicy1.setHeightForWidth(lineEdit_2->sizePolicy().hasHeightForWidth());
        lineEdit_2->setSizePolicy(sizePolicy1);

        formLayout->setWidget(4, QFormLayout::LabelRole, lineEdit_2);

        horizontalLayout->addWidget(frame);

        frame_2 = new QFrame(bottom_frame);
        frame_2->setObjectName(QStringLiteral("frame_2"));
        frame_2->setFrameShape(QFrame::StyledPanel);
        frame_2->setFrameShadow(QFrame::Raised);
        horizontalLayout_2 = new QHBoxLayout(frame_2);
        horizontalLayout_2->setSpacing(6);
        horizontalLayout_2->setContentsMargins(11, 11, 11, 11);
        horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
        label_3 = new QLabel(frame_2);
        label_3->setObjectName(QStringLiteral("label_3"));

        horizontalLayout_2->addWidget(label_3);

        horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);

        horizontalLayout_2->addItem(horizontalSpacer_3);

        label_4 = new QLabel(frame_2);
        label_4->setObjectName(QStringLiteral("label_4"));

        horizontalLayout_2->addWidget(label_4);

        frame->raise();
        frame->raise();
        label_3->raise();
        label_4->raise();

        horizontalLayout->addWidget(frame_2);

        verticalLayout_3->addWidget(bottom_frame);

        MainWindow->setCentralWidget(centralWidget);

        retranslateUi(MainWindow);

        QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
        MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0));
        pushButton_1->setText(QApplication::translate("MainWindow", "PushButton_1", 0));
        pushButton_2->setText(QApplication::translate("MainWindow", "PushButton_2", 0));
        pushButton_3->setText(QApplication::translate("MainWindow", "PushButton_3", 0));
        pushButton_4->setText(QApplication::translate("MainWindow", "PushButton_4", 0));
        label_1->setText(QApplication::translate("MainWindow", "TextLabel_1", 0));
        label_2->setText(QApplication::translate("MainWindow", "TextLabel_2", 0));
        label_3->setText(QApplication::translate("MainWindow", "TextLabel_3", 0));
        label_4->setText(QApplication::translate("MainWindow", "TextLabel_4", 0));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_MAINWINDOW_H

(this question is -basically- a follow-up from my previous question)

A: The best way is to use the generated class as a member of an appropriate widget class, in your case as a member of a QMainWindow derived class:
namespace Ui {
    class MainWindow; // forward declaration of the generated class
}

class MyMainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MyMainWindow(QWidget *parent = 0);
    ~MyMainWindow();

private:
    Ui::MainWindow *ui;
};

You then create an instance of that inside the source file
#include "ui_mainwindow.h" // include the generated header

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this); // let the generate class populate "this"
}

MainWindow::~MainWindow()
{
     delete ui;
}

This is also the structure generated by the QtCreator template for "New Designer Form Class".


text:
Q: XML Content is not allowed in prolog I don't know whether I am doing in a correct way or not. But I just tried to use namespace in xml. When i try to transform xml to xsl am getting this error XML Content is not allowed in prolog
This is my xml.
<?xml version="1.0" encoding="UTF-8"?>
<pi:Payroll_Extract_Employees xmlns:pi="urn:com.sdsd/picof">
    <pi:PayGroup>
    <pi:Header>
        <pi:Version>19</pi:Version>
        <pi:Payroll_Company_ID>ADSDP</pi:Payroll_Company_ID>
        <pi:Payroll_Company_Name>ADSDP</pi:Payroll_Company_Name>
        <pi:Pay_Group_ID>US1</pi:Pay_Group_ID>
        <pi:Pay_Group_Name>US1 Salaried</pi:Pay_Group_Name>
        <pi:Pay_Period_Start>2015-02-01-07:00</pi:Pay_Period_Start>
        <pi:Pay_Period_End>2015-02-14-07:00</pi:Pay_Period_End>
        <pi:Updated_From>2015-02-05T06:03:48.000-07:00</pi:Updated_From>
        <pi:Updated_To>2015-02-06T19:47:39.457-07:00</pi:Updated_To>
        <pi:All_Effective>false</pi:All_Effective>
    </pi:Header>
    </pi:PayGroup>
 </pi:Payroll_Extract_Employees>

This is my xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xd" xmlns:pi="urn:com.workday/picof">

<xsl:template match="/pi:Payroll_Extract_Employees/PayGroup/Header">
<folder>
    <file>
        <item><xsl:value-of select="Version"/></item>
        <item><xsl:value-of select="Payroll_Company_ID"/></item>
    </file>
    <file>
        <item><xsl:value-of select="Pay_Group_ID"/></item>
        <item><xsl:value-of select="Pay_Period_Start"/></item>
    </file>
</folder>
</xsl:template>

Could someone guide me if i do it in a wrong way?

A: If you want your template to be applied then make sure you use the prefix in all steps:
<xsl:template match="/pi:Payroll_Extract_Employees/pi:PayGroup/pi:Header"> <folder> <file> <item><xsl:value-of select="pi:Version"/></item> <item><xsl:value-of select="pi:Payroll_Company_ID"/></item> </file> <file> <item><xsl:value-of select="pi:Pay_Group_ID"/></item> <item><xsl:value-of select="pi:Pay_Period_Start"/></item> </file> </folder> </xsl:template>


text:
Q: Is it possible to use pandas shift function and keep the dtypes? When using the method shift from Pandas it reassigns dtypes different from the original dataframe, is it possible to shift without that happening? (but still using pandas shift)
Using fill_value argument is almost enough, but if there is any dtype that is not numeric it still changes the dtype.
import pandas as pd

data = [
  {'a': 1, 'b': 5.2, 'c': True},
  {'a': 5, 'b': 8.5, 'c': False},
  {'a': 2, 'b': 2.6, 'c': True}
]

df = pd.DataFrame(data)

print(df.dtypes)
print(df.shift(1).dtypes)
print(df.shift(1, fill_value=0).dtypes)

Output:
a      int64
b    float64
c       bool
dtype: object

a    float64
b    float64
c     object
dtype: object

a      int64
b    float64
c     object
dtype: object

A: you can use convert_dtypes like:
print (df.shift(1).convert_dtypes().dtypes)
a      Int64
b    float64
c    boolean
dtype: object

It is not exactly bool type but boolean but it is better than object I guess


text:
Q: Proof of 'stronger' Hensel's Lemma I'm trying to understand the proof of the following statement:

Let $f\in\mathbb{Z}_p[X]$ be a polynomial with coefficients in $\mathbb{Z}_p$. Suppose there is a $p$-adic integer $\alpha_1$ such that $$|f(\alpha_1)|_p<|f'(\alpha_1)|_p^2.$$ Then there is a unique $p$-adic integer $\alpha$ such that $f(\alpha)=0$ and $\alpha\equiv\alpha_1\;\text{mod }p^{\nu_p(f(\alpha_1))-\nu_p(f'(\alpha_1))}.$

To prove it in the case $p\neq 2$, we write $f(\alpha_1)=p^j\xi$ and $f(\alpha_1)=p^k\gamma$, with $0\leq 2k< j$ and $\nu_p(\xi)=\nu_p(\gamma)=0$, and we look for $\alpha_2=\alpha_1+b_2 p^{j-k}$  such that $f(\alpha_2)\equiv 0\;\text{mod }p^{j+1}$.
Using the Taylor expansion we have $$f(\alpha_2)\equiv f(\alpha_1)+f'(\alpha_1)b_2p^{j-k}\text{ mod }p^{j+1}=p^j\xi+b_2\gamma p^j\text{ mod }p^{j+1}.$$ Imposing $f(\alpha_2)\equiv 0\text{ mod }p^{j+1}$, we get $$0\equiv \xi+b_2\gamma \text{ mod }p,$$ which can be solved in $b_2$. Then we construct the following sequence ($\alpha_n$) by induction.
My question is about the claim. To apply induction we need that $$|f(\alpha_2)|_p<|f'(\alpha_2)|_p^2.$$ How can this condition be checked?
Thanks in advance.

A: Write
$$f(\alpha_n+x)=a_0+a_1x+a_2x^2+\cdots $$
where $a_0=f(\alpha_n)$, $a_1=f'(\alpha_n)$.
If $\alpha_{n+1}=\alpha_m+h$, then
$$ f(\alpha_{n+1}+x)=b_0+b_1x+\cdots$$
where
$$b_0=a_0+a_1h+a_2h^2+\cdots$$
and
$$b_1=a_1+2a_2h+\cdots$$
We choose our $h$ such that $a_0+a_1h$ becomes small, namely as $0<|a_0|_p<|a_1^2|_p\le 1$, our pick $h\approx -\frac{a_0}{a_1}$ will make $|h|_p=\frac{|a_0|_p}{|a_1|_p}<|a_1|_p$, hence for all $k\ge2$, we have $|a_kh^k|_p\le |h^2|_p<|a_1h|_p$ so that $$|b_0|_p=|a_0+a_1h|_p<|a_0|_p.$$
On the other hand, at least for $2\le k<p$, we have $|ka_kh^{k-1}|_p\le |h|_p^{k-1}\le |h|_p<|a_1|_p$; and for $k\ge p>2$, we also get $|ka_kh^{k-1}|_p\le |h|_p<|a_1|_p$ because certainly $h^{k-1}$ is more divisible by $p$ than $k$. Thus
$$|b_1|_p=|a_1|_p.$$
In other words, when using Newton's method in $p$-adics ($p>2$), surprisingly only the function value gets smaller while the derivative keeps its size.


text:
Q: npm install ignores own ssh+git repo In my company we use a Bitbucket server and I am developing a framework as npm module. I run npm install git+ssh://git..., npm will create a node_modules/_PACKAGE_NAME_ folder with my sources.
When I add it to the package.json and run npm install, npm asks me for a fingerprint and then finishes installing all packages, but in node_modules there is no package of my git repo. That breaks my automation workflow, because I must separately install this repo by hand.
For information: I have to type my password when I run it manually.
Does anyone have an idea?

A: it was a spelling mistake in the key, so npm could not create the folder


text:
Q: C# ASP.Net - Global.asax full of errors I am attempting to use the Global.asax file and it is failing miserably. Every line in the code has an error but the funny thing is that it does not matter how many lines, what the lines contain, etc have as it always reports an error. This makes me thing there is a configuration setting that isn't right but wouldn't know where to begin.
The project is a Web Site rather than a Web Application but I read up on Global.asax and it appears to be acceptable to use it in a Web Site. I have provided the code I am using to test that the Global.asax works in the project before writing the code needed for the project.
<%@ Application Language="C#" %>

<script runat="server">

    static string _pagePath;

    void Application_Start(object sender, EventArgs e)
    {
    // Code that runs on application startup
    _pagePath = Server.MapPath("~/Folder/Page.aspx");
    }

    // ...

    void Application_BeginRequest(object sender, EventArgs e)
    {
    string path = Request.PhysicalPath;
    if (path == _pagePath)
    {
        Response.Write("Page viewed");
        Response.End();
    }
    }

</script>

I have also provided a list of example error messages that are cropping up
'Class' statement must end with a matching
'End Class' 'If', 'ElseIf', 'Else', 'End If', 'Const', or 'Region' expected
'Namespace' statement must end with a matching 'End Namespace'
Statement cannot appear outside of a method body/multiline lambda.

Hopefully someone can pick out what I did wrong so I can use the Global.asax. Any help is widely appreciated!

A: add Language="C#" property to the directive at the top of your global.asax. right click on the file, choose view markup, add the property and rebuild.
<%@ Application Codebehind="Global.asax.cs" Inherits="GLOBAL CLASS" Language="C#" %>


text:
Q: React Router v4 in production with Apache Im attempting to deploy my code to apache. Im using react router 4 and connected react router with create react app.
The app is deployed to a nested directory, like this: http://example.com/pathTo/myApp
There are 2 optional parameters. When the first is used, it works fine. When there is an additional paramter, there is an error.

*

*http://example.com/pathTo/myApp/about -> works fine

*http://example.com/pathTo/myApp/property/23423 -> Error: Unexpected token <

Uncaught SyntaxError: Unexpected token <      1.9adc2a7a.chunk.js:1

package.json
...
"homepage": ".",
...

store.js
export const history = createHistory({
    basename: "/pathTo/myApp",
})

index.js
render(
    <Provider store={store}>
        <ConnectedRouter history={history}>
            <Switch>
                <Route path={`/:viewType?/:viewID?`} component={App} />
                <Redirect from="*" to="/about" />
            </Switch>
        </ConnectedRouter>
    </Provider>,
    target
);

.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /pathTo/myApp/index.html [L]
</IfModule>

Any help or suggestions are much appreciated.


text:
Q: Connecting to a MySQL database using AngularJS I'm trying to create a mobile application using AngularJS and Ionic Framework. However, I'm lost when trying to find a solution for backend database support. Is there a plugin or third-party API available to use to accomplish this?

A: Client side web applications do not connect directly to SQL database servers.
You need to pick a server side programming language and write a web service interface to your database.
Then access that interface using XMLHttpRequest (which Angular wraps with $http).


text:
Q: MySQLi prepared update statement in PHP How do you write a prepared update statement? Reference:mysqli::prepare
I've tried writing it as described:
  if ($stmt = $mysqli->prepare("UPDATE tblFacilityHrs SET title =? description = ? WHERE uid = ?")){
            $stmt->bind_param('sss', $title, $desc, $uid2);

            //Get params
            $title=$_POST['title'];
            $desc=$_POST['description'];
            $uid2=$_GET['uid'];

$stmt->execute();
            $stmt->close();
    }
    else {
        //Error
        printf("Prep statment failed: %s\n", $mysqli->error);
    }

Error:

Prep statment failed: You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near 'description = ? WHERE uid = ?' at line 1 Edited
  row.

A: You probably need to add commas:
$stmt = $mysqli->prepare("UPDATE tblFacilityHrs SET title = ?, description = ? WHERE uid = ?"

A: You're just missing a comma between the set columns:
UPDATE tblFacilityHrs SET title = ?, description = ? WHERE uid = ?
                                ^^^^^^

When MySQL reports an error the likes of check the manual for syntax to use near 'something, look most often to the character immediately preceding the 'something, as that is where your error occurs.
$sql = "UPDATE tblFacilityHrs SET title = ?, description = ? WHERE uid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sss', $title, $desc, $uid2);
$stmt->execute();

A: You are binding the parameters before assigning them to variables:
$title=$_POST['title'];
$desc=$_POST['description'];
$uid2=$_GET['uid'];

$stmt->bind_param('sss', $title, $desc, $uid2);

edit: scratch that, it doesn't appear to make a difference whether or not the parameters are bound before or after you have defined the variables (you learn something new everyday!), but like Michael said, logically it makes sense to define them first.


text:
Q: Cocoa - how to catch if HDD is reading/writing some data Is there any way how to determine if HDD is reading or writing data in OS X ?

A: The Instruments tool in Xcode uses DTrace to do this.
http://en.wikipedia.org/wiki/DTrace


text:
Q: Modal HUD on asynctask I am working on something in Android. There will be a menu, when accessed, requests a fairly large list of users from a server (500+) and takes about 5 seconds. During this time, the application freezes. How do I go about showing a progress hud (like MBProgressHud) where the user is aware something is happening and can't touch out of it until it is complete.
MBProgressHud:

A: Use AsyncTask :
public class MyAsyncTask extends AsyncTask<Void, Void, Result>{

                        private Activity activity;
                        private ProgressDialog progressDialog;

            public MyAsyncTask(Activity activity) {
                            super();
                this.activity = activity;
            }

            @Override
            protected void onPreExecute() {
            super.onPreExecute();
                progressDialog = ProgressDialog.show(activity, "Loading", "Loading", true);
            }

            @Override
            protected Result doInBackground(Void... v) {
            //do your stuff here
            return null;

            }

            @Override
            protected void onPostExecute(Result result) {
                progressDialog.dismiss();
                Toast.makeText(activity.getApplicationContext(), "Finished.",
                        Toast.LENGTH_LONG).show();
            }

}

Call it from the activity:
MyAsyncTask task = new AsyncTask(myActivity.this);
task.execute();

A: You need to use AsyncTask and ProgressDialog to achieve this functionality. It will off-load the heavy lifting (web calls) on a separate thread, setting your UI thread to be free from ANR (Application Not Responding).
For more info, read this answer.


text:
Q: How to create a specific Web App with WordPress? Can we make Web Apps in WordPress with specific (custom) scope, something like a mini-Facebook, a mini-Twitter, a stackoverflow, etc. What I really want to know is that how much am I free handed to build whatever Web App I want in WP? and more importantly how to?
Give me some references to books, tutorials, etc.

A: Yes, you can do that with WordPress and even more. You can even create mobile apps and web services. If you want a book: http://shop.oreilly.com/product/0636920029380.do
If you want a starting tutorial, then go: http://premium.wpmudev.org/blog/build-a-web-app-with-wordpress/


text:
Q: get value of textarea html in javascript I have a textarea
<textarea id='inputText' rows='30' style="width: 45%; margin-left: 20%;">

and in Javascript when I press a key a send the value of the textare
 $('#inputText').keypress(function (e){
conn.send($('#inputText').val());
}

my problem is that when I press a key it sends the previous state of the textare. Is there a way where I can "refresh" the textarea value before sending it?

A: You need to use $('#inputText').keyup(); since you want to run it when the key is released.


text:
Q: С2512. Person: нет подходящего конструктора по умолчанию.E0291.для класса"Person" не существует конструктор по умолчанию Как исправить ошибки С2512 и E0291,строка 29?
#include<iostream>
using namespace std;
class Person
{

protected:
string name;
string surname;
public:
Person(string n, string s)
{
    name = n;
    surname = s;
}
void Print(Person p)
{
    cout << "Name - " << name << endl;
    cout << "Surname - " << surname << endl;
}
~Person();

};
class Student:public Person
{
protected:
    string specialty;
    double grade;
public:
Student(string s,double g){
    specialty = s;
    grade = g;
}

~Student();
};
int main()
{
Person* per = new Person("name", "surname");
return 0;
}

A: В вашем конструкторе Student
Student(string s,double g){
    specialty = s;
    grade = g;
}

не указан вызов конструктора базового класса, а значит, в качестве такового будет использован конструктор по умолчанию Person::Person(). У вас такого нет, и сгенерировать его компилятор не может - поскольку есть Person::Person(string n, string s). Что компилятору остается, кроме как жаловаться на жизнь?...
Вы должны либо добавить конструктор по умолчанию Person::Person(), либо переписать
Student(string s,double g):Person(?,?) {

Здесь ? - какие-то аргументы типа string, ну, а какие и откуда их брать - это уж думайте сами исходя из своей задачи... Вы сейчас создаете безымянного студента - это намек.
И еще - не надо эти присваивания в конструкторе, используйте инициализацию:
Person(string n, string s):name(n),surname(s){}

И снова - зачем вам копировать лишний раз строки? Передавайте их по ссылке:
Person(const string& n, const string& s):name(n),surname(s){}

То же относится и к Student.
И кстати, а где же тело деструктора? Если деструктор ничего особого делать не должен - или пишите
~Person(){};

или
~Person() = default;

а то при линковке будут проблемы, если соберетесь память освободить. И это замечание относится и к Student тоже.
Дальше смотреть не буду, а то ответ никогда не закончу :)


text:
Q: Speech training files and registry locations I have a speech project that requires acoustic training to be done in code. I a successfully able to create training files with transcripts and their associated registry entries under Windows 7 using SAPI. However, I am unable to determine if the Recognition Engine is successfully using these files and adapting its model. My questions are as follows:

*

*When performing training through the Control Panel training UI, the system stores the training files in "{AppData}\Local\Microsoft\Speech\Files\TrainingAudio". Do the audio training files HAVE to be stored in this location, or can I store them elsewhere as long as the registry entries for the profile reflect the correct path?

*

*The Speech Control Panel creates registry entries for the training audio files in the key "HKCU\Software\Microsoft\Speech\RecoProfiles\Tokens{ProfileGUID}{00000000-0000-0000-0000-0000000000000000}\Files".

a) Do the registry entries created by my training code HAVE to be placed in "{00000000-0000-0000-0000-0000000000000000}\Files" or can I create a new random GUID under {ProfileGUID}?
b) Does the subkey HAVE to be named "Files"?
c) And do the registry values HAVE to follow the form "TrainingAudio-xxxx-xxxxxxxx-xxxxxxxx" or can I use other values?
d) Finally, the Registry Value Data is of the form "%1c%\Microsoft\Speech\Files\TrainingAudio\SP-xxx....xxx". Can I specify an absolute path?
e) Do the file names HAVE to follow the form "SP-xxx....xxx.wav" or can I use any unique file names?
Thanks.
Giri


text:
Q: Transfer data from Node backend to React frontend What I want to achieve is having a react application receive data posted to a Node-js server. Currently, the Node server receives a POST from an external source with a list of items. When the Node server receives the data, I want to send the data to the react application. This data will be used in the react application to display the listed items. How would I proceed to make this possible? Any advice is appreciated!
Thank you!

A: You can do this using Web Sockets. It would look something like this

*

*Your app connects to your API and maintains a socket

*The external source will POST to your API

*API handles the POST request

*Then the API passes some data on to the React app over the web socket

*Your app consumes said data

*Profit?

Socket.IO is a popular JavaScript library for web sockets with fallbacks and stuff.


text:
Q: AngularJS ng-repeat image loading issue I've recently started to use AngularJS on my projects and I've come across a big problem using ngRepeat to load thumbnails from a dynamic array into a DIV.
Since I won't be explaining the entire application here, I'll reproduce an isolated situation where the problem occurs.
Let's suppose I have an image tag with ngRepeat directive like this:
<img ng-repeat='n in [] | range: explorer.loadedLog.screenshotsNum' ng-src='getss.php?degenerated={{explorer.selectedLog}}&index={{n+1}}'>

Assuming that range is a custom filter that generates an array with explorer.loadedLog.screenshotsNum(variable modified by AJAX requests) elements and explorer.selectedLog is a string modified by AJAX requests. I feel like these informations are almost irrelevant cause a tested it with common dynamic arrays and came across the same problem.
The point is: when explorer.loadedLog.screenshotsNum and explorer.selectedLog are changed, all the new images have to be loaded.
I have a button for changing these values. When I first click it(at the first loading), it goes okay. If I wait for all the images to be loaded and change these values again, the new images are still loaded with no problems. But if I change it and change it again BEFORE all the images were loaded, it will load ALL the images that were left and then start loading the images that currently have to be loaded.
I mean, I don't know if I clearly explained this, but I thought if I modified these vars, the "old" images would just stop being loaded. But, somehow, they are still being loaded in background like the DOM from those were still somewhere in the document, and the "new" images' loading gets delayed. I actually wanted to stop the "old" images from being loaded and start loading the "new" images. I think it has to do with the way ngRepeat works, but I really wonder if there's no way to get through this without changing too much.
If I could solve this problem, the ngRepeat choice would be the best for me. But I still accept any other suggestion.
EDIT:
I've just noticed the obvious: when you set "src", it will make the request to the server and it won't stop even if you remove/change img src, so it has nothing to do with the way ngRepeat works but actually with the way <img> works. So, for my needs, window.stop() did the job(because my application doesn't have any restrictions to this), but I still wonder how I could make things work if I had any other images loading on the page simultaneously, since I couldn't simply call window.stop(). There is a way I can prevent an <img> from loading, so I could iterate over all the <img> elements inside a container and prevent them from loading one-by-one?

A: Is it possible for you to modify getss.php and add HTTP caching headers to the response? It won't change the browser trying to fetch the image when setting the src property, but it will fetch the image from the browser cache instead.
This should be helpful: How to use HTTP cache headers with PHP


text:
Q: Dell Inspiron 1525 - internal hard drive not detected Others have asked about this issue but had intermittent access to their HD, therefore their results did not apply to this situation. I have tried reseating the HD to no effect. I also tried booting from the Internal HD to no effect. Next step get a connector cable and move the data to a different HD, or send in for HD recovery? Any suggestions?

A: Due to the unfortunate possibility that the drive has failed, i would first attempt to recover the data by connecting the drive to a desktop computer, or a USB dock and see if you can recover the data yourself. If it works immediately backup your data so you no longer have to worry about it. Once your data is backed up look up the HDD manufacturers recommended testing method (seagate uses seatools). If it passes all the test then the port on the motherboard of your notebook has gone bad and you want to look at repair options.
If it does not pull up in another or on a USB dock then the drive is probably bad and you want to consult with the HDD Manufacturer about recovery options.
Some say you can freeze a HDD to recover it but be extremely careful with freezing the drive because condensation may render it unrecoverable at all.
Best of luck!


text:
Q: getting perticular listbox selected value using javascript I have html listbox as, which has same name but different id
<select name="dept"  id="vrow" >
                        <option selected="selected" > - Select Department- </option>
                        <option value="GEN">computer </option>
                        <option value="SC">mac </option>
                        <option value="ST">civ </option>
                        <option value="OBC">ele </option>
                      </select>

i had atteched it to each row fetched from database,
how can i get ID if i change perticular listbox value.

A: If you need id then use:
document.getElementById('vrow').addEventListener('change', function(e) {
   if (e.target.name==='dept') {
     alert(e.target.id);
   }
})

Working Demo
If you need value then use:
document.getElementById('vrow').addEventListener('change', function(e){
   if (e.target.name==='dept') {
       alert(e.target.value);
   }
})

Working Demo

A: You can add event listener on change event to parent node of all <select> elements it can ul if they are in list or even body.
<script type="text/javascript">
  document.getElementByTagName('UL').addEventListener('change', function(e) {
    if (e.target.name==='dept') {
      //In this case you have got element that you need and its id
      //e.target.id
      alert(e.target.id);
    }
  });
</script>

A: You Write Javascript Function or Jquery function
like this
<select onchange="dept(this.value)" name="dept"  id="vrow" >
<option selected="selected" > - Select Department- </option>
<option value="GEN">computer </option>
<option value="SC">mac </option>
<option value="ST">civ </option>
<option value="OBC">ele </option>
</select>

<script type="text/javascript">
function dept(id){
$.ajax({
url: 'ajax.php',
data: { id: id} ,
success: function (response) {
try{
alert(response);
}
catch(e){
alert("Error"+e);
}
},
error: function (e) {
alert("error"+e); or alert("error"+JSON.stringify(e));
}
});
}
</script>

Ajax.php


text:
Q: iPhone SDK: How to center map around a particular point? New to MapKit. Having problems centering map around a specified point. Here is the code. Not sure why this is not working. We are expecting to see a map centered around Cincinnati, OH. What we are seeing is the default google map of the world.
Any help appreciated.
/ Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    [super viewDidLoad];

    CLLocationCoordinate2D mapCoords[2];
    mapCoords[0].latitude = 39.144057;
    mapCoords[0].latitude = -84.505484;
    mapCoords[1].latitude = 39.142984;
    mapCoords[1].latitude = -84.502534;

    MKCoordinateSpan span;
    span.latitudeDelta = 0.2;
    span.longitudeDelta = 0.2;

    MKCoordinateRegion region;
    region.center = mapCoords[0];
    region.span = span;

    [mapView setRegion:region animated:YES];
}

A: Change:
mapCoords[0].latitude = 39.144057;
mapCoords[0].latitude = -84.505484;
mapCoords[1].latitude = 39.142984;
mapCoords[1].latitude = -84.502534;

To:
mapCoords[0].latitude = 39.144057;
mapCoords[0].longitude = -84.505484;
mapCoords[1].latitude = 39.142984;
mapCoords[1].longitude = -84.502534;

A: I do this in my code and it works fine:
MKCoordinateRegion region;
MKCoordinateSpan span;

span.latitudeDelta=0.2;
span.longitudeDelta=0.2;

CLLocationCoordinate2D location;
location.latitude = 39.144057;
location.longitude = -84.505484;

region.span=span;
region.center=location;

[mv setRegion:region animated:TRUE];
[mv regionThatFits:region];

A: The problem was a combination of the typos above and IB wiring problem.


text:
Q: Segmentation and Paging hardware The below figure illustrates the hardware implementation of segmentation :

The hardware implementation of paging is also shown below :

Source: Operating system concepts textbook
As we can see that both memory schemes use offsets in their logical address definition. In segmentation, we always check that this offset is less than the limit ( size ) of the segment, if the offset is larger than the limit of the segment, then we trap to the operating system ( addressing error ). However, this check is not available in paging hardware, although it also uses offset in its physical address?  Why is that ? Does this mean that in paging we always guarantee that no "unauthorized" memory access can be made ( for example memory access to another process's address space ) ?


text:
Q: syntax check. group two if statements if [ $DISTRO = "REDHAT"] || [ $DISTRO = "FEDORA"]; then
    if ! rpm -qa | grep -q glibc-static; then
        $BIN_ECHO -e " Package [glibc-static] not found. Installing.. "
        yum install glibc-static
    elif
        $BIN_ECHO -e " All required packages installed.. "
    fi
elif [ $DISTRO = "DEBIAN"]; then
    if ! dpkg-query -l glibc; then
        $BIN_ECHO -e " Package [glibc] not found. Installing.. "
        apt-get install glibc
    elif
        $BIN_ECHO -e " All required packages installed.. "
    fi
fi

line 156: syntax error near unexpected token `fi'
How do I put the two statements together?

A: You must have a space before the final ] on each test.
For example:
if [ $DISTRO = "REDHAT"] || [ $DISTRO = "FEDORA"]; then

must be re-written as either:
 if [ "$DISTRO" = REDHAT ] || [ "$DISTRO" = FEDORA ]; then

or
if test "$DISTRO" = REDHAT || test "$DISTRO" = FEDORA; then

Also note that there is no reason to quote literal strings, but you should quote variables.
You can also do :
if test "$DISTRO" = REDHAT -o "$DISTRO" = FEDORA; then

or
case "$DISTRO" in
REDHAT|FEDORA) ... ;;
DEBIAN) ... ;;
esac


text:
Q: Replacing a Char or part of a string to conform with an SQL query I know I've not gone about this in the easiest of manners but i'm fairly new to C#.
I'm trying to make sure that when I select from only 1,2,3 or 4 of the 5 checked list boxes that i do not end up with the following
&& or &&& etc... I would like the final string to be xxxxx&xxxxx&xxx or similar as the String is added to a preset SQL query.
Code is below:
any help would be appreciated I've had a look around online for some help but not found much I was able to get my head round.
        List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
        List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
        List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
        List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
        List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();

        string selected_fields_cb1 = string.Join(" ", list.ToArray());
        string selected_fields_cb2 = string.Join(" ", list2.ToArray());
        string selected_fields_cb3 = string.Join(" ", list3.ToArray());
        string selected_fields_cb4 = string.Join(" ", list4.ToArray());
        string selected_fields_cb5 = string.Join(" ", list5.ToArray());

        string allSelected = (selected_fields_cb1 + " " + selected_fields_cb2 + " " + selected_fields_cb3 +
           " " + selected_fields_cb4 + " " + selected_fields_cb5 + "");
        string allSelected2 = allSelected.Replace( " ", "&" );
        string allSelected3 = allSelected2.TrimEnd('&');

A: If I understand well, you try to add spaces and then replace these spaces by &.
It would be easier to do this directly.
List<object> list = checkedListBox1.CheckedItems.OfType<object>().ToList();
List<object> list2 = checkedListBox2.CheckedItems.OfType<object>().ToList();
List<object> list3 = checkedListBox3.CheckedItems.OfType<object>().ToList();
List<object> list4 = checkedListBox4.CheckedItems.OfType<object>().ToList();
List<object> list5 = checkedListBox5.CheckedItems.OfType<object>().ToList();

var allObjects = list.Concat(list2).Concat(list3).Concat(list4).Concat(list5);
var res = string.Join("&", allObjects);


text:
Q: How do I add a .NET Runtime in Edit->Prefrences? Ok I am using Windows and have .Net 3.5 and the Mono 2.6 frameworks installed.  I also have installed MonoDevelop and plan on using it. I just need to know if I am setup to use the Mono runtime.
All my projects have build options for Mono/Microsoft.NET 3.5, but in Edit->Prefrences->.NET Runtimes, all I see is Microsoft.NET. How do I add the Mono runtime to this list and make it default? Or do I even need to do this? I would think I would have to since our projects will be run on Linux, but not sure how to 'make sure' I am actually using Mono and not just .NET?

A: Mono should show up simply by virtue of being installed.  You can try reinstalling Mono to see if that helps.
If not, click the "Add" button on the Edit->Preferences->.Net Runtimes page and choose where you installed Mono to, generally it will be something like:
C:\Program Files\Mono-2.6.1
If you want it to be the default, click "Set as Default" while it's highlighted and it should turn bold, indicating it is now the default.  There is also a combobox on the main MD toolbar if you want a quicker way of switching between runtimes.

A: You shouldnt HAVE to build using Mono's compiler on Windows to have your code run on Linux.
As per answers on Performance: Compile in CS, Run in mono on windows and linux, you can compile with any compiler and run with any runtime because the compiled binary is in an Intermediate Language
You just have to be certain that your code, and the libraries that it uses, do not make operating system specific calls, P/Invoke unmanaged DLL's, or make calls to functions that are incomplete in Mono (mind you, these are getting rare)


text: Q: SQL Server OFFSET FETCH - best way to check whether there are more records left I am using SQL Server's OFFSET FETCH construct to achieve pagination. The UI client needs a way to determine whethee there are more records to be fetched. What is the standard way of achieving this? I remember having read that the results follow some kind of semantics which help the client figure out whether there are more rows, but I am not able to find that now. Can you please help me with this? If there is no such semantic, then what is the best way of achieving this? I really want to avoid having to run another query to check if there are more records.


text:
Q: Translate array of strings to user language Android studio Im facing a problem where I have an array that contains words in english, for example:
Array = ["Apple", "Orange", "Banana"]

What I want is that if the user doesn't use English as primary language, for example instead Swedish, I want the array to be translated to that language using the strings.xml provided translations. So that the array becomes this instead:
Array = ["Äpple", "Apelsin", "Banan"]

With Xcode I could just use .localized after the array but I couldn't find similar function in Android studio. Anyone that has a good solution for this?
Greetings, Pontus.


text:
Q: Default namespaces in nested elements I'm just curious about default namespaces. I have the follow xml:
<root xmlns="myNamespace">
    <someElement xmlns="anotherNamespace">
        <data>Info</data>
    </someElement>
    <anotherElement>
        <moreData>Info2</moreData>
    </anotherElement>
</root>

My guess is that myNamespace is inherit for <root> and <anotherElement>. And anotherNamespace is a default namespace in <someElement> so in this element and for its child's overrides the other myNamespace.
I know that I can rewrite the above xml code like:
<my:root xmlns:my="myNamespace">

        Info

    <my:anotherElement>
        <my:moreData>Info2</my:moreData>
    </my:anotherElement>
</my:root>

I think that both are totally valid but I have some problems with some xml beans implementation in java which doesn't accept the first one, so I'm curious if there is an xml specification where specifies if first aproach is or not correct.

A: The first approach is valid. In xml-names specification in section 6.2 Namespace Defaulting it explains:

The scope of a default namespace declaration extends from the
  beginning of the start-tag in which it appears to the end of the
  corresponding end-tag, excluding the scope of any inner default
  namespace declarations.

And also includes this example:

<book xmlns='urn:loc.gov:books'
      xmlns:isbn='urn:ISBN:0-395-36341-6'>
    <title>Cheaper by the Dozen</title>
    <isbn:number>1568491379</isbn:number>
    <notes>

          This is a funny book!

    </notes>
</book>


text:
Q: Adjust margins of grob object in r I made a grob object using the cowplot package. I'm adding grid.lines() and grid.text() objects to finished grob but as it comes out of cowplot it fills the whole page. How can I adjust the margins of the grob object to add some white space around the edges? Example code below.
library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point()
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point()
p4 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv")

A: You just use theme(plot.margin = ...) as you would in a ggplot:
library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point()
p2 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
p3 <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point()
p4 <- ggplot(mtcars, aes(qsec, mpg)) +
  geom_point()
plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv")

plot_grid(p1, p2, p3, p4, ncol = 2 ,nrow = 2,align="hv") +
  theme(plot.margin = unit(c(20,20,20,20), "points"))

Created on 2020-04-29 by the reprex package (v0.3.0)


text:
Q: `go test` succeed for individual tests but fails when testing package When I run single test with go test -run TestNewProbeServiceIsSingleton it passes as expected.
Problem occurs whenever I am trying to test the whole package/app using go test ./... from my project's root directory:
madjlzz@MadSfeirLab $ go test ./...
?       github.com/madjlzz/madprobe     [no test files]
ok      github.com/madjlzz/madprobe/controller  (cached) [no tests to run]
?       github.com/madjlzz/madprobe/internal/alerter    [no test files]
?       github.com/madjlzz/madprobe/internal/mock       [no test files]
?       github.com/madjlzz/madprobe/internal/persistence        [no test files]
--- FAIL: TestInsertReturnErrorOnGetFailure (0.00s)
panic: Fail in goroutine after TestNewProbeServiceIsSingleton has completed [recovered]
        panic: Fail in goroutine after TestNewProbeServiceIsSingleton has completed [recovered]
        panic: Fail in goroutine after TestNewProbeServiceIsSingleton has completed

goroutine 23 [running]:
testing.tRunner.func1(0xc0000f6400)
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:874 +0x3a3
panic(0x12ccca0, 0xc000095190)
        /usr/local/Cellar/go/1.13.6/libexec/src/runtime/panic.go:679 +0x1b2
github.com/golang/mock/gomock.(*Controller).Finish(0xc000098ff0)
        /Users/madjlzz/Documents/Projects/Go/pkg/mod/github.com/golang/mock@v1.4.3/gomock/controller.go:246 +0x2b2
panic(0x12ccca0, 0xc000095190)
        /usr/local/Cellar/go/1.13.6/libexec/src/runtime/panic.go:679 +0x1b2
testing.(*common).Fail(0xc0000f6200)
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:609 +0x151
testing.(*common).FailNow(0xc0000f6200)
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:631 +0x2b
testing.(*common).Fatalf(0xc0000f6200, 0x1351581, 0x2e, 0xc0000c4140, 0x5, 0x5)
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:716 +0x90
github.com/golang/mock/gomock.(*Controller).Call.func1(0xc000098de0, 0x1301ca0, 0xc000094f90, 0x1343807, 0x3, 0xc000095110, 0x1, 0x1, 0x0, 0x0, ...)
        /Users/madjlzz/Documents/Projects/Go/pkg/mod/github.com/golang/mock@v1.4.3/gomock/controller.go:201 +0x486
github.com/golang/mock/gomock.(*Controller).Call(0xc000098de0, 0x1301ca0, 0xc000094f90, 0x1343807, 0x3, 0xc000095110, 0x1, 0x1, 0x5, 0xc00008a660, ...)
        /Users/madjlzz/Documents/Projects/Go/pkg/mod/github.com/golang/mock@v1.4.3/gomock/controller.go:217 +0xb4
github.com/madjlzz/madprobe/internal/mock.(*MockPersister).Get(0xc000094f90, 0x134426b, 0x7, 0x16, 0x0, 0x0)
        /Users/madjlzz/Documents/Projects/Go/src/github.com/madjlzz/madprobe/internal/mock/entity.go:53 +0xe5
github.com/madjlzz/madprobe/internal/prober.(*service).Insert(0xc000098e70, 0x134426b, 0x7, 0x1348f2d, 0x16, 0x0, 0x0, 0x5, 0xc00008a660, 0x156df40, ...)
        /Users/madjlzz/Documents/Projects/Go/src/github.com/madjlzz/madprobe/internal/prober/service.go:63 +0x19b
github.com/madjlzz/madprobe/internal/prober.TestInsertReturnErrorOnGetFailure(0xc0000f6400)
        /Users/madjlzz/Documents/Projects/Go/src/github.com/madjlzz/madprobe/internal/prober/service_test.go:59 +0x4fb
testing.tRunner(0xc0000f6400, 0x135be98)
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:909 +0xc9
created by testing.(*T).Run
        /usr/local/Cellar/go/1.13.6/libexec/src/testing/testing.go:960 +0x350
FAIL    github.com/madjlzz/madprobe/internal/prober     0.287s
?       github.com/madjlzz/madprobe/util        [no test files]
FAIL

App builds without any errors:
madjlzz@MadSfeirLab $ go build .
madjlzz@MadSfeirLab $

My Golang version is:
madjlzz@MadSfeirLab $ go version
go version go1.13.6 darwin/amd64

I am using also mockgen to mock my interfaces in version 1.4.3
I am new to Golang but it feels I kinda miss something on how to run tests...
You can also run the tests by yourself by cloning the project

A: I assume ur code looks like (I had such problem):
for _, subtest := range subtests{
   t.Run(subtest.name,
        func(t *testing.T) {
           do something with subtest...
        }
}

But it must look like:
for _, s := range subtests{
   subtest:=s

   t.Run(subtest.name,
        func(t *testing.T) {
           do something with subtest...
        }
}

Attention on subtest:=s
This is one of the possible solutions in this situation.


text:
Q: Detecting the device presence in a Pocket My application needs to know whether the phone is in the pocket or in hand based on which few parameters are set specific to individual than to move on to perform next tasks.
I have read various blogs and also SensorManager android developer but none helped me out. The only related link I found on stack is this with no solution, Though one comment on that question suggests using Awareness API. I am going through it, my understanding is that the User Activity is the context to find this- I may be wrong. There maybe someone worked or may be doing R&D on this, please share your observation that may help me out in some way to go further.
Is there any way to find is the phone in pocket or not?If yes, Can somebody tell me How do One do that?
Any guidance/links to the concepts are helpful.
Thanks.

A: I implemented this in my project. I got readings from the Light sensor, Accelerometer and Proximity sensor. Keep in mind that it approximately detects device presence in a pocket.
Getting the current parameteres from the sensors (accelerometer, proximity and light sensors):
@Override
public void onSensorChanged(SensorEvent event) {

    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        g = new float[3];
        g = event.values.clone();

        double norm_Of_g = Math.sqrt(g[0] * g[0] + g[1] * g[1] + g[2] * g[2]);

        g[0] = (float)(g[0] / norm_Of_g);
        g[1] = (float)(g[1] / norm_Of_g);
        g[2] = (float)(g[2] / norm_Of_g);

        inclination = (int) Math.round(Math.toDegrees(Math.acos(g[2])));
        accReading.setText("XYZ: " + round(g[0]) + ",  " + round(g[1]) + ",  " + round(g[2]) + "  inc: " + inclination);
    }
    if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        proximityReading.setText("Proximity Sensor Reading:" + String.valueOf(event.values[0]));
        rp = event.values[0];
    }
    if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
        lightReading.setText("LIGHT: " + event.values[0]);
        rl = event.values[0];
    }
    if ((rp != -1) && (rl != -1) && (inclination != -1)) {
        main.detect(rp, rl, g, inclination);
    }
}

Then based on this data I decide whether or not the device is in a pocket:
public void detect(float prox, float light, float g[], int inc){
    if((prox<1)&&(light<2)&&(g[1]<-0.6)&&( (inc>75)||(inc<100))){
        pocket=1;
        //IN POCKET
    }
    if((prox>=1)&&(light>=2)&&(g[1]>=-0.7)){
        if(pocket==1){
            playSound();
            pocket=0;
        }
        //OUT OF POCKET
    }

}
Keep in mind that it's not fully accurate.
Code: https://github.com/IvanLudvig/PocketSword
Blog post: https://ivanludvig.github.io/blog/2019/06/21/detecting-device-in-a-pocket-android.html

A: The only way we can come somewhat near to the solution is using.Google Awareness API wont solve the problem as it has a entirely different usage.

*

*Light sensor(Environment sensor)

*Proximity sensor(Position sensor)

The Android platform provides four sensors that let you monitor various environmental properties. You can use these sensors to monitor

*

*relative ambient humidity

*luminescence

*ambient pressure

*ambient temperature

All four environment sensors are hardware-based and are available only if a device manufacturer has built them into a device. With the exception of the light sensor, which most device manufacturers use to control screen brightness, environment sensors are not always available on devices. Because of this, it's particularly important that you verify at run time whether an environment sensor exists before you attempt to acquire data from it.
Light sensor can be used to calculate the light intensity.For example many mobile phones having Auto brightness mode function, this function work on light sensor that will adjust screen brightness as per light intensity.
There are many unites such as Lux,candela,lumen etc, to measure light intensity.
Considering this there will be considerable difference in light intensity when you phone in in pocket or outside pocket.
Although the same will happen for the case when you are operating phone is dark room. or at those place where the light intensity is quite low. hence to distinguish among such cases is the real challenge.You can use other environments sensor in combination of light sensor to come to an effective outcome.But i assume an accurate solution is dicey.
To study more about these sensors kindly refer to following links
https://developer.android.com/guide/topics/sensors/sensors_environment.html
https://developer.android.com/guide/topics/sensors/sensors_position.html
Google awareness API wont work for this case. as provides entirely different solution.
It provides two API

*

*Fence API

*Snapshot API

You can use the Snapshot API to get information about the user's current environment. Using the Snapshot API, you can access a variety of context signals:

*

*Detected user activity, such as walking or driving.

*Nearby beacons that you have registered.

*Headphone state (plugged in or not)

*Location, including latitude and longitude.

*Place where the user is currently located.

*Weather conditions in the user's current location.

Using the Fence API, you can define fences based on context signals such as:

*

*The user's current location (lat/lng)

*The user's current activity (walking, driving, etc.).

*Device-specific conditions, such as whether the headphones are
plugged in.

*Proximity to nearby beacons.

A: For a cross-platform solution, you can now use the NumberEight SDK for this task.
It performs a wide variety of context recognition tasks on both iOS and Android including:

*

*Real-time physical activity detection

*Device position detection (i.e. presence in pocket)

*Motion detection

*Reachability

*Local weather

It can also record user context for reports and analysis via the online portal.
How to detect whether a phone is in a pocket:
For example, to record user activity in Kotlin, you would do:
val ne = NumberEight()

ne.onDevicePositionUpdated { glimpse ->
    if (glimpse.mostProbable.state == State.InPocket) {
        Log.d("MyApp", "Phone is in a pocket!")
    }
}

or in Java:
NumberEight ne = new NumberEight();

ne.onDevicePositionUpdated(
    new NumberEight.SubscriptionCallback<NEDevicePosition>() {
        @Override
        public void onUpdated(@NonNull Glimpse<NEDevicePosition> glimpse) {
            if (glimpse.mostProbable.state == State.InPocket) {
                Log.d("MyApp", "Phone is in a pocket!");
            }
        }
    });

Here are some iOS and Android example projects.
Disclosure: I'm one of the developers.


text:
Q: Cannot read properties of undefined (reading 'network') How can I replace in my chrome extension chrome.privacy.network.webRTCIPHandlingPolicy from mv2 to mv3.
Uncaught TypeError: Cannot read properties of undefined (reading 'network')
I did not find an answer in the migration documentation for manifest version 3


text:
Q: Aligning  tags within a page I have the following code:
<!DOCTYPE html>

<?php

    $i =0;
    for($i=0; $i< 5; $i++) {
        echo'

 '.$i.'
';
    }

    for($i=4; $i>= 0; $i--) {
        echo'

 '.$i.'
';
    }

?>

See it working:

0

1

2

3

4

4

3

2

1

0

Where I'm trying to print the numbers 0-4 and 4-0 in the middle of the page, where one is a bit right of the middle, and the other a bit left (margins).
I want the output to look like this:
                             0 4
                             1 3
                             2 2
                             3 1
                             4 0

Where the increasing numbers would be in the center minus 120 pixels to the left, and decreasing would be in the center minus 120 pixels to the right
I've tried adding the CSS:
.bloc{
    display:inline;
    float:left;
}

But that seems to place all the numbers in one spot, not the way I'd like them to be pictured. I also tried using the  tag which yielded the same result.

A: you could actually try

*

*using padding instead of margin

*it'd be more easy to create a wrapper with an margin 0 auto and auto width where elements will have no float.

*You could try some tricks with :nth-child(even). See here: http://www.w3schools.com/cssref/sel_nth-child.asp

*You could try to read about flex box: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Maybe I misunderstood your question. Don't hesitate to reply.

A: This will help you:

<?php
$i =0;
for($i=0; $i< 5; $i++) {
echo'
'.$i.'-

';
}

?>

<?php
for($i=4; $i>= 0; $i--) {
echo'
 '.$i.'

';
}
?>

A:

.leftdiv,.rightdiv{display:inline-block;}
.parent{text-align:center;}

0

1

2

3

4

4

3

2

1

0

A: You need to do your table in one LOOP like this.

        <?php
        $limit = 4;
        for ( $i = 0, $j = $limit; $i <= $limit & $j >= 0; $i++, $j-- ) {
            echo "
";

            echo "". "$i" . "	";
            echo "". "$j" . "	";

            echo "
";
        }
        ?>

      0
      4

      1
      3

      2
      2

      3
      1

      4
      0

A: Try this,

<?php
    for($i=0; $i< 5; $i++) {
        echo'

 '.$i.'
';
        for($j=4-$i; $j<5-$i; $j++){
            echo'

 '.$j.'
';
        }
        echo "
";
    }
?>

A: As PHP, you can use that
<!DOCTYPE html>

<?php
    $i =0;
    for($i=0; $i< 5; $i++) {
        echo'
'.$i.'
';
        echo'
'.(4-$i).'
';
    }
?>

As snippet

.bloc{display: inline-block; width: 49%;}
.left{text-align: right; padding-right:0.5%;}
.right{text-align: left; padding-left:0.5%;}

0

4

1

3

2

2

3

1

4

0

A: You could group them, and set the width to 50% to make sure they're centred correctly
<!DOCTYPE html>

    <?php for($i=0; $i< 5; $i++) : ?>
        <?php echo '
'.$i.'
'; ?>
    <?php endfor; ?>

    <?php for($i=4; $i>= 0; $i--) : ?>
        <?php echo '
'.$i.'
'; ?>
    <?php endfor; ?>


text:
Q: Graph API: Check if app already posted in the past x days before creating a wall post? I would like to post to the user wall, but I want to limit the posts my app makes to max 1 per day or week.
Can I check how many posts my app made so far in the past day / week or do I need to store this on my side?

A: You can filter the FQL stream table by app_id.
Combine that with source_id (ID of user the wall belongs to) and created_time greater than 1 day / 1 week in the past, and LIMIT 1.
If you get a result, then there was a post made through your app in the specified time range.


text:
Q: print web report in C#.Net I need to create a clients details report for a web based application in c#.Net. There will be multiple client details one by one.
When take print of this web page, the first page will be the cover page and the remaining pages contains clients details. The pages except the cover page should be numbered "page x of y" in the centre of the footer. The top of each page should display the client name that is the subject of the sub-report. If part of a sub-report section spans onto a new page, the whole section should be moved to the new page. Any solution for implementing this?

A: I would  create a template of my report with the ReportViewer control. Then I would push data into it from code behind or link it to my DB to generate report automatically. You can find a Getting start with report viewer there.