text:
Q: move content from div to another automatically Lets say I have two div's, one called div A and the other one called div B.
Now, div B must have the exact content of div A, so I have to manually copy and paste the content from A to B every time I change the content in A...
Is there a way maybe using CSS to give div B whatever is in div A?
Example:

Contact Details

Email: email@websitename.com

Telephone: 020 8202 9767

                            Call us: 020 8202 9767

Email: email@websitename.com

So as you can see above, I have two divs, one is contactDetails-normal and contactDetails-smart... each will show on a different size screen. But both will always have the same info...

A: This is not possible using CSS, you'll need to resort to Javascript if you want this to happen, e.g. in jQuery you could use:
$( "#div2" ).html($( "#div1" ).html(););
Alternatively, if you only wish to copy textual content use text()

A: Based on the edits to the question I would recommend using css media query to style one element differently based on screen size instead of having repetitive HTML and extra javascript.
html

Contact Details

Email: email@websitename.com

Telephone: 0000000

SMS: 0000000

css
#contactDetails {
    //Styling for large screen size
}

@media screen and (max-width: 400px) {

  #contactDetails {
      //Styling for screen size smaller than 400px
  }

}

If you want elements inside the contactDetails to be visible only on smaller screen sizes you can also address them in the media query like so (note: i have added the relevant classes to the above html.)
css
#contactDetails .tel, #contactDetails .sms {
    display:none;
}

@media screen and (max-width: 400px) {

  #contactDetails .tel, #contactDetails .sms {
      display:inline;
  }

}

If you use this, be careful as older browsers don't always support media queries you may need to use something like respond.js to help them along https://github.com/scottjehl/Respond

A: You can not do that in CSS because CSS does not affect DOM tree.
Instead, you could use some jQuery script to clone your div.
Here is a demo from jQuery docs:
<!doctype html>

  <meta charset="utf-8">
  <title>clone demo</title>

Hello
, how are you?

http://api.jquery.com/clone/

A: You cannot do this with CSS.
But you can use jquery to do this easily :
$(function() {
    $("#B").html($("#A").html());
 });

This will simply copy all the html code inside the A div to the B div.
Demonstration : http://jsfiddle.net/e9GBn/1/

A: Try this javascript:
document.getElementById("div2").appendChild(
    document.getElementById('"div1"')
  );


text:
Q: What is the origin of "giving [it] the old college try"? What is the origin of giving [it] the old college try?  In particular, is it referencing an old ritual that might have percolated amongst alumni of the old and prestigious New England colleges/universities?  I tried Googling, but I'm not really finding an authoritative source at the moment.  If nothing definitive can be found, I'd at least appreciate a date of first attestation.

A: For more background on the use of the phrase, including some connotations I wasn't aware of,  I offer the following entry in Paul Dickson's The Dickson Baseball Dictionary:

old college try A wild and desperate attempt to make a play. Sometimes the term carries a hint of showboating. Babe Ruth (Babe Ruth's Own Book of Baseball, 1928) defined "giving it the old college try" as "playing to the grandstand or making strenuous effort to field a ball that obviously cannot be handled." In a column that appeared in the Columbus (Ohio) Citizen (Nov. 26, 1927) and was quoted in American Speech (Apr. 1930), Billy Evans wrote that "I gave it the old college try" is a term "often used in big league baseball, when some player keeps on going after a fly ball, usually in foul territory, with the odds about ten to one he would never reach it. Teammates of such a player often beat him to it by shouting in unison with the thought of humor uppermost: 'Well, kid, you certainly gave it the old college try,' as he falls short of making the catch." Evans continued: "When some player does something that a professional player might not ordinarily attempt, such as colliding with a fielder who had the ball ready to touch him out, in the hope that he might make him drop the ball, regardless of the danger he was courting, someone is sure to say, often ironically, if the speaker happens to be one of the players in the field: 'That's the old college spirit.'" Extended Use. The term was quickly applied to any effort with limited chances of success.

A: I found this link (at the bottom of the page) that might be helpful.  Attestation in 1919 about a baseball player:

[Frankie] Frisch was taking a long hold on his club and the old college try at the ball.

Frankie Frisch played baseball in college at Fordham University.  He's a Hall of Famer whose nicknames are "The Fordham Flash" and "The Old Flash."  He left college to make his major league debut with the NY Giants in June 1919, and the article was written in October 1919, so my best guess is that the author was giving a nod to Frisch's educational background — sort of a "he's playing with as much heart and determination as he did in college."
Given the popularity of baseball and the exceptional talent of this player, it would not surprise me if that's the reason this phrase became popular.  Compare for instance "Win just one for the Gipper," which occurred around the same time period.

A: In college, you are faced with impossible situations in which you are expected to succeed.  For example, having multiple exams and papers due at the same time, and being scheduled to work many hours at your college job.
When something seems impossible to do, but you do it anyways because you have no choice, you "Give it the old college try."

(Supporting edit by FumbleFingers, from Merriam-Webster...)

Definition of COLLEGE TRY - a zealous all-out effort
   Origin of COLLEGE TRY - from the phrase "give it the old college try", First Known Use: 1927

A: Here's a citation from 1917:

courtesy of a wordorigins discussion of this very question:

A newspaper column by that title by
  Billy Sunday which has a 1917
  copyright by The Bell Syndicate Inc.
  Appears in an Elyria Ohio paper
  October of 1918.
Actually, the evangelist puts the
  expression on the lips of the great
  Giants manager John McGraw who after
  watching an rookie outfielder just out
  of college miss a heroic catch which
  resulted in a homer. While the
  "sapient birds of the Giants gave the
  kid the cackle" McGraw is quoted as
  saying, "That's the eye, young fellow.
  The old college try."

redpajama_set_name: RedPajamaStackExchange


text:
Q: KMM import common library have no color syntax Hi i am creating a new project using Kotlin Multi Platform project.
A followed all the instruction from the official documentation : https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html
The only change I made, is that i converted the Swift UI project to Swift directly in the XCode project.
The project compile successfully and launch but my problem is that the color syntax is not recognised.
Xcode Screen shot
It is recognised as Plain Text as shown below.
Xcode Screen shot after modifying the color of Plain Text
This issue seems to be even for Samples from Kotlin Officals https://kotlinlang.org/docs/multiplatform-mobile-samples.html
. And appear for Swift/Swift UI project and it is not blocking the compilation of the application and everything appart off that seems to work fine, but it make the file not as readable as it should be for me.
I tried to :

*

*Delete Derived data and everything if the XCode folder

*Delete and install XCode

*Install XCode Beta

*Create a new KMM Project in Swift

*Create a new KMM project in Swift UI

*Try on sample that already work without any modification

Nothings have made the color syntax of KMM library recognised.

A: I finally found a solution :
I added to the Build Phase of the target in the compile sources the header file listing my module.
So for example i did a cmd+click on my Greeting Class, Show definition, then right click, Navigate, show in finder, and finally drag it to the compile sources, restart Xcode
Magic should happen and color syntax has been added.
PS : Added it as reference so when you build again the module it will keep track of changes


text:
Q: Deployed Web Application Requests for User Name and Password Deployed Web Application Requests for User Name and Password
I recently deployed a .NET web application into the server.
Authentication mode is set to Windows (since the application is accessible only to Intranet users.
Testing some machines, the application loads up properly.  For some machines, a logon dialog window appears asking for User Name or Password.  These dialog windows are those that you also normally see when you are trying to log into a Windows domain.
Any idea why this happens randomly?
Thanks.

A: Assuming you're using IE.
There are a couple of things to look at:

*

*Are the machines in question joined to the domain?

*For the machines in question, is a domain user (with appropriate privileges) logged into Windows on that machine?


text:
Q: Using Java, I am unable to sort a list of alpha numeric elements I declared an ArrayList like:
ArrayList<String> columns = new ArrayList<String>();

Now I filled this list by reading a column from an HTML table like this:
for(int rnum=1;rnum<(rows.size())+1;rnum++)
{
 columns.add(driver.findElement(By.xpath(".//*[@id='main']/table/tbody/tr[" + rnum + "]/td[1]")).getText());
}

Then I need to sort this list, and I used this:
java.util.Collections.sort(rows);

But this is not sorting the ArrayList.
Please note that my ArrayList contains text with alphabets, numeric values and special characters like : Testing123@, SampleTest123, Lasttest@1 etc.

A: Try using this sort called The Alphanum Algorithm
AlphanumComparator.java
import java.util.Comparator;

public class AlphanumComparator implements Comparator
{
    private final boolean isDigit(char ch)
    {
        return ch >= 48 && ch <= 57;
    }

    private final String getChunk(String s, int slength, int marker)
    {
        StringBuilder chunk = new StringBuilder();
        char c = s.charAt(marker);
        chunk.append(c);
        marker++;
        if (isDigit(c))
        {
            while (marker < slength)
            {
                c = s.charAt(marker);
                if (!isDigit(c))
                    break;
                chunk.append(c);
                marker++;
            }
        } else
        {
            while (marker < slength)
            {
                c = s.charAt(marker);
                if (isDigit(c))
                    break;
                chunk.append(c);
                marker++;
            }
        }
        return chunk.toString();
    }

    public int compare(Object o1, Object o2)
    {
        if (!(o1 instanceof String) || !(o2 instanceof String))
        {
            return 0;
        }
        String s1 = (String)o1;
        String s2 = (String)o2;

        int thisMarker = 0;
        int thatMarker = 0;
        int s1Length = s1.length();
        int s2Length = s2.length();

        while (thisMarker < s1Length && thatMarker < s2Length)
        {
            String thisChunk = getChunk(s1, s1Length, thisMarker);
            thisMarker += thisChunk.length();

            String thatChunk = getChunk(s2, s2Length, thatMarker);
            thatMarker += thatChunk.length();

            int result = 0;
            if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
            {
                int thisChunkLength = thisChunk.length();
                result = thisChunkLength - thatChunk.length();
                if (result == 0)
                {
                    for (int i = 0; i < thisChunkLength; i++)
                    {
                        result = thisChunk.charAt(i) - thatChunk.charAt(i);
                        if (result != 0)
                        {
                            return result;
                        }
                    }
                }
            } else
            {
                result = thisChunk.compareTo(thatChunk);
            }

            if (result != 0)
                return result;
        }

        return s1Length - s2Length;
    }
}

Which would then be called
java.util.Collections.sort(columns, new AlphanumComparator());

You can check if it worked by using
System.out.println(columns.toString);


text:
Q: Group by SQL with count Lets say we have got rows like that:
MyTable
ID Name  Product
------------------
1  Adam  x
2  Adam  y
3  Adam  z
4  Peter a
5  Peter b

Using query like:
Select Name, Count(Product) from MyTable
group by Name

results will be:
Adam 3
Peter 2

But I would like results like:
1 Adam x 3
2 Adam y 3
3 Adam z 3
4 Peter a 2
5 Peter b 2

I hope Ypu know what I mean
Could You help me with that query,
thanks for help,
Bye

A: You can join the table with a subquery run on the table to select the counts:
SELECT a.ID as ID, a.Name as Name, a.Product as Product, ISNULL(b.cnt,0) as Cnt
FROM MyTable a
LEFT JOIN (SELECT Name, COUNT(*) as Cnt FROM MyTable GROUP BY Name) b
ON a.Name = b.Name

A: How about?
Select *, Count() OVER(PARTITION BY Name) As C
from MyTable

A: Select a.Id,
       a.Name,
       a.Product,
       IsNull(b.CountOfUsers,0) as CountOfUsers

From MyTable a
Left Join (Select Name, Count(Product) as CountOfUsers from MyTable
          group by Name)b on a.Name = b.Name

A: ;WITH c AS (SELECT Name, COUNT(Product) CountOfProduct
            FROM MyTable
            GROUP BY Name)
SELECT t.Id, t.Name, t.Product, c.CountOfProduct
FROM MyTable t
INNER JOIN c ON c.Name = t.Name

A: Use:
   SELECT x.id,
          x.name,
          x.product,
          COALESCE(y.name_count, 0) AS num_instances
     FROM MyTable x
LEFT JOIN (SELECT t.name,
                  COUNT(*) AS name_count
             FROM MyTable t
         GROUP BY t.name) y ON y.name = x.name

COALESCE is the ANSI standard means of handling NULL values, and is supported by MySQL, SQL Server, Oracle, Postgre, etc.


text:
Q: Finite covering of a closed interval of $\mathbb{R}$ Let $a<b$ be a pair of real numbers. For each $n\in\mathbb{N}^\times$, I want to construct a finite cover $(U_k)_{1\leq k\leq n}$ for $[a,b]$.
Attempt: Let $1\leq n$. For each $0\leq k\leq n$, write
$$x_k:=a+\frac{k(b-a)}{n}.$$
I would like to show that $(B(x_k,1/n))_{0\leq k\leq n}$ covers $[a,b]$. Let $a\leq y\leq b$. If $y=a$, then $y\in B(x_0,1/n)$. If $y=b$, then $y\in B(x_n,1/n)$. Assume $a<y<b$. How do I show that there exists a $0\leq k\leq n$ such that $y\in B(x_k,1/n)$?
Should prove it by contradiction? A hint would be appreciated.

A: First of all you could have just taken the single open set $(a-\epsilon,b+\epsilon)$, where $\epsilon>0$.
Secondly the collection of open sets you have taken would not cover $[a,b]$ if $b-a>2$, this is because $x_k-x_{k-1}=\frac{b-a}{n}>\frac2n$. Hence for $y=\frac{x_k+x_{k-1}}{2}$, $y\in[x_{k-1},x_{k}]\subseteq[a,b]$ but $y\not\in B(x_{k-1},\frac1n)$ and $y\not\in B(x_k,\frac1n)$.
It would have worked if you took the sets $B(x_k,\frac{b-a}{n})$.


text:
Q: Python Selenium not letting me sign in to ancestry I have used selenium and the chromedriver to sign in to ancestry.com, however it says that it is not finding the id for login information. It opens up the browser and goes to the page, put the does populate and login. I have tried this on other sites yet it has worked, not sure why it is not working here. I had tried to make it sleep for a few seconds thinking the page needed to load fully (coming from my beginners knowledge)....Code is below, I would appreciate if anyone has had trouble or knows how to deal with this login.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

chrome_path= r"C:\Users\....\chromedriver_win32\chromedriver.exe"
driver= webdriver.Chrome(chrome_path)
driver.get("https://www.ancestry.com/account/signin")
sleep(15)

username= "username"
password= "password"
driver.find_element_by_id("username").send_keys(username)
driver.find_element_by_id("password").send_keys(password)
driver.find_element_by_id("signInBtn").click()
print("Logged in Successfully")

A: Actually, you need to switch to the frame, I've used the explicitWait instead of sleep
driver.get("https://www.ancestry.com/account/signin")

username= "username"
password= "password"

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_id("signInFrame")))

userName = WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,"username")))
userName.send_keys(username)

passWord = WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.ID,"password")))
passWord.send_keys(password)

signIn = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.ID,"signInBtn")))
signIn.click()

print("Logged in Successfully")


text:
Q: jQuery fadeTo not working on page exit I've scoured the internet for solutions for hours, but my code still doesn't work. I am creating a jQuery page transition whereby my website's main content (other than the header and footer) will fade in as a page loads, and fade out as a page exits/transitions to another page. I am using fadeTo() to change its opacity as fadeIn() and fadeOut() removes the main content, causing the footer to 'move up' the page in its place.
The problem is that my current code does not show any fading transition effect:
(function( $ ) {
"use strict";

$(function() {

    // Your code here
        $("#main.site-main").css('opacity', '0');
        $("#main.site-main").fadeTo(1000, 1);

$(".nav-menu li").click(function(event) {

            event.preventDefault();

            newLocation = this.href;

$("#main.site-main").fadeTo(1000, 0, function () {

            window.location = newLocation;

        });

});

}(jQuery));

But the following code works, which only shows the main content 'fade in' as a page loads:
(function( $ ) {
    "use strict";

$(function() {

    // Your code here
        $("#main.site-main").css('opacity', '0');
        $("#main.site-main").fadeTo(1000, 1);

});

}(jQuery));

So how can I achieve the fade in AND fade out effect for my page transition? And why isn't the top code working?

A: It should work, I've done it in this way, you may adopt that code:
jQuery('a').click(function(event) {

    // don't exec the link loading (a href stuff) - we do it explicitly
    event.preventDefault();
    var that = jQuery(this);
    var target = jQuery(this).attr("target");
    if (jQuery.trim(target).length > 0)
    {
        window.open(that.attr("href"), target);
    }
    else
    {
        // fade out content, load next document
        jQuery('.content-style').animate({
            opacity : "0"
        }, {
            duration : 700,
            "complete" : function() {

                document.location = that.attr("href");
            }
        } // complete callback
        ); // animate properties
    }
}); // click callback

A: Try this:
$(".nav-menu li").on("click", function(event) {
    $("#main.site-main").fadeTo(1000, 0, function() {
        window.location = event.currentTarget.href;
    });
});

A: With the help of some people on this site, and trial and error, the following code does just what I want. It's a bit slow for me though, but that's a question for another day.
The code:
   (function( $ ) {

        "use strict";

        $(function() {

            // Your code here

    var $sitemain = $( "#main" ).find( "div.site-main" );

            $sitemain.fadeTo(200, 1);

    $($( "#site-navigation" ).find( "a" ), $( "#masthead" ).find( "a.home-link"   )).on("click", function(event) {
    $sitemain.fadeTo(200, 0, function() {
        window.location = event.currentTarget.href;
        });
    });

    });
    }(jQuery));


text:
Q: popen doesn't run a proces I have a function that should run a process in background
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen('start /B '.$cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
}

I try to run script
$cmd = "php ..\runffmpeg.php";
execInBackground($cmd);

But it does nothing. When I try to run
$cmd = 'ffmpeg -i video_in.mp4 video_out.avi';
execInBackground($cmd);

Its all right. And when I try to run
exec("php ..\runffmpeg.php");

It's also all right.
So, pclose(popen('start /B php ..\runffmpeg.php', "r")); doesn't run a command. Whats a problem?
I'm using Windows and php 5.4.7

A: You can use: $cmd= include("php ..\runffmpeg.php");

A: hmm; forget process mgmt and just popen() the resource.
If it is a daemon, you get access to it, else a subprocess is created/destroyed with the popen()/pclose().


text:
Q: How to store queried custom data and use it in multiple pages? <?php
                    $contact = new WP_Query(array(
                        'post_type' => 'contact'
                        // 'post_status' => 'publish'
                    ));
                    while($contact -> have_posts()){
                        $contact -> the_post();
                        $watsapp = get_field('watsapp_no');
                        $mobile = get_field('mobile_no');
                        $telephone = get_field('telephone_no');
                        $address = get_field('address');
                    }
                    wp_reset_query();
                    ?>

*

*I need to echo the contact details in multiple pages

*Do i need to call it in each page  or  there is any simple way to not
repeating the same query?

A: Though it's not clear exactly what do you want. But, you can do this by two ways.

*

*Make a Function like
         function wpse_1001(){
           $contact = new WP_Query(array(
           'post_type' => 'contact'
                // 'post_status' => 'publish'
            ));
            while($contact -> have_posts()){
                $contact -> the_post();
                $watsapp = get_field('watsapp_no');
                $mobile = get_field('mobile_no');
                $telephone = get_field('telephone_no');
                $address = get_field('address');
            }
            wp_reset_query();
          }

Use the Code anywhere on your Code.

*You can Use Shortcodes by add_shortcode(), so that you can use it from your Editor also.

https://codex.wordpress.org/Function_Reference/add_shortcode

If you like Shortcodes then you can use on your Code by do_shortcode() function.

https://developer.wordpress.org/reference/functions/do_shortcode/


text:
Q: What is the standard for PROD database password in the Springboot fat jar application connecting a database I have a springboot application which connects to database, currently the database password is in plain text inside the application properties.
What is the standard for securely protecting password in PROD environment?
How to change the database password if the application password is inside the application properties which is built in as part of the JAR and especially when the application is live?

A: You could use jasypt to handle the encryption and then use Jasypt's Spring integration or this Jasypt Spring Boot Starter to wire it into Spring.
This will allow you to define an encrypted database password property, for example in application.properties e.g.
db.password=ENC(.....)

The other part of your question is:

How to change the database password if the application password is inside the application properties

You can do this by overring properties defined in your properties file with system properties. For example: -Ddb.password='....'. You could also define an additional properties source which is external to your JAR and can be edited at runtime. For example:
@PropertySources({
        @PropertySource(value = "classpath:/**.properties"),
        @PropertySource(value = "file:/some/external/directory/override.properties", ignoreResourceNotFound = true)
})
public class Application {
    // ...
}

Creating the file /some/external/directory/override.properties and populating it with db.password=... would cause your application - on next restart - to use  that property value.


text:
Q: SQL Query to retrieve values that belong exclusively to a group Suppose I have one table with the following values and columns:
ID1 | ID2
1   | 1
2   | 1
3   | 1
4   | 1
4   | 2
3   | 3
4   | 3
4   | 4
4   | 4

I'd like to retrieve the ID2 values that belong exclusively to records where ID1 = 4. So for the above example, I'd like to see the following response:
ID1 | ID2
4   | 2
4   | 4

A: Try working it out contrapositively like this.
Finding all elements where ID1 is only 4 is the same as finding all elements that don't not have ID1 = 4.
CREATE TABLE #temp (ID1 NVARCHAR(10), ID2 NVARCHAR(10))
INSERT INTO #temp(ID1,ID2) VALUES  (N'1',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'2',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'3',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'1')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'2')
INSERT INTO #temp(ID1,ID2) VALUES  (N'3',N'3')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'3')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'4')
INSERT INTO #temp(ID1,ID2) VALUES  (N'4',N'4')

SELECT * FROM #temp AS t

SELECT DISTINCT * FROM #temp AS t
WHERE id2 NOT IN (SELECT ID2 FROM #temp AS t WHERE ID1 <> 4)

A: These queries will probably be useful to you for the more general cases (and by general I mean when ID1 is something other than 4):
select distinct t1.id1, t1.id2
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)

select t1.id1, count(distinct t1.id2)
from T as t1
where not exists (
    select 1
    from T as t2
    where t2.ID1 <> t1.ID1 and t2.ID2 = t1.ID2
)
group by t1.id1

A: You can also do this:
select 4,id2 from
(select distinct ID1 , ID2 from t) t1
group by id2
having count(*)=1

A: There are a few ways to do this:
SELECT t1.id1, t1.id2
  FROM mytable t1
 WHERE t1.id1 = 4
   AND NOT EXISTS ( SELECT 1 FROM mytable t2
                     WHERE t2.id2 = t1.id2
                       AND t2.id1 != 4 );

or:
SELECT id1, id2 FROM (
    SELECT id1, id2
      FROM mytable
     GROUP BY id1, id2
    HAVING COUNT(*) = 1
) WHERE id1 = 4;

or:
SELECT id1, id2 FROM (
    SELECT id1, id2, COUNT(*) OVER ( PARTITION BY id2 ) AS cnt
      FROM mytable
) WHERE id1 = 4
    AND cnt = 1;


text:
Q: React native Button not working when i tap it on my mobile using expo application I am having a problem with my button. i have just started learning reactnative.
import { StatusBar } from 'expo-status-bar';
import React,{ useState } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [name, setName] = useState('Hamza');
  const clickHandler= () => {
    setName('Awais');
  };
  return (
    <View style={styles.container}>
      <Text >My Name is { name }</Text>
      <Text></Text>
      <View style={styles.buttonContainer}>
        <Button title='update State' onPress={ clickHandler }/>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonContainer:{
    marginTop:20,
  },
});

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

A: Try this way
<Button title='update State' onPress={() => clickHandler() } />


text:
Q: Are there any tables that I can get all Oracle supported system privileges and object privileges? Are there any tables that I can get all Oracle supported system privileges and object privileges? I know there is a view called all_sys_privs in Oracle. But I can't find more information about it.
Thanks.

A: Perhaps you are looking for SYSTEM_PRIVILEGE_MAP?

A: Try this query for object privileges by object type.
SELECT o.object_type, t.privilege
FROM dba_tab_privs t
JOIN dba_objects   o
  ON t.owner = o.owner
 AND t.table_name = o.object_name
GROUP BY o.object_type, t.PRIVILEGE
ORDER BY o.object_type, t.PRIVILEGE
;

The following takes into account privilege types that exist in table_privilege_map but not in the existing database objects.
SELECT o.object_type, m.name AS privilege
FROM table_privilege_map m
LEFT OUTER JOIN (dba_tab_privs t
      JOIN dba_objects   o
        ON t.owner = o.owner
       AND t.table_name = o.object_name)
  ON m.NAME = t.PRIVILEGE
GROUP BY o.object_type, m.NAME
ORDER BY o.object_type, m.name
;

A: You can look into sys.table_privilege_map (at-least 11g onwards, might exist before but I have no way to check) for a listing of possible object privileges, be warned not all apply to all object types.


text:
Q: List of Table names from SQL queries I am trying to look for a way to get the list of all the table names used in various queries executed in a SQL Server database in last 30 days.
I have the queries and like to know if we can programmatically (rather than manually parsing it ) get the list of table names out of it or can get the details from any SQL Server system table.

A: Assuming the server hasn't been restarted in the last 30 days, a potentially more accurate way to determine what tables have been queried (in the event that your collection of queries is incomplete):
SET ANSI_WARNINGS OFF;
SET NOCOUNT ON;
GO

;WITH agg AS
(
    SELECT
        [object_id],
        last_user_seek,
        last_user_scan,
        last_user_lookup,
        last_user_update
    FROM
        sys.dm_db_index_usage_stats
    WHERE
        database_id = DB_ID()
)
SELECT
    [Schema] = OBJECT_SCHEMA_NAME([object_id]),
    [Table_Or_View] = OBJECT_NAME([object_id]),
    last_read = MAX(last_read),
    last_write = MAX(last_write)
FROM
(
    SELECT [object_id], last_user_seek, NULL FROM agg
    UNION ALL
    SELECT [object_id], last_user_scan, NULL FROM agg
    UNION ALL
    SELECT [object_id], last_user_lookup, NULL FROM agg
    UNION ALL
    SELECT [object_id], NULL, last_user_update FROM agg
) AS x ([object_id], last_read, last_write)
GROUP BY
    OBJECT_SCHEMA_NAME([object_id]),
    OBJECT_NAME([object_id])
ORDER BY [Schema],[Table_Or_View];

If you want to rely on the queries you've collected, there is no magic system table that maps queries to table(s). So, not sure exactly where are how these queries you've collected are stored, but you could attempt to parse the table or index names out of the plan XML using sys.dm_exec_cached_plans and sys.dm_exec_sql_text. This will not be simple and, unless you have more memory than you could possibly need, it is highly unlikely that all of the plans for 30 days worth of queries are currently in the plan cache.


text:
Q: Does Moodle cache User Profile Field for activity restriction? I am trying to restrict access to Moodle course activities based on a user profile field.  The profile field tracks eligibility based on other criteria such as whether they have filled in certain important information about their business.
The field is required, locked and set to a default value, although setting it to unlocked made no difference. It is hidden from view in the user profile and signup screen using CSS (because Moodle user profile fields that aren't displayed in the sign up screen don't get a mdl_user_info_data row created when the user is created - but that's another issue). The relevant row in mdl_user_info_data is updated when the user submits a form that I've created.  This part works absolutely fine, except that the user still needs to log out and back in again in order for the change to trickle down to the course page (i.e. for them to be able to access the course activities).
It appears that the user profile fields are being cached when the user logs in, and are not being updated.  Does anyone know if this is so?  And the obvious follow up questions would be - Can I force this cache to be updated and, if I can, how would I go about triggering this?
I'm using Moodle 2.7.3.

A: The data is cached in the $USER global object (which is, itself, cached on the session data), in the $USER->profile field. You should be able to update the value there or call a function to reload it (I can't remember the function off the top of my head, but it will be in user/profile/lib.php).


text:
Q: Use of typedef name in elaborated specifier According to ($ 3.4.4) A typedef name followed by a class-key is invalid. But I'm not sure about which scope? For example: In the following, compiler doesn't complain if elaborated specifier was used in a block such as inside a function.
typedef class { /* ... */ } S;

// invalid
class S;

// ok
void foo() {
   class S;
}

Is it valid to declare a class inside a local scope with typedef-name, Why?

A: 7.1.3 paragraph 3 tells :

In a given scope, a typedef specifier shall not be used to redefine
  the name of any type declared in thascope to refer to a different
  type.
  [Example:

class complex { /* ... */ };
typedef int complex; //

error: redefinition

Then it goes :

—end example] Similarly, in a given scope, a class or enumeration
  shall not be declared with the same name as a typedef-name that is
  declared in that scope and refers to a type other than the class or
  enumera- tion itself. [Example:

typedef int complex;
class complex { /* ... */ };

// error: redefinition

This is your example.

A: The problem is that you declared the class with no name, but with an alias (the typedef). Later, you used the same name to declare without defining another class (I know that was not the intention, but that's what the compiler understood) and its name clashed with the typedef. When you did the same thing inside foo(), that was a separated scope and so was acceptable. But notice that the 'class S' inside foo() is NOT the same type as that declared in the first line.

A: Outside the function, you cannot declare a class with the same name as a typedef in the same namespace.
Inside the function, you are declaring a new class, scoped inside the function. It is not the same as the anonymous class declared in the surrounding namespace. Within the function, this hides the declaration of the typedef.


text:
Q: How to properly (quickly) iterate over Reminders using AppleScript/osascript? What is the proper, efficient way to iterate over Reminders using AppleScript?  The script below works as expected, but takes 18 seconds to iterate over 180 Reminders when run from the command line using osascript!  (This same script takes only 2-3 seconds when run from within the ScriptEditor.)
# Find all Reminders whose name contains "Alumni"
set findMe to "Alumni"
set answer to "Maches: "

tell application "Reminders"
    set names to name of every reminder
end tell

repeat with name in names
    if name contains findMe then
        set answer to answer & " --- " & name
    end if
end repeat

return answer

I've run this script two ways from the command line: As a compiled script:  osascript testReminders2.scrpt and as a text file:  ./testReminders2.applescript (where this file begins with #! /usr/bin/osascript.  Both versions take about the same amount of time.


text:
Q: How to use Ning API in iphone development I have Ning Network and I have already developed an iOS app for the network.
I would like to use the Ning API for make possible for user upload pictures from the app to the network.
I known that i have to use the Ning API, but I have no idea how to use it in X-Code.
If someone could help me I would appreciate.
thanks in advance!
Guilherme

A: Though your question is too broad to answer I would summarize as,
If you are new to iOS development you have to learn iOS programming and following are the options I see currently,

*

*See these  tutorials, where in depth knowledge is given and also step by step, so easy to learn.

*You can also download ebook if you are fan of digital book reading.

*You can search around net and will find lots of tutorials how to learn iOS programming.


text:
Q: Insertion Sort For A Singly Linked List C++ I am given a head file which defines how the nodes of the linked list are to be created
#ifndef _LISTNODE
#include <cstddef>
#define _LISTNODE

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
#endif

My task is to create a function that will do an insertion sort for a linked list and sort the items in decreasing order (can assume there are no cycles in the linked list.
The function is defined as
ListNode *insertionSortList(ListNode *head)

So my current logic is that I iterate through the linked list until I find that the node that the iterator is currently on is less than the value of the node next to it. In that case, it takes the value of the node that contains the greater number and stores it in a temp pointer. Then my iterator that was on the number that was previous to the node that has just been put into the temp pointer makes it so that this node now points past the node that is breaking the order and to the node after that.
Then I have another iterator go through the list until it finds the spot where it would go to make the order work and then place the node that is being stored with the temp pointer and have the next pointer within this node point to the node that the new iterator has found to be less than it.
I'm sorry if this explanation is a bit messy but it seems to make sense when I draw a diagram out, and I don't see where my code could be breaking this logic, but when I run it with some test cases, it either doesn't sort or sometimes it doesn't sort and doesn't print all the values.
#include <iostream>
#include "ListNode.h"
using namespace std;

ListNode *insertionSortList(ListNode *head)
{
    ListNode *temp;
    for (ListNode *iterator = head; iterator->next != NULL; iterator = iterator->next) //first iterator to find node that breaks the pattern
    {
        if (iterator->val >= iterator->next->val) // if it doesn't break the pattern
        {
            break;
        }

        else //if it does break the pattern
        {
            temp = iterator->next; //store pattern breaking node
            iterator->next = iterator->next->next; //have linked list skip over this pattern breaking node
            for (ListNode *replacementit = head; replacementit->next != NULL; replacementit = replacementit->next) // find place for patteern breaking node
            {
                if (replacementit->val < temp->val) //if found the right place
                {
                    temp->next = replacementit; //put node into place
                    break;
                }
            }
        }
    }

    return head;
}

int main() //test cases
{
    ListNode A(5);
    ListNode B(6);
    ListNode C(10);
    ListNode D(21);
    ListNode E(25);

    ListNode* head = &A;
    A.next = &B;
    B.next = &C;
    C.next = &D;
    D.next = &E;

    insertionSortList(head);

    for (ListNode *print = head; print->next != NULL; print = print->next) //print out sorted Linked List
    {
        cout << print->val << " ";
    }
}

OUTPUT
5 10 %

A: Your implementation is incorrect on the first line inside the first for loop in insertionSortList function.
For example - if the first element of linked list is greater than or equal to the second element of linked list, your code will not execute any more lines in the for loop, it will "break". You can check with list 2 -> 1 -> 3.
Also, at last when you print the linked list, it will always not print the last element because the termination condition is buggy.


text:
Q: Injecting IPrincipal in ASP.NET MVC 3 - What am I doing wrong? I've got a custom IIdentity implementation:
public class FeedbkIdentity : IIdentity
{
    public int UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public string Name { get; set; }

    public FeedbkIdentity()
    {
        // Empty contructor for deserialization
    }

    public FeedbkIdentity(string name)
    {
        this.Name = name;
    }

    public string AuthenticationType
    {
        get { return "Custom"; }
    }

    public bool IsAuthenticated
    {
        get { return !string.IsNullOrEmpty(this.Name); }
    }
}

and custom IPrincipal
public class FeedbkPrincipal : IPrincipal
{
    public IIdentity Identity { get; private set; }

    public FeedbkPrincipal(FeedbkIdentity customIdentity)
    {
        this.Identity = customIdentity;
    }

    public bool IsInRole(string role)
    {
        return true;
    }
}

In global.asax.cs I'm deserializing FormsAuthenticationTicket userData and replacing
HttpContext.Current.User:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        FeedbkIdentity identity = serializer.Deserialize<FeedbkIdentity>(authTicket.UserData);

        FeedbkPrincipal newUser = new FeedbkPrincipal(identity);
        HttpContext.Current.User = newUser;
    }
}

Then, in Razor Views I can do:
@(((User as FeedbkPrincipal).Identity as FeedbkIdentity).FirstName)

I'm already using Ninject to inject custom User Repository for the membership provider and I've been trying to bind IPrincipal to HttpContext.Current.User:
internal class NinjectBindings : NinjectModule
{
    public override void Load()
    {
        Bind<IUserRepository>().To<EFUserRepository>();
        Bind<IPrincipal>().ToMethod(ctx => ctx.Kernel.Get<RequestContext>().HttpContext.User).InRequestScope();
    }
}

but it doesn't work.
All I'm trying to do is to be able to access my custom IIdentity properties like this:
@User.Identity.FirstName
How can I make this work?
EDIT
I was expecting that by binding IPrincipal to HttpContext.Current.User as suggested here: MVC3 + Ninject: What is the proper way to inject the User IPrincipal? I will be able to access @User.Identity.FirstName in my application.
If this is not the case, what is the purpose of binding IPrincipal to HttpContext.Current.User as shown in the linked question?

A: I'd recommend creating your own base WebViewPage. See http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx
Then inside that you could do
public FeedbkPrincipal FeedbkPrincipal
{
    get
    {
        return User as FeedbkPrincipal;
    }
}

public FeedbkIdentity FeedbkIdentity
{
     get
     {
         return FeedbkPrincipal.Identity as FeedbkIdentity;
     }
}

Then it's just
@FeedbkIdentity.FirstName

within the view.

what is the purpose of binding IPrincipal to HttpContext.Current.User as shown in the linked question

Dependency injection lets you choose your components at run time. In the example given, you could do
public MyClassConstructor(IPrincipal principal) { // }

and IPrincipal would automatically be bound to the User. Note this would not let you access your specific FeedbkPrincipal properties because even though at runtime it would become of type FeedbkPrincipal, your class doesn't know that. Dependency injection isn't a solution to your current issue because you do need a way of accessing your concrete classes.

A: Assuming that HttpContext.User gets set correctly, you could create a global filter to automatically populate your ViewBag with your FeedbkIdentity.
E.g.
Create it
public class FeedbkPrincipalIntoViewBagAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var principal = filterContext.HttpContext.User as FeedbkPrincipal;
        if (principal != null)
        {
            filterContext.Controller.ViewBag.Identity = principal.Identity as FeedbkIdentity;
        }
    }
}

Register it
protected void Application_Start()
{
    GlobalFilters.Filters.Add(new FeedbkPrincipalIntoViewBagAttribute());
}

Use it
@ViewBag.Identity.FirstName


text:
Q: How to extract the tree structure from an rpart object? Warning to those who read this later ...
My background in tree and graph algorithms meant that I expected this to be a simple question with a simple answer. But, it is not.
How this could work in the context that I come from is, say, functions left and right that get the left and right node of the current node. So that root(fit) is the root node and left(root(fit)) is the left child of the root node. And that other functions such as split(node) would give the information about the decision in the node.
However, the real answer is - almost no one who uses rpart, including the developer, thinks of a decision tree as being anything to do with a tree in that sense. Most of the answers given involve merely printing the tree out in human readable form as a diagram or text.
Several people have asked this question and the best answer is to look at getAnywere(summary.rpart), which lists the code that produces the text version of the tree. Is is quite mucky.
The original question follows.

I have a decision tree obtained by ...
makeDecisionTree <- function(ndata, fp, fn) {

   ctrl <- rpart.control( nobs = nrow(ndata), mincut = 2,  minsize=20, maxdepth=20)

   mytree <- rpart( formula = PredictedLabel ~ . ,
                   data=ndata,
                   minsplit=1,
                   method="class",
                   control = ctrl,
                   parms=list(split="information",
                               loss=matrix(c(0, fp, fn, 0),
                               byrow=TRUE, nrow=2))   )
   return(mytree)
}

I can print it out and get a listing of the decisions such as x>6, and I can understand what the tree is doing and so on. But, what I cannot see is how to work directly with the tree structure - in the sense of a recursive descent of the tree from the root node, under program control.
I have got to the point that I am considering seriously to print the tree to a text file and parse the resulting file just to get the actual tree structure. As this seems somewhat absurd -- I am assuming that I am missing something.
I have looked at the structure of the types, and looked at the splits matrix and so on. But, it is not clear to me how any of this produces a tree structure.

A: This is only a partial answer, but it was the core of the clue I needed to keep going. And I put it here in case someone else finds this question when confronted with the same problem.
Suppose that you create a fitted tree by ...
fit = rpart( ... )

Then fit$frame is a dataframe whose rows describe the nodes. The name of the row is the node number. The children of node n are 2n and 2n+1. The columns include var which gives the name of the field used in the split the node represents. A leaf node has the name <leaf>.
In the example below, 1 is the root node, with child nodes 2=2*1+0 and 3=2*1+1. The top node was split on MOB.
               var      n     wt    dev yval  complexity ncompete
1              MOB 121841 121841 295428    1 0.249854448        4
2           <leaf>  30302  30302   5514    1 0.000000000        0
3        MONTHS_TO  91539  91539 216100    2 0.205237824        4
6        MONTHS_TO  26002  26002  37842    1 0.092878806        4
12          <leaf>  18270  18270   1788    1 0.010000000        0
13       MONTHS_TO   7732   7732   8615    2 0.017249550        4
26          <leaf>   1622   1622   1644    1 0.010000000        0
27          <leaf>   6110   6110   1875    2 0.010000000        0
7        STAT_CD_1  65537  65537 117625    2 0.048749611        4
14          <leaf>   4724   4724   5028    1 0.000000000        0
15           DISCH  60813  60813  98195    2 0.019574990        4
30          SENDER  11248  11248  27522    1 0.014570386        4
60            PORT  10344  10344  22770    1 0.014570386        4
120         <leaf>   6878   6878  10908    1 0.005544498        0
121         <leaf>   3466   3466   7445    2 0.003743721        0
61          <leaf>    904    904    560    2 0.010000000        0
31          <leaf>  49565  49565  64890    2 0.000000000        0

For a more complete description, please see
https://henckr.github.io/distRforest/reference/rpart.object.html
But you will also need this
R: Extracting Rules from a Decision Tree


text:
Q: Erro ao executar: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ Alguém sabe como resolver esse erro? Não sei o motivo, meu projeto estava normal, mas deu queda de energia e o pc desligou direto, após isso não consigo mais executa-lo no celular, ocorre esse erro aí:

Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'.
  java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

A: [RESOLVIDO]
Consegui, fui na aba build->Clean Project
E então tentei executar dnv e funcionou
(Se alguém poder me explicar melhor oque ocorreu eu agradeço)


text:
Q: Trouble finding a way to simulate a player moving in React game I am building a simple game using react that involves a 3x3 grid of buttons. The player is represented by the middle button. The other buttons are populated by items (chests, energy, etc.) that are randomly generated from a weighted loot table function.
The player can "move" to any of the surrounding buttons by clicking on them, in which case I will need the clicked button to become the player, keep the existing loot table rolls and add new ones based on the direction the player "moved" in. I am having a really difficult time figuring this out (in terms of even where to start) and would love any input or guidance :)
import LootTable from "./LootTable";

var loot = new LootTable();
loot.add("chest", 1);
loot.add("energy", 1);
loot.add("roll", 1);
loot.add("empty", 5);

//create square
const Square = (props) => {
  return <button className="square">{props.value}</button>;
};

//create board with 9 squares
const Board = () => {
  const renderSquare = (i) => {
    return <Square value={i} />;
  };

  return (
    <>

          {renderSquare(loot.choose())}
          {renderSquare(loot.choose())}
          {renderSquare(loot.choose())}

          {renderSquare(loot.choose())}
          {renderSquare("player")}
          {renderSquare(loot.choose())}

          {renderSquare(loot.choose())}
          {renderSquare(loot.choose())}
          {renderSquare(loot.choose())}

    </>
  );
};

export default Board;

I tried creating a variable to temporarily store the results of the rolls and refresh only the "new" buttons but I could not figure out a way to accomplish both tasks. Either all of the buttons re-roll or none of them do


text:
Q: Egit does not allow me to add files to index I have been able to add two files to the index, but when I add other files to the index nothing happens. The other files don't show up in the Team > Commit dialog either.
I noticed this started happening after I accidentally exited out of Eclipse while an EGit commit was in progress of these very same files. I checked and the commit never took place.
I have tried restarting eclipse and looking for .gitignore files.
Update:
Apparently commit is stored somewhere, I just have to push it.

A: Just had to push it to upstream and it worked.


text:
Q: CURLOPT_URL codification with PREG_REPLACE value When i get the $url varible by preg_replace feedback it doesn't work but it i specify the $url value with the commented line it works. What's wrong in my code please? Many thanks.
$content = preg_replace('/(plugin_[^ ]+)/', getPlugin('$1'), $content);

function getPlugin($plugin) {
    $url = "http://".$_SERVER['HTTP_HOST']."/{$plugin}.php?language=en";
    //$url = "http://".$_SERVER['HTTP_HOST']."/plugin_contact.php?language=en";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

A: My solution
if (preg_match("/(plugin_[^ ]+)/", "$content", $match)) {
        $content = preg_replace('/(plugin_[^ ]+)/', getPlugin($match[0]), $content);
}

A: Your original code doesn't work because getPlugin() runs before preg_replace(). It is called with the literal '$1' as argument, there is nobody to replace $1 with something else because preg_replace() is not involved.
I suppose you are refactoring a call to preg_replace() that uses the deprecated e(PREG_REPLACE_EVAL) modifier:
$content = preg_replace('/(plugin_[^ ]+)/e', 'getPlugin("$1")', $content);

In order to remove the /e modifier you can use preg_replace_callback():
$content = preg_replace_callback('/(plugin_[^ ]+)/', 'getPlugin', $content);

function getPlugin(array $matches) {
    $plugin = $matches[1];
    $url = "http://".$_SERVER['HTTP_HOST']."/{$plugin}.php?language=en";
    //$url = "http://".$_SERVER['HTTP_HOST']."/plugin_contact.php?language=en";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}


text:
Q: Testing a node-cron Job function with Jest I have a javascript class that contains a function that starts a cron job using the node-cron library.
But I can't seem to find a way to test the class and the function.
The variables that control the node-cron are in a .env file.
To do the testing I'm using jest.
My job is started when the app.js of my node application is started(the class file is imported and is export instantiated)
.env file
#CRON JOB
FREQUENCY_CRON='30 00 * * *'
TIMEZONE="America/Sao_Paulo"
SCHEDULED=true
INACTIVE_EXPIRATION_TIME=2592000000 #30 DAYS

CronJob.js
class CronJob {
  constructor() {
    this.startJob();
  }

  async startJob() {
    cron.schedule(
      process.env.FREQUENCY_CRON,
      async () => {
        //DO SOME DATA PROCESSING
      },
      {
        scheduled: process.env.SCHEDULED,
        timezone: process.env.TIMEZONE
      }
    );
  }
}

export default new CronJob();

A: You could use jest.mock(moduleName, factory, options) to mock node-cron module. Use dotenv package load the environment variables from .env before running the test cases.
E.g.
cronJob.js:
import cron from 'node-cron';

class CronJob {
  constructor() {
    this.startJob();
  }

  async startJob() {
    cron.schedule(
      process.env.FREQUENCY_CRON,
      async () => {
        console.log('DO SOME DATA PROCESSING');
      },
      {
        scheduled: process.env.SCHEDULED,
        timezone: process.env.TIMEZONE,
      },
    );
  }
}

export default new CronJob();

cronJob.test.js:
import cron from 'node-cron';
import path from 'path';

require('dotenv').config({ path: path.resolve(__dirname, './.env') });

jest.mock('node-cron', () => {
  return {
    schedule: jest.fn(),
  };
});

describe('61765291', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    cron.schedule.mockImplementationOnce(async (frequency, callback) => await callback());
    require('./cronJob');
    expect(logSpy).toBeCalledWith('DO SOME DATA PROCESSING');
    expect(cron.schedule).toBeCalledWith('30 00 * * *', expect.any(Function), {
      scheduled: 'true',
      timezone: 'America/Sao_Paulo',
    });
  });
});

.env:
#CRON JOB
FREQUENCY_CRON='30 00 * * *'
TIMEZONE="America/Sao_Paulo"
SCHEDULED=true
INACTIVE_EXPIRATION_TIME=2592000000 #30 DAYS

unit test results with 100% coverage:
 PASS  stackoverflow/61765291/cronJob.test.js (8.148s)
  61765291
    ✓ should pass (30ms)

  console.log
    DO SOME DATA PROCESSING

      at CustomConsole.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |
 cronJob.js |     100 |      100 |     100 |     100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.145s, estimated 10s


text:
Q: My Ubuntu 20.04.1 LTS PC restarts randomly My operating system restarts by itself randomly, sometimes it reboots few minutes after boot, it happens 2-3 times and after that it's ok for a month, and I can't find anything suspicious in /var/log/dmesg A guy who was checking my hardware (doing stress tests for 12 hours, but on windows, I didn't give him my SSD with the system) didn't find any hardware issue.
Maybe you can find something and point me, or give me some idea where to look
Here is my /var/log/dmesg file: https://gist.github.com/pmartini/e849b65ffd6ce8ad5c14deed1b2b602a
and journalctl output: https://gist.github.com/pmartini/1e843d0f1de982f53daeaf617fa7767b
lsblk output:
    NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
loop0    7:0    0  96,6M  1 loop /snap/core/9804
loop1    7:1    0  29,9M  1 loop /snap/snapd/8790
loop2    7:2    0  55,3M  1 loop /snap/core18/1885
loop3    7:3    0  14,9M  1 loop /snap/ubuntu-mate-welcome/524
loop4    7:4    0    16K  1 loop /snap/software-boutique/54
loop5    7:5    0  97,1M  1 loop /snap/core/9993
loop6    7:6    0  14,9M  1 loop /snap/ubuntu-mate-welcome/539
loop7    7:7    0    55M  1 loop /snap/core18/1880
loop8    7:8    0 197,5M  1 loop /snap/viber-unofficial/37
loop9    7:9    0  30,3M  1 loop /snap/snapd/9279
sda      8:0    0 111,8G  0 disk
├─sda1   8:1    0 107,1G  0 part /
├─sda2   8:2    0     1K  0 part
└─sda5   8:5    0   4,7G  0 part [SWAP]
sr0     11:0    1  1024M  0 rom

fdisl -l output: https://gist.github.com/pmartini/acceb0fac6c20631b4eb8c1044b724e9
grep sda5 /etc/fstab outut:
# swap was on /dev/sda5 during installation
grep sda5 /proc/mounts doesn't show any output

A: It looks like I found the source of the problem, I ran memtest86 before logging into Unbuntu, and it was stopping at 40% each time I ran it. I played with RAM sticks ( I have three) for a while and found that one of them is broken (when I keep only this stick inserted the system didn't load at all and pc speaker was beeping). I bought 2 RAM sticks from a list recommended by a motherboard manufacturer and everything seems ok now.

A: For the next person with this problem...
I recently built a new Ubuntu 20.04.2 system, using AMD Ryzen 3700x with an NVidia GP108 graphics card, and it has had a similar behavior -- mostly works fine, but occasionally spontaneously reboots with nothing much in the system logs.  It doesn't seem related to what I'm doing at the time - sometimes reboots when I'm just typing email, other times when the computer is sitting idle waiting for the timer to trigger suspend.   Not a heat issue either, running below 30C with several fans installed.
I suspected a hardware issue.  The system is a Ryzen 3700x, with 16GB of DDR3200 memory.  As part of building, I had set the BIOS to use DDR3200.  Today, I changed that BIOS setting back to Auto, letting the MB decide what memory setting to use.  System has been stable for many hours now, when before I would have expected at least a few spontaneous reboots.
So, suggestion -- try changing your memory settings; the system might be a few percent slower, but that's better than rebooting at random.

A: It seems there is a problem with sdb5 partition.
Here are the relevant log entries:
вер 28 18:43:03 pc systemd[1]: dev-sdb5.device: Job dev-sdb5.device/start timed out.
вер 28 18:43:03 pc systemd[1]: Timed out waiting for device /dev/sdb5.
вер 28 18:43:03 pc systemd[1]: Dependency failed for File System Check on /dev/sdb5.
вер 28 18:43:03 pc systemd[1]: Dependency failed for /mnt/files.
вер 28 18:43:03 pc systemd[1]: Dependency failed for Local File Systems.
вер 28 18:43:03 pc systemd[1]: local-fs.target: Job local-fs.target/start failed with result 'dependency'.
вер 28 18:43:03 pc systemd[1]: mnt-files.mount: Job mnt-files.mount/start failed with result 'dependency'.
вер 28 18:43:03 pc systemd[1]: systemd-fsck@dev-sdb5.service: Job systemd-fsck@dev-sdb5.service/start failed with result 'dependency'.
вер 28 18:43:03 pc systemd[1]: dev-sdb5.device: Job dev-sdb5.device/start failed with result 'timeout'.

I think you have a 2nd disk /dev/sdb, which is not present all the time and that it is "required" to boot. It could be an USB stick.


text:
Q: Iterating over CActiveDataProvider to get value from different model I'm currently learning Yii. I'm trying to iterate over CActiveDataProvider results and get the value of one index from every result and use that to pull data from another model. I'm not sure exactly if I'm going about it correctly.
public function actionIndex()
{
    // This next line works and return data, but I want it to index with each record in $dataProvder
    // $name = Artist::model()->findByPk(1);
    $name = Artist::model();
    $dataProvider=new CActiveDataProvider('Album');
    foreach($dataProvider->getData() as $record){
        $name->findByPk($record->artist_Id);
        $this->name[] = $name->firstName . " " . $name->lastName;
    }
    $this->render('index',array(
        'dataProvider'=>$dataProvider,
        'name' =>$this->name,
    ));
}

What is causing my results to be blank when I use dataProvider for index?

A: You should be using Active Record relations for a situation like this.  Data providers can take into account relations and join data automagically.  This is a vital concept to learn in order to effectively use Active Record in Yii, so I suggest reading and practicing examples.  Here's a link to the official guide:
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
For your specific case, the relations would look something like this:
Album Class relations function:
class Album extends CActiveRecord{
    //beginning of model
    public function relations(){
        return array(
            'artist' => array(self::BELONGS_TO, 'Artist', 'artist_Id'),
        );
    }
    //rest of model
}

Artist Class relations function:
class Artist extends CActiveRecord{
    //beginning of model
    public function relations(){
        return array(
            'albums' => array(self::HAS_MANY, 'Album', 'artist_Id'),
        );
    }
    //rest of model
}

Controller Action:
public function actionIndex()
{
    $names = array();
    $dataProvider=new CActiveDataProvider('Album', array(
        'criteria' => array(
            'with' => 'artist',
        )
    ));
    foreach($dataProvider->getData() as $record){
        $names[] = $record->artist->firstName . " " . $record->artist->lastName;
    }
    $this->render('index',array(
        'dataProvider'=>$dataProvider,
        'name' => $names,
    ));
}

By passing a criteria to the Albums data provider telling it to join "with" the artists, all artists and albums will be fetched in 1 SQL query.  You can access the Artist information from the data provider, for example, in a Grid View in your view file:
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        'name',                  // album name
        'artist.firstName',      // display the first name of the artist
        array(                   // display the full name of the artist
            'name'=>'fullName',
            'value'=>'$data->artist->firstName." ".$data->artist->lastName',
        ),
    ),
));


text:
Q: Laravel controller with included files issue In order to consolidate some bulky code in a controller I have been able to do this inside function
public function myCustomFunction(Request $request){
 include(app_path() . '/myFunctions/myCustomFunction1.php');
}

It does successfully work but by doing the include, I noticed it doesnt carry the namespace and/or other variables set in the controller.
If its just a simple model it needs I was able to add
Use \App\myModel;

to the top of the controller and it runs the code just fine as if its part of the controller.
What I am having issue with is when I want to run validation.  I cant figure out what to "use" to work on the included page.
If I run my logic in the controller without doing include it works, but if put inside the include it does not, and I get NO errors either.
I tried this inside the include page to activate the validation from within
the include file
namespace App\Http\Controllers;
use Validator;
use Request;

which mimics the original controller, but still does not work.  Is what I'm trying to do possible but I'm doing something wrong? Or am I doing something that will never work?  If all else fails I can keep the code within the actual controller to make it work, but I'm trying to accomplish some sort of clarity on complex controllers.  Such as...
public function myCustomFunction(Request $request){
    if(request('value1')=='1'){
      include(app_path() . '/myFunctions/myCustomFunction1.php');
    }else{
      include(app_path() . '/myFunctions/myCustomFunction2.php');
    }
}

This structure is already working on anything that doesn't need validation so I'm hoping there is a simple way to hook the include page into the same set of validation tools the original controller has access to.

A: In the controller, so include the files incorrectly. It's best for you to create a Helpers folder in the app folder, in it create classes with your functions.
namespace App\Helpers;

class HelpersOne {
  public function myFunctionOne(){.../*youre code*/}
  public function myFunctionTwo(){.../*youre code*/}
}

And already in your controller you can call these classes.
use App\Helpers\HelpersOne;
...
public function myCustomFunction(Request $request){
    if(request('value1')=='1'){
      $myFunction = new HelpersOne();
      $myFunction->myFunctionOne();
    }else{
      $myFunction = new HelpersTwo();
      $myFunction->myFunctionTwo();
    }
}


text:
Q: Map viewmodel to model created with TPH pattern I have one base class and 3 sub classes and single viemodel with all properties. I want in my controller create action to bind this viewmodel to concrete sub type.
Here is my create action which doesn't work (I'm getting Error mapping types):
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(AdViewModel vm)
{
    if (ModelState.IsValid)
    {
         var ad = Mapper.Map<Ad>(vm);
        _context.Ads.Add(ad);
        _context.SaveChanges();
         return RedirectToAction("Index");
    }
    return View();
}

This is automapper configuration:
Mapper.Initialize(config =>
        {
            config.CreateMap<AdViewModel, Ad>().ReverseMap();
            config.CreateMap<AdViewModel, Realty>().ReverseMap();
            config.CreateMap<AdViewModel, Auto>().ReverseMap();
            config.CreateMap<AdViewModel, Service>().ReverseMap();
        });

And this is working code, but I doubt to use it:
public IActionResult Create(AdViewModel vm)
{
    if (ModelState.IsValid)
    {
        if (vm.RealtyType != null)
        {
            var ad = Mapper.Map<Realty>(vm);
            _context.Add(ad);
        }
        else if (vm.AutoType != null)
        {
            var ad = Mapper.Map<Auto>(vm);
            _context.Add(ad);
        }
        else
        {
            var ad = Mapper.Map<Service>(vm);
            _context.Add(ad);
        }
        _context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View();
}

A: You have to put the logic to create the correct subclass somewhere. If you want to hide it in the Automapper config, you can achieve this by defining a constructor function. This will only work if the target entities are related (I will assume that Ad is the baseclass of Realty, Auto and Service).
// construct correct subtype of entity, depending on ViewModel state
var ctorFunc = new Func<AdViewModel, Ad>(vm => {
    if (vm.RealtyType != null) {
        return new Realty();
    }
    // etc.
});

// create correct subclass, map common properties of base class,
// then dispatch to map properties of child class
CreateMap<AdViewModel, Ad>()
    // construct correct subclass of target entity
    .ConstructUsing(ctorFunc)
    // map common members to base class
    .ForMember(ent => ent.CommonField, o => o.MapForm(vm => vm.CommonField)
    // dispatch to mapping of child class
    // NOTE: this assumes that this profile was used to configure the static AutoMapper
    .AfterMap((vm, ent) => Mapper.Map(vm, ent, vm.GetType(), ent.GetType()));

// define rules for special members of child classes
CreateMap<AdViewModel, Realty>().ReverseMap();
// etc.

Then you should be able to call var ad = Mapper.Map<Ad>(vm); successfully.


text:
Q: How to telnet into facebook chat I was able to use facebook chat with an external application using the following information:

First, find your Facebook username by
  going to
  http://www.facebook.com/your_user/.
  Next, Open iChat, then select iChat »
  Preferences and click on the Accounts
  tab.
Click on the + (plus) sign to add a
  new account, with these settings:
* Account Type is Jabber Account
* Account name is your_user@chat.facebook.com, and enter

your password
      * Click the drop-down arrow to reveal Server options. Enter
  chat.facebook.com as the server name.
      * Enter 5222 as the port and click Done.
Click Done again, and you are good to
  go.

From reading this, it seems that it might be possible to telnet into facebook chat. I tried, but wasn't able to. Is it possible? How?

A: There is no practical way to do this using a telnet client, as you would have to type all of the XML yourself, which is incredibly impractical. There are however several command-line XMPP clients available, as discussed in this stack overflow question.

List of Jabber Console Clients

*

*centericq

*Fama IM

*GNU Freetalk

*mcabber

If you are interested in learning about the XMPP protocol, I suggest you install Pidgin and take a look at the XMPP console by right-clicking on the Pidgin notification icon and choosing XMPP Console from the menu. All of the XMPP messages sent to and from your client will be shown, including every typing notification, status update, etc. It's very interesting to look at, and you can even try your hand at sending custom XMPP status codes from the console.

A: From (very) limited testing, it seems possible.

Run telnet chat.facebook.com 5222 to connect, then proceed sending valid XML conforming to the Jabber protocol specification.
$ telnet chat.facebook.com 5222
Trying 69.63.181.105...
Connected to chat.facebook.com.
Escape character is '^]'.
<?xml version="1.0">
<stream>
// here I was looking up auth
Connection closed by foreign host.

Be aware that the server closes your connection within about a minute of inactivity, so looking up the protocol ad-hoc isn't practical. Or anything related to raw Jabber, as typing XML flawlessly isn't that easy, and once you send malformed XML, the connection closes immediately.
$ telnet chat.facebook.com 5222
Trying 69.63.181.105...
Connected to chat.facebook.com.
Escape character is '^]'.
<stream>
<?xml version="1.0"?><stream:stream id="5D13A2D5" from="chat.facebook.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" xml:lang="en"><stream:error><invalid-namespace xmlns="urn:ietf:params:xml:ns:xmpp-streams"/></stream:error></stream:stream>Connection closed by foreign host

If you want to suffer while chatting, a command-line client might be a better option. Alternatively, create a minimal client yourself, if it's about the protocol, so you don't have to type the XML under pressure -- and you don't suffer from the Telnet differences.

A: Using telnet probably won't work as well as you'd like it to -- you probably mean a "raw socket connection."  If you know the Jabber protocol really really well, you can do it with PuTTY:

*

*putty -raw chat.facebook.com 5222

The best thing to do is to just get a Jabber client and connect to the hostname chat.facebook.com with it.


text:
Q: 450mA in CK1050 rotary switch So i bought CK1050 rotary switch i now i realized that it's rated only for 150mA 250V AC/DC on the data sheet. I need to use it with 12V DC at 450mA so will it be safe? If you think the watts it should be safe 250V*0.15A=37.5W and 12V*0.45A=5.4W

A: You completely misunderstand the ratings. Power, as you calculate it, is irrelevant. All that matters is the current. You seem to want to switch 450 mA with a switch rated for 150 mA. So, no, you can't do it - or at least you can't do it too many times before it fails.
The only possible workaround is to turn off your power supply when switching. In this case, the load current will be zero when switching, and when the power supply comes back on, the non-switching limit (5 amps) will permit operation.


text:
Q: mysql exclusive relation possibility Does mysql support exclusive relations?
E.g., I have 3 tables: CUSTOMER, FLAT, HOUSE. CUSTOMER is related to FLAR xor HOUSE.
If there possibility in mysql to use one relation for it?
Like, CUSTOMER would have 2 fields, one is related to object (FLAT or HOUSE), one is stored id.
I'd like to check on db level that this relation is not null. Don't want to create to foreign key to every table (FLAT and HOUSE).
Thanks.
added later:
sorry for not correct explanation. I don't want to create two different columns for each foreign key (to FLAT, to HOUSE). I suggest that there's something like exclusive relation and I create one column for id which can be foreign key to one of tables FLAT or HOUSE

A: create table flat (
    id int auto_increment,
    primary key (id)
);
create table house (
    id int auto_increment,
    primary key (id)
);
create table customer (
    id int auto_increment,
    flat_id int,
    house_id int,
    primary key (id),
    index flat_id (flat_id),
    index house_id (house_id),
    foreign key (flat_id) references flat(id) on delete cascade,
    foreign key (house_id) references house(id) on delete cascade
);

A: I think that it'd be better to use base parent table for my problem .
Thanks for George Cummins comment.
I can create DWELLING table with only id field.
CREATE TABLE DWELLING (
    ID INT NOT NULL AUTO_INCREMENT
  , PRIMARY KEY (ID)
);

And add FK to CUSTOMER, FLAT, HOUSE tables.
CREATE TABLE FLAT (
    ID INT NOT NULL AUTO_INCREMENT
  , DWELLING_ID INT NOT NULL
  , PRIMARY KEY (ID)
  , CONSTRAINT FK_DWELLING_FLAT FOREIGN KEY (DWELLING_ID) REFERENCES DWELLING (ID) ON DELETE cascade
);
CREATE TABLE HOUSE (
    ID INT NOT NULL AUTO_INCREMENT
  , DWELLING_ID INT NOT NULL
  , PRIMARY KEY (ID)
  , CONSTRAINT FK_DWELLING_HOUSE FOREIGN KEY (DWELLING_ID) REFERENCES DWELLING (ID) ON DELETE cascade
);
CREATE TABLE CUSTOMER (
    ID INT NOT NULL AUTO_INCREMENT
  , DWELLING_ID INT NOT NULL
  , PRIMARY KEY (ID)
  , CONSTRAINT FK_DWELLING_CUSTOMER FOREIGN KEY (DWELLING_ID) REFERENCES DWELLING (ID) ON DELETE cascade
);

After that if the flat or house need to be deleted, I have to delete relating DWELLING object.
I used this http://www.slideshare.net/billkarwin/practical-object-oriented-models-in-sql, slide 29
If you're not agree with me please add a comment. I'd be glad to see your comments.
Thanks.


text:
Q: Xcode Swift Autocomplete Failure <> When declaring an outlet, the AutoCompleter outputs "error type". The outlet also loses properties.
Deleting derived data and some files in Xcode project's packet did not help.
Example:

A: To avoid this issue you should to update the project's cash which Xcode generates for every project. To do that, go to

/Users/UserName/Library/Developer/Xcode/DerivedData

directory and remove

ModuleCache

directory from there.
After you do that, quit from Xcode and open your project again.
Xcode will rebuild project index and error should be out.

A: You should also ensure that the class you are having an issue autocompleting is listed in the "Compile Sources" build phase for your target. I've had several occasions where source files mysteriously disappear - with the same result you are seeing.

A: An Xcode restart fixed this problem for me.
I had a very similar problem. When I used dot.notation to drill into a Class Instance I created, the autofill did not recognize the types for each property. The class property in question was explicitly defined as a String? [Optional] Type.
I expected the autofill to show that:
myInstance.name is of type "String?"

but the autofill said that:
myInstance.name is of type "error".  This appeared:  "<< error type >>"

A restart of Xcode, to my surprise, fixed the problem.
Maybe, the restart effectively did the "resetting" techniques others posted here.  Looks like a performance or refresh issue on Xcode's part.  Things running smoothly now.

A: Note: If you can reference your class fine in other places the file where you call the "error" class is the issue, not the "error" class itself. The only thing that works for me is deleting (removing reference) the file that references the "error" class and adding the file back to the project.


text:
Q: SQL Server express service is not starting I've bought my first VPS yesterday, and I have installed Microsoft SQL Server 2012 Express on it.
Then I have restarted my VPS. But SQL Server Service didn't start. I've tried to start it manually, but It can't start:

What is the problem? How to solve it?
P.S: This is my first server management, and I'm a newbie, if you need any further details about this, please leave a comment. I'll update the question.
Update 1: This is some log details from Event viewer that I thought that they may be useful for this problem:

FCB::Open failed: Could not open file
  e:\sql11_main_t.obj.x86release\sql\mkmastr\databases\objfre\i386\MSDBData.mdf
  for file number 1.  OS error: 3(The system cannot find the path
  specified.).
The resource database build version is 11.00.3000. This is an
  informational message only. No user action is required.
FileMgr::StartLogFiles: Operating system error 2(The system cannot
  find the file specified.) occurred while creating or opening file
  'e:\sql11_main_t.obj.x86release\sql\mkmastr\databases\objfre\i386\MSDBLog.ldf'. Diagnose and correct the operating system error, and retry the
  operation.
Starting up database 'model'.
FCB::Open failed: Could not open file
  e:\sql11_main_t.obj.x86release\sql\mkmastr\databases\objfre\i386\model.mdf
  for file number 1.  OS error: 3(The system cannot find the path
  specified.).
FileMgr::StartLogFiles: Operating system error 2(The system cannot
  find the file specified.) occurred while creating or opening file
  'e:\sql11_main_t.obj.x86release\sql\mkmastr\databases\objfre\i386\modellog.ldf'.
  Diagnose and correct the operating system error, and retry the
  operation.

I'm confused about these e:\s, my VPS has just one C:\ drive, So what is e:\ ?

A: There a few topics on it, but someone posted a good workaround here
NET START MSSQL$SQLEXPRESS /f /T3608

SQLCMD -S .\SQLEXPRESS

1>SELECT name, physical_name, state_desc FROM sys.master_files ORDER BY database_id;

Now notice those wrong file names; and run following commands ...

Note: you need to change the file name location ..

1>ALTER DATABASE model MODIFY FILE ( NAME = modeldev, FILENAME = 'c:\model.mdf');
2>ALTER DATABASE model MODIFY FILE ( NAME = modellog, FILENAME = 'c:\modellog.ldf');
3> go

ALTER DATABASE msdb MODIFY FILE ( NAME = MSDBData, FILENAME = 'c:\MSDBData.mdf');
ALTER DATABASE msdb MODIFY FILE ( NAME = MSDBLog, FILENAME = 'c:\MSDBLog.ldf');

ALTER DATABASE tempdb MODIFY FILE ( NAME = tempdev, FILENAME = 'c:\temp.mdf');
ALTER DATABASE tempdb MODIFY FILE ( NAME = templog, FILENAME = 'c:\temp.ldf');

go

exit;

NET STOP MSSQL$SQLEXPRESS


text:
Q: Smallest Square Function Consider a positive integer n. What will be the smallest number k such that if we concatenate the digits of n with those of k we get a perfect square?
For example, for n=1 the smallest k is 6 since 16 is a perfect square.
For n=4, k has to be 9 because 49 is a perfect square.
For n=35, k is 344, since 35344=1882 is the smallest perfect square starting with the digits 35.
Define the smallestSquare function that takes a positive integer n and returns the smallest integer k whose concatenation of the digits of n,k results in a perfect square.
For now all I have is this, which checks wether the given number is a perfect square or not.
I would like to solve this using recursion but I'm not even sure where to start.
from math import sqrt

def isSquare(n):
  return n == int(sqrt(n) + 0.5) ** 2

def smallestSquare(n):

A: No recursion is necessary:
def smallestSquare(n):
    x = 1
    while isSquare(int(str(n)+str(x))) == False:
        x += 1
    return int(str(n)+str(x))

A: If, given some number 'n', you are looking for the smallest perfect suqare that begins with 'n', the following is an approach that should work:
import math

def find_smallest_perfect_square(start: int) -> int:
    while True:
        if int(math.sqrt(start)) != math.sqrt(start):
            start += 1
        else:
            return start

def find_concatenation(n: int) -> int:
    str_n = str(n)
    while True:
        val = find_smallest_perfect_square(n)
        if str(val).startswith(str_n):
            return val
        else:
            n = val + 1

Testing:
for i in range(10):
    print (f'The smallest perfect square that begins with {i} is {find_concatenation(i)}')

# Result:
    # The smallest perfect square that begins with 0 is 0
    # The smallest perfect square that begins with 1 is 1
    # The smallest perfect square that begins with 2 is 25
    # The smallest perfect square that begins with 3 is 36
    # The smallest perfect square that begins with 4 is 4
    # The smallest perfect square that begins with 5 is 529
    # The smallest perfect square that begins with 6 is 64
    # The smallest perfect square that begins with 7 is 729
    # The smallest perfect square that begins with 8 is 81
    # The smallest perfect square that begins with 9 is 9

If what you're looking for is "the smallest value of k" which, when concatenated with n, yields a perfect square - the above approach is not guaranteed to give you what you want. If that's what you require, please specify.


text:
Q: Closed expressions for divergent series over Bernoulli numbers? Motivation
In a recent post (Asymptotic behaviour of sums involving $k$, $\log(k)$ and $H_{k}$) I asked for the asymptotic behaviour of the sum
$$\sigma_{c}(n)=\sum_{k=1}^n H_{k} \log(k)\tag{1}$$
and I found that the constant in the asymptotic expression contained, among other known constants, the sum
$$\kappa_{c} = \sum_{m=1}^\infty \frac{B(2m)}{2m} \zeta'(2m)\\=\frac{1}{12} \zeta '(2)-\frac{\zeta '(4)}{120}+\frac{\zeta '(6)}{252}-+...\tag{2}$$
where $B(n)$ is the Bernoulli number of order $n$ and $\zeta'()$ is the derivative of the Riemann zeta function. This is a strongly divergent series, and I had to resort to the limit
$$\lim_{n\to\infty} (\sigma_{c}(n) - (\text{leading terms}))\tag{3}$$
for calculating the complete constant, a sum of known constants and $\kappa_{c}$, which, however, I could only use numerically.
Quite recently, however, in an answer to Constant term in Stirling type formula for $\sum^N_{n=1} H_n \cdot \ln(n)$, a consistent interpretation of the sum in (2) was given in terms of a convergent integral and the numerical value calculated.
Questions
This motivated me to ask for the values of similar divergent series, and for a proof of the interpretation of the following two examples:
$$\kappa_{d} :=\sum_{m=1}^\infty B(2m)\dot{=} \frac{\pi^2}{6}-\frac{3}{2}\simeq 0.144934$$
and
$$\kappa_{e} :=\sum_{m=1}^\infty \frac{B(2m)}{2m}\dot{=}\gamma -\frac{1}{2}\simeq 0.0772157 $$
Here $\gamma$ is the Euler-Mascheroni constant and $\dot{=}$ means "is understood as" in the Ramanujan sense that $1+2+3+... \dot{=} -\frac{1}{12}$

A: In both, use the following formula, available as Gradshteyn&Rhyzik 3.411.2
$$\frac{B_{2n}}{2n} = (-1)^{n+1}\,2 \int_0^\infty \frac{x^{2n-1}}{e^{2\pi\,x}-1}\,dx $$
Then a convergent integral for the second sum is derived by
$$ \sum_{n=1}^\infty \frac{B_{2n}}{2n} \,\dot{=}
2 \int_0^\infty \frac{dx/x}{e^{2\pi\,x}-1}\,\sum_{n=1}^\infty (-1)^{n+1}x^{2n}
=2 \int_0^\infty \frac{dx\,x}{(x^2+1)(e^{2\pi\,x}-1)}.$$
Mathematica knows this integral, although G&R 3.415.1 can also be used:
$$ (A) \quad \int_0^\infty \frac{dx\,x}{(x^2+b^2)(e^{2\pi\,x}-1)} =
\frac{1}{2}\big( \log{b} - \psi(b) - \frac{1}{2b} \big) $$
For $b=1$ we therefore have
$$ \sum_{n=1}^\infty \frac{B_{2n}}{2n} \,\dot{=} \,\gamma - \frac{1}{2} .$$
The other sum is similar,
$$ \sum_{n=1}^\infty B_{2n} \,\dot{=}
4 \int_0^\infty \frac{dx/x}{e^{2\pi\,x}-1}\,\sum_{n=1}^\infty (-1)^{n+1}n\,x^{2n}
=4 \int_0^\infty \frac{dx\,x}{(x^2+1)^2(e^{2\pi\,x}-1)}.$$
Differentiate eq. $(A)$ and set $b=1$ to find
$$ \sum_{n=1}^\infty B_{2n}\,\dot{=} \,\frac{\pi^2}{6} - \frac{3}{2} .$$


text:
Q: How to make redirect to some specific language from next.config.js by using cookies Below you can see my next.config.js :
module.exports = {
  trailingSlash: true,
  async redirects() {
    return [
      {
        source: '/',
        destination: '/en',
        permanent: false
      }
    ]
  }
}

As you can see from / I want to direct user to specific language . When user first time came on site , it is ok to redirect on /en/language , but when he will change language on the site I should remember it and second time redirect user to language he choosed , I first what came to my mind save it too cookies , and then get it from there , but I haven't found any solution for next js config I can use. Is it possible to make it from next.config.js or maybe there some another way to make it better ?

A: Next.js has automatic locale detection when you land on the root of the site. So the user will be redirected to his locale if the application supports it, or it will be served the default locale.
Next.js also honors the NEXT_LOCALE cookie, so if that cookie is present in the user's browser, it will be used to redirect the user to the locale of the cookie for example, NEXT_LOCALE=fr will always redirect the user to the fr locale regardless of the user's true browser locale.
If your application has a way for the user to choose his locale when it does, just set the cookie with the chosen locale, and you are good to go.


text:
Q: How can i change the negative numbers to 0 from my webpage I'm trying to convert or disable the negative numbers to 0 on my
Website which appear when i select some products on the column 'Unidad Minima'    and 'Unidad Maxima'for example 10 or more for each one.
I've tried by using the format number jquery plugin  but it didn't work in this case.
There is some code from my webpage.
$("tr.txtMult").each(function () {
    var $val3 = $('.val3', this).val();
    cantidadesminimas = (8260 - cantidadfinal) / $val3;
    cantidadesmaximas = (12390 - cantidadfinal) / $val3;

    $('.val5', this).html(cantidadesminimas.toFixed(0));
    $('.val6', this).html(cantidadesmaximas.toFixed(0));
});

$("#cantidadmin").html(8260 - cantidadfinal.toFixed(0));
$("#cantidadmax").html(12390 - cantidadfinal.toFixed(0));

}
Some comment will be apreciated.
Thanks!

A: You could use the short if else like this:
$('.val5', this).html((cantidadesminimas < 0 ? 0 : cantidadesminimas));

A: You could use the built in Math.max(x, 0) method. The result will be which ever is highest, your input or zero.
e.g.
var x = -1;
var a = Math.max(x, 0);

If 'x' is negative 'a' will be zero else 'a' will be equal to 'x'.


text:
Q: Dynamically loaded Theme components based on Customizer Settings values : changes not appearing in Customizer preview - (Workaround found) I'm trying to create a WP theme (for personal learning purposes, still pretty new to wp) where Header/Container/Footer are each chosen based on a dedicated customizer setting (still plain text, possible choices will be based on a pre-defined list probably).
The idea:
A Theme singleton(i know... that's not an happy choice) handles class instances which will be created in the "after_theme_setup" hook.
After this, each instance will have the right to hook depending on its needs (for example , to register customizer sections/controls etc...)
class VTheme extends VRSharedContextSingleton{
    protected $mHeader = null;
    protected $mContainer = null;
    protected $mFooter = null;

    protected function __construct(){
        add_action( 'after_setup_theme' , function(){
            spl_autoload_register(function ($class) {
                $fn = '/classes/' . $class . '.class.php';
                if(file_exists(get_stylesheet_directory().$fn)){
                    include get_stylesheet_directory().$fn;
                }else if(file_exists(get_template_directory().$fn)){
                    include get_template_directory().$fn;
                }
            });

            $hc=caw_get_theme_mod('vs_header_class','vrm_HeaderA');
            $cc=caw_get_theme_mod('vs_container_class','vrm_ContainerA');
            $fc=caw_get_theme_mod('vs_footer_class','vrm_FooterA');

            if(class_exists($hc)) $this->LinkHeader(new $hc());
            if(class_exists($cc)) $this->LinkContainer(new $cc());
            if(class_exists($fc)) $this->LinkFooter(new $fc());

        });

         add_action( 'customize_register', function($wp_customize){
             require get_template_directory().'/auxiliary/wp-core-customizer.part.php';
         });
    }

    public function &LinkHeader(VRModule $module){
        if($module) {$this->mHeader = $module->LinkTo($this);}
        return $this;
    }
...

abstract class VRModule{
    protected $mParent = null;
    protected $mStreams = array();

    public final function &LinkTo(VRSharedContext &$parent){
        $this->mParent = $parent;
        $this->OnLink();
        return $this;
    }
    ...

 class vrm_HeaderA extends VRModule{
        protected function OnLink(){
            add_action( 'customize_register', function($wp_customize){
                $wp_customize->add_setting( 'vscst_header_fontcolor_setting',
                array(
                   'default' => '',
                   'validate_callback' => '',
                   'sanitize_callback' => '',
                   'sanitize_js_callback' => '',
                ));
                $wp_customize->add_control( 'vscst_header_fontcolor_control',
                array(
                   'settings'=>'vscst_header_fontcolor_setting',
                   'label' => __( 'Font color' ),
                   'description' => esc_html__( 'Font color' ),
                   'section' => 'vscst_header_settings_section',
                   'type' => 'text',
                ));
            });
        }
...

The main issue i'm stuck against is that module changes ( for example , changing Header class name in the customizer) , do not reflect in Customizer preview iFrame...(at least not until i fully refresh the page from browser after saving)
I supspect that might be because of hooks order (p.s: using "QueryMonitor" plugin to check behaviour) ..or maybe "get_theme_mod" acting differently while customizing?
P.s: trying to hook on "customizer_preview_init" and using the conditional "is_customize_preview()" made the changes reflect in Customizer iFrame, but i think that is a bit hacky and restricts what can be done in the hooked function ("customizer_preview_init" is way further "after_setup_theme")
Other issues i'm having (dynamically registered, by an Header for example, customizer's panels/controls etc , not appearing before save and refresh), i think are both related to the first issue , and might involve some js/ajax as a workaround as well...
Any idea about this?
Is it reasonable to try to achieve this kind of "modular" behaviour with this approach in WP?
Thanks in advance !
Update:
Digging into wp-customize-manager.php and Customizer API docs, i think i found a relatively elegant workaround:
Creating an auxiliary function "caw_get_theme_mod" (standing for "customize aware"..) with this definition:
function caw_get_theme_mod( $name, $default = false){
    if(is_customize_preview()){
        global $wp_customize;
        $s = new WP_Customize_Setting($wp_customize,$name);
        $v = $s->post_value();
        if($v!==null) return $v;
    }
    return get_theme_mod($name,$default);
}

And using in the theme in place of get_theme_mod, customizer is now able to successfully show the preview with the temporarly updated fields and newly registered elements also show as expected in the customizer UI without the need of a full/hard page refresh.
That works because "post_value()" returns the value , sanitized as far as i could read, taken from the request sent to server (that's why i have to test against the default "null" , since there is no request sent on the first customizer load, in this case i fallback to the default get_theme_mod)
I leave link references to documentation, they might be usefull for anyone interested:
https://developer.wordpress.org/reference/classes/wp_customize_setting/


text:
Q: Ajax Control Toolkit in .NET I need some help on ajax control toolkit in asp.net Visual Studio 2010 .net frame work
version 4.
We have hosted on interland server and it does not support ajax control toolkit .DLL as it is a third party dll.
Could anybody give us an workaround on this, can we download the source code for this toolkit which is in javascript  and can we include this .js files in our aspx pages so we can have ajax control toolkit for our website.
Any examples would be helpful if we can try this workaround working.
thanks

A: Just copy the DLL to your Bin folder.

A: If you're deploying an ASP.net app, and your project has a reference to the relevant assembly, the dll should be copied to your .\bin folder as part of the publish process, just like the compiled assemblies that comprise your app.


text:
Q: text editing & saving in IOS app I have a UITextview showing certain text by calling rtf files.
I want to let users to edit the text on UITextView and save the changes they made in rtf file.
Is there any way I can change the rtf file itself by changing the text on UITextView??

A: If you want a save-as-you-type solution to the problem:

*

*Make your view controller conform to UITextViewDelegate

*Connect the text view's delegate to the view controller

*Add the following function to your view controller:

// Path to your RTF file
let url = NSBundle.mainBundle().URLForResource("my_document", withExtension: "rtf")!

func textViewDidChange(textView: UITextView) {
    let data = try! textView.attributedText.dataFromRange(NSMakeRange(0, textView.attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
    data.writeToURL(url, atomically: true)
}

This will save every keystroke to the file. No idea on the performance though. I have not tested this on a real iPhone. If it's too hard on the device, consider putting a time delay between saves or have an NSTimer to save every n seconds.


text:
Q: Reduxjs or simply state I have often heard questions that ' Why one should use redux whether there is also a State in the ReactJs. Which extra facilities redux does provide to the developer ? '

A: For small applications when there aren't a lot of components, you can do without redux. But in large applications, it becomes pretty complicated/tedious to chain props through components especially if one that is deep 6 levels needs it.
This is a great article that explains it
https://blog.logrocket.com/why-use-redux-reasons-with-clear-examples-d21bffd5835

A: The Redux docs page about organizing state (here), list out a few reasons one might lean to using Redux store over component state. However, they do clearly state that "using local component state is fine" and that, in the end, the developer should find the proper balance for the work at hand.

Some common rules of thumb for determining what kind of data should be put into Redux:

*

*Do other parts of the application care about this data?

*Do you need to be able to create further derived data based on this original data?

*Is the same data being used to drive multiple components?

*Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?

*Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?

A: Redux is required when your application is big with many components. Redux works as global meaning if you set value in one component you can get that value across components. This is the primary advantage with state management Library.
If your application is small with 10 to 20 components then we don't need redux. We can pass down state to child components as props but when application grows big you will have so many components and it's very difficult to play with component level state and you won't have control of the flow and you can't track of values between components
So redux is very useful in such cases.