text:
Q: React: rendering images before pressing the button I've been trying to work on an image search react project where you can click and store images that you want after searching. Right now I am able to search for and show the image as buttons, but the images appear on the button only after you click it.
function Image(props) {
  return (
  <button className = "photo" onClick = {props.onClick}>
    <img
      width={200} height={200}
      src = {props.value}
      alt = ""
      onClick={myfunction()} />
  </button> )
}

These functions below are inside another class
handleClick(i){
    const image = this.state.image.slice();
    console.log(global.imageLinks);
    image[i] = global.imageLinks[i];
    this.setState({
      image: image,
    })
}

renderImage(i) {
    return (
        <Image
        value = {this.state.image[i]}
        onClick={() => this.handleClick(i)}
    />)
}

I tried deleting the onClick part in the button or moving the image section but it just causes a lot of errors. Is there any way so that the image will appear on the button as soon as it detects that the value is a link?
Many thanks!


text:
Q: bitbucket pipeline deployment approval I have been looking for implementing deployment approval within bitbucket pipeline. Basically it's similar to Octopus deploy you can implement 'awaiting for approval' step.  Has anyone ever implemented it with bitbucket pipeline ?

A: Yes, you can trigger steps manually by specifying trigger: manual in your step.
See the docs for more information

redpajama_set_name: RedPajamaStackExchange


text:
Q: struts 2 assigning value of property tag to hidden field I want to assign the value from field Description to a hidden field test.
But the problem is the "Description" contains sequence of words and the following code is assigning only first word to "test"
<s:hidden value=<s:property  value="Description" />  name="test">
I am kind of new to struts. Can someone please help.
Also it would be nice if i get to know good tutorial links of struts2.

A: <s:hidden  value="%{description}" name="test" />

A: If this is a property in your action class you need not to use <s:property value="Description" /> as the Description will be available at the top of value stack and you can use OGNL to fetch the value from value-stack.This is what you need to do
<s:hidden  value="%{description}" name="test" />

Please make sure the value in hidden filed should be similar to the name of property in your action class as it will be resolved to either the getter and setter in your action class or the public property defined in your action.
So this means value="%{description}" will be converted by OGNL like getDescription() and will try to find the getter in your action class to fetch the property value.


text:
Q: gunicorn.service: Failed at step CHDIR spawning */env/bin/gunicorn: No such file or directory gunicorn.service cannot open WorkingDirectory and the gunicorn executable. I think it's about permissions but I don't know how I can solve it.
sudo systemctl status gunicorn:
Mar 15 12:12:42 ns1.localhost.com systemd[1]: Started gunicorn daemon.
Mar 15 12:12:42 ns1.localhost.com systemd[16439]: gunicorn.service: Changing to the requested working directory failed: No such file or directory
Mar 15 12:12:42 ns1.localhost.com systemd[16439]: gunicorn.service: Failed at step CHDIR spawning /home/radarkes-api/env/bin/gunicorn: No such file or directory
Mar 15 12:12:42 ns1.localhost.com systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR
Mar 15 12:12:42 ns1.localhost.com systemd[1]: gunicorn.service: Failed with result 'exit-code'.

/etc/systemd/system/gunicorn.service:
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=root
Group=www-data
WorkingDirectory=/home/radarkes-api/src
ExecStart=/home/radarkes-api/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/radarkes-api/src/core.sock core.wsgi:application

[Install]
WantedBy=multi-user.target

I can run /home/radarkes-api/env/bin/gunicorn manually, this is the output which means I can access the gunicorn executable:
usage: gunicorn [OPTIONS] [APP_MODULE]
gunicorn: error: No application module specified.

I tried:

*

*Adding "source /home/radarkes-api/env/bin/activate &&" at the start of ExecStart.

*chmod -R 777 /home/radarkes-api

tree -d -L 2 /home/radarkes-api/:
radarkes-api/
├── env
│   ├── bin
│   └── lib
└── src
    ├── api
    └── core

How can I solve this?


text:
Q: Error NULL DEFAULT NULL Laravel migration with MariaDB I have the following migration, where I'm adding an extra column in a table:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddTenantIdToPeopleTable extends Migration
{
    public function up()
    {
        /*
        * Need to create the column as null and then mark it as non-null to
        * avoid SQLite problem General error: 1 Can not add to NOT NULL column with default value NULL
        */

        Schema::table('people', function (Blueprint $table) {
            $table->integer('tenant_id')->nullable()->unsigned();
            $table->index('tenant_id');
        });

        Schema::table('people', function (Blueprint $table) {
            $table->integer('tenant_id')->nullable(false)->change();
        });
    }

    public function down()
    {
        Schema::disableForeignKeyConstraints();
            Schema::table('people', function (Blueprint $table) {
                $table->dropColumn('tenant_id');
            });
        Schema::enableForeignKeyConstraints();
    }
}

I can run this migration with PostgreSQL, SQLite and MySQL without any errors, but when I try to run with Maria DB, this error happens:
Error
I tried some things but nothing works.

A: I've managed to get this thing working.
I just added the "->default(null)"
I did this:
public function up()
    {
        Schema::table('people', function (Blueprint $table) {
            $table->integer('tenant_id')->nullable()->unsigned();
            $table->index('tenant_id');
        });

        Schema::table('people', function (Blueprint $table) {
            $table->integer('tenant_id')->nullable(false)->default(null)->change();
        });
    }


text:
Q: How can I resolve it with Insert Into sprintif? I installed a system with Xampp 5.6. Apache 5.6 and PhpMyAdmin 4.7.7. and I have this problem when insert on system.

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1

My code for insert is:
<pre>

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "agrega_inventario")) {
    $insertSQL = sprintf("INSERT INTO inventario_computo
                        (fecha_alta, observaciones, valor, iva, total,
                        comodato, num_factura, id_personal,
                        id_computo_categoria, id_inventario_lugar,
                        id_inventario_proveedor, id_municipio, nombre,
                        descripcion, num_serie, num_modelo, marca,
                        status, num_baja, num_inventario,
                        resguardo, rubro)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
                        %s, %s, %s, %s, %s, %s, 0,%s,0,%s)",
        GetSQLValueString($_POST['fecha_alta'], "date"),
        GetSQLValueString($_POST['observaciones'], "text"),
        GetSQLValueString($_POST['valor'], "double"),
        GetSQLValueString($_POST['iva'], "double"),
        GetSQLValueString($_POST['total'], "double"),
        GetSQLValueString($_POST['comodato'], "int"),
        GetSQLValueString($_POST['num_factura'], "text" /* "int" BOMS (05/Oct/2015) Se cambio el Tipo de dato */),
        GetSQLValueString($_POST['id_personal'], "int"),
        GetSQLValueString($_POST['id_inventario_categoria'], "int"),
        GetSQLValueString($lugar_post, "int"),
        GetSQLValueString($proveedor_post, "int"),
        GetSQLValueString($_POST['id_municipio'], "int"),
        GetSQLValueString($_POST['nombre_bien'], "text"),
        GetSQLValueString($_POST['descripcion'], "text"),
        GetSQLValueString($_POST['num_serie'], "text"),
        GetSQLValueString($_POST['num_modelo'], "text"),
        GetSQLValueString($_POST['marca'], "text"),
        GetSQLValueString($_POST['id_inventario_status'], "int"),
        GetSQLValueString($_POST['num_inventario'], "text"),
        GetSQLValueString($_POST['rubro'], "int"));

I can't fix it.


text:
Q: How to check more than one year in 'leap year' Just recently started learning C# and did in class the 'leap year'. We came up with this solution. But it only allows to check one year at a time. Is there a nice way to check more at once? Let's say I need to check 10 different years if they are leap or not. All I could think of is copying the block and giving new variable.
int a = int.Parse(Console.ReadLine());

bool div1 = a % 4 == 0;
bool div2 = a % 100 != 0;
bool div3 = a % 400 == 0;

if ((div1 && div2) || div3)
{
    Console.WriteLine($"{a} is a leap year");
}
else
{
    Console.WriteLine($"{a} is not a leap year");
}

A: One way to do this is to write a function that takes in an int and returns true if the int represents a leap year. For example, the method below uses a simplified, one-line version of the code you wrote above:
public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

Then, you can get a bunch of years from the user (in this example we're using a comma-separated list of years), split the years into an array (on the comma character), and call this method for each year in a loop:
private static void Main()
{
    // Get a list of years from the user
    Console.Write("Enter some years separated by commas: ");
    var input = Console.ReadLine();

    // Split the user input on the comma character, creating an array of years
    var years = input.Split(',');

    foreach (var year in years)
    {
        bool isLeapYear = IsLeapYear(int.Parse(year));

        if (isLeapYear)
        {
            Console.WriteLine("{0} is a leap year", year);
        }
        else
        {
            Console.WriteLine("{0} is not a leap year", year);
        }

    }
    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output

Another thing you can do, if you want to enter them one at a time, is just ask the user for a new year inside a loop, and give them the answer after they enter an integer. Here's an example, where I also added another function called GetIntFromUser, which forces them to enter a valid integer (it keeps asking until one is entered):
private static void Main()
{
    // In this loop, ask for a year and tell them the answer
    while (true)
    {
        int input = GetIntFromUser("Enter a year to check: ");
        string verb = IsLeapYear(input) ? "is" : "is not";
        Console.WriteLine($"{input} {verb} a leap year.\n");
    }
}

public static int GetIntFromUser(string prompt)
{
    int input;

    // Show the prompt and keep looping until the input is a valid integer
    do
    {
        Console.Write(prompt);
    } while (!int.TryParse(Console.ReadLine(), out input));

    return input;
}

public static bool IsLeapYear(int year)
{
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

Output

A: First, you put the existing code into a function, so it can be re-used:
public bool IsLeapYear(int year)
{
    bool div1 = year % 4 == 0;
    bool div2 = year % 100 != 0;
    bool div3 = year % 400 == 0;
    return ((div1 && div2) || div3);
}

Then let's say you have a set of 40 years in an array:
//don't worry about how this works right now.
// just know it gives you an array with 40 years starting in 1980
int[] years = Enumerable.Range(1980, 40).ToArray();

You can check all of them like this:
foreach (int year in years)
{
    if (IsLeapYear(year))
    {
        Console.WriteLine($"{year} is a leap year");
    }
    else
    {
        Console.WriteLine($"{year} is not a leap year");
    }
}

A: You can use LINQ.
var years = new int[] { 1999, 2000, 2001, 2002 };  //etc...

Console.WriteLine(String.Join(Environment.NewLine, years
    .Select(y => $"{y} {(DateTime.IsLeapYear(y) ? "is" : "is not")} a leap year")
    .ToArray()));

A: You can read a string of years (e.g.: 1991,1992,2001,2004), then split the string to array with string.split(','). Loop through the array to check for leap year.

A: First of all, if you are using int.Parse(), you should use it in try-catch block. Otherwise your program will crash everytime when user enters nonsense.
Second, if you want to implement your own method for studying purposes - it`s okay, but you can use DateTime structure, which has IsLeapYear():
    // Summary:
    //     Returns an indication whether the specified year is a leap year.
    //
    // Parameters:
    //   year:
    //     A 4-digit year.
    //
    // Returns:
    //     true if year is a leap year; otherwise, false.
    //
    // Exceptions:
    //   T:System.ArgumentOutOfRangeException:
    //     year is less than 1 or greater than 9999.

So, the implementation is:
class LeapYear
{
    static void Main(string[] args)
    {
        for (int input = 0; input < 10;) // Ask user until he enters year 10 times correctly
        {

            Console.Write("Please enter a year: ");

            try
            {
                int year = int.Parse(Console.ReadLine());

                if (DateTime.IsLeapYear(year))
                {
                    Console.WriteLine($"{year} is leap");
                    input++;
                }
                else
                    Console.WriteLine($"{year} is not leap");
            }

            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("Argument Out Of Range");
            }

            catch (FormatException)
            {
                Console.WriteLine("Bad Format");
            }

            catch (OverflowException)
            {
                Console.WriteLine("Overflow");
            }

        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }
}


text:
Q: Scala application running in Eclipse but not as a jar I have a Scala application (maven based) which is running fine till yesterday. Today I tried to add the log4j2 functionality to it. I added the required maven dependencies and the corresponding configurations (log4j2.xml). I created a small scala program which writes simple logger.info message. It is running fine from Eclipse. I used mvn package to generate the jar with dependencies. When I run it from command line, it giving me an exception saying "java.lang.ClassNotFoundException: org.apache.logging.log4j.core.appender.AbstractAppender". I can see the log4j class files in the exported jar. Also, I can see the dependency jars(log4j-core, log4j-api) in the Project -> Configure Build Path window. I also deleted the .m2 folder and clean build the project. What am I missing here? Please help me out. Below is my pom.xml file.
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>datamover</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <name>BI - Data Mover</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.microsoft.azure/applicationinsights-logging-log4j2 -->
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-logging-log4j2</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api-scala_2.11</artifactId>
            <version>11.0</version>
        </dependency> -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-hive -->
        <!-- <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-hive_2.10</artifactId>
            <version>2.1.0</version> </dependency> -->

        <!-- https://mvnrepository.com/artifact/com.databricks/spark-avro_2.10 -->
        <dependency>
            <groupId>com.databricks</groupId>
            <artifactId>spark-avro_2.11</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.11 -->
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.microsoft.azure/azure-data-lake-store-sdk -->
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-data-lake-store-sdk</artifactId>
            <version>2.2.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>6.2.2.jre8</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.databricks/spark-csv_2.10 -->
        <dependency>
            <groupId>com.databricks</groupId>
            <artifactId>spark-csv_2.11</artifactId>
            <version>1.5.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.test.bi.ScalaLogTestV2</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id> <!-- this is used for inheritance merges -->
                        <phase>package</phase> <!-- bind to the packaging phase -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <description>Spark application to move data folders.</description>
</project>

A: This should work if you are working with eclipse IDE.
Please try this approach.
Go to Project properties -> Deployment assembly and ensure that the maven dependencies entry is included.
I've seen that this configuration gets missed whenever you execute Maven -> Update Project.


text:
Q: Using paging in UITableViewController I have a UITableViewController that looks like this:
https://www.dropbox.com/s/dy6o55qa8squi9f/Screen%20Shot%202015-04-14%20at%2000.13.29.png?dl=0
And i want to implement a paging system by using UIScrollView. Now from what i understood UITableView inherits from UIScrollView. Still i have no clue how to proceed to make this happen.
So what i want to be able to do is when the users enters the view i showed on the picture the user can swipe to get to another UITableView with different data of course.
I tried myself using gestures for a while but i learned that i should not use it and use this method instead. I have been trying out this for a while to but i am getting nowhere.
Some guidance or code snippets would be of great help!
I am using storyboards.
Thank you

A: If you want to page vertically up and down within the table view, set pagingEnabled to YES on it and set its contentSize. That might get to be an issue if you start having rows that don't line up with the contentSize perfectly though.
If you want to page horizontally between different table views, you need to put each table view into a UIScrollView, set it's contentSize to be the width of each of the table views summed together, and set pagingEnabled to yes on it.


text:
Q: Aframe React dynamic string value Just trying to get my head around using react and aframe together with the spread operator etc.
So I have an Entity using Meshline
<Entity meshline="lineWidth: 20; path: -2 -1 0, 0 -2 0, 2 -1; color: #E20049" />

I'm trying to make that path string dynamic with 2 objects i.e. something like
buttonConfig.position = {
    x:config.position.x-3,
    y:config.position.y+3,
    z:config.position.z,
}

lineX = {
    lineWidth : 20,
    path: {...config.position,...buttonConfig.position},
    color: '#ffffff',
}

But that's obviously not working because I get a

TypeError: value.split is not a function

How do I turn that object into a string of values via AFRAME/React? Or am I trying to be too clever here and should just build the string?

A: Although the component should be taking object arrays as its input, it seems to always parse the path with its parse() function (64th line).
I've tried with [{x,y,z},{x,y,z}], but with no luck.
The workaround is easy though: the AFRAME.utils.coordinates.stringify function, which turns an {x,y,z} object into a "x y z" string.
So having an array of coordinate objects, you can get Your coords with one forEach:
array.forEach((el, index)=>{
  stringified += AFRAME.utils.coordinates.stringify(el)
  if(index != array.length - 1) {
     stringified +=","
  }
}

and use the stringified as Your meshline path.

It's a bit late, but i've managed to get a working fiddle.


text:
Q: salesforce web to lead with "notes" I'm trying to use Web to Lead functionality of salesforce. I can create a lead, but the Notes field does not get the data I supplied in the form. Here's the form I'm sending:

<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">

<input type=hidden name="oid" value="xxxxxxx">
<input type=hidden name="retURL" value="http://www.mycompany.com">

First Name<input  id="first_name" maxlength="40" name="first_name" size="20" type="text" />

Last Name<input  id="last_name" maxlength="80" name="last_name" size="20" type="text" />

Email<input  id="email" maxlength="80" name="email" size="20" type="text" />

Company<input  id="company" maxlength="40" name="company" size="20" type="text" />

Notes:<textarea  id="00N6100000C5D5Z" name="00N6100000C5D5Z" type="text" wrap="soft"></textarea>

Street<textarea name="street"></textarea>

<input type="submit" name="submit">

</form>

Every field gets populated in the new lead entry, except Notes. Has anyone ran into this issue? How did you resolve it?
Thanks in advance!

A: I haven't got why you have specified type="text" with your textarea. Textarea itself is a type.
Can you replace

Notes:<textarea  id="00N6100000C5D5Z" name="00N6100000C5D5Z" type="text" wrap="soft"></textarea>

With:

Notes:<textarea  id="00N6100000C5D5Z" name="00N6100000C5D5Z" wrap="soft"></textarea>

Give it a try.


text:
Q: the attribute "href" of a  tag is a URL,but it calls functions after clicking the  tag.How it works I found this question in jQuery UI demos.If you downloaded the jQuery UI,and so it located in "demos/droppable/photo-manager.html".
In this html page,there were several  tags showing the delete icons in photo div.These  tags' property named "href" are URLs,but it would call functions after clicking the  tags.
URLs->functions?How to do that?

A: You can attach a click event to a link and null the browser's default behaviour.
HTML
Example

jQuery
$('a').click(function(event) {
   event.preventDefault();
   func();
});


text:
Q: Valuation rings over a field that is algebraic over a finite subfield, are there any? I am studying an article by Koji Sekiguchi and am stuck at a corollary that states:
$Zar(K) =\{K\} $ if and only if $K$ is an algebraic extension over a finite field.
Where $Zar(K)$ denotes the set of all valuation rings with quotient field $K$
This result follows a lemma that states:
Let $K$ be a field and $A$ a subring of $K$.
The next three conditions are equivalent:
-$Zar(K\mid A)$={$K$}  $\ \ \ $ (($Zar(K\mid A)$ is simply the set of valuation rings containing the ring $A$))
-$K$ is an integral extension over $A$.
-$A$ is a field and $K$ is an algebraic extension over $A$.
I am still struggling with how is it sufficient for $K$ to be an algebraic extension over just one finite field, in order for it to contain no valuation rings.
Here's a citation for the article:
Sekiguchi, Koji, Prüfer domain and affine scheme, Tokyo J. Math. 13, No. 2, 259-275 (1990). ZBL0726.14001.


text:
Q: SQL Server using dateadd I am re-posing my question. I have a simple table below:
Item       Date       QTY
Chair      12/6/08    69

I like to use SQL Server to pull these items from the Item column for three years prior to the Date column and three years on or after the Date column.
For example, Chair item, I like to know how many chairs were sold three years prior to 12/6/08; and how many chair sold on 12/6/08 or after 12/06/08.
Below is my desired output with each year and chair sold. I was thinking to use the Dateadd function but not sure how to write it yet. Thanks a lot.
Year3   Year2   Year1     Date      Year1    Year2     Year3
12/5/05 12/5/06 12/5/07   12/6/08   12/6/09  12/6/10   12/6/11
199     322     233                 344      783       564

A: Below is just prove of concept from tsql, as I am not sure for the yearly aggregation do you need a roll up or a slice of sum
declare @t table (item varchar(50), [date] date, Qty int)

insert into @t
values
('Chair', '20080612', 69),
('Chair', '20070612', 7),
('Chair', '20060612', 6),
('Chair', '20050612', 5),
('Chair', '20040612', 4),
('Chair', '20030612', 3),
('Chair', '20020612', 2),
('Chair', '20010612', 1),
('Chair', '20090612', 9),
('Chair', '20100612', 10),
('Chair', '20110612', 11),
('Chair', '20120612', 12)

select t.item
    , sum(case when  t1.[date] >= Dateadd(year, -3, t.[date]) and t1.[date] < t.[date] then t1.Qty else 0 end) as [-year3]
    , sum(case when  t1.[date] >= Dateadd(year, -2, t.[date]) and t1.[date] < t.[date] then t1.Qty else 0 end) as [-year2]
    , sum(case when  t1.[date] >= Dateadd(year, -1, t.[date]) and t1.[date] < t.[date] then t1.Qty else 0 end) as [-year1]
    , t.date
    , SUM(case when t1.[date] <= DATEADD(year, 1, t.[date]) and t1.[date] > t.[date] then t1.Qty else 0 end) as [+year1]
    , SUM(case when t1.[date] <= DATEADD(year, 2, t.[date]) and t1.[date] > t.[date] then t1.Qty else 0 end) as [+year2]
    , SUM(case when t1.[date] <= DATEADD(year, 3, t.[date]) and t1.[date] > t.[date] then t1.Qty else 0 end) as [+year3]
from @t t join @t t1 on t.item = t1.item
group by t.date, t.item
order by 1

A: You can use conditional approach to get the desired data.. make your desired date as pivot


text:
Q: I want to create a special column in sharepoint? I need your help
I want to create a special column in sharepoint
Similar to an ID column with a beginning of 00000001
Thank you

A: You could try to create a calculated column.
=CONCATENATE("000001",ID)

If you want to create a column that does not depend on the ID, you can try to create a custom column type.


text:
Q: How to get rid of multiple panes on Sublime Text 3? I'm using Sublime Text 3 and somehow 2 additional panes popped up. I might have pressed some keys but I don't know which. I couldn't any help online and I've even tried re-installing sublime text 3. Nothing works.

A: I think you mistakenly adjusted the layout. It can sometimes be in the row (in your case), grid or column.
And for others who might run into this problem later on, here is the solution:
To fix this simply open your Sublime Text 3, go to the menu bar click "View" then "Layout" and click "Single" to have your default view back.
Note: This solution is for Sublime Text 3 (ST3).


text:
Q: how xlsxwriter worksheet write formula to calculate between columns column C =column A + column B
how to write the code in xlsxwriter, only find the code for cell
worksheet.write_formula('C1', 'B1+A1')

A: Here is one way to do it:
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

last_row = 10

for row_num in range(last_row):
    # Write some sample data.
    worksheet.write(row_num, 0, row_num)
    worksheet.write(row_num, 1, row_num * 2)

    # Create and write the formula.
    cell_row = row_num + 1
    formula =f'=A{cell_row} + B{cell_row}'
    worksheet.write_formula(row_num, 2, formula)

workbook.close()

Output:


text:
Q: How to not change the keys while renewal for SSL pinning mechanism I have installed LetsEncrypt on Ubuntu 16.04 Apache server. It generated 4 .pem files under its letsencrypt/live directory. I am using the public and certificate pinning mechanism and dumping them into the iOS app bundle. To avoid updating the app on renewal i have read that it has to be renewed using a --csr flag but couldn't get much help on this. Can letsencrpyt renew the way i want to or i need to use some other client? Do i have to regenerate all the certs as am sure it generated only pem and no csr files while creating certificates with Letsncrypt. Thanks.

A: The csr generated by LE can be found out in /etc/letsencrypt/csr. I picked the latest csr file (usually the one which has the highest integer is the latest, e.g.: 0005_csr-letsencrypt.pem will be latest to 0004) and renewed the certificate with the above command:
letsencrypt certonly —csr /etc/letsencrypt/csr/0005_csr-letsencrypt.pem

This will generate 3 files called in the same directory:
000x_chain.pem - has same PubKey but new expiry (what we need)
000x_chain.pem - has some CA information
000x_cert.pem - the cert which will match the PubKey of the cert

I used the 000x_cert.pem for my app bundle. So every time i renewed the certificate i could hit the server even though i dont replace the 000x_cert.pem in the app. It works as the public key will be same. Thanks.


text:
Q: Appium - Driver.source() showing android home page even with app on screen I'm new on Appium, and I'm trying to make it work on a react-native app. I'm following this tutorial but I have some issues.
I'm trying to find an element with accessibilityLabel="testview" but when I execute the code, I can't find this element. So, I put the command console.log(await driver.source()); to see the XML code. Even with the app opened on the emulator, I get the XML code from the Android home page, but not the code from my app.
My test code is:
import wd from 'wd';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
const PORT = 4723;
const config = {
  platformName: 'Android',
  deviceName: 'Android Emulator',
  app: './android/app/build/outputs/apk/debug/app-debug.apk', // relative to root of project
  appPackage: 'com.example.android',
  appActivity: 'com.example.MainActivity'
};
const driver = wd.promiseChainRemote('localhost', PORT);

beforeAll(async () => {
  await driver.init(config);
  await driver.sleep(8000); // wait for app to load
})

test('appium renders', async () => {
  console.log(await driver.source());
  expect(await driver.hasElementByAccessibilityId('testview')).toBe(true);
});

Does anyone know why I'm getting this XML code instead of the XML code from my app? Is there any configuration that is wrong? I am using Windows, genymotion, the android emulator, and the uiautomator.

A: I solved this error by changing the version of uiautomator used. I just added a line in the configuration:
const config = {
  platformName: 'Android',
  deviceName: 'Android Emulator',
  app: './android/app/build/outputs/apk/debug/app-debug.apk', // relative to root of project
  appPackage: 'com.example.android',
  appActivity: 'com.example.MainActivity'
  automationName: 'uiautomator2'
};


text:
Q: Getting error while fetching data using angularjs and REST api from sharepoint list I'm fetching data from the sharepoint list using angularjs in regular intervals. After sometime, I'm getting error in the console as SCRIPT7002: XMLHttpRequest: Network Error 0x2eff, Could not complete the operation due to error 00002eff. I'm using IE 10 as browser. Any idea about this error ?
Please find the method which i repeatedly calls to get data below.
// Method to get all the notifications for the user
    var getUserNotifications = function () {

        // Create a deferred object
        var deferred = $q.defer();

        // Url for getting the list with filters
        var url = _spPageContextInfo.webServerRelativeUrl +
                "_api/web/lists/getByTitle('" + list + "')/items?" + filters;

        // API call to get the notification items from list
        var method = $http({
            method: "GET",
            url: url,
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        });

        // Executing the method
        method.then(

            // Success function
            function (data) {

                var d = data.data.d.results;

                notification = d;

                // If timer is not started, then start it.
                if (!isTimerStarted) {

                    setInterval(function () {

                        getUserNotifications();

                    }, 3000);

                    isTimerStarted = true;
                }
        deferred.resolve(d);

            },
            // Error
            function (err) {
                deferred.reject("Error");
            }
        )
        return deferred.promise;
    };


text:
Q: Dynamically setting meta tag using DocHead in Meteor I am dynamically setting <meta> tag in my <head> for Twitter card. The following sets the meta tag when I inspect the <head> on my Chrome:
  FlowRouter.route('/', {
    name: 'home',
    action() {
      let title = 'my app';
      DocHead.setTitle(title);

      DocHead.removeDocHeadAddedTags();
      DocHead.addMeta({name: 'twitter:card', content: 'summary'});
      DocHead.addMeta({name: 'twitter:site', content: '@myapp'});
      DocHead.addMeta({name: 'twitter:title', content: 'my app title'});
      DocHead.addMeta({name: 'twitter:description', content: 'my app desc'});
      DocHead.addMeta({name: 'twitter:image', content: 'logourl'});

      mount(MainLayoutCtx, {
        content: () => (<Home />)
      });
    }
  });

But when I debug it using tools such as social debug, I always get that no meta tag was found for Twitter. What gives? I am using spiderable in my app. This also happens on production.


text:
Q: Is there a way to pass an Arraylist from a Controller class to Javascript in a JSP page in a Spring Application? I'm trying to pass an ArrayList of objects from a controller class to an array in Javascript when a particular @RequestMapping value in the mapping controller is called. Typically if I wanted to print the contents of the ArrayList from the java side I would use model.addAttribute("events", events); like below and have a c:foreach loop with c:out to print the values on the welcome page when the / or welcome mapping route is called. However, I want to store the objects in an array in javascript instead and I'm finding little information online about doing this within a Spring Framework.
I want to do this as the objects contain latitude and longitude values that I plan to use to print to print markers on a map. Any suggestions?
@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {

       ArrayList<Event> events = seeEvents.getAllEvents();
       System.out.println(events);

       model.addAttribute("events", events);

    return "welcome";
}

A: Either you create an API that serve events in json  and you use an "ajax call" in your application to get it
@RequestMapping(value = "/events", method = RequestMethod.GET)
public List<Event> events() {
    return seeEvents.getAllEvents();
}

And on (modern) javascript:
fetch("/myContext/events").then(function(response) {
    return response.json().then(function(json) {
        // Do your thing...
});

another possibility is just to set in your JSP a code to create a static array:
var events=[<c:forEach ...>"<c:out ...>",</c:forEach>];


text:
Q: Getting Python to work on Cygwin I installed cygwin and python but for some reason I can't get python to work.
when I type  type python it gives me:
python is /cygdrive/c/Users/pnwar/AppData/Local/Programs/Python/Python36/python

however my python path should be:
C:\Users\pnwar\AppData\Roaming\Microsoft\Windows\'Start Menu'\Programs\'Python 3.6'

I tried messing with the PATH, echo $PATH gives:
/usr/local/bin:/usr/bin:/cygdrive/c/ProgramData/Oracle/Java/javapath:/cygdrive/c/Program Files (x86)/Razer Chroma SDK/bin:/cygdrive/c/Program Files/Razer Chroma SDK/bin:/cygdrive/c/Program Files (x86)/Intel/iCLS Client:/cygdrive/c/Program Files/Intel/iCLS Client:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/cygdrive/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/cygdrive/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/IPT:/cygdrive/c/Program Files/Intel/Intel(R) Management Engine Components/IPT:/cygdrive/c/Users/Administrator/AppData/Local/Microsoft/WindowsApps:/cygdrive/c/Program Files (x86)/Skype/Phone:/usr/bin:/cygdrive/c/Program Files (x86)/PuTTY:/cygdrive/c/Users/pnwar/AppData/Local/Programs/Python/Python36/Scripts:/cygdrive/c/Users/pnwar/AppData/Local/Programs/Python/Python36:/cygdrive/c/Users/pnwar/AppData/Local/Microsoft/WindowsApps:/cygdrive/c/Users/pnwar/AppData/Roaming/Microsoft/Windows/Sta rt Menu/Programs/Python 3.6:/cygdrive/c/Users/pnwar/AppData/Roaming/Microsoft/Windows/Sta rt Menu/Programs/Python 3.6

Towards the end you can see some erroneous paths that I can't seem to edit correctly to get things to work.
I tried PATH=echo $PATH | sed -e 's/:\/cygdrive/c/Users/pnwar/AppData/Local/Programs/Python/Python36\/$//'
because I found it somewhere but that just erased all of my paths.
I added the correct path to my .bash_profile with PATH=\$PATH:/cygdrive/c/Users/pnwar/AppData/Roaming/Microsoft/Windows/'Start Menu'/Programs/'Python 3.6'
But I still can't seem to get it to work.
If anyone could push me in the right direction that would be much appreciated, I'm kind of confused as to what is going on exactly and how to get it to work.

A: I am not familiar with Cygwin, but had the same problem.
I solved it in my case by removing Cygwin from the PATH (Windows environment) variable, but it should be enough to place the path to Cygwin after the path to your Python installation.

A: Here is how I got Python working for me in Windows 10 x64 under Cygwin x64, actually quite simple:
$> which python
/usr/bin/python
$> which python3
/usr/bin/python3
I installed the versions of Python (2.7 and 3.6) via Cygwin. It seems to me you try to get the native Windows version Python running, which can be difficult if you are going to use it from a Cygwin terminal.


text:
Q: Outlook Add-in - Connect to SQL Server May I know is there any tutorial or guide for me to learn how to connect to the SQL Server for my Outlook Add-in project? Been searching high and low through the web but couldn't find any decent guide. Appreciate if you can provide a link to the guide.
Thanks!

A: You will need to use a PHP driver for SQL Server. The following link will show you how to use PHP to connect to SQL.
MSDN Link

A: You can easily import contacts into Outlook with a .csv file.
Open SQL Server Management Studio
Connect to database
Goto Tools > Options > Query Results > SQL Server > Results to Text
Under Output format choose Comma Delimited
Confirm the "Include column headers" box is checked
Click OK
Open a new query window
Run your query

Similarly, consider exporting your dats sets from SQL Server, as a CSV, and import the same into Outlook.


text:
Q: ID doesn't exist although it does I'm working on a project for class, and I have a dropdown box with the id of "idSelect." But when I try to grab the value of the dropdown box into a variable, it says that idSelect isn't defined.
I tried changing the name of the id, but the same thing happened. If I try to console.log(idSelect.value), it shows up as whatever I have selected, but it still shows an error that idSelect is not defined.
This is in the head tags & script tags
var selectedHero = idSelect.value;

This is in the body tags
Change your avatar:
    <select id="idSelect">
        <option>Batman</option>
        <option>Spider-Man</option>
        <option>Iron Man</option>
        <option>Superman</option>
        <option>Wolverine</option>
    </select>

The variable selectedHero should store whatever the player has selected in the dropbox such as "Iron Man" or "Superman," but instead in the Inspect element all it says is this:
Monster Project (BLANK).html:22 Uncaught ReferenceError: idSelect is
not defined
    at file:///C:/Users/chim%20chimoi/Desktop/Ifra/APCOMSCI/Monster_Project_HOME/Monster%20Project%20(BLANK).html:22:22

This worked before and I didn't change anything, but when I ran it again this error just started popping up.

A: You are passing a HTML's id into Javascript, and in Javascript there's no such variable idSelect being declared, e.g.:
var idSelect;

But even if you declare it in Javascript, the way to pass the HTML's value into Javascript is not correct.
If you want to keep the same variable name, you can do this:
var idSelect = document.getElementById('idSelect').value;

A: Most probably there was a variable "idSelect" which does not exist, or is not accessible at the point you are referencing it.
Try making it global:
<script>
    window.idSelect = document.getElementById('idSelect');
</script>

or reference it like this every time you need it:
<script>
    var idSelect = document.getElementById('idSelect');
    var selectedHero = idSelect.value;
</script>


text:
Q: How to make correct regex for matching content from html? I use regexr for making regular expression, but can't matching anything.
I wrote such regex '.dataLayer = (.+)</script>'
I have such structure of template:
<!DOCTYPE html>
<html lang="en-PH" dir="ltr">
<head> … </head>
<body class="is_full PdpV4">
<script> This one script which I should get </script>
 <script> window.dataLayer = window.dataLayer || []; dataLayer.push({"feature_test":"VariableControl:1"}); dataLayer.push({"feature_set":"Control"});
</script>
<script>....</script>
<script> … </script>
 </body>
</html>

And I need to get the first one script... /script
<script>
    dataLayer = [
        {
            "agent_id": 558921,
            "agent_name": "The City Townhouse",
            "attributes": {
                "agent_ratings_enabled": 0,
                "approved": 1,
                                "attribute_set_id": 1,
                                "categories": JSON.parse("[15,19]"),
                "indoor_features": ["Balcony","Maid's room"],
                "is_agent": 1,
                "listing_type": "Classifieds",
                "other_features": [],
                "outdoor_features": ["Garage"],
                "price_formatted": "₱ 11,300,000 ",
                "price_not_shown": false,
                "seller_is_trusted": 1,
                "show_listing_address": 1,
                "show_mobile": 1
        }
    ];
</script>

I need to get everything inside tags  . Thanks a lot.

A: Avoid parsing HTML with regular expressions. A seminal stack overflow answer explains why.
Instead, you should use a package like html5lib to parse the HTML and extract the contents of the <script> elements and then parse out the contents you want from that. This will mean you only need to look at the JavaScript code, which should be a much simpler task.

A: First, what Paul said, don't use a regex to parse HTML.
Second, and I don't recommend it, but if you're really intent on doing this for whatever reason, this regex will match characters on the inside of a <script>..</script> tag:
(?<=<script>).*(?=<\/script>)

You have been warned.


text:
Q: Switching Git from HTTPS to SSH, says permission denied I have a repository that was initialized using HTTPS and am trying to switch it over to SSH.  I'm working on a computer running Pop!_OS which is basically Ubuntu.  I have generated keys following these instructions: https://gist.github.com/zhujunsan/a0becf82ade50ed06115
When I try to test the connection using sudo -u axiomtutor ssh -T git@github.com it says my user is unknown.  Which seems strange because I have set my user name globally in the terminal.  When I try to push I get
ERROR: Permission to axiomtutor/asking.git denied to deploy key
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

The content of my local .git/config file looks like:
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
[remote "origin"]
        url = git@github.com:me/repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
        remote = origin
        merge = refs/heads/master

I've run the ssh-agent and entered ssh-add -k ... to add my SSH key to the path.  I've put the key in the "Deploy Key" section of the settings on my repo.  So I'm just not seeing what the issue could be.
Following these instructions didn't change anything:
Switching Git to use SSH

A: Gah, I think I figured it out.  Something somewhere didn't work, so I generated a new key.  But when I did that, I put it somewhere new, and forgot to correspondingly edit ~/.ssh/config.


text:
Q: Same code works in Jyputer but MemoryError in Command Line Python I defined a function that read 9 CSVs and returns as 9 dataframes.
Those code works well in Jupyter Notebook but when I export the code as .py and run it on the command line. I get MemoryError
I tried to run the command line as admin but still failed.
Here is the code. Just normal read_csv
def read_matrixs():
    import pandas as pd
    df1 = pd.read_csv("../Data/1.csv")
    df2 = pd.read_csv('../Data/2.csv', index_col = 0)
    df3 = pd.read_csv("../Data/3.csv", index_col = 0)
    df4 = pd.read_csv('../Data/4.csv', index_col = 0)
    df5 = pd.read_csv('../Data/5.csv', index_col = 0)
    df6 = pd.read_csv('../Data/6.csv', index_col = 0)
    df7 = pd.read_csv('../Data/7.csv', index_col = 0)
    df8 = pd.read_csv('../Data/8.csv', index_col = 0)
    df9 = pd.read_csv('../Data/9.csv', index_col = 0)
    return (df1, df2, df3, df4, df5, df6, df7, df8, df9)

df1, df2, df3, df4, df5, df6, df7, df8, df9 = read_matrixs()

A: It is likely that you are dealing with code that is too intensive for your computer. I am not familiar with Jupyter Notebook, but it would be really helpful if you could post the code you are trying to run. (Sorry for posting an answer, this should really be a comment. My reputation isn't high enough to comment.)


text:
Q: looping ansible registered results in jinja template I will have a output from one of the task is like,
    "msg": [
        "colours",
        "fruits",
        "animals",
        "people",
        "men"
    ]

using the above list, in another task it will return the associated results in stdout_lines like,
ok: [localhost] => {
    "msg": [
        {
            "stdout_lines": [
                "red",
                "blue",
                "green"
            ]
        },
        {
            "stdout_lines": [
                "mango",
                "banana",
                "orange"
            ]
        },
        {
            "stdout_lines": [
                "line",
                "tiger",
                "elephant"
            ]
        },
        {
                "trump",
                "obama",
                "ivanka"
            ]
        },
        {
            "stdout_lines": [
                "trump",
                "obama"
            ]
        },
    }

Now I want to use jinja template to create a file like below format
[colours]
red
blue
green

[fruits]
mango
banana
orange

[animals]
lion
tiger
elephant

[.]
.
etc...

I'm able to get the list in jinja template using for loop but not able to map them. Appreciate help on this
{% for i in iddmn.stdout_lines %}
 [{{ i }}]
{% endfor %}

[colours]
[fruits]
[animals]
[people]
[men]

Im able to get this, but not able to map it to the results


text:
Q: Advice on battery powered ESP32 with NFC Design I'm new to PCB design (First one) and I want some advice and tips from more knowledgeable people in regard to basic design elements and especially the power consumption part. I want to make the hardware consume as little as possible during sleep. I spent a lot of time researching, but would like some expert proofing before I pull the trigger.
I'm trying to design a battery powered esp32 that will turn on the motor when the NFC breakout board connected through SPI is reading the correct code. It only wakes up by a built in touch sensor and is in deep sleep most of the time. I choose the ESP32 to add some IoT capabilities. I'm using low quiescent current LDO voltage regulator (4uA) for 3.3V. I have connected ground of the motor, voltage divider for battery measurement , and the NFC module to N-Channel logic level (>1.8V) MOSFET to operate and save power by turning off NFC module and the divider constant drain. This specific MOSFET has a low 1uA leakage IDSS.
Capacitors are the same as the data sheets suggest. Motor current is not more than 1.4A for 5 seconds. Batteries will be 2x2 lithium-ion (~6V-8.4V). The NFC module will be connected by male 2.54 1x6 header on the back side of the board (GND to SCK). Also note that the pcb and breakout board's top,left, and right sides are meant to match. Only the bottom side on my pcb is shorter. There are external UART connectors. Also I'll be soldering all components by hand.
Old Schematic:

Old PCB:

Project link on EasyEda for PCB and Schematic for close up inspection
Feel free to request any info that I could've missed.
Update:
I've reworked the voltage divider/motor circuit. It Now it uses a pmos connected to battery in both drain and gate (Motor is a 6 Ohm resistance so the gate is connected to VB) If my theory works, the traces have so little resistance in relation to the motor (about 0.1 Ohm to 6 Ohm of the motor) the voltage at the gate would be still much lower than the drain (1V vs 8-6V if my calculations are correct, threshold is 1.2V difference) so pmos will be turned on. There's no direct connection between any pin to VB when the circuit is off.
I divided the schematic into smaller parts. Added a diode for reverse voltage protection, reworked the SPI lines to make them adjutant since they were just software SPI. Made battery traces slightly thicker.
I've decided to not put any terminations resistors. UART have one internally, while the breakout board have resistance for each line. Of course, ideally you would put the resistors at the sender, but given that they seem to work fine with 20cm of ribbon cables, I think I could skip it? Also used smaller caps for 100nf values. I've bought separate BMD for my Li-ion so I don't have to fiddle with that.
Ver0.2 Schematic:

PCB:

Link to new
If you have any tips, questions, or corrections, feel free to leave them in an answer. I'll mark Umar response as the correct answer for now.

A: I will try to answer
1. Aesthetics:
Please never draw a schematics like this. I wish your second schematics will be nicer one.
The ground should always be in the bottom and the supply should always be on the top. Poor drawing simply sets off readers because it is so difficult to comprehend and needless to say it doesn't look good. You should really follow the tips in the link below.
Rules and guidelines for drawing good schematics
The pulldown is very difficult to identify.

The free wheel diode can be connected directly across the 2 pin connector, it will then speaks it purpose to the reader by itself.

2. Battery reverse voltage protection:
One wrong connection would fry the board. There are options to protect the circuit from reverse voltage without the loss of voltage drop or battery usage. Example is a PMOSFETconnected in such a way they the body diode comes in series with the battery.
3. Battery voltage monitoring Pin safety
When the Q2 Transistor is off the battery voltage (~7V) will be directly applied to the IO4 pin of ESP. though the current flow is limited it is still the violation as per of the datasheet. Also, plan a clamp diode so that in such a case the voltage will remain clamped to a safe level across the pin. Other option is to use a PMOS switch.
5. Misc

*

*Pull-up and Pulldown resistor values can be 100K.

*How is touch realised?

*What is the expected interval of motor re-activation?

*The switches for individual modules is a good idea. You are trying to bring down the quiescent current to a lesser value which is good.

*Have you calculated the trace width of the PCB trace for power pins especially the motor current path? There are free online calculators

*Please provide some de coupling capacitors near the connector for NFC section

*LED forward voltage is unknown. When is the LED blinked? Will it be ON always?

*The capacitor C4 should be placed closer to the VCC pin (in the PCB)

*How are you communicating with NFC module. SPI? I2C? Have you considered pullups or line terminations for those?

*Series resistors for UART, NFC communication lines if possible will help limit the IO current in case of accidental errors.

*What is the purpose of IO21 GPIO. It seems like you have missed putting a switch for the NFC module

*Vbattery trace is dangerously thin. The same track goes to drive the motor.

*How long should the product be alive in your application?

*The battery voltage divider needs your attention. The resistor combination should be in such a way that the voltage developed across the botttom resistor (which is connected to Q2) should be measurable. Always less than ADC Reference voltage for example. Consider use case if fully charged battery which is about 8 V according to you, 5% regulator tolerance, tolerance of resistors too


text:
Q: Swift nested functions vs Closure Variables I want to make a function that fetches a record from CloudKit, if it encounters a temporary network error the function should retry.
func fetchRecord(withRecordID recordID: CKRecordID, returnBlock: (optError: ErrorType?) -> Void){

    func internalReturnBlock(optError optError: ErrorType?){
        if NSThread.isMainThread() {
            returnBlock(optError: optError)
        }
        else{
            dispatch_async(dispatch_get_main_queue(), {
                returnBlock(optError: optError)
            })
        }
    }

    func internalWork(){
        privateDB.fetchRecordWithID(recordID) { (optRecord, optError) in
            if let error = optError{
                // IF NETWORK ERROR RETRY
                internalWork()
            }
            else{
                internalReturnBlock(optError: nil)
            }
        }
    }

    internalWork()
}

Here I define such function (simplified), If the fetch encounters an error it retries by calling the nested function internalWork()
My question is what would be the difference between using nested functions or creating local closure variables?
For example, here I change the internalReturnBlock to a closure variable:
func fetchRecord2(withRecordID recordID: CKRecordID, returnBlock: (optError: ErrorType?) -> Void){

    var internalReturnBlock = { (optError: NSError?) in
        if NSThread.isMainThread() {
            returnBlock(optError: optError)
        }
        else{
            dispatch_async(dispatch_get_main_queue(), {
                returnBlock(optError: optError)
            })
        }
    }

    func internalWork(){
        privateDB.fetchRecordWithID(recordID) { (optRecord, optError) in
            if let error = optError{
                // IF NETWORK ERROR RETRY
                internalWork()
            }
            else{
                internalReturnBlock(nil)
            }
        }
    }

    internalWork()
}

What are the differences between using a nested function vs a variable block?
Any advantages or problems?

A: There is no difference in effect. One is a declared function with a name, the other is anonymous. But they are both functions. And a function is a closure in Swift, so they are both closures.
An anonymous function is permitted to use some abbreviations of form, such as the omission of return in a one-liner that returns a value. But none of those abbreviations makes any ultimate effective difference.
However, an anonymous function in Swift has one feature a declared function does not — a capture list. This can help avoid retain cycles.
f {
    [unowned self] in
    return self.name
}

Also, an anonymous function is defined after the declaration of the function that takes it as a parameter, so it can use terms that appear in that declaration:
f(param:String) {
    return param
}

But if you are not using those features, then it doesn't matter which you use. They work identically.


text:
Q: input with data validation doesn't trigger change event $(function() {
    $("#collapseNew div[data-role=contractContainer] .table-row-b > .row input").change(function () {
        //find if is need a new line
        var $this = $(this);
        var lineContainer = $this.closest("div.row");
        if (typeof(lineContainer.data().requestLine) === "undefined") {
            addRow($this, function() {
                lineContainer.data("requestLine", true);
            });
        }
    });
});

this simple jquery code never trigger in my page is possible is related to those inputs have validations with jquery.validate
how can I get change event without pressing of validation
FYI: $("#collapseNew div[data-role=contractContainer] .table-row-b > .row input") is valid and contain the inputs in question
In fact, validation related with those input work find. so, I guess unobtrusive-validation is subscribed to the change event but in some way it override my subscriptions
thanks in advance


text:
Q: How to number and cross-reference \subsubsection-level headers I'm trying to cross-reference 2 subsubsections from my document.
My structure is like:
\chapter{something}
\section{1.1}
\subsection{1.1.2}
\subsubsection{Number 1} \label{sssec:num1}
\subsubsection{Number 2} \label{sssec:num2}

I'm trying to reference both the subsubsections from my section 1.1 above. But when I use \ref{sssec:num1} and \ref{sssec:num2}, the reference is always pointing to the \subsection{1.1.2} for some reason.
My ToC depth is 2, so it's only showing as far as the subsection. Does anyone know a fix to this?
Thanks

A: Your comment that the tocdepth counter's value is equal to 2 suggests that the value of the counter secnumdepth is also set to 2; if true, it would certainly explain why you can't seem to cross-reference subsubsections correctly.
The following example uses \setcounter to set the value of secnumdepth to 3. If secnumdepth were left at 2 (the default value for the report document class), the subsubsection counter doesn't get incremented, and in consequence both \labels will end up pointing to the most recently incremented counter, which happens to be subsection. That's the problem behavior you're experiencing, right?

\documentclass{report}
\setcounter{secnumdepth}{3} % default value for 'report' class is "2"
\begin{document}
\chapter{Something}

Here are cross-references to subsubsections \ref{sssec:num1} and \ref{sssec:num2}.

\section{A section header}
\subsection{A subsection header}
\subsubsection{First subsubsection} \label{sssec:num1}
\subsubsection{Second subsubsection} \label{sssec:num2}
\end{document}


text:
Q: TLS termination behind AWS ELB on HAProxy (tcp mode) I am using AWS ELB as entry point (in Proxy mode) to load balance among 2 HAProxy-es behind it from where traffic goes further to MQTT broker.

*

*Those 2 HAProxies are responsible for client TLS termination (2 way TLS).

*Certificates kind of work. I've tested on local setup between 2 servers. I've been able to publish with 2-way TLS, properly terminate it, and publish message to mqtt. Problem arise when moving everything to AWS.

*I am using self signed root CA, intermediate CA, server certificate and client certificates. Using Elliptic Curve...

*Problem might be due to a servers CN. I think it has to be the same as hostname connecting to with tools like mosquitto_pub.

*Error that I get is TLS error, whith debug -> ssl handshake failure. Somehow I am not able to produce more verbose errors. Using openssl with s_client and debug for max debug output. Which produce me ssl handshake failure.
I would really appreciate any hint/suggestion.
Thanks in advance.
Tomaz

A: I solved this by using subjectAltName feature. I edited openssl.cnf and add new section [alt_names] and reference it later on in configuration. Under alt_names I added 1 DNS key, and 2 IPs. Found with man x509v3_config.
Best,
Tomaz


text:
Q: Addhandler fcgid-script.php error Recently I started using Scriptcase and it requires me to first install PHP and apache.
During apache installation, I need to make some modification in httpd.conf, which is located in C:\apache24\conf
I added contents in the script as following:

The installation was successful but leaving one error. I tried to restart but the error is still appears:

I've Googled looking for solution but so far I found nothing.
Anyone maybe?

A: It looks like you're missing a space after the handler fcgid-script.
It should be AddHandler fcgid-script .php not AddHandler fcgid-script.php
Similar issue on the following line with the FcgidWrapper directive.


text:
Q: What folder does Path::GetTempFileName Method save to? I need to get the temp file to see what happened because the actual file is never output. However, I can't seem to find where the temp file is created.
I need to find this out without writing code or building the application because there are too many dependencies scattered all over the place. I would not be able to deploy a debug version.

A: That method returns the path of a temporary file.  The path will tell you where its pointing.
For example:
Console.WriteLine(Path.GetTempFileName());

produces:
C:\Users\will\AppData\Local\Temp\tmp9BD5.tmp

for me on this machine, because the TEMP environment variable is pointing to C:\Users\will\AppData\Local\Temp\
But the whole point of a method like GetTempFileName is that you shouldn't have to care where the file ends up.   On the off-chance that you do, you can always get there at command prompts or file-open dialogs by using %TEMP%


text:
Q: infinite recursion options(expressions=) at R startup and updating packages i have a problem i can't find a solution to. On startup R says:
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
then, R works up until i try to update packages: "digest 0.6.16", "stringi 1.2.4", "tinytex 0.7"
this gives the error again:
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Execution halted
In R CMD INSTALL
The same when i try to build the website through blogdown.
i run R version 3.5.1 (2018-07-02) -- "Feather Spray" on R studio Version 1.1.456
I tried the following:
modifying options(expression= 500000) (and other values)
i tried reinstalling R and R studio
thanks in advance for the help


text:
Q: Efficiently iterate through all MATCHING keys in a hashmap? I have a HashMap with millions of entries.
Need to retrieve all entries whose keys match a specific set of criteria (in this case, each key is an object with two integer properties; I need to retrieve all keys where each of these integers fall within a specified range).
What is the fastest, most efficient way to iterate through all such keys?
UPDATE:
In this particular case, though I didn't specify it up front, the first integer in the key has a natural precedence over the second integer.

A: A HashMap is not an efficient data structure for finding keys that lie within a certain range. Generally the only keys you can find efficiently in a hash map are keys with the same hash as what you have (i.e. equal keys).
For finding keys that lie within a certain range, you are better off using a SortedMap of some kind, such as a TreeMap, which can then be viewed with the SortedMap.subMap(low, high) view method.
As for finding a key based on two keys, that is even more difficult. Your best bet is probably to iterate over the subMap of the range of the first integer, and then to check for each one if the second integer falls within the specified range. This at least limits the scan to the keys which have one of the integers within the range. Try to sort the map based on the integer that has a more natural distribution of values over the possible ranges you might have to search for.

A: Here's a solution using TreeMap:
public static void main(String[] args) {
    Comparator<Foo> fooComparator = new Comparator<Foo>() {
        @Override
        public int compare(Foo o1, Foo o2) {
            return o1.compareTo(o2);
        }
    };

    TreeMap<Foo, String> map = new TreeMap<Foo, String>(fooComparator);

    map.put(new Foo(1, 4), "");
    map.put(new Foo(1, 3), "");
    map.put(new Foo(2, 4), "");
    map.put(new Foo(3, 4), "");
    map.put(new Foo(8, 10), "");
    map.put(new Foo(8, 17), "");
    map.put(new Foo(10, 10), "");

    int a = 2;
    int b = 5;

    for (Foo f : getKeysInRange(map, a, b)) {
        System.out.println(f);
    }
}

public static List<Foo> getKeysInRange(TreeMap<Foo, String> map, int low, int high) {
    Foo key1 = new Foo(low, low);
    Foo key2 = new Foo(high, high);

    Foo fromKey = map.ceilingKey(key1);
    Foo toKey = map.floorKey(key2);

    if (fromKey != null && toKey != null && fromKey.compareTo(toKey) < 0)
        return new ArrayList<Foo>(map.subMap(fromKey, true, toKey, true).keySet());
    return new ArrayList<Foo>();
}

public static class Foo implements Comparable<Foo> {
    private int i;
    private int j;

    private Foo(int i, int j) {
        super();
        this.i = i;
        this.j = j;
    }

    public int min() {
        if (i < j)
            return i;
        else
            return j;
    }

    public int max() {
        if (i > j)
            return i;
        else
            return j;
    }

    @Override
    public String toString() {
        return "I=" + i + "J=" + j;
    }

    @Override
    public int compareTo(Foo o) {
        if (this.min() > o.min()) {
            return 1;
        } else if (this.min() < o.min())
            return -1;
        else {
            if (this.max() > o.max())
                return 1;
            else if (this.max() < o.max())
                return -1;
            else
                return 0;
        }
    }
}

A: You can't do it without iterating through the entire keySet.
You can use a TreeMap with a sort criteria that will sort by some combination of the two integer properties if you're sure that you won't have other entries that have the same value of those integer properties, and then you can find the first match directly and then just iterate from there to the first non-match.  But it seems unlikely you can achieve those conditions.
Because collections have pretty low overhead (everything is stored by reference), I would consider making two sorted collections, possibly TreeSets, one sorted by the first property and one sorted by the second, and then pick out all the values that meet the criteria from both collections and union them together.

A: The solution provided by bruno conde is a good start.  However, the way I read the original question is that the key Object contains two integers and that the question was regarding the fastest way to retrieve all the key/value pairs that match one range for the first integer and match a second range for the second integer.  The bruno solution is assuming that keys have a natural order where the first integer always has precedence over the second integer.  It also assumes there is only one range.
For this more general case, I would:
 insert key/values into a TreeMap using a comparator that favors integer1
 insert the same key/values into a second TreeMap using a comparator that favors integer2
You can then use subMap() on each TreeMap using the range to get an ordered view of the underlying TreeMap.  You can then create a new result TreeSet based on the intersection (retainAll()) of the keySet() of these subMaps.

A: There likely won't be a faster solution than something like:
for (final KeyObj key : map.keySet()) {
    // do work
}

A: If a TreeSet won't work for some reason, the standard way to iterate is with the entry set.
for (Map.Entry<MyKeyType, MyValueType> entry : myMap.entrySet()) {
    MyKeyType key = entry.getKey();
    if (isValid(key)) {
        // do whatever
        validList.add(entry.getValue());
    }
}

This way, you don't have to do an extra myMap.get(key) call for valid keys.

A: You may want to consider some sort of SQL DB, maybe an in-memory one like Derby or H2. Much depends on how important this is and how important that it be fast. Then you could do this in SQL and let the engine do all the optimization work.


text:
Q: Yum command is not working in Docker images [root@8b473cb5f656 sysconfig]# yum update
Loaded plugins: fastestmirror, ovl
Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=container error was
12: Timeout on http://mirrorlist.centos.org/?release=7&arch=x86_64&repo=os&infra=container: (28, 'Resolving timed out after 30543 milliseconds')

 One of the configured repositories failed (Unknown),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

A: *

*Are you connected to the internet from within the docker container?

*Can you share the output of the following command from within the container?
cat /etc/resolv.conf

*Are you using the default yum repo or anything specific?

*Restart the network driver on the host and the container for once.


text:
Q: How to use two conditions in conditional formatting? I want to use both "text contains" and "text exactly is" at the same time with a logical "OR" in between.
How can I do this with custom formula?

A: Conditional formatting uses custom formula.
For column A:A the formula may be:
=or($A1 = "text1", regexmatch($A1, "text2") )
regexmatch is a simple and powerful way to check text contains.


text:
Q: Grails: Add new attribute in select I want to add a new attribute in select tag of grails. Let's say the attribute name is "currencyId". How will I do that? or is that even possible?
I've tried this but it didn't work

    <g:select name="${textFieldName}" from="${from}" class="commonSelectSize3Cols"
              value="${instanceFieldValue}"
              noSelection="${['': message(code: (noSelectionMessageCode ?: "noSelection.label"))]}"
              optionKey="${optionKey}" optionValue="${optionValue}" ${newAttribute}="${newAttributeValue}" />

A: Simply add it like any other HTML attribute:

    <g:select name="${textFieldName}" from="${from}" class="commonSelectSize3Cols"
              value="${instanceFieldValue}"
              noSelection="${['': message(code: (noSelectionMessageCode ?: "noSelection.label"))]}"
              optionKey="${optionKey}" optionValue="${optionValue}" data-new-attribute="${newAttributeValue}" />

Since g:select doesn't use that attribute, it will simply pass it along undisturbed, so that it gets rendered.


text:
Q: Making specific threads wait until a state's counter reaches 0 I'm using a HashMap to keep track of each state's counter and I'm trying to make certain threads that call await(State s) with the same state block until the state's counter is 0. Each thread uses decrementCounter(State S) and then calls await(State s)
I thought about adding a condition to my lock but i dont think it makes sense since i could have two different sets of threads waiting on two counters and when a thread uses signalAll() for one of the counters it wakes up both sets.
Any hints would be greatly appreciated.
Note: the counter is being incremented in another part of my code but is not relevant.
In the worker thread:
    private final static Counter counter = new Counter();
    if (condition) {
        counter.decrementCounter(s);
        counter.await(s);
    }

Counter class:
public class Counter{
    private HashMap<State, Integer> count = new HashMap<State, Integer>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock writeLock = lock.writeLock();
    private final Lock readLock = lock.readLock();

    public void await(State s) throws InterruptedException {
        readLock.lock();
        try {
            //check if state s counter is 0. if it's not 0 block until it is.
        } finally {
            readLock.unlock();
        }
    }

    public void decrementCounter(State s) {
        writeLock.lock();
        try {
            int temp = count.get(s);
            if (temp > 0) {
                count.put(s, temp - 1);
            }
        } finally {
            writeLock.unlock();
        }
    }
}


text:
Q: Best way to deploy a mobile Powerpoint Add In Do any of you know what the best way is to deploy a mobile Powerpoint Add-In?
I developed an add-in that logs the time whenever a teacher switches slides, and also exports all the slides as separate JPEG files. This is necessary, because we also record the presentations on video, and want to combine the two using a second-screen. The whole back-end behind this is finished and is working (but we need to manually type in the positions of the 'slide'. So we figured we could automate this).
The users the add in needs to run on don't have any Administrator rights, and we don't have access to the administrator account either (this is in an Educational environment). But we do need to launch a Powerpoint application with the add in already installed, so we can record the presentation.

A: Can you write a few entries to the registry, in HKEY_CurrentUser?  Specifically:
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\PowerPoint\AddIns\YourAddinName
Under that, add a new
String:  Path = the full path to your add-in's PPA/PPAM file
DWORD:   AutoLoad = ffff ffff hex
That will cause PPT to load your add-in automatically when it starts up.


text:
Q: upgrade issue from 2.1.14 to 2.2 :: magento2 I have upgrade magento version from 2.1.14 to 2.2.0.
First time when i run run php bin/magento setup:upgrade command it gives this error:
Module 'Magento_TaxImportExport':
Module 'Magento_BundleStaging':
Upgrading schema.. SQLSTATE[HY000]: General error: 1025 Error on rename of './databasem2/#sql-3b4_94f' to './databasem2/catalog_product_bundle_selection' (errno: 150 - Foreign key constraint is incorrectly formed)

Now every time upgrade command gives this error:
Module 'Magento_TaxImportExport':
Module 'Magento_BundleStaging':
Upgrading schema.. SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'sequence_product_bundle_option' already exists, query was: CREATE TABLE sequence_product_bundle_option (
                     sequence_value integer UNSIGNED NOT NULL AUTO_INCREMENT,
                     PRIMARY KEY (sequence_value)
            ) AUTO_INCREMENT = 0 ENGINE = INNODB

I have try to remove tables but it gives same error.
I have read this link1 and link2 but still not working for me.
Any help will be appreciated, Thanks in advanced.


text:
Q: Are Hibernate Pessimistic Locks Distributed with EHCache/Terracotta? Can Hibernate implement pessimistic locking at the start of a Java transaction, or does it instead rely on a pessimistic lock being applied when all the work in the Java realm is done, and then the changes are applied to the database as part of a database transaction?
I ask as I've got a Java transaction, halfway through which a call to a remote web service is made, which is non-transactional and thus cannot be rolled back. If Hibernate holds a pessimistic lock on the data being acted upon, then the processing of the transaction should be blocked as Hibernate knows another thread is already acting upon those data. If Hibernate doesn't keep a track of such locks itself, then the Java transaction will continue, invoking the webservice, and then blocking on the DB commit.
What I really want to happen is for the Java transaction to start, another thread attempt to start another transaction, and block/fail because there's already one in progress for the relevant data.
How is the locking behaviour affected when Hibernate's using EHCache as a 2LC in a distributed fashion with Terracotta?

A: Hibernate pessimistic locks are database locks. The locking is delegated to the database. The second-level cache has nothing to do with it.

A: "Hibernate does not lock objects in memory."
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/transactions.html
Nothing like a bit of RTFM :)


text:
Q: Wordpress how to get specific post data using WP_REST_Posts_Controller How I can get specific post data in foreach loop? (only title for example)
Here is my PHP (returns all post data):
function myspace_get_posts_by_tag(WP_REST_Request $request) {

    $slug = $request['slug'];
    $page = $request['page'];

    $term = get_term_by('slug', $slug, 'post_tag');
    $posts_per_page = 1;

    $args = array(
        'tag__in'           => $term->term_id,
        'posts_per_page'    => $posts_per_page,
        'paged'             => $page,
        'orderby'           => 'date',
        'order'             => 'desc',
    );

    $query = new WP_Query( $args );

    $max_pages = $query->max_num_pages;
    $total = $query->found_posts;

    $posts = $query->posts;

    $controller = new WP_REST_Posts_Controller('post');

    foreach ( $posts as $post ) {

        $response = $controller->prepare_item_for_response( $post, $request );
        $data[] = $controller->prepare_response_for_collection( $response );

    }

    $response = new WP_REST_Response($data, 200);
    $response->header( 'X-WP-Total', $total );
    $response->header( 'X-WP-TotalPages', $max_pages );
    return $response;

}

I cut down some code just for the sake of example.

A: You are using WP_Query() to fetch the posts later in the foreach loop.
In that case, $post is a WP_Post Object. So you can access its properties, in your case - the post's title:
$post->post_title


text:
Q: How to view content of Cache in JCache There are options to read the cache by using keys. Like this :
   Collection<Integer> userIds = context.getUserDao().allUserIds();
   for (Integer userId : userIds) {
        User user = cache.getUserCache().get(userId);
        System.out.println(user.toString());
    }

With the latter it will load the expired ones to the cache and then display it.
But the requirement is to view all the content currently in the cache.

A: This is how to view all the content of the Cache. Found the method after going through the Java Docs of JCache.
public void printAllCache(){

    Cache<String, String> cache = cacheManager.getCache(CACHENAME, String.class, String.class);

    Iterator<Cache.Entry<String,String>> allCacheEntries= cache.iterator();
    while(allCacheEntries.hasNext()){
        Cache.Entry<String,String> currentEntry = allCacheEntries.next();
        System.out.println("Key: "+currentEntry.getKey()+" Value: "+ currentEntry.getValue());
    }
    return returnProperties;

}

A: See if the following link is of help
https://docs.oracle.com/middleware/1213/coherence/develop-applications/jcache_basic.htm#COHDG5812


text:
Q: How to duplicate specific table content(given condition) into a new database table using php codeigniter How to duplicate specific table content(given condition) into a new database table using php codeigniter ?
For example, I should get from db job table the following:

*

*job_id, job_title, job_description, client_id provided that the job was already awarded by client to provider (i.e. "status"=="Awarded")
NOTE: I should be able to completely "copy/duplicate" these entries to avoid missing link if ever the specific job was later on deleted by client

*provider_id , proposal_id from db job_proposal table (again, I think condition here is status==approved)
and then add NEW fields that are nowhere in the existing tables in my db..
I would appreciate any help.. thanks!

A: CREATE TABLE 'new_table_name' LIKE 'your_table_name';

Then
INSERT INTO New_table SELECT * FROM Old_table1,Old_table2 GROUP BY ID;

This will create a new table with all the datas.This command is used as a backup for the tables.
NOTE: If the second table doesn't have the same strucutre, u hv to first create the necessary columns, and then get the backup of the datas from the second table


text:
Q: Comparing Apache Livy with spark-jobserver I know Apache Livy is the rest interface for interacting with spark from anywhere. So what is the benefits of using Apache Livy instead of spark-jobserver. What are the drawbacks of spark-jobserver for which Livy is used as an alternative. And I couldn't find much on this on the internet. Can you please help me to get clarity on this.
Thanks,

A: There are a couple of major differences that were relevant to my use case.
Livy's advantages:

*

*Livy does not require any changes to your code, while SJS jobs must extend a specific class.

*Livy allows submitting code snippets as well as precompiled jars, while SJS only accepts jars.

*In addition to REST Livy has a Java and Scala APIs. A Python API is in development, SJS has a "python binding"

SJS Advantages:

*

*SJS can manage the jars as well. It allows you to upload and store Jars, then deploy jobs from these jars with a separate REST call. Livy requires the jar whenever you need to deploy a job.

*SJS jobs can be configured with HOCON format which can be submitted as part of the REST call.

Additionally, SJS has better documentation, although in both cases, it's not comprehensive.
And of course, keep in mind that both projects are pre v1, so things could change quickly.
In my case we ended up going with SJS since I had no use for submitting snippets, and Jar management and HOCOCN configuration came in handy. I am, however, considering revisiting Livy in the near future for a more thorough evaluation.
Sources:

*

*https://livy.incubator.apache.org/

*https://github.com/spark-jobserver/spark-jobserver

*Livy presentation: https://www.youtube.com/watch?v=C_3iEf_KNv8

A: As of September 2018, the only major difference between Livy and the (Ooyala) Spark Job-server is the fact that although (the current version of) Livy is built against Spark 2.2.0, the version of Spark used when running Livy does not need to match the version used to build Livy. Livy internally handles the differences between different Spark versions.
This behaviour is different from Spark Job-server which has tight coupling with the Spark version it is built against.

A: For people who read this after 4 years, there is no support for Spark 3.x for Spark Jobserver. So with the tightcoupling of Spark version as mentioned above, this seems to be a dead-end in 2023.


text:
Q: Looking for suggestion, loop terminate on time conditions I am trying to implement a simple python based code into the LabVIEW and for this, I am trying to implement this logic by using loop-timer termination but don't know how to run a loop that will terminate on time conditions.
Looking for your suggestions.

A: The problem is solved by using local variables and while loop combinations .


text:
Q: 3 tier architecture on kubernetes I have 1 master kubernetes server and 9 nodes. In that, I want to run backend on 2 nodes and frontend on 2 nodes and DB on 3 nodes.
For all backend, frontend, DB I have ready DockerImage.
How to run an image using kubernetes on only desired(2 or 3).
Please share some ideas to achieve the same.

A: The Kubernetes scheduler most of the time will do a good job distributing the pods across the cluster. You may want to delegate that responsibility to the scheduler unless you have very specific requirements.
If you want to control this, you can use:

*

*Node selectors

*Node Affinity or Anti-Affinity

*Directly specify the node name in the deployment spec

From these three, the recommended approach is to use node affinity or anti-affinity due to its flexibility.

A: You may use labels and nodeSelector. Here it is:
https://kubernetes.io/docs/concepts/configuration/assign-pod-node/

A: *

*Run the front end as a Deployment with desired replica count and let kubernetes manage it for you.

*Run Backend as Deployment with desired number of replicas and Kubernetes will figure out how to run it. Use node selectors if you prefer specific nodes.

*Run the DB as Deployment OR StatefulSet, Kubernetes will figure out how to run it.
https://kubernetes.io/docs/tutorials/stateful-application/mysql-wordpress-persistent-volume/
Use network policies to restrict traffic.


text:
Q: Why does magento wait for a request to complete before processing others? I have added a script to an admin page on a magento site to initiate a long running process and periodically query the progress using AJAX (or XHR) requests so that it can update a progress bar.
The first request is to the controller function that starts a long running process:
var startfeed = new XMLHttpRequest();
startfeed.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        feedComplete(this);
    }
};
startfeed.open("GET", thisFeedUrl, true);
startfeed.send();

In the code above, the thisFeedUrl variable is the appropriate URL for the following controller action:
public function thistakesalongtimeAction()
{
    very_slow_function();
}

The very_slow_function writes it's current progress to a file, which can be accessed by the following controller action:
public function getprogressAction(){
    $progressFileName = getProgressFileName();
    echo file_get_contents($progressFileName);
}

This controller is accessed by the following javascript:
var feedProgress = new XMLHttpRequest();
feedProgress.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        progress = JSON.parse(this.responseText);
        // Update progress bar
        setProgress(progress);
    }
};
feedProgress.open("GET", thisFeedUrl, true);
feedProgress.send();

The problem is that the requests for progress do not complete until the long running action has completed. How can I get the progress bar to update correctly while the long running process is incomplete.

A: The AJAX requests for the progress reports are probably being forced to wait for the first request because they are running in the same PHP session. The request that takes a long time to complete acquires the session lock and holds it until thistakesalongtimeAction() has returned. That means that the other action will wait for the lock to be released.
You can force the lock to release early by closing the session with session_write_close():
public function thistakesalongtimeAction()
{
    session_write_close();
    very_slow_function();
}

You should also be careful that you don't start too many long running requests. If you have lots of slow actions that you run concurrently, you might hit the browser's limit for the number of concurrent requests and then you won't be able to make the progress-report requests.


text:
Q: Solutions for a simple multi tenant web application with entity framework I'm developing a multi-tenant web app (stack: MVC 4 + Entity framework 4.3).
My requirements are pretty simple: each tenant has the same UI and CodeBase.
In my database I have some tables with a TenantId field (and other tables without).
I have set up a very simple generic repository:
public class GenericRepository<TEntity> where TEntity : class
{
    internal Database.CRMEntities context;
    internal DbSet<TEntity> dbSet;
    internal int tenantId;

    public GenericRepository(Database.CRMEntities context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
        this.tenantId = 1;
    }

I'd like the "get" methods to filter for my tenantId. My insert, update and delete method should also constrain the appropriete TenantId.
My Entities are autogenerated POCO classes.
I have considered these solutions:
1- GenericRepository should implement a "ITenant" interface that defines TenantId. Problem is that some entities haven't got the TenantId property. Also, I don't really like to modify the T4 template I use to generate POCO objects to make them implement my interface
2- Reflection (but of course EF can't translate it to a SQL statement)
if (typeof(TEntity).GetProperty("TenantId") != null)
            query = query.Where(x => (int)   (x.GetType().GetProperty("TenantId").GetValue(x, null)) == tenantId);

What would you do in my case? I'm willing to reconsider my architecture if necessary.
Thanks,
Nicola

A: You can do the reflection check and then manually create an expression tree that EF can understand.
For example:
int tenantId = 5;

var tenantIdInfo = typeof(TEntity).GetProperty("TenantId");

if (tenantIdInfo != null)
{
    var entity = Expression.Parameter(typeof(TEntity), "it");

    var predicate = (Expression<Func<TEntity, bool>>)Expression.Lambda(
        Expression.Equal(
            Expression.MakeMemberAccess(entity, tenantIdInfo),
            Expression.Constant(tenantId, typeof(int))),
        entity);

    query = query.Where(predicate);
}


text:
Q: Agile Dashboard import error - Tuleap 7.2.99.51 I installed Tuleap to a CentOS 6.5 server following these instructions: http://doc-en.tuleap.net/en/latest/installation-guide/full-installation.html
I had had no issues, I then decided to implement the agile dashboard following these instrctions: http://tuleap-documentation.readthedocs.org/en/latest/user-guide/agile-dashboard.html?highlight=agile
I downloaded the tuleap_agiledashboard_template.xml but when I try to import it I get the following error:
Error Listing
src/utils/php-launcher.sh src/utils/import_project_xml.php 101 admin ~/agiledashboard_template.xml
PHP Warning:  file_get_contents(/root/agiledashboard_template.xml): failed to open stream: No such file or directory in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 45
Warning: file_get_contents(/root/agiledashboard_template.xml): failed to open stream: No such file or directory in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 45
PHP Warning:  DOMDocument::loadXML(): Empty string supplied as input in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 62
Warning: DOMDocument::loadXML(): Empty string supplied as input in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 62
*** ERROR: String could not be parsed as XML
[root@tuleap-alm-server codendi]# src/utils/php-launcher.sh src/utils/import_project_xml.php 101 admin /home/root/agiledashboard_template.xml
PHP Warning:  file_get_contents(/home/root/agiledashboard_template.xml): failed to open stream: No such file or directory in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 45
Warning: file_get_contents(/home/root/agiledashboard_template.xml): failed to open stream: No such file or directory in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 45
PHP Warning:  DOMDocument::loadXML(): Empty string supplied as input in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 62
Warning: DOMDocument::loadXML(): Empty string supplied as input in /usr/share/tuleap/src/common/project/ProjectXMLImporter.class.php on line 62
*** ERROR: String could not be parsed as XML
Kind regards
Dennis

A: You should try to import the XML directly from the web interface in Agile Dashboard admin

A: When I import the xml directly from the web interface in Agile Dashboard admin I get: Trackers have been disabled in this project.
When I import the xml directly from the web interface via a user with admin rights I get the following error:
XML file doesnt have correct format
:
:
:
:
:
:
   1/themes/FlamingParrot/images/clear.png
   2/themes/FlamingParrot/images/clear.png
   3/themes/FlamingParrot/images/clear.png
   4/themes/FlamingParrot/images/clear.png
   5/themes/FlamingParrot/images/clear.png      Epics
   6/themes/FlamingParrot/images/clear.png      agile_epic
   7/themes/FlamingParrot/images/clear.png      A tracker of Epics
   8/themes/FlamingParrot/images/clear.png
   9/themes/FlamingParrot/images/clear.png
  10/themes/FlamingParrot/images/clear.png
  11/themes/FlamingParrot/images/clear.png          column_top_1
  12/themes/FlamingParrot/images/clear.png          Column Top 1
...
Kind regards

A: make sure that you run ' yum install  tuleap-plugin-agiledashboard '
and go to agile Dashboard admin import the XML directly.


text: Q: MS Access 2010 - When running a report, field shows IDs instead of values I'm running a report off of a query to create room signs showing people in that room.  The query shows the actual room number, but when I create the report from the query, the ID number for the room is shown instead.  How do I fix this?


text:
Q: Framing problem : How can I solve this problem? Let  $f$  be a function and $(a,b,c,x,y,z)\in \mathbb R ^6$;
We have $f(x,y,z,a,b,c)=7x+9z+\sqrt3 y+\cos(2a)+2a+b+c$
We suppose that :
$$x^2+y^2+z^2+a^2+b^2+c^2+(\cos 2a)^2=4$$
What's the exact framing of $f$
$$ \cdots\text{?}\cdots\le f(x,y,z,a,b,c) \le \cdots\text{ ?}$$

A: Hint: Use Cauchy inequality:
$$(a_1b_1+...a_nb_n)^2\leq (a_1^2+...+a_n^2)(b_1^2+...+b_n^2)$$
if $n=7$.
Further hint: Take $$(a_1,a_2,...a_7)= (7,9,\sqrt{3},1,2,1,1)$$ and
$$(b_1,b_2,...b_7)= (x,z,y, \cos (2a),a,b,c)$$


text:
Q: Server parameter in Perl DBI->connect() I'm new to Perl, I have a database connect like this:
DBI->connect("dbi:Sybase:server=JDBC", 'guest', 'sybase');

I want to know how Perl knows that what is IP of JDBC server and connect to that?
Should it saved in other place?
Thank you

A: Have a look at the documentation for DBD::Sybase. In http://search.cpan.org/~mewp/DBD-Sybase/Sybase.pm#The_interfaces_file you will find the following:

The DBD::Sybase module is built on top of the Sybase Open Client Client Library API. This library makes use of the Sybase interfaces file (sql.ini on Win32 machines) to make a link between a logical server name (e.g. SYBASE) and the physical machine / port number that the server is running on. The OpenClient library uses the environment variable SYBASE to find the location of the interfaces file, as well as other files that it needs (such as locale files).

So the mapping is done with the interfaces file.


text:
Q: How I can call a file in CodeIgniter, that has existed in core folder I am a absolute beginner of CodeIgniter, Now I was creating a simple project with CI. But I don't know how I can call a file that has existed in core folder.
Core folder is like the following
/core/bootstrap/bootstrap.css

I want to call bootstap.css from my view/admin/index.php
How I can call it?
I already try it like the following
<link href="/application/core/bootstrap/bootstrap.css" rel="stylesheet" media="screen">

but it still doesn't work.

A: Look at documentation and read about url_helper.
Use internal links with function site_url() or base_url()

A: First of all I will not put my css files in the core folder.
I will create folder which is in the same level as in the "application" and "system" folder.
Secondly, you need to configure the base url at application/confi/config.php like
$config['base_url'] = 'http://localhost/NV/';

With in the folder "NV", I have my CI files such as "application" and "system".
Then in the view I will just use
<link rel="stylesheet" href="<?php echo base_url();?>css/ace.min.css"/>

In this case, the "CSS" folder resides as in the same level as "application" and "system" folders.

A: You should not put your CSS files in the core folder. Best practice with CI is the following:
- application
- assets
 -- css
 -- js
 -- images
- system
 -- <all CI folders here>

Use a URL helper to point to the assets folder like:
function asset_url(){
    return base_url().'public/';
}

more info on url_helpers
Then you can point to your assets in your view like this:
<link rel="stylesheet" href='<?php echo asset_url()."css/YOUR_FILE.css" ?>'/>