Q: Multi undefined variables from a form and subsequent sql statement The outcome I seek is to loop through items taken from a form that isset or true and then have a sql statement query the database. The complication comes from I have 9 fields that the user could choose one or more or all fields (It is a search database but every time you choose an extra field it refines the search). The part of the code to return true I can get my head around by using a foreach loop but how would you link it to SQL query if the outcome is varied?

A: You generate a different query depending on which fields are entered.
Luckily this isn't too hard in SQL: all those fields are in the WHERE clause:
$where = [ 'foo' => 'bar', 'baz' => 0 ];
$sth = $db->prepare( "SELECT * FROM $table WHERE " .
    implode( " AND ",
        array_map( function($i) { return "$i=?"; }, array_keys( $where ) ) )
    );
$sth->execute( array_values( $where ) );

Of course, if there are relationships between the fields, the query may become more complicated, but this is the gist of it.

A: Learning this takes time and patience I have cut past the variables from the form
    if(isset($_POST['Search'])){
    $packID = $_POST['packID'];
    $supplier_name = $_POST['supplier_name'];
    $timber_species = $_POST['timber_species'];
    $timber_product = $_POST['timber_product'];
    $timber_grade = $_POST['timber_grade'];
    $timber_finish = $_POST['timber_finish'];
    $timber_treatment = $_POST['timber_treatment'];
    $width = $_POST['width'];
    $thickness = $_POST['thickness'];
    $length = $_POST['length'];
    $markup = $_POST['markup'];
} else{

    $packID="";
    $supplier_name="";
    $timber_species="";
    $timber_product="";
    $timber_grade="";
    $timber_finish="";
    $timber_treatment="";
    $width= "";
    $thickness= "";
    $length="";

}

How would you write this Kenney when the variables may or may not be set. I must admit I am a novice and keen to learn. It takes time and patience.


Q: Stars & Bars w/ global maximums - (Combinatorics) The "Stars & Bars" technique has proven very helpful in solving various combinatoric problems I have been dealing with. I have been able to tweak it slightly to fit various examples, but one form still elludes me:
Is there a formulaic answer when there is a general/global maxium?
Ex: if you have 15 balls; how can you sort them into 10 bins, if each bin is only capable of holding 4 balls maximum? (and how would the amount of combinations change if each bin could hold a max of 5 or some other number)
I have a feeling there is a formula out there to encompass or help with this but have been unable to find it. Thank you very much for any help you may have.


Q: What is the difference between creating String as new() (inside heap not in string pool)and literal(inside string pool)? When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap. is it right ????????
Is my explanation correct.....


Q: Is there any way to prevent destroying a component in angular? We know that there is a method ngOnDestroy() in angular which runs on destroying a component but I want to know that is there any way to prevent it from destroying?

A: The CanDeactivate guard has access to the instance of the active component, so you can implement a hasChanges() that check if there have been changes and conditionally ask for the user confirmation before leave.
In the following example the CanDeactivateComponent implements the methods hasChanges() that returns a boolean value indicating if the components has detected any changes.
The implementation of CanDeactivate guard is similar to the CanActivate guard implelementaion (you can create a function, or a class that implements the CanDeactivate interface):
import { CanDeactivate } from '@angular/router';
import { CanDeactivateComponent } from './app/can-deactivate';

export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent>
{
  canDeactivate(target: CanDeactivateComponent)
  {
    if(target.hasChanges()){
      return window.confirm('Do you really want to cancel?');
    }
    return true;
  }
}

Even though, this is a very trivial implementation, CanDeactivate uses a generic, so you need to specify what component type you want to deactivate.
In the Angular router of the component:
{
  path: '',
  component: SomeComponent,
  canDeactivate: [ConfirmDeactivateGuard]
}

Last, like all other services on Angular, this guard needs to be registered accordingly:
@NgModule({
  ...
  providers: [
    ...
    ConfirmDeactivateGuard
  ]
})
export class AppModule {}

You can have multiple guards protecting a single route, which helps you implementing sophisticated use cases, where a chain of different checks is needed.


Q: Should we ask users to confirm an e-mail address when they change it? I have a service that requires an active e-mail address where users can receive notifications. Users can optionally receive notifications on multiple e-mail addresses by adding them.

*

*Should I require a new e-mail address be confirmed before I activate it?

*Should I require an e-mail address be confirmed before changing it?

I'm looking for best practices. I'm not dealing with any sensitive or billing information.

A: Yes, it would be best to do so. Imagine.. What if the email address they provided is not correct(misspelled) or not existing or worse--someone else's? Regarding the last case, I don't mean that your service is spam, but simply that the notifications they had hoped to receive would be sent to someone else. I think it would still be beside the point even if no important information is included in the notification--it would be a matter of the wrong person receiving notifications meant for someone else. :)

A: I would suggest that you have to confirm the new email before it can be changed so you still have contact with the user. The old email could potentially be stored in a separate database so is not visible to the user and only deleted when he/she has confirmed the new email.

A: Yes.  Doing so protects users who have had their site accounts compromised from having someone change the main e-mail address and completely lock the user out of his account.
This is good practice regardless of whether or not the account protects sensitive information because nobody wants to deal with being locked out of an account by an attacker.


Q: CodeIgniter sess_destroy() for current session I have this code in Session.php:
// Is the session current?
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
{
    $this->sess_destroy();
    return FALSE;
}

for each session CodeIgniter sets cookies expire date as $this->sess_expiration + time();
if i set this->sess_expiration = 5, and send get request after 6 seconds it will contain no cookie, because browser will destroy it due to exp date. So CI will just create new session record, what is the solution for deleting old ones?

A: You need to cleanup the session table in database, which is used to store the session information. This table should be named ci_sessions.


Q: Getting the center of a grid's cell - unity I'm working on an isometric game with Unity and I need to know the centre of the cell in the world coordinates. I'm using the tilemap's GetCellCenterWorld() method, but it gives me back bad results.
Here is what I expect to be the centre of the cell (basically the logical centre), but here is what Unity gives back (the top vertex of the cell?). I believe it has something to do with the sprite's pivot point (now set to its top centre) or the cell anchor in the tilemap's properties (I set it to (1,1)).
Here's the code I use to "select" the tiles:
public class GridSelection : MonoBehaviour
{
    public Tilemap tilemap;
    public Transform selector;

    void Update()
    {
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        worldPos.z = 0;

        Vector3Int tilemapPos = tilemap.WorldToCell(worldPos);
        selector.position = tilemap.GetCellCenterWorld(tilemapPos);
    }
}

How do I get the actual middle point of the cell?

A: Okay, I think I found what the issue was.
If anyone has the same problem, here's how I resolved it:

*

*Set the sprite pivot point to the place you want the middle of the cell to be (in my case, the centre of the grass section)

*Set tile anchor back to (0.5, 0.5)

*Use the GetCellCenterWorld() method normally

The code I've posted in the question works just fine now.

A: [SerializeField] private Tilemap map;
private Camera camera;
[SerializeField] private Transform playerTransform;

void Start(){
    camera = Camera.main;
}

// Update is called once per frame
void Update(){
    if (Input.GetMouseButtonDown(0)){
        var worldPos = camera.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int tilemapPos = map.WorldToCell(worldPos);
        playerTransform.position = map.CellToWorld(tilemapPos);
        Debug.Log(tilemapPos);
    }
}

playerTransform.position = map.CellToWorld(clickedCellPosition);

Just convert it back and provide tilemapPos

A: Try tilemap.cellBounds.center
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html


Q: Put subscript underneath instead of in the bottomright corner I wonder if there is a way to create an equation like that where the "subscript" is placed underneath instead of in the bottom right corner. I also want the "subscript" to be center aligned with the number above.

A: A simple realization is with amsmath and \underset:
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\[
y=\underset{(20)}{35}\cdot x + \underset{(3)}{39}\cdot z + \underset{(11)}{3859}
\]
\end{document}

However, you see that the first pair is perhaps too wide, because the subscript width is taken into consideration. If the subscript is never much wider than the number, you can use also \mathclap from mathtools; with a new command also the syntax is handier.
\documentclass{article}
\usepackage{mathtools}% also loads amsmath

\newcommand{\twonums}[2]{\underset{\mathclap{(#2)}}{#1}}

\begin{document}
\[
y=\twonums{35}{20}\cdot x + \twonums{39}{3}\cdot z + \twonums{3859}{11}
\]
\end{document}


Q: My system still boots from the key i installed how can stop and makes it boot from hard disk drive Sudo apt-get install unity-tweak-tool gnome-tool
But an error message appeared which reads unable to locate package unity-tweak-tool
Unable to locate gnome-tool

A: Your question title doesn't match the question body.
However from your previous questions, you have just finished installing Ubuntu. Now you can remove your USB and boot normally.
Coming to tweak-tool, even I couldn't find gnome-tool. Its gnome-tweak-tool.
While installing packages from apt-get, the first step to do is,

*

*Update your local package index using sudo apt-get update.

*Use bash-completion key (tab) after typing partial text of whole word to find correct name package.
sudo apt-get install bash-completion
then do:
sudo apt-get install gnome-tweak- press tab here. It will give list of packages with similar name.
Or

*Use apt-cache search "package-name"  (without quotes).eg: apt-cache search unity-tweak-tool. It will return the description of that package. You can use tab key here also.

The last type will help you to find whether certain package exist or not.


Q: Using static factory methods to prevent unwanted input Many years ago, I posted a problem I had with some code and received a well written detailed answer that suggested the use of factory methods. I liked this approach, because I can provide a method name to let clients know
what was being created, and to prevent wrong parameters.
// Left out additonal parameters and validation
private Student(StudentType type, List<String> documents) {
    this.type = type;
    this.documents = documents;
}

public static Student createDomestic() {
    return new Student(StudentType.DOMESTIC), Collections.emptyList());
}

public static Student createInternational(List<Document> documents) {
    return new Student(StudentType.INTERNATIONAL, new ArrayList<>(documents);
}

Benefits:

*

*I don't need a private method to validate the List based on the
StudentType, it made the code shorter and cleaner. All I needed was
to check if the List provided for the International students
contained documents (by checking the length of the List).

*The static factory prevents clients from assigning a Domestic
student a List of documents, which according to the requirements it
shouldn't have.

Leaving aside the POLA, is using a static factory method the way it was suggested on SO, considered a code smell or bad practice?

A: This seems like a perfectly good use of static factory methods.
The requirement that a international student should have documents, but a domestic student shouldn't, does make me question why you didn't use an object hierarchy in which you have DomesticStudent and InternationalStudent classes deriving from Student, but I'll assume that there were other requirements driving that decision.

A: An simpler alternative might be to have a single constructor taking a single parameter, the List.  Skeletal code:
public Student(List docs) {
  this.documents = docs;
  this.type = (docs.length() > 0)?
                         StudentType.INTERNATIONAL :
                         StudentType.DOMESTIC;
}

Not sure if this makes more sense for your application.
Also, makes you wonder if the type field is required - couldn't you just check for docs.length?  e.g.
public boolean isInternational() {
  return docs.length() > 0;
}


Q: Performance comparison of atomic operations on different sizes How do the performance of atomic operations operating on the natural word size of the processor (4-byte or 8-byte) compare to that of operating on other sizes (2-byte or 1-byte)?
If I need to maintain a boolean atomic variable, I'm trying to figure out the what the best practice is: use 1-byte to optimize for space, or 4/8-byte to (potentially) optimize for performance.

A: http://agner.org/optimize/ for lots of details.
On x86, an array of 1-byte data should be good.  It can be loaded with movzx (zero-extend) just as fast as with a plain mov.
x86 has bit ops to support atomic bitfields, if you want to pack your data by another factor of 8.  I'm not sure how well compilers will do at making efficient code for that case, though.  Even a write-only operation requires a slow atomic RMW cycle for the byte holding the bit you want to write.  (On x86, it would a lock OR instruction, which is a full memory barrier.  It's 8 uops on Intel Haswell, vs. 1 for a byte store.  A factor of 19 in throughput.)  This is probably still worth it if it means the difference between lots of cache misses and few cache misses, esp. if most of the access is read-only.  (Reading a bit is fast, exactly the same as the non-atomic case.)
2-byte (16bit) operations are potentially slow on x86, esp. on Intel CPUs.  Intel instruction decoders slow down a lot when they have to decode an instruction with a 16bit immediate operand.  This is the dreaded LCP stall from the operand-size prefix.  (8b ops have a whole different opcode, and 32 vs. 64bit is selected by the REX prefix, which doesn't slow down the decoders).  So 16b is the odd-one-out, and you should be careful using it.  Prefer to load 16b memory into 32b variables to avoid partial-register penalties and 16bit immediates when working with a temporary.  (AMD CPUs aren't quite as efficient at handling movzx loads (takes an ALU unit and extra 1 cycle latency), but the savings in memory are still almost always worth it (for cache reasons)).

32b is the "optimal" size to use for local scratch variables.  No prefix is needed to select that size (increasing code density), and there won't be partial-register stalls or extra uops when using the full register again after using the low 8b.  I believe this is the purpose of the int_fast32_t type, but on x86 Linux that type is unfortunately 64bit.


Q: Haskell Zip Parse Error I am trying to use the zip function in Haskell to join two lists together. The lists could be defined and info gathered as follows:
 priority <- getLine
 let priorityList = []
 priority : priorityList

 name<- getLine
 let nameList = []
 name : nameList

After gathering the info, the expected output would be priorityList = [1,2,3] & nameList = [test1, test2, test3]. However, this is unimportant for the purpose of the question, it can be assumed that the two lists are in the following format:
  priorityList = [1,2,3]
  nameList = [test1, test2, test3]

I need to combine the lists and print with the following function. However, i am getting the error 'parse error on input `zip''
printList :: IO ()
printList = do putStrLn "Printed Combined List"
               zip [nameList][priorityList]

A: printList :: IO ()
printList = do putStrLn "Printed Combined List"
    zip [NameList][PriorityList]

There are many things wrong with this code.
The parse error you are seeing is because the do block is not properly aligned. The zip on the last line must line up with the putStrLn on the line before. So either
printList :: IO ()
printList = do putStrLn "Printed Combined List"
               zip [NameList][PriorityList]

or
printList :: IO ()
printList = do
    putStrLn "Printed Combined List"
    zip [NameList][PriorityList]

But that still won't work. printList is declared to be an IO action, which means the final line of the do block must be an IO action also... but zip produces a list. You may have meant this:
printList :: IO [(String, Int)]
printList = do
    putStrLn "Printed Combined List"
    return (zip [NameList][PriorityList])

but that will only print out the result when you run it directly from the ghci prompt. Better to print it out explicitly:
printList :: IO ()
printList = do
    putStrLn "Printed Combined List"
    print (zip [NameList][PriorityList])

But it still won't do what you want! Because NameList and PriorityList are, presumably, lists. That you want zipped together. But that's not what you're giving to zip: you're giving zip two new single element lists. You no doubt intended just to pass the lists directly.
printList :: IO ()
printList = do
    putStrLn "Printed Combined List"
    print (zip NameList PriorityList)

Oh, but it still won't work. Won't even compile. And why is that? Because variable names must start with lower case letters (or an underscore). And you've started both NameList and PriorityList with capital letters. Which is one reason why your first block of code so obviously could not have worked.
printList :: IO ()
printList = do
    putStrLn "Printed Combined List"
    print (zip nameList priorityList)

A: Using the above assistance, i have been able to construct a function (below) to achieve a successful ZIP (Excluding information gathering).
printList :: IO ()
printList = do
    let nameList = ["test1", "test2", "test3"]
    let prioirtyList = [1, 2, 3]
    putStrLn "Printed Combined List"
    print (zip nameList prioirtyList)

My output is as follows:
*Main> printList
 Printed Combined List
 [("test1",1),("test2",2),("test3",3)]


Q: Adding A Node To A Nodelist Using XmlParser In Groovy When I add a Node to a NodeList using the XmlParser in Groovy, the NodeList does not appear to reflect the change. Here is the code that I'm testing within the GroovyConsole. If you run this code, you should see the output "ADD FAILED" followed by a dump of the three elements of the NodeList. I've also tried the same thing with XmlSlurper but switched to XmlParser when I read that the DOM in XmlSluper is basically immutable and that changes only get applied during serialize. But with XmlParser, should this work?
def xml = '''
<site id='myCoolSite'>
  <pages/>
  <templates/>
  <properties>
    <property name='good' value='true'/>
    <property name='nice' value='true'/>
    <property name='expensive' value='false'/>
  </properties>
  <stuff/>
</site>
'''

site = new XmlParser().parseText( xml )
assert site != null

assert site.properties.property instanceof NodeList
assert site.properties.property.size() == 3

def newNode = new Node(null, "property", [name: "foo", value: "bar"] )

site.properties.property.add( 0, newNode )

def foo = site.properties.property.find { it.@name == "foo" }

if ( foo == null ) {
    println "ADD FAILED. Here are the only properties found: "
    site.properties.property.each { println "${it.@name}=${it.@value}" }
}
else {
    println "SUCCESS"
}

A: It works if you add it to the children of properties rather than the property node-list.  Ie change:
site.properties.property.add( 0, newNode )

To
site.properties[0].children().add( 0, newNode )


Q: In a pure user level thread strategy, why can't a multithreaded application take advantage of multiprocessing? My textbook states the following:

In a pure ULT (user level thread) strategy, a multithreaded
  application cannot take advantage of multiprocessing. A kernel assigns
  one process to only one processor at a time. Therefore, only a single
  thread within a process can execute at a time. In effect, we have
  application-level multiprogramming within a single process. While this
  multiprogramming can result in a significant speedup of the
  application, there are applications that would benefit from the
  ability to execute portions of code simultaneously.

I understand the elementary concepts, such as user level threads, multithreading, and multiprocessing. However, I don't understand the above justification for why a multithreaded application can't take advantage of multiprocessing in a pure ULT strategy.
I would greatly appreciate it if someone could please take the time to clarify this with a clearer explanation.

A: The important fact is that user level threads (or green threads) are handled by the programming language and are not exposed to the operating system. In ULT the threads are entirely "hidden within the python runtime". This has the advantage that the programming processing envinroment has the full control over the threads. To the OS the program looks like a single thread and thus only runs on one core at a time.
On the other hand, kernel threads are handled by the OS. They can run on different cores at once and benefit from this speed improvement. The downside is that things like "thread safe memory access" need to be handled by the threads themselves and there is no "outside language scheduler" (as in user level threads) which can guarantee the thread safety. That's why for instance in python there's a "global interpreter lock" which guarantees, that two kernel threads never run at the same time.
That's just a short summary. If you're interested to know more, look up "global interpreter lock" (python, ruby) or see this answer


Q: a problem about an equilateral triangle that is projected from a plane P to another plane P'
An equilateral triangle $ABC$ is projected orthogonally from a given plane P to another plane P' intersecting P.

*

*Show that if two lines are perpendicular in P, then then their orthogonal projections into P' are also perpendicular.

*Show that if $L$ is the line of intersection of the two planes and if $AB$ makes an angle of $\phi$ with $L$, $BC$ and $CA$ make angles of $f(\phi+\pi/3)$ and $f(\phi+2/3 \pi)$ with $L$ or vice versa, where $f(x) = \min\{x, \pi - x\}$.

Here's my attempt to prove 1:
Suppose we have a plane $P$ given by the equation $a_1 x + b_1y+c_1 z = d_1, a_1^2+b_1^2+c_1^2\neq 0$ and another (distinct) plane $P'$ intersecting $P$ given by $a_2x+b_2 y + c_2 z = d_2, a_2^2+b_2^2+c_2^2\neq 0.$ Note that $P'$ must have a different normal than $P$ (one can see this by considering the equations of the planes). From here on, all vectors should be treated as column vectors but will be written in the form $(a,b,c)$ for real numbers $a,b,c$ for convenience. Now, consider the following derivation of the projection of a point $(x_1,x_2,x_3)$ onto P, which can be arbitrary: The projection is the intersection $k$ of the line with equation coordinates $L(t) = (x_1,y_1,z_1) + t(a_1,b_1,c_1)$ with $P$, since $(x_1,x_2,x_3) - k$ is orthogonal to P (being parallel to the normal of P). We get $t(a_1^2 + b_1^2 + c_1^2) + a_1x_1+b_1y_1 + c_1z_1 = d_1\Rightarrow t = \dfrac{d_1-a_1x_1-b_1y_1-c_1z_1}{a_1^2 + b_1^2 + c_1^2}$ and hence $k= (\dfrac{a_1d_1+(b_1^2+c_1^2)x_1-a_1b_1y_1-a_1c_1z_1}{a_1^2 + b_1^2 + c_1^2},\\ \dfrac{b_1d_1-b_1a_1x_1+(a_1^2+b_1^2)y_1-b_1c_1z_1}{a_1^2 + b_1^2 + c_1^2}
    , \\\dfrac{c_1d_1-c_1a_1x_1-c_1b_1 y_1+(a_1^2+b_1^2)z_1}{a_1^2 + b_1^2 + c_1^2}).$ Let $(x_i,y_i,z_i)$ be in $P$ for $1\leq i\leq 3$. Let $L_i$ be the line through $(x_i,y_i,z_i)$ and $(x_{i+1},y_{i+1},z_{i+1})$ for $i=1,2$. If lines $L_1$ and $L_2$ in plane $P$ are orthogonal (and thus their dot product is zero), then they are also orthogonal in $P'.$ To see why, observe that it suffices to show that if $(x_i',y_i',z_i')$ is the projection of $(x_i,y_i,z_i)$ into $P', $ $(x_3'-x_2',y_3'-y_2',z_3'-z_2')$ is perpendicular to $(x_2'-x_1',y_2'-y_1',z_2'-z_1').$ It seems very tedious to perform the required calculations for this however.
To prove 2, I was thinking of something similarly tedious that involves considering separately the cases where $\phi \leq 60$ and when $\phi > 60$. I think it might be useful to observe that in the diagram below, $BC$ is a rotation of $AB$ about B that's $\pi/3$ radians counterclockwise. I know how to get a formula for the coordinates of a point when it's rotated $\theta$ radians about another point that involves complex numbers, though I think there's a simpler approach to this problem.
Diagram (fairly rough):


Q: Pascal's triangle series in php I am trying to get pascal's triangle using two dimensional array. But it not works.
can anyone solve this program.
Thanks in advance.

    <form name="form1" action="pascaltriangle4.php" method="post">
        Enter the number of rows in pyramid of stars you wish to see  : <input type="text" name="n">
                <input type="submit" name="submit" value="submit">
    </form>

<?php
if($_POST['submit']==='submit')
{
    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    $n=$_POST['n'];
    $arr=array();
    //print_r($arr);
    for($i=0;$i<=$n;$i++)
    {
        echo "
";
        for($j=0;$j<=$i;$j++)
        {
            if($j==0)
            {
                //echo "1";
                $arr[$i][$j]=1;
                //print_r($arr);
                if($n!=$i)
                {
                    echo "	";
                }
                    echo "".$arr[$i][$j]."	";
                    echo "	";
                }
            elseif($i==$j)
            {
                //echo "1";
                $arr[$i][$j]=1;
                //echo $arr;
                echo "".$arr[$i][$j]."	";
                    //echo "	";
            }
            else
            {
                $arr[$i][$j]=$arr[$i-1][$j-1]+$arr[$i-1][$j];
                echo "".$arr[$i][$j]."	";
                echo "	";
            }

        }echo "
";
    }
    //echo "
";
    //print_r($arr);
    //echo "
";
}
?>

A: $size = 32;
$pascal = array(
    array(1),
);

for ($i = 1; $i <= $size; ++$i) {
    $prevCount = count($pascal[$i-1]);
    for ($j = 0; $j <= $prevCount; ++$j) {
        $pascal[$i][$j] = (
            (isset($pascal[$i-1][$j-1]) ? $pascal[$i-1][$j-1] : 0) +
            (isset($pascal[$i-1][$j]) ? $pascal[$i-1][$j] : 0)
        );
    }
}
var_dump($pascal);


Q: Docker Port forwarding doesn't call css and images I have setup port concepts in docker to access my container  magento2  to locally connected another system.
This is Docker Container Setup:
  docker run -it -d --name containerName -h www.myhost.net -v /var/www/html -p 3000:80 --net mynetwork --ip 172.11.0.10 --privileged myimagename

then, Execute the Container:
      docker exec -it containerName bin/bash

volume path /var/www/html with in the volume path i write one index.html file and  access to anoter locally connected system its working fine.
   hostmachineip:3000

After I installed magnento2 in my container with in volume(/var/www/html),
Then test Its working for me.But Doesn't call css and images.
  hostmachineip:3000

But Magento2 Working file in host machine and also port forwarding working file, Because if i call hostmachineip:3000/index.html It working fine.
But: if I call host machine its working file,
 hostmachineip:3000

Its redirect to right server, show magento2 home page with css and images.
remote machine only not calling css and images.
Configuration File:  /etc/nginx/site-available/default (server 172.10.0.30)
# nginx Confoguraration

    server {
        listen 80;

        server_name www.xxxxx.net  xxxx.net;

        access_log /var/log/nginx/access_log;
        error_log  /var/log/nginx/error_log;

        root  /var/www/html;

        location / {
        index index.html index.php;
        try_files $uri $uri/ @handler;
        }

        # Deny access to specific directories no one
        # in particular needs access to anyways.
        location /app/ { deny all; }
        location /includes/ { deny all; }
        location /lib/ { deny all; }
        location /media/downloadable/ { deny all; }
        location /pkginfo/ { deny all; }
        location /report/config.xml { deny all; }
    #    location /var/ { deny all; }

        # Allow only those who have a login name and password
        # to view the export folder. Refer to /etc/nginx/htpassword.
        location /var/export/ {
        auth_basic "Restricted";
        auth_basic_user_file htpasswd;
        autoindex on;
        }
     # Deny all attempts to access hidden files
        # such as .htaccess, .htpasswd, etc...
        location ~ /\. {
         deny all;
         access_log off;
         log_not_found off;

     }

        # This redirect is added so to use Magentos
        # common front handler when handling incoming URLs.
        location @handler {
        rewrite / /index.php;
        }

        # Forward paths such as /js/index.php/x.js
        # to their relevant handler.
        location ~ .php/ {
        rewrite ^(.*.php)/ $1 last;
        }

       # my proxy Configuration

       # pass the PHP scripts to FPM socket

       location ~ \.php$ {
        try_files $uri =404;

    #   fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
    #   fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;

        #fastcgi_param SCRIPT_FILENAME /usr/share/nginx/www$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT  /var/www/html;
        fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;
        # send bad requests to 404
        fastcgi_intercept_errors on;

        include  fastcgi_params;
        }
    }

Loadbalancer Machine Conf file:
    upstream backend {
       ip_hash;
       server 172.10.0.30 weight=5;
       server 172.10.0.40 weight=2;

    }

    server {
        listen 80;
        server_name  chennaihousing.net  www.chennaihousing.net;

       location / {

        proxy_pass http://backend;
        include /etc/nginx/proxy_params;

        }

    }

include /etc/nginx/proxy_params File:
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    client_max_body_size 100M;
    client_body_buffer_size 1m;
    proxy_intercept_errors on;
    proxy_buffering on;
    proxy_buffer_size 128k;
    proxy_buffers 256 16k;
    proxy_busy_buffers_size 256k;
    proxy_temp_file_write_size 256k;
    proxy_max_temp_file_size 0;
    proxy_read_timeout 300;

Why? magento 2 need php support for install in hostmachine, So, Remote Machine also need same Support?. or Any think i miss in this Configuration? Suggest Me How to resolve this problem.


Q: How to convert string to integer in BIRT after fetching it from the database? I use BIRT for reports and i am a beginner BIRT user. In my report i must calculate the average of a column. (database is an oracle)
In my open script I have sth. like this:
sqlText = "select A, B, C, D, ((date1-date2) day to second) as differencedate from problem";

difference date column values are like this: 0 0:22:15 and in my fetch I have
if (!maximoDataSet.fetch())
    return (false);

row["A"] = maximoDataSet.getString("A");
row["B"] = maximoDataSet.getDate("B");
....

row["differencedate"]=maximoDataSet.getString("differencedate");

return (true);

I tried to split the string and get the seconds from the differencedate and convert it to integer using plain JavaScript but I am getting an error like "split null" etc. So my question is how can i convert this column to integer in BIRT?

A: Try retrieving the date difference from the database as a number - like so:
select A, B, C, D,
       ((date1-date2) day to second) as differencedate,
       (date1-date2) * 86400 as differenceseconds
from problem


Q: Jquery calculate the total of all textboxes (addition and subtraction) Hello I am trying to calculate the total of multiple fields in a row (my code will contain multiple rows) on key press (some of them uses addition method and some of them uses subtract method) but as I am newbie I am not too much familiar to JQuery. In my scenario B.Salary, Rec.comm, Sal.comm will add into total field and Advance, deduction fields will subtract from total field and the adjustment field will use addition method if contains positive value and subtraction method if contains negative value. I tried my best to figure out some related scenario but no success.
Here is my HTML

#

Employee#

FullName

B.Salary

Advance

Rec.Comm

Sal.Comm

Deduction

Adjustment

Total

<input name="checked1" checked="" type="checkbox">

E17-00001

Employee Name 1

<input class="form-control input-sm" value="50000" name="txtMonthlyRate1" type="text">

<input class="form-control input-sm" value="0" name="txtAdvance1" type="text">

<input class="form-control input-sm" value="35" name="txtRecovery1" type="text">

<input class="form-control input-sm" value="2350" name="txtsales1" type="text">

<input class="form-control input-sm" value="0.00" name="txtdeduction1" type="text">

<input class="form-control input-sm" value="0.00" name="txtadjustment1" type="text">

<input class="form-control input-sm" value="52385" name="txttotal1" type="text">

<input name="checked2" checked="" type="checkbox">

E17-00002

Employee Name 2

<input class="form-control input-sm" value="10000" name="txtMonthlyRate2" type="text">

<input class="form-control input-sm" value="0" name="txtAdvance2" type="text">

<input class="form-control input-sm" value="0" name="txtRecovery2" type="text">

<input class="form-control input-sm" value="0" name="txtsales2" type="text">

<input class="form-control input-sm" value="0.00" name="txtdeduction2" type="text">

<input class="form-control input-sm" value="0.00" name="txtadjustment2" type="text">

<input class="form-control input-sm" value="10000" name="txttotal2" type="text">

Here is My JS
$(document).ready(function(){
$("[input[name^=txt]").keyup(function(){
calcPullTotal();
console.log(calcPullTotal);
);
function calcPullTotal() {
        var basic_salary = parseInt($('input[name^=txtMonthlyRate]').val());
        var advance_salary = parseInt($('input[name^=txtAdvance]').val());
        var recover_comm = parseInt($('input[name^=txtRecovery]').val());
        var sales_comm = parseInt($('input[name^=txtSales]').val());
        var deduction_salary = parseInt($('input[name^=txtDeduction]').val());
        var adjustment_salary = parseInt($('input[name^=txtAdjustment]').val());
        var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary;
        $('input[name^=txtAdjustment]').val(total_sum);
}

});

A: A exemple add and remove divs by id  (jquery)

$( '#add' ).click(function() {
    var n = 0;
    n = $( "div" ).length;
    if(n!=1){
      n = n-2;
    }
    n = n+1;
    var div_id = "div_"+n;
    $( document.body ).append( $( '
' ));
    $( "#count" ).val("There are " + n + " divs.");
  })
  // Trigger the click to start
  //.trigger( "click" );
 $( '#remove' ).click(function() {
    var n = 0;
    n = $( "div" ).length;
    if(n!=1){
      n = n-2;
    }
    var div_id = "div_"+n;
    $( "#"+div_id ).remove( );
    if(n!=0){
      n = n-1;
    }
    $( "#count" ).val("There are " + n + " divs.");
  })
body {
    cursor: pointer;
  }
  div {
    width: 50px;
    height: 30px;
    margin: 5px;
    float: left;
    background: blue;
  }
  span {
    color: red;
  }
<meta charset="utf-8">

 Create and remove divs by id

<input id = "count" type = "text" val = "0">
<button id = "remove" >Remove</button>
<button id = "add" >Add</button>

To add div with id:
$( document.body ).append( $( '
' ));

To remove div with id:
$( "#"+div_id ).remove( );

To calculate the number of divs:
n = $( "div" ).length;

For a specific type of class:
var numItems = $('.clas').length;


Q: Resetting ThreadLocal Value I initialize my ThreadLocal with a valueFactory Func.
I would also like to reset the Value back to null on occasion.
Perhaps I'm doing something wrong, but if I set my threadLocal.Value = null, it still seems to think that threadLocal.IsValueCreated == true.
How can I truly reset the threadlocal so that it will regenerate the Value lazily when it is asked for?

A: Not that I'm aware of.
You could always make it a ThreadLocal<Lazy<T>>, and set it to a new Lazy<T> whenever you wanted to reset it. If this is something you use more than once, you might want to consider encapsulating it as a ResettableThreadLocal<T> or something like that.


Q: Facebook og:image (link image) does not display when sharing my website I cannot get the image to show when sharing my site in FB. Below is my open graph code.
I have rescraped using the FB sharing debugging tool (https://developers.facebook.com/tools/debug). soooo many times, and it never displays, in the tool or in a share.
The debugger reports no errors, and lists the correct image.
The image is 1200x630 and exists on the same site.
Using open graph checker displays the expected image.
https://iplocation.io/open-graph-checker.
I have tried everything i can find in posts. but i really need this working for marketing.
Hope someone has the secret sauce.
cheers,
    <meta property="fb:app_id" content="123456789"/>
    <meta property="og:type" content="website"/>
    <meta property="og:image" content="http://www.example.com/images/og2.jpg"/>
    <meta property="og:image:secure_url" content="https://www.example.com/images/og2.jpg"/>
    <meta property="og:image:type" content="image/jpeg" />
    <meta property="og:title" content="my title"/>
    <meta property="og:description" content="my description."/>
    <meta property="og:image:width" content="1200"/>
    <meta property="og:image:height" content="630"/>


Q: Sequencing RXJS chaining / processing of NGRX observables in an HttpInterceptor I am having trouble attaching a JWT access token to the header of an HTTP request within a class which derives from the HttpInterceptor (Angular 8) base class.
I have narrowed the issue down to the sequence in which the operations are performed within the Http Interceptor. It appears the request is sent to the caller before the token is returned back from the NGRX store (async).
I am unclear how to ensure that the request is only returned back once the token has been received back from the NGRX store.
export class ServerInterceptor implements HttpInterceptor, OnDestroy {

    private state$: Observable<any>;
    private unsubscribeAll: Subject<any>;

    constructor(
        private store: Store<AuthenticationState>
    ) {
        this.unsubscribeAll = new Subject();
        this.state$ = this.store.select(getAccessToken);
    }

    ngOnDestroy(): void {
        this.unsubscribeAll.next();
        this.unsubscribeAll.complete();
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const output = next.handle(request).pipe(
            takeUntil(this.unsubscribeAll),
            withLatestFrom(
                this.store.select(selectAuthenticationState), (_action, state) => {
                    console.log(state.accessToken);
                    if (state.accessToken) {
                        request = request.clone({
                            setHeaders: {
                              Authorization: `Bearer ${state.accessToken}`
                            }
                          });
                    }
                    console.log('1');
                    return request;
                }
            ),
            switchMap((req) => {
                console.log('2');
                return next.handle(req);
            }),
        );
        console.log('3');
        return output;
    }
}

The output of the console processes the interceptor in the sequence 3, 1 and 2. It should be processed 1, 2 and 3.

A: You can consider using select operator with your selector getAccessToken, and "chain" observables.
No need to subscribe if you use first() or take(1) operators. Observable will automatically complete after one value.
Your code for HttpInterceptor could looks like below:
export class ServerInterceptor implements HttpInterceptor {

  constructor(
    private store: Store<AuthenticationState>
  ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.store.pipe(
      select(getAccessToken),
      first(),
      mergeMap(accessToken => {

        const authReq = !!accessToken ? request.clone({
          headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        }) : request;

        return next.handle(authReq);
      })
    );
  }
}

Some resources on the subject :

*

*Using NgRx Store Auth Token with Angular HttpInterceptor by Antony Derham

*Add JWT Token to Angular HTTP Requests Using NGRX by WASi


Q: Multiple Submit Changes and Exceptions Simple scenarios.
Reading data from one source and saving to SQL database using LinqToSQL.
There are many rows in the file. It's possible that SQL exception can occur for some rows but we want to ignore it (log exception) and still save the rest of the data.
Currently we do submitchanges after each row of input data. The first time SQL Exception is encountered none of the following rows can be processed because the same exceptions seems to be resubmitted.
What is the best way to handle this?

A: Ok. I seem to have found a solution and wanted to share it.
The way to do this is to clear out all pending changes before proceeding. So if the SubmitChanges fails I now call this extension method on the datacontext - RejectPendingChanges().
When the next row is processed it now longer tries to resubmit bad data.
public static void RejectPendingChanges(this System.Data.Linq.DataContext db){
        var chgset = db.GetChangeSet();
        if (chgset != null)
        {
            foreach (object objToInsert in chgset.Inserts)
            {
               db.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);
            }
            //Undo deletes
            foreach (object objToDelete in chgset.Deletes)
            {
                db.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);
            }
            ///this._DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Deletes);
            db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, chgset.Updates);
        }
    }


Q: Fazer um get com parâmetros opcionais em GoLang Preciso fazer uma api onde pesquisa usando parâmetros query string opcionais.
Eu tentei algo como:
func (app *App) getFunctionarys(w http.ResponseWriter, r *http.Request) {
    v := r.URL.Query()

    Id := v.Get("Id")
    Name := v.Get("Name")
    Cpf := v.Get("Cpf")
    Role:= v.Get("Role")
    Status := v.Get("Status")

    dbdata := &Funcionary{}
    err := app.Database.QueryRow("SELECT Id,DataCad,Role,Cpf,Name,Uf,Salary,Status FROM `funcionary` WHERE Id = ? OR Name= ? OR Cpf = ? OR Role= ? OR Status = ?", Id, Name, Cpf, Role, Status).Scan(&dbdata.Id, &dbdata.DataCad, &dbdata.Role, &dbdata.Cpf, &dbdata.Name, &dbdata.Uf, &dbdata.Salary, &dbdata.Status)

    if err != nil {
        log.Println(err)
    }

    w.WriteHeader(http.StatusOK)
    if err := json.NewEncoder(w).Encode(dbdata); err != nil {
        panic(err)
    }
}

Eu tenho 5 registros, mas minha api está retornando apenas o primeiro registro, independente de quais query strings eu colocar. Como eu posso fazer uma api que realize um where com base nos parâmetros opcionais recebidos da requisição?

A: Tente usar a função Query ao invés da função QueryRow, QueryRow retorna no máximo um elemento enquanto Query retorna todos do resultado da consulta.
Porém a função Query não retorna um ponteiro de Row mas sim um ponteiro de Rows, então não é possível usar a função Scan diretamente para ler cada linha do resultado da consulta. Você pode fazer um loop para ler o resultado usando o método Next do Rows.
No seu caso o código seria algo assim:
rows, err := app.Database.Query("SELECT Id,DataCad,Role,Cpf,Name,Uf,Salary,Status FROM `funcionary` WHERE Id = ? OR Name= ? OR Cpf = ? OR Role= ? OR Status = ?", Id, Name, Cpf, Role, Status)

var dbdata []*Funcionary

for rows.Next() {
    funcionary := &Funcionary{}
    err := rows.Scan(&funcionary.Id, &funcionary.DataCad, &funcionary.Role, &funcionary.Cpf, &funcionary.Name, &funcionary.Uf, &funcionary.Salary, &funcionary.Status)
    if err != nil {
      // tratar o erro como vc achar adequado
      log.Fatal(err)
    }
    dbdata = append(dbdata, funcionary)
  }

Caso você esteja interessado em saber mais sobre a função: documentação oficial da função Query.


Q: How to optimize navigation and user-experience into a login form? I have developed an Universal app that uses a login form, that allowing users to connect or to create an account.
It is a simple page that looks like this:

This XAML code is also very simple:
    <ScrollViewer>
        <StackPanel>
            <TextBlock x:Uid="loginRegisterTextblockMessage"
                       Style="{StaticResource TitleTextBlockStyle}"
                       Text="Remplissez vos informations d'inscription" />
            <TextBox x:Uid="loginRegisterTextboxOrganizationURL"
                     Header="Organisation ou URL"
                     IsSpellCheckEnabled="False"
                     IsHitTestVisible="True"
                     IsTextPredictionEnabled="False"
                     Text="{Binding OrganizationURL, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxLastName"
                     Header="Nom"
                     Text="{Binding LastName, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxFirstName"
                     Header="Prénom"
                     Text="{Binding FirstName, Mode=TwoWay}" />
            <TextBox x:Uid="loginRegisterTextboxEmail"
                     Header="Email"
                     InputScope="EmailSmtpAddress"
                     Text="{Binding Email, Mode=TwoWay}"/>
            <PasswordBox x:Uid="loginRegisterPasswordboxPassword"
                         Header="Mot de passe"
                         Password="{Binding Password, Mode=TwoWay}" />
            <PasswordBox x:Uid="loginRegisterPasswordboxConfirmPassword"
                         Header="Confirmez le mot de passe"
                         Password="{Binding PasswordConfirmation, Mode=TwoWay}" />
            <CheckBox x:Uid="loginRegisterCheckboxTermsOfUse"
                      IsChecked="{Binding TermsOfUse, Mode=TwoWay}" >
                <TextBlock Style="{StaticResource BaseTextBlockStyle}">
                    <Run x:Uid="loginRegisterTextblockTermsOfUse1"
                         Text="J'accepte les " />
                    <Underline>
                        <Hyperlink x:Uid="loginRegisterHyperlinkTermsOfUse"
                                   NavigateUri="http://termsofuse.html" >
                            <Run x:Uid="loginRegisterTextblockTermsOfUse2"
                                 Text="conditions générales d'utilisation" />
                        </Hyperlink>
                    </Underline>
                </TextBlock>
            </CheckBox>
            <Button x:Uid="loginRegisterButtonRegister"
                    Content="S'inscrire"
                    Command="{Binding RegisterCommand}" />
        </StackPanel>
    </ScrollViewer>

But I meet a "problem" for navigating between each fields of this page:

=> The user must click outside of a TextBlock to hide the keyboard and select the next field: this is not very user-friendly
I took a look at a similar "system" form: the page used to create an account to access to the Windows Store.
The page looks very similar to my own page:

But it is there possible to activate the next field by clicking on its header:

The focus moved on the field and the keyboard is also automatically displayed:

If I click on the the next header "Nom d'utilisateur", I can see that the next field is now "Domaine", by moving automatically into the displayed content:

=> Is there an easy way to reproduce this comportment?  Is it based on the "Header" of the "TextBox", or by using seperated "TextBlock" to show the header?

A: I always looking for a good solution but I didn't find it.
I've added events in the XAML for the TextBox and PasswordBox on GetFocus and KeyDown.
In the Code-Behind, I can now manage the "Enter" Key, that gives the focus to the next TextBox:
        private void RegisterTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        TextBox currentTextBox = (TextBox)sender;
        if (currentTextBox != null)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
            }
        }
    }

But I haven't yet managed the ScrollViewer autoscroll like I hope.
I tried to inspire me from this link, but to no avail:
Keyboard-Overlaps-Textbox
=> Is there really a way to reproduce the autoscroll that is used on the registration form for the Windows Store?


Q: How to get map values by index when inside each loop in JavaScript? I try to write tests in a clean way.
I iterate through the rows (each of which shows info about attached file) of the table on the page and verify if each attached file has correct size:
   it('attaches many documents', () => {
     const fileSizes = ['17.19 KB', '12.06 KB', '67.75 KB']
     cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])

     cy.get('div.table-body>.table-row').each(($el, index) => {
       expect($el.find('.col-upload-size')).to.contain.text(fileSizes[index])
     })

   })

But earlier in the code I have this map defined:
const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

Can I somehow get rid of fileSizes list inside of the test and make use of fileSizesMap instead?

A: I understand you want to replace fileSizes with the values from your fileSizesMap:
const fileSizes = Array.from(fileSizesMap.values())

A: You could try to return an iterable for values and do your assertions:
const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

it('attaches many documents', () => {
    cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])
    for (const value of fileSizesMap.values()) {
        cy.get('div.table-body>.table-row').then(() => {
            expect($el.find('.col-upload-size')).to.contain.text(value)
        })
    }
})


Q: Input 0 of layer time_distributed_30 is incompatible with the layer: expected ndim=5, found ndim=4. Full shape received: (None, None, None, None)
*

*I am trying for classification of MSTAR data set with 10 classes

*I have used the modal that contains DCNN and BILSTM with 15 time steps

My questions are:

*

*How to overcome the error

*How to get the good classification results.

My code is:
inputs=Input(shape=(15,60,60,3))
model = Sequential()
# 1st Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=16 ,kernel_size=(5,5), padding='valid'),input_shape=(15,60,60,3)))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 2nd Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=32, kernel_size=(5,5), padding='valid')))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 3rd Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=64, kernel_size=(5,5), padding='valid')))
model.add(Activation('relu'))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
# Pooling
model.add(TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid')))

# 4th Convolutional Layer
model.add(TimeDistributed(Conv2D(filters=128, kernel_size=(4,4), padding='valid')))
model.add(TimeDistributed(Activation('relu')))
# Batch Normalisation
model.add(TimeDistributed(BatchNormalization()))
model.add(TimeDistributed(Flatten()))
#add dropout
model.add(Dropout(0.0))
#bidirectional lstm
model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=True)))
#2 nd bidirectional layer
model.add(Bidirectional(LSTM(1024,activation='tanh',return_sequences=False)))
# Output Layer
model.add(Dense(10))
model.add(Activation('softmax'))

# (4) Compile
model.compile(loss='categorical_crossentropy', optimizer='adam',\
 metrics=['accuracy'])
model.summary()


Q: Put teaser content, more-link and full content in different divs if existing... Possible? im working on a flip-card template and have a problem.
<div class="card" id="card-<?php the_ID(); ?>">

<?php the_title( '', '' ); ?>

<?php the_content(); ?>

        <button class="btn btn-sm btn-link flip-btn">FLIP</button>

<?php the_title( '', '' ); ?> (2)

Text

<button class="btn btn-sm btn-link flip-btn">FLIP BACK</button>

i would like to place the teaser text before the more link on the front page, place a more link if there is more at the FLIP button and post the content after the more link on the second page. Is that possible? how ca i call the different parts?
i found some help in : Only show content before more tag
// Fetch post content
$content = get_post_field( 'post_content', get_the_ID() );

// Get content parts
$content_parts = get_extended( $content );

// Output part after  tag
echo $content_parts['extended'];

but this gives my the content of the second part withoud functioning shortcodes. so it outputs [] for zotero for example

A: Found a solution which is working.
Splitting the array like above just gives you the plain text so shortcodes wont work.
this works:
global $post;
$content = get_extended( $post->post_content ); //get the_content

$excerpt = $content['main']; //get the teaser part before more tag
$main_content = apply_filters('the_content', $content['extended']); //get part after more tag

echo $excerpt; //post teaser part
echo $main_content; //post main part

my head is smoking. too much for a beginner
and if you want to have  in your html use this:
echo wpautop( $main_content );


Q: How to call a UDF from a JSON file in Python? I'm working on a chatbot project which fetches "delivery status" information from a database. I've defined a function (lets call it db_info) which will connect to my DB and then get the results.
I have a .json file which has different intents like "Greeting", "Status Check", "Closing" etc. The way the application works is - whenever the user types in something, the text is classified into an intent. For ex: when the user types "Hi" the application recognizes it is from the intent "Greeting" and then gives out one of the responses I hard coded in the .json file.
However, for the "Status Check" intent I don't want the application to give out some hard coded response from .json file. Instead, I'd like it to call the db_info function when the intent "Status Check" is identified.
I'm aware that a function map (dictionary) can be created in .py file and then its value can be called in the json file. But I'm not sure how this is done exactly.
def db_info(): --> lives in .py file
   # connect to postgres and get some information

if intent == 'greetings':
   # pick random statement from "responses" of tag "greeting" from json file

if intent == 'status_check':
   # go to "responses" under tag "status_check" and run the func mentioned there
   def db_info():
       # instead of picking up a random statement from "response" this func needs to be called

My json file:
{"tag": "greetings",
 "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"],
 "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"]
},
{"tag": "status_check",
 "pattern": ["Where's my shipment", "Track my shipment"],
 "responses": ["GetDBInfo function"]
}

A: You can modify your json to match the following parsing process:

*

*find the intent the pattern matches

*get a response

*pass it as an argument to the function of that intent

This means that you will add a "function" field to the json and call it when you parse. All intents will simply have it as "print" (or whatever other default operation you're doing) and the "Status_Check" intent will have its own special function. Then, just map the names to actual function objects that you can call.
So the json can look like this:
[{"tag": "greetings",
  "pattern": ["Hi", "How are you", "Hey", "Hello", "Good Day"],
  "function": "print",
  "responses": ["Hello!", "Hey there", "Hi, how can I help you today?"]
 },
  {"tag": "status_check",
    "pattern": ["Where's my shipment", "Track my shipment"],
    "function": "GetDBInfo",
    "responses": [""]
  }]

And to parse it:
import json
import random

def db_info(useless_arg):
    print("from func")

func_mapping = {"print": print,
                "GetDBInfo": db_info}

with open("test.json") as file:
    intents = json.load(file)

text = input("input: ")

for intent in intents:
    if text in intent["pattern"]:
        function = intent["function"]
        arg = random.choice(intent["responses"])
        func_mapping[function](arg)

An example run:
input: Where's my shipment
from func

input: Hi
Hello!


Q: How to plot wide dataframe After training a model, I want to plot the accuracy, validation accuracy, etc. In Seaborn, this is what I tried to do:
df_model_history = pd.DataFrame(
    np.array([
        history.history['accuracy'],
        history.history['val_accuracy']
    ]).T,
    columns=['Accuracy', 'Validation Accuracy']
)

df_model_history.index.name = 'Epochs'

That creates a data frame that looks like this:

Epochs
Accuracy
Validation Accuracy

0
0.769296
0.766673

1
0.858553
0.894064

2
0.915641
0.901508

3
0.936782
0.892285

And when I want to plot, I do this:
sns.set(rc={'figure.figsize':(11.7,8.27)})

sns.lineplot(
    x='Epochs',
    y='Accuracy',
    data=df_model_history
)

However, this only plots a single variable in the figure, but I wanted both 'accuracy' and 'val_accuracy' in the same figure. Also, compared to Matplotlib, I have a lot more steps in Seaborn to plot the same output, so I was wondering if I'm doing it incorrectly.


Q: Interrupting DataAdapters? I have a circumstance where I'm popping up a dialog window containing a "Please Wait" message, running an SQL query, then replacing the "Please Wait" message with a DataGridView containing the collected results.
The code I'm using for this is basically:
    Dim X As New Data.SqlClient.SqlCommand
    X.CommandText = "SELECT some_data FROM someTable"
    Dim XAdapter As New System.Data.SqlClient.SqlDataAdapter(X)
    Dim XSet As New DataSet
    XAdapter.Fill(XSet, "MyTable")

    Me.someDataGridView.DataSource = XSet.Tables("MyTable").DefaultView

I would like to put the retrieval of this data into a background thread, so that the UI doesn't freeze up while I'm loading larger datasets, but, having done this, I'd also like to allow the user to cancel and close the dialog, if accessing the data takes longer than they want to wait.
At the moment, this Dialog window can take some arbitrary SQL string and display the results (using SQLDataAdapter) without any extra code.
How can I make this process interruptible, while also retaining the ease of access of the SQLDataAdapter?

A:
How can I make this process
  interruptible, while also retaining
  the ease of access of the
  SQLDataAdapter?

According to the documentation you should be able to call Close on the underlying SqlConnection instance. The documentation says this will terminate and rollback any pending transactions. Also, instead of using a SqlDataAdapter (which unfortunately does not have the async Fill methods) you could use SqlCommand.BeginExecuteReader and once that is done you can fill a DataTable by calling the overload of DataTable.Load that accepts an IDataReader. If you want to interrupt a pending a command just call Close.


Q: Android Video View turns black This seems to be a very common problem, but I couldn't search for it on SO.
I have a simple videoview and it play video from a mp4 file. It continously plays video and loop through the video.
Problem is when playing I went to settings and came back then video turns black.
This is my Code:
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
    video = (VideoView) findViewById(R.id.video);
    // Load and start the movie
    Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
    video.setVideoURI(video1);
    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
        }
    });
    video.start();

I don't want anything special in this, just a full screen of video playback which loops video till user tap back button.

A: try this
private int stopPosition;
   private VideoView splashVideoView;  <-- my Video view

in onCreate
 //video player

    if (savedInstanceState != null) {
            stopPosition = savedInstanceState.getInt("position");
        }

  @Override
    protected void onResume() {
        super.onResume();
        splashVideoView.seekTo(stopPosition);
        splashVideoView.start();
    }

// This gets called before onPause so pause video here.
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        stopPosition = splashVideoView.getCurrentPosition();
        splashVideoView.pause();
        outState.putInt("position", stopPosition);
    }

A: try this
  private int videoViewStopPosition ;

   @Override
    protected void OnPause(){
    super.onPause();
    videoViewStopPosition = vidView.getCurrentPosition();
    vidView.pause();
    }

  @Override
    protected void OnResume() {
     super.onResume();
     vidView.seekTo(videoViewStopPosition);
     vidView.start();

    }

A: I had the same issue. I found that the main reason for that was the use of FrameLayout as the parent layout. I changed it into RelativeLayout as parent layout of the VideoView and the problem get solved.

A: You need to create Video view in onResume() also. Try this:
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_video);

        setVideoBackground();
    }

    @Override
    protected void onResume() {
      super.onResume();

        setVideoBackground();
    }

   private void setVideoBackground(){
       video = (VideoView) findViewById(R.id.video);
       // Load and start the movie
       Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
       video.setVideoURI(video1);
       video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
       @Override
       public void onPrepared(MediaPlayer mp) {
       mp.setLooping(true);
    }
  });
       video.start();
}


Q: QList destructor behavior - Does call delete/free() on pointers in the list? I have a class SomeObjectList : public QList<SomeObject*>
I am creating pointers to SomeObject and sticking them in the list like so:
SomeObjectList MyClass::getSomeObjects()
{
    SomeObjectList list;

    for( int i=0; i<10; ++i )
    {
        list << new SomeObject();
    }

    return list;   // Crashes approximately here in QList::~QList
}

I'm getting a crash in the QList destructor, and it looks like free() may be being called.  I found the source code for the function (Qt 4.8.2) and it looks like this:
template <typename T>
Q_OUTOFLINE_TEMPLATE QList<T>::~QList()
{
    if (!d->ref.deref())
        free(d);
}

Does this mean that free() is being called on any pointers left in the list when the destructor is called?  I have used lists in other places without this problem.  Under what circumstances does the destructor call free()?

A: To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees.
(That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]).
That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that.


Q: Create thrift service We have a some mobile service, google maps based (mobile applications for iOS and Android). So, the server part is a Java application, which accepts connection from clients.
In one moment, without me, server was moved (relocated) to another one, and they not moved the Thrift service on the new server. Server works fine, but Android app works only via Apache Thrift. So, the Android developer provided to me the .thrift file.
Can I create service with this data? How? What do I need to read?
The part of .thrift file:
namespace cpp gb65.HelpMeService
namespace csharp gb65.HelpMeService
namespace java com.gb65.HelpMeService
namespace php com.gb65.HelpMeService

//Version
const i32       SERVICE_API_MAJOR_VERSION = 1;
const i32       SERVICE_API_MINOR_VERSION = 0;

enum Res
{
    SUCCESS                             = 0,
    EMAIL_AND_PASSWORD_NOT_FOUND        = 1,
    EMAIL_NOT_UNIQUE                    = 2,
    EMAIL_VALUE_WRONG                   = 3,
    CELLPHONE_NOT_UNIQUE                = 4,
    CELLPHONE_VALUE_WRONG               = 5,
    FIRST_NAME_VALUE_WRONG              = 6,
    LAST_NAME_VALUE_WRONG               = 7,
    PASSWORD_VALUE_WRONG                = 8,
    PHOTO_IS_TOO_LARGE                  = 9,
    SESSION_NOT_FOUND                   = 10,
    TASK_NOT_FOUND                      = 11,
    PHOTO_NOT_FOUND                     = 12,
    USER_NOT_FOUND                      = 13,
    OTHER                               = 14,
    MESSAGE_NOT_FOUND                   = 15,
    OFFER_NOT_FOUND                     = 16,
    ALREADY_FRIENDS                     = 17,
    FRIENDSHIP_OFFER_NOT_FOUND          = 18,
    _LAST                               = 19
}

If needed, I can provide all of the .thrift file code.

A: Like CORBA, Thrift has developped a neutral language.
As shown in this tutorial, you have to compile the .thrift file with
thrift -r --gen java YourFile.Thrift

After that you have to implement the client calls.


Q: Multiplicative group $\mathbb{G}_m$ is connected I wanted to show the elementary fact mentionned in the title.
Context:
Let $\mathbb{k}$ be an algebrically closed field of caracteristic 0. (I know that I don't need that much hypothesis, but these are the general hypothesis I'm working on). Then the multiplicative group $\mathbb{G}_m \simeq \mathbb{k} \backslash \{0\}$ is a connected algebraic group.
I Know for sure that $\mathbb{G}_m$ is an affine standard set (i.e. $\mathbb{G}_m \simeq D(P) = \mathbb{k} \backslash V(P)$) where $P$ is the polynomial $P(T) = T$. I have the intuition that the proof of the connectedness lies in here, but I don't know how to explicit it. Maybe a general fact that an affine standard open set is irreductible?
Could you enlight me please? Thanks in advance.
K. Y.


Q: SharePoint 2016 - Require Check Out to Edit I've set my libraries to require a check out to be able to edit a file. However when I check out a file, it opened in read only and I am unable to save the file. I have no column requirements and there's no other fields that required in the metadata. How can I get the file to not open in read only mode if I use the check out requirement?
Thank you for all your help in advance.

A: I want to confirm some information with you:
1.What’s your permission on this library? There are many possible reasons listed in this article, please compare your settings against it.
2.Does the issue only occur in the excel file? Try to open other office file (such as docx document )then check the result.
3.Change another library, set “Require check out”, then compare the result.
4.What will happen if you uncheck the “Require check out”, can you edit the file successfully without any issue?
Please feel free to post it back.


Q: ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) I'm trying to use cosine metric with Ball_tree algorithm since my data is of high dimensions. e.g.
nbrs = NearestNeighbors(n_neighbors=2,algorithm='ball_tree',metric='cosine').fit(data_seed)

However i get the following error:
ValueError: Metric 'cosine' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['ball_tree']) to get valid options. Metric can also be a callable function.

I don't understand why i cannot use cosine similarity with ball tree?

A: check valid matrics sklearn.neighbors.VALID_METRICS['ball_tree'])
and use instead of cosine


Q: Why the function strlen() returns different values for the same length of two char arrays? #include <stdio.h>
#include<string.h>

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

The output is
the size of a is 50,
the size of B is 54

But what i expect is the size of a is 50
the size of B is 50
what is the problem here?

A:
what is the problem here?

The problem is that you don't terminate your strings.
C requires strings to be null terminated:

The length of a C string is found by searching for the (first) NUL byte. This can be slow as it takes O(n) (linear time) with respect to the string length. It also means that a string cannot contain a NUL character (there is a NUL in memory, but it is after the last character, not "in" the string).

#include <stdio.h>
#include<string.h>

int main() {

    char a[50],b[50];// same sized arrays

    for(int j =0;j<50;j++){
        b[j]='b';a[j]='a';// initializing with the same number of elements
    }

    // Terminate strings
    a[49] = b[49] = 0;

    printf("the size of a is %ld,",strlen(a));
    printf("the size of B is %ld",strlen(b));

    return 0;
}

Gives the correct result.


Q: reuse a widget in GWT I have a label widget and im trying to add this widget to the multiple cells in the flex table but the widget is appearing only in the first cell. Is it possible to reuse a widget in gwt?? how?
Label l1=new Label("USER") ;
tweetFlexTable.setWidget(0,0,l1);
tweetFlexTable.setWidget(0,1,l1);

A: Every widget can only have one parent.
So you have to create as many widgets as you have cells, like this:
Label l1=new Label("USER") ;
tweetFlexTable.setWidget(0,0,l1);
Label l2=new Label("dunno") ;
tweetFlexTable.setWidget(0,1,l2);


Q: copy the same row from multiple sheets into one sheet in excel I need to copy the same row from multiple sheets into one row.
Example: I have an excel file with 5 sheets. I have to copy the 10th row (or the 15th row, or the 21th row) of every sheet in a 6th sheet, in the order of the sheets.
Thanks in advance.

A: This code will copy 7th row from all first 5 sheets into 6th sheet.
Sub row_copy()

For i = 1 To Worksheets.Count - 1

Sheets(i).Rows(7).Copy Sheets(6).Cells(i, 1)

Next i

End Sub

A: Here is a sample for 6 sheets and rows # 7:
Sub copyrow()
    Dim Nrow As Long, Nsheet As Long
    Dim i As Long

    Nrow = 7
    Nsheet = 6

    For i = 1 To Nsheet - 1
        Sheets(i).Cells(Nrow, 1).EntireRow.Copy Sheets(Nsheet).Cells(i, 1)
    Next i
End Sub

The row # 7 from the first 5 sheets will be copied into the 6th sheet.


Q: Using Reflection to get property from field I have these classes:
public class Foo
{
    public Bar bar;
}

public class Bar
{
    public List<int> Something { get; set; }
    public string Else { get; set; }
}

I have a lot of classes like Foo. They all contain exactly one field. This field, Bar in my example, will be a different type of object every time, it doesn't have to be of type Bar. Whatever object it is (Bar or otherwise), this field will always be an object that has two properties, Something and Else.
My challenge: given any object that's like Foo (with one Field that holds two properties), get the value of the two properties. Given this method:
public void DoStuff(object myObject)
{
    var asdf = myObject.GetType().GetFields().First();
}

I can get the FieldInfo for Bar. What I'm looking for is the values of Something and Else. The names of these properties never change. Whatever the type is of the Field, it will always have two properties named Something and Else that will be of the same type.
Sadly, my problem involves auto generated code, and there are no shared interfaces or base types I can easily use.

A: Using this code you can retrieve the PropertyInfos for the Something and for the Else property:
Foo myObject = new Foo { bar = new Bar() };

// the FieldInfo for Foo.bar
var barField = myObject.GetType().GetFields().First();

// the Bar instance, i.e. myObject.bar
var barValue = barField.GetValue(myObject);

var somethingProperty = barField.FieldType.GetProperty("Something", BindingFlags.Instance | BindingFlags.Public);
var elseProperty = barField.FieldType.GetProperty("Else", BindingFlags.Instance | BindingFlags.Public);

as PsiHamster noted, you can then use GetValue and SetValue to retrieve and set the values of somethingProperty and elseProperty like this:
// get the value
var somethingValue = somethingProperty.GetValue(barValue);

// set the value
somethingProperty.SetValue(barValue, new List<int>());

A: //Get Bar FieldInfo
var barFieldInfo = myObject.GetType().GetFields().First();

// Get all public instance properties info
var barProps = barFieldInfo.FieldType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

// Get Something and Else properties info
var smthPropInfo = barProps.First(prop => prop.Name == nameof(Bar.Something));
var elsePropInfo = barProps.First(prop => prop.Name == nameof(Bar.Else));

// Get values
var bar = barFieldInfo.GetValue(myObject);
var smth = smthPropInfo.GetValue(bar);
var else = elsePropInfo.GetValue(bar);


Q: Windows 7 host for Windows 7 guest on Windows Virtual PC I have Windows 7 Professional (64-bit) and Windows Virtual PC (version 6.1). I made my virtual PC and I wanted to install Windows 7 Professional (32-bit, because I read you cannot install 64-bit on Windows Virtual PC) by using ISO file. I read that there is a danger to use the same operating system for both PCs (https://www.vmware.com/support/ws5/doc/ws_disk_dualboot_sameos.html), but, because it was not clearly sad it is for all the cases, I tried and it was offering me something in the lines of burning the previous ISO, what I strictly do not want.
I cannot go lower than Windows 7, because I want to install LabVIEW on the Virtual PC and it does not have a support by lower versions (I have LabVIEW 2019 - http://www.ni.com/product-documentation/53409/en/).
I am stuck and I have no knowledge background of working with OS and there is no option for me to upgrade to a later Windows version for now.
Is it possible for me to use any other Windows 7 version (like Windows 7 Ultimate)? I really want to make sure I am making the right choice.
Thank you!

A: The VMware article you linked refers to bouncing the same instance of an operating system between a VM and a physical host.  There is no issue with running a second copy of the same OS in a VM, nor is there a problem with dual-booting between two copies of the same OS installed in different partitions on a physical host.
That being said, VirtualPC is the wrong choice here due to its lack of support for 64-bit.  The best option is to use VirtualBox, which is free to download and use, even for commercial purposes.  It fully supports 64-bit Windows 7 guests, as long as the host is 64-bit and the CPU supports hardware virtualization.
It looks like you're trying to use software that interfaces with scientific instruments.  It's been my experience that these types of devices to not work well with virtualization.  Be aware that you may not be able to virtualize it successfully depending on the device.  In that case, your second-best option would be to dual boot by installing another copy of Win7 into a separate partition.


Q: Transform a function into something that lapply works on properly (lists) I'm trying to make a list with 10 elements, each element consisting of 5 * i items drawn from a uniform distribution, i being the ith entry, and I want to use lapply.
Currently I made this function:
z_list <- list()
z_list_generator <- function(n) {
  for(i in 1:n){
  a <- runif(5 * i)
  tmp <- list(a)
  mybiglist[[i]] <- tmp
  }
  mybiglist
}

This function does give the correct outcome when I just put z_list_generator(2), it prints a list with the first element consisting of 5 elements, the second of 10 elements.
What I want to achieve is that I do lapply(some number, z_list_generator) such that it generates this same list, and such that when I do length(lapply(some number, z_list_generator)), the outcome is 'some number'.

A: Do you mean something like this?
z_list_generator  <- function(k) lapply(1:k, function(i) runif(5 * i))

set.seed(2018)    # Fixed random seed for reproducibility
z_list_generator(2)
#[[1]]
#[1] 0.33615347 0.46372327 0.06058539 0.19743361 0.47431419
#
#[[2]]
# [1] 0.3010486 0.6067589 0.1300121 0.9586547 0.5468495 0.3956160 0.6645386
# [8] 0.9821123 0.6782154 0.8060278

length(z_list_generator(2))
#[1] 2

A: Your z_list_generator is strange.
1) You do not initialise mybiglist in your function code. It probably modifies some global variable.
2) You assign mybiglist elements with another list (of lenght 1), which first element contains a sample from a uniform distrubution. Better assign a, not tmp there.


Q: django-tables2: Adding columns/fields dynamically I want to add a new field when somebody checks an option in my web page ("Add column 'external id' ")
table = IssueTable(issue_list)
show_ext = request.GET.get('show_ext', 0)
if show_ext:
    table._meta.fields = table._meta.fields + ('external_id',)

I thought doing that it was the solution but I didn't succeed. The external_id is part of the model. table._meta.fields doesnt get updated and of course I cannot see the column in the table when this one is rendered.
class IssueTable(tables.Table):

    def render_id(self, value, record):
        if record.status.upper() in ['RESOLVED', 'INVALID']:
            return mark_safe('<s>#%s</s>' % (reverse('issues.views.view', args=(record.pk,)), record.pk))
        else:
            return mark_safe('#%s' % (reverse('issues.views.view', args=(record.pk,)), record.pk))

    def render_title(self, value, record):
        return mark_safe('%s' % (reverse('issues.views.view', args=(record.id,)), value))

    class Meta(object):
        model = Issue
        fields = ('id', 'title', 'product', 'type', 'priority', 'status', 'created')
        attrs = {'class': 'table table-bordered'}
        empty_text = _('No records found')

Any ideas?


Q: C#, I want to call a method with parameters like var test = new test1.test2.Method("parameter1","parameter2") I want to call a method in a fixed structure like below in C#:
var Test = new test1.test2.test3("parameter1","parameter2");

Is this possible in C#?
Here test1 and test2 can be classes and test3 is my method name and it will return string text.
I can manage if need to remove new keyword.
I am assuming it should something like this :-
Public class test1
{
   Public class test2
   {
     Public string test3("parameter1","parameter2")
     {
       //Do something
     }
   }
}

A: Yes, you can if test3 is public structure type nested inside public structure type test2 which is nested inside test1
struct test1{
    public struct test2{
        public struct test3{
            public test3(string p1,string p2) {/*do something*/}
            //some params
        }
        //some params
    //some params
}

Also test1 and test2 could be namespaces.


Q: How to delete all files with certain suffix before file extension I was just handed a directory with some 40,000+ images, and the directory includes three versions of every file, which makes it a bear to have to transfer between servers.
I'm looking for a way using bash (OSX Terminal) to find and remove (rm) all files, for example, with _web, or _thumb on the end of the filename, just before the .jpg (or .gif, or .png, or .bmp, etc.) extension.
So, to be clear, I have the following files:
1.jpg
1_web.jpg
1_thumb.jpg
2.gif
2_web.gif
2_thumb.gif
etc.

And I only want "1.jpg", "2.gif", etc. to remain.
I've been able to rename extensions in the past, but my command-line-fu is pretty weak, and I'm at my wits end trying to figure out something that's reusable (I'm going to need to do this a couple times, as I'm working on a continuous migration script for this project).
Edit: After a bit more work on this, I found a few odd limitations of rm and xargs that I had to work around. I basically adapted the accepted answer below and ended up with:
$ find . -name '*_thumb.*' -print0 | xargs -0 rm -f
$ find . -name '*_web.*' -print0 | xargs -0 rm -f

Now I'm down to about 10,000 files - quite a savings in terms of pushing files around on the web!

A: One (relatively robust) option is to run
find . -iregex ".*\(_web\|_thumb\)\.\(jpg\|png\|bmp\)" -delete

Assuming that you don't have anything other than image files in the directory, another (simpler) option is to run
 rm *_web.* *_thumb.*

Warning: this will also delete files that are named something like my_web.file.jpg, so if you want to play safe, you'll have to add all the extensions instead of relying on .*
If you know that your extensions are always going to be 3 characters long, you can use something like *_thumb.???

A: I don't have a MAC or a UNIX terminal in front of me, but I imagine something like the following might work
rm *_web.jpg
rm *_web.jpg
rm *_thumb.gif


Q: Update jquery scrollbar after ng-repeat render Scrollbar don't see height of div because scrollbar update apply before child elements render.
How i can watch what elements is compiled?
I used watch to see when object adding to array. It works fine, but tinyscrollab_update sees empty div, because ng-repeat no compiled yet.
$scope.$watch('comments', function(){
    angular.element('#comment-list').tinyscrollbar_update('relative');
});

A: I write it in directive.
app.directive('commentsDirective', function(){
   $scope.$watch('comments', function(){
      angular.element('#comment-list').tinyscrollbar_update('relative');
   });
})


Q: CasperJS click() doesn't load new html I'm trying to use CasperJS' click() to follow a link which generates a modal on the current screen. When I query the proper selector and click it in the browser console using document.querySelector().click() it works, but even when I casper.evaluate() this it doesn't work. I found someone who had a very similar problem, but his question remains unanswered, and I am experiencing almost identical problems. casperjs button click doesn't navigate to next page
the code I'm currently using is
this.waitForSelector('div.talk-sharing__tools a.rate-button', function() {
    this.then(function() {
        this.evaluate(function() {
            document.querySelector('a.rate-button').click();
});

the page I'm trying to scrape is http://www.ted.com/talks/uri_alon_why_truly_innovative_science_demands_a_leap_into_the_unknown

A: It is really impossible to do those navigation steps with the phantomjs engine. It seems that the QtWebkit fork of phantom (version 1.9.7) is not up to the task anymore. Although your code works fine as is with slimerjs. You can comfortably install slimerjs through npm:
npm install -g slimerjs

and run your script with
casperjs --engine=slimerjs script.js

I tried several things with phantomjs that did not work. I added casper.on listeners for remote.message and resource.error, but those didn't show any errors when running the script in phantom. logLevel: "debug" also didn't show anything.
First: Using a casperjs function.
casper.thenClick("div.talk-sharing__tools a.rate-button");

Second: Trying to explicitly show the modal for the button (specific to the page).
casper.then(function(){
    var name = this.evaluate(function(){
        var modal = document.querySelectorAll(".modal-wrapper > .modal")[0];
        modal.className += " modal--show";
        return modal.className;
    });
    this.echo("name: "+name); // null
});

casper.waitUntilVisible(".modal__head__title");

Third: Let jQuery do the work.
var casper = require('casper').create({
    remoteScripts: [ "http://code.jquery.com/jquery-1.11.1.min.js" ]
});

casper.waitForSelector(selector, function() {
    this.evaluate(function() {
        jQuery("a.rate-button").click();
    });
});

A: Encountered similar issue today. After executing this.click() on start page (which I verified that PhantomJS is executing - by hooking into resource.requested and resource.received events), current page remained on start page (and it should go to clicked link page).
Solution was to update to the latest PhantomJS (1.9.8 at this moment).
Please note that I had PhantomJS 1.9.7 when the above described problem occurred.


Q: Getting binary data directly off the windows clipboard I've been beating my head against the desk for about an hour now just trying to find some way of getting say... an array of bytes off the clipboard.  Instead, all I can seem to find is information on how to get plain text from the clipboard... that's not helpful at all.
I've tried following this: Java getting bytes of clipboard
I've also tried following this: http://mrbool.com/manipulating-clipboard-content-with-java/24758
Every time I run into the silly DataFlavor being "unsupported".  Surely there's just something simple that I'm missing here... I mean... how can it support plain text, images, and java objects, but NOT have the basic functionality that just has to be under the hood of all this?
Sorry if I sound sarcastic and pissed off here... Java seems to have that effect on me. :(

A: Awt Clipboard and MIME types
InsideClipboard shows that the content's MIME type is application/spark editor
You should be able to create a MIME type DataFlavor by using the constructor DataFlavor(String mimeType, String humanReadableFormat) in which case the class representation will be an InputStream from which you can extract bytes in a classic manner...
However, this clipboard implementation is very strict on the mime type definition and you cannot use spaces in the format id, which is too bad because your editor seems to put a space there :(
Possible solution, if you have access to JavaFX
JavaFX's clipboard management is more lenient and tolerates various "Format Names" (as InsideClipboard calls them) in the clipboard, not just no-space type/subtype mime formats like in awt.
For example, using LibreOffice Draw 4.2 and copying a Rectangle shape, awt only sees a application/x-java-rawimage format whereas JavaFX sees all the same formats as InsideClipboard :

[application/x-java-rawimage], [PNG], [Star Object Descriptor (XML)], [cf3], [Windows Bitmap], [GDIMetaFile], [cf17], [Star Embed Source (XML)], [Drawing Format]

You can then get the raw data from the JavaFX clipboard in a java.nio.ByteBuffer
//with awt
DataFlavor[] availableDataFlavors = Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors();
System.out.println("Awt detected flavors : "+availableDataFlavors.length);
for (DataFlavor f : availableDataFlavors) {
    System.out.println(f);
}

//with JavaFX (called from JavaFX thread, eg start method in a javaFX Application
Set<DataFormat> contentTypes = Clipboard.getSystemClipboard().getContentTypes();
System.out.println("JavaFX detected flavors : " + contentTypes.size());
for (DataFormat s : contentTypes) {
        System.out.println(s);
}

//let's attempt to extract bytes from the clipboard containing data from the game editor
// (note : some types will be automatically mapped to Java classes, and unknown types to a ByteBuffer)
// another reproducable example is type "Drawing Format" with a Rectangle shape copied from LibreOffice Draw 4.2
DataFormat df = DataFormat.lookupMimeType("application/spark editor");
if (df != null) {
    Object content = Clipboard.getSystemClipboard().getContent(df);
    if (content instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) content;
        System.err.println(new String(buffer.array(), "UTF-8"));
    } else
        System.err.println(content);
}