text:
Q: script is send then Page is not redirect If click the submit button, then this code should execute, but this is not working.
header('Location: http://www.yourtargeturl.com'); //script api
echo '<script>window.open("'.$_SERVER['PHP_SELF'].'","_self")</script>';

A: You're mixing PHP and Javascript. The header alone will send the user to the new location in that window.
Note: PHP exists on the server, and is then sent to the browser after being generated/ran, so the javascript you have needs to be echoed to the browser to do anything.

A: Your header('Location: http://www.yourtargeturl.com'); will redirect the page, and make the browser load that page instead.
Everything after that is ignored.  So, your JavaScript window.open is never written to the page and ran.


text:
Q: React Native ScrollView TypeError: undefined is not an object (evaluating 'this._subscribableSubscriptions.forEach') I'm building React Native app with Expo. It works fine on my Android device via Expo application. But I have the error after I've built apk via exp build:android command.
TypeError: undefined is not an object (evaluating 'this._subscribableSubscriptions.forEach')
This error is located at:
  in ScrollView
  in RCTView
  in r
  in Connect(r)
  in n
  in t
  in r
  in RCTView
  in RCTView
  in t

Problem is inside ScrollView. It is gone if I remove ScrollView. Here is my code snippet.
class Main extends Component {
state = {
    refreshing: false
};

renderCurrencies() {
    if (!Object.values(this.props.currencies).length) {
        return <View />;
    }

    return Object.values(this.props.currencies).map(item => {
        return (
            <CurrencyRow
                key={item.code}
                code={item.code}
                title={item.title}
            />
        );
    });
}

onRefresh = () => {
    Object.values(this.props.currencies).map(item => {
        this.props.sellBuyFetch(item.code);
    });
};

render() {
    return (
        <View style={styles.container}>
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this.onRefresh}
                    />
                }
            >
                {this.renderCurrencies()}
            </ScrollView>
        </View>
    );
}
}

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

A: This bug is caused by uglify-es 3.3.X which is used when building a release version.
Add this block to your package.json:
"resolutions": {
  "uglify-es": "3.2.2"
}
I tried both publishing on Expo and building a standalone app and it's working like a charm now.

A: Had same issue.
Way to resolve this:
change
this._subscribableSubscriptions.forEach(

to
this._subscribableSubscriptions && this._subscribableSubscriptions.forEach(

in that file:
YOUR_PROJECT/node_modules/react-native/Libraries/Components/Subscribable.js

A: Thanks, @kykapetuk and @chillypenguin. Looks like this React Native bug https://github.com/facebook/react-native/issues/17348. In case with Expo we can't use the @kykapetuk workaround, cause APK builds on the Expo server. The current workaround for me - don't use Expo. Probably, the possible solution here to use another version react-native library.

A: I think your code would be much simpler with a FlatList, however your problem might in this method: renderCurrencies()
Try to change it to this:
renderCurrencies = () => {
Maybe is not finding the props. Do you see any other issue in the log? If that does not help, debug the issue and find if (this) have that method inside it.
Note: I havewn't worked with Expo yet.

A: May be a bug in React Native 0.5.1.
I fixed it by evaluating variable this._subscribableSubscriptions on line 33 on react native file project/node_modules/react-native/Libraries/Components/Subscribable.js
Changing this:
this._subscribableSubscriptions.forEach(

To this:
this._subscribableSubscriptions && this._subscribableSubscriptions.forEach(

https://github.com/facebook/react-native/issues/17348

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate the intersection point between an infinite line and a line segment? Basically, a function that fulfills this signature:
function getLineIntersection(vec2 p0, vec2 direction, vec2 p2, vec2 p3) {
   // return a vec2
}

I have looked around at existing solutions, and they all seem to deal with how to find the intersection between two line segments, or between two infinite lines. Is there a solution for this problem where the line has an initial position, an angle, and needs to determine if it intersects with a line segment? Basically, something like this:

There should be one line segment that starts in a location and has a unit direction, and another line segment that is just a line connected by two points. Is this possible, and if so, is there a good way of calculating the intersection point, if it exists?

A: If you've a endless line which is defined by a point P and a normalized direction R and a second endless line, which is defined by a point Q and a direction S, then the intersection point of the endless lines X is:

alpha ... angle between Q-P and R
beta  ... angle between R and S

gamma  =  180° - alpha - beta

h  =  | Q - P | * sin(alpha)
u  =  h / sin(beta)

t  = | Q - P | * sin(gamma) / sin(beta)

t  =  dot(Q-P, (S.y, -S.x)) / dot(R, (S.y, -S.x))  =  determinant(mat2(Q-P, S)) / determinant(mat2(R, S))
u  =  dot(Q-P, (R.y, -R.x)) / dot(R, (S.y, -S.x))  =  determinant(mat2(Q-P, R)) / determinant(mat2(R, S))

X  =  P + R * t  =  Q + S * u

If you want to detect if the intersection is on the lien, you need to compare the distance of the intersection point with the length of the line.
The intersection point (X) is on the line segment if t is in [0.0, 1.0] for X = p2 + (p3 - p2) * t
vec2 getLineIntersection(vec2 p0, vec2 direction, vec2 p2, vec2 p3)
{
    vec2 P = p2;
    vec2 R = p3 - p2;
    vec2 Q = p0;
    vec2 S = direction;

    vec2 N = vec2(S.y, -S.x);
    float t = dot(Q-P, N) / dot(R, N);

    if (t >= 0.0 && t <= 1.0)
        return P + R * t;

    return vec2(-1.0);
}

A: Start with the intersection of two infinite lines, expressed in parametric form (e.g., A + tp, where A is the "start point", p is the direction vector and t is a scalar parameter). Solve a system of two equations to get the two parameters of the intersection point.
Now if one of your lines is really a segment AB, and B = A + p (i.e., the direction vector goes from A to B), then if the parameter t is between 0 and 1, the intersection lies on the segment.


text:
Q: How can I convert a date to this particular string representation? LblExpirydate.Text = dataReader(0).ToString()

Output in asp.net form  : 01/05/2013 12:00:00 AM
I want to change format to (01/05/2013)
Notes : My database
Column : Expirydate
data type : Date

A: You can format the string using .ToString() in several different ways:
dataReader(0).ToString("dd/MM/yyyy");

dataReader(0).ToString("d");

The second option is better as it will format using the current locale. See this MSDN article for more info:
http://msdn.microsoft.com/en-gb/library/az4se3k1.aspx

A: DateTime thisDate1 =  DateTime.Now;
 Label1.Text =thisDate1.ToString("MM/dd/yyyy") ;

output:
03/30/2013
 DateTime thisDate1 =  DateTime.Now;
    Label1.Text =thisDate1.ToString("MM-dd-yyyy") ;

output:
03-30-2013
DateTime thisDate1 =  DateTime.Now;
Label1.Text =thisDate1.ToString("MM,dd,yyyy") ;

output:
03,30,2013
DateTime thisDate1 =  DateTime.Now;
Label1.Text =thisDate1.ToString("MMMM,dd,yyyy") ;

output:
March,30,2013
and so on...


text:
Q: Vagrant/virtualbox no SSH connection and timeout (Windows) I a trying to setup this machine: https://github.com/ByteInternet/hypernode-vagrant
When I do vagrant up i get following error: Timed out while waiting for the machine to boot.
Full context of the error:
$ vagrant up
Bringing machine 'hypernode' up with 'virtualbox' provider...
==> hypernode: Will use PHP 7. If you want PHP 5.5 instead change the php version in local.yml.
==> hypernode: Checking if box 'hypernode_php7' is up to date...
==> hypernode: Clearing any previously set forwarded ports...
==> hypernode: Clearing any previously set network interfaces...
==> hypernode: Preparing network interfaces based on configuration...
hypernode: Adapter 1: nat
hypernode: Adapter 2: hostonly
==> hypernode: Forwarding ports...
hypernode: 80 (guest) => 8080 (host) (adapter 1)
hypernode: 3306 (guest) => 3307 (host) (adapter 1)
hypernode: 22 (guest) => 2222 (host) (adapter 1)
==> hypernode: Running 'pre-boot' VM customizations...
==> hypernode: Booting VM...
==> hypernode: Waiting for machine to boot. This may take a few minutes...
hypernode: SSH address: 127.0.0.1:2222
hypernode: SSH username: vagrant
hypernode: SSH auth method: private key
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period.

If you look above, you should be able to see the error(s) that
Vagrant had when attempting to connect to the machine. These errors
are usually good hints as to what may be wrong.

If you're using a custom box, make sure that networking is properly
working and you're able to connect to the machine. It is a common
problem that networking isn't setup properly in these boxes.
Verify that authentication configurations are also setup properly,
as well.

If the box appears to be booting properly, you may want to increase
the timeout ("config.vm.boot_timeout") value.

When I boot the VM manually, I can see the networking is not working as it should be. There is no connection. When I change the VM's settings to bridged network the networking does work. But the vagrant is configured as NAT. So any changes I make in the settings or in the vagrant file seem to be resetting back.
I tried Vagrant 1.9.3, 1.9.2 and 1.9.0 on two different PC's. I am using Virtualbox 5.1.18. When I filter down the logs with "NAT" is see following errors (this is not the complete log, only a small portion):
00:00:00.575454 SUP: Loaded VMMR0.r0 (C:\Program     Files\Oracle\VirtualBox\VMMR0.r0) at 0xfffff80c897b0000 - ModuleInit at     fffff80c897d3590 and ModuleTerm at fffff80c897d3a80 using the native ring-0 loader
00:00:01.681747 Driver = "NAT" (cb=4)
00:00:01.962037 SUP: Loaded VBoxDDR0.r0 (C:\Program Files\Oracle\VirtualBox\VBoxDDR0.r0) at 0xfffff80c898d0000 - ModuleInit at         0000000000000000 and ModuleTerm at 0000000000000000 using the native ring-0 loader
00:00:02.196495 NAT: Guest address guess set to 10.0.2.15 by initialization
00:00:02.204465 NAT: DNS#0: 192.168.178.1
00:00:02.271317 NAT: Failed to redirect TCP 127.0.0.1:2222 -> 0.0.0.0:22 (Unknown error)
00:00:02.271732 NAT: Failed to redirect TCP 0.0.0.0:3307 -> 0.0.0.0:3306 (Unknown error)
00:00:02.272033 NAT: Failed to redirect TCP 0.0.0.0:2200 -> 0.0.0.0:80 (Unknown error)
00:00:09.976199 NAT: Link up
00:00:39.428974 NAT: DHCP offered IP address 10.0.2.15
00:00:39.429404 NAT: DHCP offered IP address 10.0.2.15
00:03:02.167191 NAT: DHCP offered IP address 10.0.2.15
00:03:02.167820 NAT: DHCP offered IP address 10.0.2.15
00:07:58.531621 NAT: Zone(nm:mbuf_cluster, used:0)
00:07:58.532221 NAT: Zone(nm:mbuf_packet, used:0)
00:07:58.532232 NAT: Zone(nm:mbuf, used:1)
00:07:58.532419 NAT: Zone(nm:mbuf_jumbo_pagesize, used:0)
00:07:58.532961 NAT: Zone(nm:mbuf_jumbo_9k, used:0)
00:07:58.533255 NAT: Zone(nm:mbuf_jumbo_16k, used:0)
00:07:58.533424 NAT: Zone(nm:mbuf_ext_refcnt, used:0)
00:07:58.536529 Changing the VM state from 'DESTROYING' to 'TERMINATED'

How can I solve or debug this?
UPDATE
Last couple of days I also retried with different version of virtualbox and Vagrant listed below without any results:

*

*Virtualbox 5.0.18

*Virtualbox 5.0.20

*Virtualbox 5.0.36

*Vagrant 1.9.3

I also tried another box, which has the same problem. So it seems it's not the box but the host.
Furthermore I tried a setup on a Windows 7 machine with exactly the same results. I think I am missing something in the configuration but I don't know what since there is not a definitive guide to get this working on a Windows machine.
UPDATE 2: Could it be possible the machines I try this on do not support this kind of a setup? I tried looking for virtualizations options in the BIOS.
UPDATE 3: When I do ssh -v 127.0.0.1 -p 1222 from my host to the guest I get following error. SSH service is up and running on the guest. I checked with sshd service status.
$ ssh -v 127.0.0.1 -p 1222
OpenSSH_7.3p1, OpenSSL 1.0.2k  26 Jan 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to 127.0.0.1 [127.0.0.1] port 1222.
debug1: connect to address 127.0.0.1 port 1222: Connection refused
ssh: connect to host 127.0.0.1 port 1222: Connection refused

UPDATE 4: I cannot ping any internet IP's or domains from the guest machine.
UPDATE 5: SOLVED! Switched to Linux for quite a while now. Best decision ever :D

A: First of al, changing the first interface to NAT is normal behavior. It's a requirement in order to make vagrant work.
You can check two things:
1) preferences > network > nat-network. (settings should be like this):
network settings
2) make sure you're virtual cable is connected
cable connected
3) maybe you can try another vagrant box.

A: When I have this error on Windows 10 Pro:
    ...
    homestead: SSH auth method: private key
Timed out while waiting for the machine to boot. ...
...

I have found that all I need to do is have the VirtualBox GUI open and the VM selected while running this on a command line:
vagrant reload --provision
If the GUI is closed, it repeatedly times out that throws the error above.
If the GUI is opened, then the process continues as normal with no errors, and everything starts working.
I have also found that sometimes after automatic Windows restarts, my network adapter does not have the VirtualBox NDIS6 Bridged Networking Driver installed, and that can also cause this error.
This can be fixed by opening the network connection properties and clicking Install -> Service -> Oracle Corporation -> VirtualBox NDIS6 Bridged Networking Driver to install the driver.

It should just appear in the list without having to go through a driver install, but if you somehow never had that driver installed before, then this might put you through a driver install process.
On Windows, the typical path to the folder with that driver in it is below. You probably won't have to manually install anything, but in case you do, open that folder and then Right-Click -> Install the VBoxNetFlt.inf file.
%ProgramFiles%\Oracle\VirtualBox\drivers\network\netflt


text:
Q: iOS Instagram Tags Text Layout? How Is It Done? I've always been curious how instagram gets it's tags to layout fluidly and wanted to know what goes behind this functionality? To me, it seems like they're using UIButton's and just calculating placement of the buttons line by line? Is that right? Or is there a simpler method of doing it without having to manual calculate the placement of each tag line by line / or side by side given that multiple tag's width's fit together?
Or, are they using NSAttributedStrings?
Any ideas?
Here's an example of the layout I'm referring to.

A: Well, I'm currently working on NSAttributedString and UITextView to get all this working, and my current code can do it. So I'm going to explain a possible version of doing this.
Here are the tips and big steps, with iOS7:
NSAttributedString, in iOS7 has a new attribute : NSLinkAttributeName. You can add it to your NSAttributedString, and with a detection method (combining: how to make #key and @key clickable in IOS7 and Get word from tap in UITextView) you can manage it. That's for the general way of doing it. For previous version, you'll have to do a little more of work, but keeping this general idea.
But since, it only for hashtags, since you can detect the world behind the tap, you can do this: Detect what word has been tapped (see previous links), detect if this word has an hashtag, and if yes, you can do whatever action you want. You can play with a NSRegularExpression to know where are the hashtags, and know when to "color" them.

A: Here is a simplified way to do it using UITextView and NSAttributedString:

*

*Use regular expressions to get character ranges for links.

*Add link styling to the matched ranges.

*Add custom attribute to range that references tap action to execute.

*On touch, if index of character is inside a matched range, change the link formatting to highlight it and run the associated tap action.

How to get index of character at location in iOS7:
- (NSUInteger) getCharIndexAt: (CGPoint) location
{
    NSLayoutManager *layoutManager = self.layoutManager;
    NSUInteger characterIndex = NSNotFound;
    characterIndex = [layoutManager characterIndexForPoint:location inTextContainer:self.textContainer fractionOfDistanceBetweenInsertionPoints:NULL];

    return characterIndex;
}

Also check out WWDC 2013 intro to TextKit Demo
ios7 text utilities


text:
Q: E/RecyclerView: No adapter attached;, data does not want to appear in the fragment home,
E/RecyclerView: No adapter attached; skipping layout

Activity_agent.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AgentActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recylcerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="745dp"
    tools:layout_editor_absoluteY="-51dp" />
</RelativeLayout>

moole.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">
    <TextView
        android:id="@+id/idagent"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:text="1"
        android:textSize="30dp"
        android:singleLine="true" />
    <TextView
        android:id="@+id/nomagent"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:layout_toRightOf="@+id/idagent"
        android:text="mohamed"
        android:textSize="30dp"
        android:textColor="@color/design_default_color_primary_dark"
        android:singleLine="true" />
</RelativeLayout>

</android.support.constraint.ConstraintLayout>

Agent.java
package com.exemple.android.espacemembre;

public class Agent {
    private int idagent;
    private String nomagent;
    private boolean disponible;
    private int id_admin;

public Agent(int id_agent,String nom_agent) {
    this.idagent=id_agent;
    this.nomagent=nom_agent;
 //   this.disponible=disponible;
  //  this.id_admin=id_admin;
}
public int getIdagent(){
    return idagent;
}
public String getNomagent(){
    return nomagent;
}

}

AgentActivity.java
package com.exemple.android.espacemembre;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AgentActivity extends AppCompatActivity {

//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
    private static final String URL_AGENT =
     "http://192.168.43.174/php_agent.php";

    //a list to store all the products
    List<Agent> agentList;
      //the recyclerview
   public  RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agent);
    //getting the recyclerview from xml
    recyclerView = findViewById(R.id.recylcerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    //initializing the productlist
    agentList = new ArrayList<>();

    //this method will fetch and parse json
    //to display it in recyclerview
    loadAgent();

}
public void loadAgent(){
    /*
     * Creating a String Request
     * The request type is GET defined by first parameter
     * The URL is defined in the second parameter
     * Then we have a Response Listener and a Error Listener
     * In response listener we will get the JSON response as a String
     * */
    StringRequest stringRequest=new StringRequest(Request.Method.GET,
URL_AGENT, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONArray array = new JSONArray(response);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject agent = array.getJSONObject(i);
                    agentList.add(new Agent(
                            agent.getInt("idagent"),
                            agent.getString("nomagent")
                    ));

                }
                AgentAdapter adapter = new
AgentAdapter(AgentActivity.this, agentList);
                recyclerView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    Volley.newRequestQueue(this).add(stringRequest);
}

AgentFragment.java
package com.exemple.android.espacemembre;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class AgentFragment extends Fragment {
    View rootView;
    public AgentFragment(){

}
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
       ViewGroup container, @Nullable Bundle savedInstanceState) {

          View rootView=
         inflater.inflate(R.layout.activity_agent,container,false);

   return rootView;

}
}

AgentAdapter
      package com.exemple.android.espacemembre;

    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;

     import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;

   import java.util.List;

 public class AgentAdapter extends
 RecyclerView.Adapter<AgentAdapter.AgentViewHolder> {

private Context g_ctx;
private List<Agent> agentList;

public AgentAdapter(Context g_ctx,List<Agent>agentList){
    this.g_ctx=g_ctx;
    this.agentList=agentList;
}

@NonNull
@Override
public AgentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
  viewType) {
   // LayoutInflater inflater = LayoutInflater.from(g_ctx);
   // View view = inflater.inflate(R.layout.moole, null);
      View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.moole, parent,
false);

   /* @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
        View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.ingredient_row,
parent, false);
        return new ViewHolder(v);*/
    return new AgentViewHolder(v);
}
@Override
public void onBindViewHolder(AgentViewHolder holder, int position) {
    //getting the product of the specified position
    Agent agent = agentList.get(position);
    //binding the data with the viewholder views
    holder.idagent.setText(String.valueOf(agent.getIdagent()));
    holder.nomagent.setText(agent.getNomagent());

}
@Override
public int getItemCount(){
    return agentList.size();
}
class AgentViewHolder extends RecyclerView.ViewHolder{

    TextView idagent ,nomagent;
    public AgentViewHolder(View itemView){
        super(itemView);
        idagent=itemView.findViewById(R.id.idagent);
        nomagent=itemView.findViewById(R.id.nomagent);

    }

}
}

agent.php
<?php

/*
* Created by Belal Khan
* website: www.simplifiedcoding.net
* Retrieve Data From MySQL Database in Android
*/

//database constants
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'espace_membre');

//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
    echo "Failed to connect to agent: " . mysqli_connect_error();
    die();
}

//creating a query
$stmt = $conn->prepare("SELECT idagent ,nomagent FROM agent;");

//executing the query
$stmt->execute();

//binding results to the query
$stmt->bind_result($idagent, $nomagent);

$agent = array();

//traversing through all the result
while($stmt->fetch()){
    $temp = array();
    $temp['idagent'] = $idagent;
    $temp['nomagent'] = $nomagent;

    array_push($agent, $temp);
}

//displaying the result in json format
echo json_encode($agent);
?>`

E/RecyclerView: No adapter attached; skipping layout

data does not want to appear in the fragment
je veut realser une application de gestion dorder de mission pour une entreprise je doit recuperer les information des agents

A: You have to set AgentAdapter after setting LayoutManager, and then refresh the data set onResponse where you were setting adapter.
To refresh the data set just make a small function inside your AgentAdapter like:
public void refreshAgents(List<Agent> agentList){
     this.agentList.clear()
     this.agentList = agentList;
     notifyDataSetChanged()
}

A:
E/RecyclerView: No adapter attached;, data does not want to appear in the fragment home,

It's because your didn't add any data to your fragment but to your Activity.

E/RecyclerView: No adapter attached; skipping layout

It's because you never attached the adapter to your RecyclerView inside your Activity. You need to initialize your adapter first then attach it to your RecyclerView, with something like this:
List<Agent> agentList;

public  RecyclerView recyclerView;

// declare the adapter so it can be re-accessed later.
private AgentAdapter mAgentAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agent);

    //getting the recyclerview from xml
    recyclerView = findViewById(R.id.recylcerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    //initializing the productlist
    agentList = new ArrayList<>();

    // initialize the adapter
    mAgentAdapter = new AgentAdapter(this, agentList);

    // attach the adapter to the RecyclerView
    recyclerView.setAdapter(mAgentAdapter);

    ...
}

Then, whenever you change the whole list for the adapter tell it to refresh:
// sample of adding data from your backend.
for (int i = 0; i < array.length(); i++) {
    JSONObject agent = array.getJSONObject(i);
    agentList.add(new Agent(
            agent.getInt("idagent"),
            agent.getString("nomagent")
    ));

}

// update the adapter.
mAgentAdapter.notifyDataSetChanged();


text:
Q: Perl how to join all threads My code is like below:
use threads;
use threads::shared;
use Thread::Queue;

my $q = Thread::Queue->new();
my @threads = ();
my $run :shared = 1;

$SIG{'TERM'} = sub {
    $run = 0;
    $q->enqueue('exit');
    foreach(@threads){
        $_->join();
    }
};

push @threads, threads->create(proc1);
push @threads, threads->create(proc2);

sub proc1 {

    while($p = $q->dequeue()){
        if($p eq 'exit'){
            last;
        }
        .....
    }
    $q->end();
    threads->exit();
}

sub proc2 {
    while($run){
       .....
    }
}

On TERM signal im trying to wait till all threads are ended. However, whenever I pass TERM signal my program gets terminated with an error
Segmentation fault

How to fix this ?

A: Assuming threads->create(proc1) even works (and that would only be because you didn't use use strict; as you should), then your program exits immediately after creating the threads. You need to have your main thread wait for the children threads to finish.
Fixing that problem (and applying some simplifications) results in the following:
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Queue 3.01 qw( );

my $q = Thread::Queue->new();
my $run :shared = 1;

$SIG{TERM} = sub {
    print("Received SIGTERM. Shutting down...\n");
    $run = 0;
    $q->end();
};

print("$$\n");

threads->create(\&proc1);
threads->create(\&proc2);

$_->join() for threads->list();

sub proc1 {
    while(my $p = $q->dequeue()) {
        sleep 1;  # Placeholder
    }
}

sub proc2 {
    while($run){
        sleep 1;  # Placeholder
    }
}

I don't get a seg fault, but the program doesn't exit either. The signal handler is simply not called. It's because Perl is waiting for join to return before calling the signal handler. You can solve that by polling the list of joinable threads. In other words, replace
$_->join() for threads->list();

with
my $running_threads = 2;
while ($running_threads) {
    for my $thread (threads->list(threads::joinable)) {
        $thread->join();
        $running_threads--;
    }

    sleep 1;
}


text:
Q: TYPO3 10 Solr scheduler baseVariants domain name Scheduler task "Index Queue Worker (solr)" works correctly for baseVariant testing.mydomain.nl when started manually.
However when the task is running automatically www.mydomain.nl is used. This I can see in the TYPO3 solr log under /var/log
How to configure using the corresponding baseVariant domain name?

A: You probably have a condition for the baseVariant checking for an environment variable (like TYPO3_CONTEXT) which is set using the webserver configuration or .htaccess. That means they're not set when the script is run through cronjob (or CLI). You can set the variable by adding VARIABLE=value before the command, so for example: TYPO3_CONTEXT=Development /path/to/my/htdocs/vendor/bin/typo3 scheduler:run


text:
Q: Semi-Transparent Wizard Form I was working on an Inno Setup design when I faced this mighty question in front of me...How to make the Wizard form semi-transparent?
I know Delphi too so I'm thinking if there is any way we can use FMX's Fill.Color and transparency=true with Inno Setup?
I'm currently using this function for Wizard creation:
procedure CreateWizardForm;
begin
  with WizardForm do begin
    BorderStyle:=bsNone;
    ClientWidth:=900;
    ClientHeight:=540;
    InnerNotebook.Hide;
    OuterNotebook.Hide;
    Center;
    Bevel.Hide;
    NextButton.Width:=0;
    CancelButton.Width:=0;
  end;

  Form:=ImgLoad(WizardForm.Handle,ExpandConstant('{tmp}')+'\form.png',0,0,900,540,True,True);
end;

Regards
Ramiro

A: There is Inno Setup plug-in as for NSIS called IsWin7 or MegaFileUpload.
It works for Windows Vista and Windows 7 - both systems support Aero effects.
Keep in mind that iswin7.dll is non-official.
Sample:
[Files]
Source: ".\ISWin7.dll"; DestDir: "{tmp}"; Flags: dontcopy nocompression

[Code]
procedure iswin7_add_glass(Handle:HWND; Left, Top, Right, Bottom : Integer; GDIPLoadMode: boolean);
   external 'iswin7_add_glass@files:iswin7.dll stdcall';
procedure iswin7_add_button(Handle:HWND);
   external 'iswin7_add_button@files:iswin7.dll stdcall';
procedure iswin7_free;
   external 'iswin7_free@files:iswin7.dll stdcall';

procedure InitializeWizard();
begin
   iswin7_add_button(WizardForm.BackButton.Handle);
   iswin7_add_button(WizardForm.NextButton.Handle);
   iswin7_add_button(WizardForm.CancelButton.Handle);
   iswin7_add_glass(WizardForm.Handle, 0, 0, 0, ScaleY(47), True);
end;

procedure DeinitializeSetup();
begin
    iswin7_free;
end;

A: Is the feature you are trying to achieve called Aero (from Windows Vista)?
I think this is not possible to do in pure Inno Setup.

Check this NSIS plug-in: http://nsis.sourceforge.net/Aero_plug-in.
It is open source and uses some Windows API functions -- for inspiration.


text:
Q: fit exponential cdf to data python? I am trying to fit an exponential CDF to my data to see if it is a good fit/develop an equation from the fit, but am not sure how since I think scipy.stats fits the PDF, not the CDF. If I have the data below:
eta = [1,0.5,0.3,0.25,0.2];
q = [1e-9,9.9981e-10,9.9504e-10,9.7905e-10,9.492e-10];

How do I fit an exponential CDF to the data? Or how do find the distribution that fits the data the best?

A: You can define a general exp function, and use curve_fit from scipy.optimize:
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def exp_func(x, a, b, c):
    return a * np.exp(-b * x) + c

eta = np.array([1,0.5,0.3,0.25,0.2])
cdf = np.array([1e-9,9.9981e-10,9.9504e-10,9.7905e-10,9.492e-10])
popt, pcov = curve_fit(exp_func, eta, cdf)
plt.plot(eta, cdf)
plt.plot(eta, exp_func(eta, *popt), 'r-', label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
plt.legend()
plt.show()

And you'll get an exp function which is very similar to your values:

From the fitted parameters, you can see the function is y=np.exp(-19.213 * x).
* Update *
If you want to make sure this is really a CDF function, you'll need to calculate the pdf (by taking the derivative):
x = np.linspace(0, 1, 1000)
cdf_fit = exp_func(x, *popt)
cdf_diff = np.r_[cdf_fit[0], np.diff(cdf_fit)]

You can do a sanity check:
plt.plot(x, np.cumsum(cdf_diff))

And then use scipy to fit the pdf to an exponent distribution:
from scipy.stats import expon
params = expon.fit(cdf_diff)
pdf_fit = expon.pdf(x, *params)

I must warn you the something doesn't sum up. pdf_fit doesn't align with cdf_diff. Maybe your CDF isn't a real distribution function? The last value of a CDF should be 1.


text:
Q: SQL return only rows where value exists multiple times and other value is present I have a table like this in MS SQL SERVER
+------+------+
|  ID  | Cust |
+------+------+
|   1  |  A   |
|   1  |  A   |
|   1  |  B   |
|   1  |  B   |
|   2  |  A   |
|   2  |  A   |
|   2  |  A   |
|   2  |  B   |
|   3  |  A   |
|   3  |  B   |
|   3  |  B   |
|   3  |  C   |
|   3  |  C   |
+------+------+

I don't know the values in column "Cust" and I want to return all rows where the value of "Cust" appears multiple times and where at least one of the "ID" values is "1".
Like this:
+------+------+
|  ID  | Cust |
+------+------+
|   1  |  A   |
|   1  |  A   |
|   1  |  B   |
|   1  |  B   |
|   2  |  A   |
|   2  |  A   |
|   2  |  A   |
|   2  |  B   |
|   3  |  A   |
|   3  |  B   |
|   3  |  B   |
+------+------+

Any ideas? I can't find it.

A: You may use COUNT window function as the following:
SELECT ID, Cust
  FROM
  (
    SELECT ID, Cust,
       COUNT(*) OVER (PARTITION BY Cust) cn,
       COUNT(CASE WHEN ID=1 THEN 1 END) OVER (PARTITION BY Cust) cn2
   FROM table_name
  ) T
WHERE cn>1 AND cn2>0
ORDER BY ID, Cust

COUNT(*) OVER (PARTITION BY Cust) to check if the value of "Cust" appears multiple times.
COUNT(CASE WHEN ID=1 THEN 1 END) OVER (PARTITION BY Cust) to check that at least one of the "ID" values is "1".
See a demo.


text:
Q: How to remove the mail built-in icon from content_main I want to remove the mail icon.
I can't find any way to do it.
Below is the default icon that i see when i start a 'Blank Activity' on the Android Studio
screenshot attached

A: In the activity_main.xml you have a layout like this:

You can:

*

*remove the FloatingActionButton (also in the MainActivity!)

*change the entire layout

A: In MainActivity Class, remove the below code
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });


text:
Q: How not to add duplicate items to an asp:ListBox function add_items() {
        var gdOption = document.createElement("OPTION");

        for (var i = 0; i < document.getElementById("ListBox_AllItems").length; i++) {
            if (document.getElementById("ListBox_AllItems").options[i].selected == true) {

                gdOption.text = document.getElementById("ListBox_AllItems").options[i].text;
                gdOption.value = document.getElementById("ListBox_AllItems").options[i].value;
                document.getElementById("ListBox_ItemsInvolved").add(gdOption);
                document.getElementById("ListBox_AllItems").removeChild(document.getElementById("ListBox_AllItems").childNodes[i]);
            }
        }
    }

I have the above JavaScript code that adds items to ListBox_ItemsInvolved on the click of a button like below.
<p>
 <input class="btnAction" title="Add Items involved" style="width: 65px; height: 19px" onclick="add_items();" type="button" value="Add">
</p>

Problem: If the button is clicked twice, the item is added twice to the listbox. What is the best way of making sure that an item is added only once. If an item has already been added, it should not be added again even if the button is clicked several times.
I have tried below code but that isn't working.
 if (!document.getElementById("ListBox_ItemsInvolved").options[i].text.length > 0) {
                    document.getElementById("ListBox_ItemsInvolved").add(gdOption);
     }


text:
Q: Static methods requiring var Ok, i'm stuck on this, why don't i get what i need?
class config
{

    private $config;

    # Load configurations
    public function __construct()
    {
        loadConfig('site'); // load a file with $cf in it
        loadConfig('database'); // load another file with $cf in it
        $this->config = $cf; // $cf is an array
        unset($cf);
    }

    # Get a configuration
    public static function get($tag, $name)
    {
        return $this->config[$tag][$name];
    }
}

I'm getting this:
Fatal error: Using $this when not in object context in [this file] on line 22 [return $this->config[$tag][$name];]

And i need to call the method in this way: config::get()...

A: public static function get
need to be
public function get
You can't use $this in static methods.
EDITED
I could do this, but I'm not sure if it's the best design for you.
class config
{

    static private $config = null;

    # Load configurations
    private static function loadConfig()
    {
        if(null === self::$config)
        {
            loadConfig('site'); // load a file with $cf in it
            loadConfig('database'); // load another file with $cf in it
            self::$config = $cf; // $cf is an array
        }
    }

    # Get a configuration
    public static function get($tag, $name)
    {
        self::loadConfig();
        return self::$config[$tag][$name];
    }
}

A: The problem is that you're Using $this when not in object context... Declaring a method as static removes the possibility to use the $this-reference inside the method.

A: There is no $this reference inside static methods as they belong to the class. Static methods can only access static members, so if it is important that get() is a static method, make $this->config a static member and return self::$config[$tag][$name]. However, the static keyword makes methods accessible without an instance of the class and I'd advise either making get() non-static, or making the class a singleton (depending on how you wish to use it).


text:
Q: What does 'to hook up later' mean? My classmate asked me if I want to 'hook up' later.
What does that mean?
Does he mean to meet up and study? Or something else, like meeting up for food?
I have never heard of hooking up before, please explain me.

A: To expand a bit on Ustanak's answer, I would say that the exact meaning depends on the context.
Given that you refer to this person as a classmate, I hope he's asking to meet later to discuss something pertaining to your academic studies.  However, a few other possibilities might exist:
He could be romantically interested you, and casually asking you on a date (perhaps to go get coffee together).
He could be crudely propositioning you for sexual relations (I hope this isn't the case!).  A somewhat flippant way to say that you had sex with someone is to say that you "hooked up with him/her", and you might refer to that person as "a hookup" (many people consider this disrespectful, as it implies that the only interest you had in that person was sexual, and that you don't intend to pursue a relationship).
From what you've said, I think the first case is most likely, but if you're learning English, it can be difficult to pick up on the cues that would indicate romantic (or other) intent.

A: hook up = meet someone.
In this case, your mate asked if you want to meet her/him later. (The activity is unknown, the only thing you get for sure is that you'll meet her/him.)


text:
Q: What could be the cause of an "UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY" error? A couple of days ago I got the error:
UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY

when rebooting my 20.04 machine. The last thing I did before rebooting was running some game in Steam, the game tried to open a link in a web browser and that failed and I think the game crashed, iirc. After that, Steam just gave me a black screen, so I rebooted and got this error.
I am not asking how to reboot successfully, since I fscked manually, but what could be the cause? I am ruling out a hard drive error since the SSD is only a year old and SMART seems to be fine:

(By the way, I am not taking that 99C temp as accurate, it has always said that, must be a bug in reading the temp of the drive).
The partition that gave the error was /dev/sdc6, which is /home.
What could be the cause of the UNEXPECTED INCONSISTENCY error? I am guessing Steam did something, but is it possible that it would cause such an error?


text:
Q: Large amount of static values in linked selects! - ASP.NET MVC I have a conceptual problem.
For an ASP.NET MVC / C# website (although the exact technology may not be that important) I have 2 linked drop downs (html select) with Countries and Cities of a continent.
These are currently kept in 2 database tables and as you imagine the Cities table has round 10 000 records.
The current functionality is:
- initially the country select is populated.
- the user selects a country, an ajax request goes to the server, retrieves the cities for that country_id and populates the second (cities) select.
Sometimes it gets a bit slow as you might imagine, and since these are in the end static values (the lists will not change) what will be the best way to treat this situation?

A: I would recommend implementing it,  using the jquery chosen plugin Chosen
plugin that can be used to filter, results, but since you are getting such a big response you can incorporate a search filter functionality with ajax as shown here,  Jquery Ajax-Chosen


text:
Q: Using Node.js to cluster millions of points on the server side Situation:
I am testing out different visualization techniques for web mapping a data set that has about 2.5 million points and a lengthy set of attributes (almost 30 fields). So its quite a large file. I want to try clustering this data. I know sending that much data to a client will either result in a time-out or crash so I've been look at other methods and found the supercluster with mapbox. I used the top rated answer in this question to build a web map with Leaflet that handles about 500 000 points pretty well (approx 6 seconds to load). While this is good its only a subset of the data and its not as instantaneous as the Supercluster claims. Now I want to test using Node.js to do the clustering serverside, this way I can hopefully load the full 2.5 million point data set quickly.
Question(s):
I've never used Node.js before but I'm getting the gist of it. I need some help figuring out how to use the supercluster with Node.js because the GitHub site doesn't have clear instructions for beginners. I'm at the stage where I'm using the Demo index.html and its not showing me any points (I have not changed anything in the scripts).
Has anyone used the supercluster with Node before or has any general tips and tricks for me?
Also can I use GeoServer with Node.js?
Or if someone has a different suggestion for clustering 2.5 million points on the fly I'm interested in any and all options!
Specs:
OS -> Windows 10, Node.js -> 12.14.1, Leaflet -> 1.3.1

A: Shortly:

*

*Firstly, define your supercluster and load with geojson.
const Supercluster = require('supercluster');
const index = new Supercluster({
  radius: 40,
  maxZoom: 17
});
index.load(geojson);

*Get map zoom and map bounds from frontend. Than, pass it in index to get data.
let clusterMarkers = index.getClusters(box.bounds, box.zoom);

*Then, just send clusterMarkers to front. That's it. For example:
socket.emit('get_clusters', clusterMarkers);

*If you want to get data when user click the cluster you have to send getClusterExpansionZoom parameter to supercluster (
instead of box bounds).
BTF, the demo of supercluster is written very clear. Try to get concept.


text:
Q: How to use ManagementObjectSearcher in silverlight client side? I want to use ManagementObjectSearcher in the System.Management namespace to get properties of client system.I'm using Silver light as a client side. Does it possible? Please reply...Thanks.

A: ManagementObjectSearcher doesn't supported in silverlight.


text:
Q: Is there a way to display other websites' images onto my own? I'm making a website that grabs restaurant information from my database and displays it using PHP. I was wondering what the best way is to also grab the restaurants' images from their websites at the same time.
Thank you!

A: This is generally not a great idea, unless you have explicit permission from those restaurants and/or the license-holders of the images you might be scraping.
If you scrape image URLs, you should be aware that hotlinking (loading an image hosted on a server that isn't yours) is frowned upon for a few reasons: you're possibly incurring them additional bandwidth costs, the image might be removed or have its URL changed which will then break your site, and so on.


text:
Q: How should I structure my city in order to make up for the teamster's terrible AI? I notice that in Tropico 4, once my city starts becoming large with ~350-400 people, my teamster's AI starts going berzerk. They leave all my goods in the factories and don't bother exporting even when I build many teamster offices.
After some observation, I believe that this is because the large city size and its complicated road network confuses the AI; they tend to use very, very suboptimal route choices. For instance, on the game I just played, they decided to resupply my factories using the port on the other side of the island, even though there's one right next to their office!

A: This answer is courtesy of FritoPatata's excellent guide which you totally should read on optimizing traffic in Tropico 3. Everything still applies in Tropico 4.
His key insight is that:

*

*Raw Materials should be given the fastest possible path to factories, and in turn factory goods should be taken to the dock for
  export as quickly as possible.

*Based on the above ideas, the ideal place for a Tropican to live is as close as possible to work while keeping their needs in check and in
  the best manner possible. The tropican also should not reasonably
  interfere with the transportation of materials whether raw or
  finished.

Hence, it is necessary to give the teamsters priority on the fastest transportation route on the island, while minimizing tourist traffic (by placing the tourism district separate from the main city) and building residential buildings within walking distance of the factories to encourage workers to walk to work:

The main thing I am advocating in my model, is a clear and
  traffic-free route for your raw materials to make it to the factories
  and the finished goods from the factory to the dock as quickly as
  possible. Thus, it is important that you make every effort possible to
  provide a continuous stretch of road from raw materials, through
  production, all the way to export with as few intersections as
  possible. While it is important for your people to get to and from
  work as quickly as possible so they can produce and refine the goods,
  they often work in shifts, and usually half of them will be working at
  any given time (averaged out). But, all the production in the world
  doesn't mean anything until those goods get to a dock.

He provides the following design (which works quite well):

The reason for the circular design is because the intersection logic in the game is bad and can lead to gridlock (and confusion for the teamsters as in my case).


text:
Q: В одномерном массиве найти числа,сумма которых будет равна 7 Моё задание :
Дан массив целых чисел.
Массив не отсортирован, числа могут повторяться.
Необходимо найти в данном массиве такие два числа n и m ,
что бы их сумма была равна 7.
Например: 2+5=7,6+1=7,-2+9 = 7 ( хотя бы одну пару)
,массив задать вручную.
Гугл результатов не дал(
       int[] q = {10, 2, 1, 4, 3, 6, 7, 8, 9, 10};
    System.out.println(" ---- Начальный вид массива ---- ");
    System.out.println(Arrays.toString(q));
    Arrays.sort(q);
    System.out.println("Сортируем с помощью Arrays.sort() ");
    System.out.println(Arrays.toString(q));

A: Вот так решается:
public static void main(String[] args){
    int[] q = { 10, 2, 1, 4, 3, 6, 7, 8, 9, 10 };
    int n = 7;
    System.out.println(" ---- Исследуемый массив ---- ");
    System.out.println(Arrays.toString(q));
    for (int i = 0; i < q.length - 1; i++) {
        for (int j = i + 1; j < q.length; j++) {
            if (q[i] + q[j] == n) {
                System.out.println("*****************");
                System.out.println("q[" + i + "] = " + q[i]);
                System.out.println("q[" + j + "] = " + q[j]);
                System.out.println("q[" + i + "] + q[" + j + "] = " + n);

            }
        }
    }
}

Результат:
 ---- Исследуемый массив ----
[10, 2, 1, 4, 3, 6, 7, 8, 9, 10]
*****************
q[2] = 1
q[5] = 6
q[2] + q[5] = 7
*****************
q[3] = 4
q[4] = 3
q[3] + q[4] = 7


text:
Q: Dynamically adding a TabPanel to a Panel Region I have a Panel layout with a TreePanel in one region.  A user clicks on an node in the tree and a TabPanel should be displayed in another region with information, editing tools etc. for that tree node.
I have a working layout with tree panel and an on('click') event that fires.  However, I don't seem to be able to get the TabPanel to be able to render in the layout.
If I allow the TabPanel to render as part of the panel rather than in the on click event it works as expected.
I'm not sure what I'm missing in terms of rendering the tab panel into a named element.  Any help would be appreciated.
Below is the code in question.
Many Thanks
Stephen
    var treePanel = new Ext.tree.TreePanel({
    id: 'tree-panel',
    title : 'Site Tree',
    region : 'center',
    height : 300,
    minSize: 150,
    autoScroll: true,
    rootVisible: false,
    lines: false,
    singleExpand: true,
    useArrows: true,

    dataUrl:'admin.page.getSiteTreeChildren',
root: {
        nodeType: 'async',
        text: 'nowt here',
        draggable: false
    }
});

treePanel.on('click', function(n){
    var sn = this.selModel.selNode || {}; // selNode is null on initial selection
    renderPageTabs(n.id);
});

function renderPageTabs(resourceid) {
    pageTabPanel.render('contentpanel');
    alert('resourceid'+resourceid);
}

var pageTabPanel = new Ext.TabPanel({
    activeTab: 0,
    plain:true,
    defaults:{autoScroll: true},
    items:[{
            title: 'Page Overview',
            html: 'This will be the page overview detail tab'
        },{
            title: 'Content Editor',
            html: 'This will be the page editor tab'
        },{
            title: 'Property Editor',
            html : 'This will be the property editor tab'
        },{
            title: 'Workflow',
            html : 'This will be the workflow tab'
        }
    ]
})

var contentPanel = {
    id : 'contentpanel',
    region : 'center',
    margins : '0 0 0 0',
    border : false
};

// TODO perhaps the tool bar should be in a north region of this panel
var dashPanel = new Ext.Panel({
            layout : 'border',
            height : 500,
            items : [{
                        layout : 'border',
                        id : 'site-nav',
                        region : 'west',
                        collapsible : true,
                        border : false,
                        split : true,
                        margins : '0 0 0 0',
                        width : 275,
                        minSize : 100,
                        maxSize : 500,
                        items : [actionPanel, treePanel]
                    }, contentPanel],
            renderTo : 'dashboardPanel'
        });

A: I don't think you are using the render method in the correct way.
Tab Panel: render

If you are using a Container object to house this Component, then do not use the render method.

Is your tree going to allow a tab to be opened any time a tree node is clicked?  Will there be multiple tabs at one time? If so, I think maybe you just want to use .add(), instead of .render().  After you do .add(), you will also need to call .doLayout() on the container panel as well so it will show up.
You may need to alter your renderPageTabs function so that it builds the pageTabPanel object inside of it for each tab, then uses .add() to place it in the contentpanel object.

A: I assume pageTabPanel isn't defined at the time you trigger the handler.
Try to remove the var keyword in front of "var pageTabPanel =" to make it a global variable.
If that works, it's a scope/variable issue.
The better solution is to give the tabpanel an id and call Ext.getCmp('tabpanelid').render('contentpanel') in your renderPageTabs method.
Hope that helps.
Regards,
Steffen


text:
Q: Gobblin grouping workunits for Kafka source In https://gobblin.readthedocs.io/en/latest/case-studies/Kafka-HDFS-Ingestion/#grouping-workunits section of Gobblin documentation we can read about Single-level packing with following desc

The single-level packer uses a worst-fit-decreasing approach for assigning workunits to mappers: each workunit goes to the mapper that currently has the lightest load. This approach balances the mappers well. However, multiple partitions of the same topic are usually assigned to different mappers. This may cause two issues: (1) many small output files: if multiple partitions of a topic are assigned to different mappers, they cannot share output files. (2) task overhead: when multiple partitions of a topic are assigned to different mappers, a task is created for each partition, which may lead to a large number of tasks and large overhead.

Second overhead seems to stand in contradiction to what we can read in the other parts.
One paragraph higher we can red

For each partition, after the first and last offsets are determined, a workunit is created.

and here https://gobblin.readthedocs.io/en/latest/Gobblin-Architecture/#gobblin-job-flow in point 3:

From the set of WorkUnits given by the Source, the job creates a set of tasks. A task is a runtime counterpart of a WorkUnit, which represents a logic unit of work. Normally, a task is created per WorkUnit

So for what I understand there always is task associated with Kafka partition unless WorkUnits are grouped together (then we have one task for many WorkUnits thus many paritions)
Do I understand something wrong here or second overhead in single-level packaging make no sens?


text:
Q: How to make the text font shrink and match JTextArea height? I have a JTextArea that receives a text, but the problem is when the text is too long it doesn't fit and the scroll bar appears. What i want is to automatically shrink the font size to match The JTextArea height.

A: Use below method, (update max and min size's according to your requirement)
public static int getMatchingFontSize(JComponent comp, String string) {
    int minSize = 10;
    int maxSize = 60;
    Dimension size = comp.getSize();

    if (comp == null || comp.getFont() == null || string.isEmpty()) {
        return -1;
    }
    //Init variables
    int width = size.width;
    int height = size.height;

    Font font = comp.getFont();
    int curSize = font.getSize();
    FontMetrics fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
    while (fm.stringWidth(string) + 4 > width || fm.getHeight() > height) {
        maxSize--;
        fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), maxSize));
        curSize = maxSize;
    }
    while (fm.stringWidth(string) + 4 < width || fm.getHeight() < height) {
        minSize++;
        fm = comp.getFontMetrics(new Font(font.getName(), font.getStyle(), minSize));
        curSize = minSize;
    }
    if (curSize < minSize) {
        curSize = minSize;
    }
    if (curSize > maxSize) {
        curSize = maxSize;
    }
    return curSize;
}


text:
Q: Automate ssh-add passphrase using Expect In a shell script, I need to automatically fill the passphrase when running ssh-add.
I came across expect and tried this script, but with no luck:
expect -c "spawn ssh-add; expect -re \".*passphrase.*\"; send \"mypass\r\n\";"
The script doesn't throw any errors, but when it ssh it asks for password (meaning it didn't work).
EDIT: If run ssh-add and add the passphrase manually it works as expected.

A: Here is a better way to automate it.
Create a script (e.g. ps.sh with executable flags) which prints your passphrase, e.g.:
#!/bin/sh
echo 'my_passphrase'

Then specify this script via SSH_ASKPASS variable, so it can be used for the authentication, e.g. :
$ cat id_rsa | SSH_ASKPASS=./ps.sh ssh-add -

Another way is to use named pipe:
$ mkfifo -m=600 ~/.fifo
$ cat id_rsa > ~/.fifo | SSH_ASKPASS=./ps.sh ssh-add ~/.fifo

You can read more about SSH_ASKPASS in man ssh-add:

If ssh-add does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS.

A: If you use expect to pass the password, it means that you need to store the password somewhere along width the key - both readable by the same user. This does not enhance security at all since an attacker which is able to access the key would be able to access the password at the same time.
Simply use a key without a password.


text:
Q: JSON string won't print to console I have this service:
getCert(p: string): Promise<string> {
  return ApiService.getData(this.apiUrl + p + this.certEndpoint).then(
    (response) => response.data
  );
}

This is an example of data:
{
    "state": "success",
    "message": "Message received."
}

If I return response.data.state or response.data.message I get the relevant value.
If I call it with this:
async componentDidMount() {
    const queryString = require('query-string');
    const parsed = queryString.parse(location.search);
    return this.docListingService.getPks(parsed.policy).then(async pks => {
        this.setState({ isLoading: false, packs });
        this.certService.getCert(parsed.policy).then( response => {
            console.log('RESPONSE: ' + response);
        });
        return pks;
    }).catch((error) => {
        this.loggingService.logError('Error returning Docs ' + error);
        this.setState({ errorOccured: true});
    });
}

response is a string but my consle.log prints RESPONSE [object Object]. I tried console.log('RESPONSE: ' + response.state); and console.log('RESPONSE: ' + response.message); but they error. As does:
console.log('RESPONSE: ' + JSON.parse(response));

How do I resolve this?

A: console.log() accepts as many arguments as you like. So you can just use it like this:
console.log('response ', response)
If you want to log multiple variables, you can do it like this:
console.log(variable1, variable2, variable3, 'some string', variable4);

A: Just use:
JSON.stringify(response)

This will show the Object structure as string value.

A: you have a bug in console.log of your code, you are trying to concat a string and json object. you can try this code
console.log('response ', JSON.parse(response));

//or

console.log('response ', JSON.parse(response).data.message);

//or

console.log('response ' + JSON.parse(response).data.message);


text:
Q: What happens if I lock an object while another thread use that variable? I am not sure how lock works.
What happens if I have a List<T> list and 2 threads ?
What happens if thread1 start running first and enumerate that list
foreach(T t in list)
{
  // code
}

and in the same time, but after thread1 has started, thread2 will lock the list
lock(list)
{
  // code
}

I use ThreadPool do to some processing and I need to know how lock really works and if is thread safe
ThreadPool.QueueUserWorkItem(new WaitCallback(method), obj);

A: lock keyword doesn't "lock" or "freeze" target object (in a sense preventing from changes).

lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.

So in your case it won't prevent other threads from enumerating the list.

A: In the code as written - the enumerator will keep on going. The point about lock is that all your code needs to agree. If you had used:
lock(list)
{
    foreach(T t in list)
    {
        // code
    }
}

Then when your other thread attempts to acquire the lock it will queue behind the first - waiting for the first thread to release the lock (either by exiting the lock (Monitor.Exit), or calling Monitor.Wait).

A: Lock isn't magic, and it must be used cooperatively. If I want to ensure that changes to some mutable object don't get accidentally stomped on or corrupted by multiple threads then I need to ensure that I only make changes to the object within a lock block.
The only thing that lock ensures is that any other code that is locking on the same object is not running on other threads at the same time, it's just syntactic sugar for acquiring and releasing a mutex.
lock(x) // acquire mutex associated with x, or wait until it becomes available
{
    // do stuff
} // release mutex associated with x

Edit: MSDN has very worthwhile under-the-hood details on lock(), for those who are curious.


text:
Q: Use force and delay to produce stream of even integers in generate-and-filter style I am trying to learn the use of delay and force in Scheme. I created a function which outputs the even numbers in the list. Now I am trying to use delay and force with function. But I am getting error : unbound symbol : "delay" [].
Can someone explain what I am doing wrong?
(define (even-filter ls)
  (if (null? ls)  '()
    (filter even? ls)))

(even-filter '(1 2 3 4 5 88))

(let ((delayed (delay (even-filter '(1 2 3 4 5 88)))))
  (force delayed))

A: Make sure that you're using the right language, because both force and delay are primitive forms, part of the standard language. If using Racket, in the bottom-left corner select "Determine language from source", and type the following:
#lang racket

(define (even-filter ls)
  (filter even? ls))

(let ((delayed (delay (even-filter '(1 2 3 4 5 88)))))
  (force delayed))

It works as expected:
'(2 4 88)


text:
Q: webkitnotifications not defined on one machine We are working on a webapp for chrome. We use this browser for the rich notifications and today we had a "FML" kind of a problem.
One of the customers rang us about having problem with log-in to the webapp. His Google Chrome Browser couldn't find webkitNotifications. And the problem is, on other Google Chrome Browsers it works.
How should i face this problem? We tried to re-install chrome manually (via. Team Viewer). We deleted old settings, files etc. but still we face the same issue.
EDIT: Ok. We found out that the update 35.0.1916.114 made this mess. I don't like the idea to wait for the Google to repair the issue so I'm asking desperately - what can i do in this case (ofcourse I'm aware of the posibility to rebuild the whole notification system but I don't want to do this...)?


text:
Q: Add  tags programatically in Java I have a HTML code like this :
<p> This is paragraph 1 </p>
This is paragraph 2
<p> This is paragraph 3 </p>

I will process the above HTML in Java and I wanted the processed HTML to be :
<p> This is paragraph 1 </p>
<p> This is paragraph 2 </p>
<p> This is paragraph 3 </p>

And there might be big paragraphs with more than one line. Therefore, line by line processing doesn't work in this case. For example,
<p> ...
...
...
</p>

And there can be cases like,
<p> This </p> can be <p> the case too. </p>

I need the above line to be converted to :
<p> This </p><p> can be </p><p> the case too. </p>

I want to achieve this because Jsoup doesn't identify text without < p > tags. If Jsoup can do that by any means, I am happy with that too. I don't want any text to be missed out from the document.

A: JSoup can give you the parts which are not in <P>. Since they are not enclosed in a tag, they are text nodes rather than elements. So you should traverse the nodes rather than elements. Here is an example:
public class SimpleTest {

    public static final String HTML = "<p> This is paragraph 1 </p>\n"
                                    + "This is paragraph 2\n"
                                    + "<p> This is paragraph 3 </p>";

    public static void main(String[] args) {

        Document doc = Jsoup.parse(HTML);

        List<Node> nodes = doc.body().childNodes();

        for ( Node node : nodes ) {
            System.out.printf("Node of %s, %s%n", node.getClass(), node);
        }
    }
}

The output is:
Node of class org.jsoup.nodes.Element, <p> This is paragraph 1 </p>
Node of class org.jsoup.nodes.TextNode,  This is paragraph 2
Node of class org.jsoup.nodes.Element, <p> This is paragraph 3 </p>

So when you want to do something practical with an unknown node, you should test it with instanceof to see if it's a TextNode, an Element or something else. Then you cast it to the relevant class, and you can use all its methods in addition to the ones that are available in Node.

A: Have you tried writing a parser to check if there's a p tag at the beginning of each line?
Code could look something like that:
String[] splitted = html_code.split("\n");
String solution="";
for(String s : splitted){
    s = s.trim();
    if(s.startsWith("<p>"){
        solution+=s;
    }else{
        solution = "<p>"+s+"</p>;
    }
}

A: Cool, I figured it out with RealSkeptic's help. This is just the improved version of the code appropriate for the question :
for( Node node : nodes ) {
       if( node.getClass() == Element.class ) {
           Element element = (Element) node;
           System.out.println( element.tag() + " " + element.text() );
       }
       else if( node.getClass() == TextNode.class && ! node.toString().trim().isEmpty() )
           System.out.println( node.toString().trim() );
}

Here I checked node isEmpty because Jsoup considers each line as a TextNode.


text:
Q: TFS 2018 API - Generate PAT or SSH I would like to generate SSH public key or Personal Access Token using the TFS API. Is there any way to do that? I searched through the documentation of the API on (https://learn.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-4.1) but I didn't find what I am looking for. We are currently using TFS 2018 Update 2.
Thank you very much for your help.

A: Unfortunately, no such an API to generate PAT or SSH for now. There is a related user voice submitted here, you can go and vote it up to achieve that in future. You can also submit a new user voice to suggest the feature.

*

*For now we can only generate the PAT via web portal and the PAT will
be displayed only once.
You will need to copy it and store it somewhere safe, so that you can
retrieve it as needed.

Make sure you copy the token now. We don't store it and you won't be
  able to see it again.

*To generate and use the SSH public keys you can refer to Use SSH key
authentication for details.


text:
Q: Changing x-axis range in MATLAB without including ticks Two of my data points are barely visible:

based on this code:
x = 1:8;
y = [70 74 77 78 80 80 82 83];
err = [14 11 12 10 10 7 7 5];
errorbar(x,y,err,'red')
ylabel('Classification results','fontsize',20);
xlabel('Nr of features used', 'fontsize',20);
title('Feature selection with Genetic Algorithm','fontsize',24)
ylim([55 100])

A: Simply use xlim and permute the beginning and end ranges by a slight amount... say 0.2:
xlim([min(x) - 0.2, max(x) + 0.2]);

I use min and max here to make it adaptive so that the smallest x value displayed is the smallest one in x subtracted by a 0.2 buffer.  Similar logic is applied for the largest x value where the value displayed is the largest one with a 0.2 buffer added.
I now get:


text:
Q: PostgreSQL: Column "crab_id" Specified More than Once With PostgreSQL call,
CREATE TABLE condor_xrootd AS
       SELECT * FROM condor INNER JOIN xrootd_ext
       ON (
xrootd_ext.CRAB_Id = condor.CRAB_Id AND
REPLACE(condor.CRAB_ReqName, '_', ':') = xrootd_ext.CRAB_ReqName
);

I get the error,
$ psql condor -f ./sql/inner_join.sql
psql:./sql/inner_join.sql:6: ERROR:  column "crab_id" specified more than once

Which is understandable because each table has a Crab_Id column. I would like to be able to do my inner join without having to specify the columns because I have around 400 columns in the two tables combined.
Please let me know if I can somehow get rid of this error without listing columns individually.
EDIT:
I forgot to mention that speed and stability is crucial here as my join might take several days.

A: create table condor_xrootd as
select *
from
    condor
    inner join
    xrootd_ext using (crab_id)
where replace(condor.crab_reqname, '_', ':') = xrootd_ext.crab_reqname

A: You create table from a result set which is build of two tables. Your error says that column crab_id exists in both condor and xrootd_ext tables and Postgresql doesn't know which should be selected.
You should specify fields of which you want to create table. Like this:
CREATE TABLE condor_xrootd AS
       SELECT
          condor.*, -- here we take all fields from condor table
          xrootd_ext.crab_reqName -- here we take crab_reqName field from xrootd_ext
       FROM condor INNER JOIN xrootd_ext
       ON (
xrootd_ext.CRAB_Id = condor.CRAB_Id AND
REPLACE(condor.CRAB_ReqName, '_', ':') = xrootd_ext.CRAB_ReqName
);


text:
Q: What could intro_pt_not_on_line be? I am reading this paper where the authors attempt to translate Hilbert's work on geometry into a computer verified work using Isabelle/Isar. In section 5.2 they illustrate how to computer verifiably prove that there exists a point between any two distinct points. The point of this segment is to stress that Hilbert relied on the geometric intuition too much. They make the following observation:

Proving this mechanically also required using a lemma called intro_pt_not_on_line, which had to show the existence of $AC$.

They do not present what intro_pt_not_on_line is. True, they observe that Hilbert would have need to have shown the existence of $AC$, but  I thought that it followed easily from their definition of Axiom 1:
AxiomI12: "A≠B ⇒ ∃! a. on_line A a ∧ on_line B a"

This does not seem like an blunder in geometric intuition as so much a minor ommision, nor does it seem like something that would need an entire lemma. I could not find the complete code, the closest I came to finding the code was a page on Isabelle projects.
My questions is:
Is the point of intro_pt_not_on_line simply to show that $A \neq C \implies \exists!AC$? If not, what other things did intro_pt_not_on_line show?

A: I talked with one of my professors about this. Although we cannot be entirely sure, it is like intro_pt_not_on_line is equivalent to the following statement in English:

Given two distinct points $A$ and $C$, there exists a point not on $AC$.

Axiom I3 simply says there exists 3 non-colinear points, it does not state given any two distinct points there is a non-colinear points.
However, I believe this result can be derived:
Suppose that we are given two distinct points $A$ and $C$. Suppose otherwise that there does not exist a non-colinear point (1). Then from Axiom I3 we have that there are 3 distinct non-colinear points $D$, $E$, and $F$. But by (1) it must be that $D \in AC$, $E \in AC$, and $F \in AC$. But every two distinct points lie on a distinct line, so $D$, $E$, and $F$ all lie on $AC$ and are all colinear, but this contradicts that $D$, $E$, and $F$ are non-colinear.


text:
Q: Acumos Installation need some help getting acumos running.
Have VM with Ubuntu 20.04.4
Followed flow-1 here: https://docs.acumos.org/en/latest/submodules/system-integration/docs/z2a/tl-dr.html#flow-1
acumos-k8s-portal-be-569bf85dc-kx89b-shows pending
When I go to https://localhost/ on VM, I get 504 gateway timeout - nginx
gateway timeout
Not sure where to look for the issue?
Any help would be appreciated.

A: Just in case someone runs into the same issue, I havent resolved it on my local VM but got all all setup and working as follows:
So I used Oracle VirtualBox for my VM's with Ubuntu desktop 20.04.4 - the issue persists no matter what I tried, even tried Ubuntu 18 with same results.
My current solution:
Got an Ubuntu cloud server from Hetzner (ubuntu server 20.04), went thru the same process and it's all up and running :), just bizarre.
Not sure if different results will come from vmware, will give it a try sometime.
Cheers.


text:
Q: Installing and enabling both master and slave semisynchronous plugins on same server I want to run a semisynchronous replication setup, and for simplicity I'd like to not have to INSTALL and UNINSTALL plugins when a slave is promoted to a master. So I'm wondering if I'll experience any problems having both master and slave plugins installed and enabled (see here)
It looks like after installing the second plugin, both variables rpl_semi_sync_master_enabled and rpl_semi_sync_slave_enabled are reset to off (the non-default). When I include these lines in my.cnf:
loose-rpl_semi_sync_master_enabled = 1
loose-rpl_semi_sync_slave_enabled = 1

...and restart MySQL, both plugins are loaded and enabled.
Is this going to cause any problems for me?

A: This will not cause any problems. I have always setup all MySQL 5.5. DB servers for clients with both plugins. In fact, I answered a question back on Aug 05, 2011 where I posted an update on Aug 08, 2011 on how to install both plugins at the same time
Please see Is MySQL Replication Affected by a High-Latency Interconnect?
Here is the excerpt from that update
EXCERPT
The configuration of MySQL 5.5 Semisynchronous Replication is straightforward
Step 1) Add these four(4) lines to /etc/my.cnf
[mysqld]
plugin-dir=/usr/lib64/mysql/plugin
#rpl_semi_sync_master_enabled
#rpl_semi_sync_master_timeout=5000
#rpl_semi_sync_slave_enabled

Step 2) Restart MySQL
service mysql restart

Step 3) Run these commands in the MySQL client
INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so';
INSTALL PLUGIN rpl_semi_sync_slave  SONAME 'semisync_slave.so';

Step 4) Uncomment the three rpm_semi_sync options after the plugin-dir option
[mysqld]
plugin-dir=/usr/lib64/mysql/plugin
rpl_semi_sync_master_enabled
rpl_semi_sync_master_timeout=5000
rpl_semi_sync_slave_enabled

Step 5) Restart MySQL
service mysql restart

All Done !!! Now just setup MySQL Replication as usual.


text:
Q: Service doesnt work correctly in Background I am making Music Player which downloads music from Firebase.
Its working fine but I cannot play music in background.
It works for like 1.5 minute (after locking screen)  and it stops.
In logs after I lock screen it says "Inactivity, disconnecting from Service".
I think this may be main problem here.

Here code :
Fragment of Playing Music:
    public class PlayerFragment extends Fragment {
        private FirebaseStorage storage;

        private ImageButton main_btn, next_btn, back_btn, fav_btn, settings_btn;
      private Uri localSong;
    private   Intent myService;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
          View view=  inflater.inflate(R.layout.fragment_player, container, false);
          storage = FirebaseStorage.getInstance();
        main_btn=  view.findViewById(R.id.player_main_btn);
        next_btn=  view.findViewById(R.id.player_next_btn);
        back_btn=  view.findViewById(R.id.player_back_btn);
        fav_btn = view.findViewById(R.id.player_song_fav_btn);
        settings_btn = view.findViewById(R.id.player_song_options_btn);

            storage.getReference().child("songs/ni_bien_ni_mal.mp3").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    localSong=uri;
                }
            });
            MainActivity mainActivity = (MainActivity) getActivity();
             myService = new Intent(getActivity(), BackgroundSoundService.class);

            main_btn.setOnClickListener(v -> {

                if( main_btn.getDrawable().getConstantState().equals( main_btn.getContext().getDrawable(R.drawable.ic_play).getConstantState()))
                {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            myService.putExtra("uri",localSong.toString() );
                            mainActivity.startService(myService);
                        }
                    }).start();

                   main_btn.setImageResource(R.drawable.ic_pause);
                }
                else
                {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                          //  mainActivity.stopService(myService);
                            main_btn.setImageResource(R.drawable.ic_play);
                        }
                    }).start();

                }

            });

        fav_btn.setOnClickListener(v->{

            if( fav_btn.getDrawable().getConstantState().equals( fav_btn.getContext().getDrawable(R.drawable.ic_heart_empty).getConstantState()))
            {
                fav_btn.setImageResource(R.drawable.ic_heart_full);
            }else{
                fav_btn.setImageResource(R.drawable.ic_heart_empty);
            }
        });
          return view;
        }
    }

Manifest: ( Service declaration is at bottom)
        <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.company.altasnotas">

        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/altas_notes"
            android:label="@string/app_name"
            android:roundIcon="@drawable/altas_notes"
            android:supportsRtl="true"
            android:testOnly="false"
            android:theme="@style/Theme.AltasNotas">

            <activity
                android:name=".IntroActivity"
                android:label="@string/app_name"
                android:theme="@style/Theme.AltasNotas.NoActionBar"
                android:screenOrientation="portrait">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>

            <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/facebook_app_id"
                tools:replace="android:value" />
            <meta-data
                android:name="preloaded_fonts"
                android:resource="@array/preloaded_fonts" />

            <activity
                android:name="com.facebook.FacebookActivity"
                android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
                android:label="@string/app_name" />
            <activity
                android:name="com.facebook.CustomTabActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.VIEW" />

                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.BROWSABLE" />

                    <data android:scheme="@string/fb_login_protocol_scheme" />
                </intent-filter>
            </activity>
            <activity
                android:name=".MainActivity"
                android:screenOrientation="portrait">
            </activity>
            <service android:enabled="true" android:name=".BackgroundSoundService" />
        </application>

    </manifest>

Service :
    public class BackgroundSoundService extends Service {
        String  song_string;
        int x;
        private static final String TAG = "BackgroundSoundService";
        MediaPlayer player;

        public IBinder onBind(Intent arg0) {
            Log.i(TAG, "onBind()" );

            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();

        }

        @Override
        public void onStart(Intent intent, int startId) {
            super.onStart(intent, startId);

        }

        public int onStartCommand(Intent intent, int flags, int startId) {

            song_string= intent.getStringExtra("uri");

            if (song_string != null) {
                    System.out.println("Song string : " + song_string);
                player = MediaPlayer.create(this, Uri.parse(song_string));
                player.setLooping(false); // Set looping
                player.setVolume(0.5f, 0.5f);
                if (!(String.valueOf(x) == null || String.valueOf(x).isEmpty())) {
                    player.seekTo(x);
                }
                player.start();
            }

            return Service.START_STICKY;
        }

        public IBinder onUnBind(Intent arg0) {
            Log.i(TAG, "onUnBind()");
            return null;
        }

        public void onStop() {
            Log.i(TAG, "onStop()");
        }
        public void onPause() {
            Log.i(TAG, "onPause()");
            x=player.getCurrentPosition();
            player.pause();
        }
        @Override
        public void onDestroy() {
            if(player!=null) {
                player.stop();
                player.reset();
                player.release();
                 Log.i(TAG, "onCreate() , service stopped...");
            }
        }

        @Override
        public void onLowMemory() {
            Log.i(TAG, "onLowMemory()");
        }

    }

Despite Sticky and declaration in Manifest , it still doesnt work in background. Also I want to add pause button and I dont know exacly how can I do that.


text:
Q: Remove list items from select menu with jQuery I have a tiny bit of script that allows the user to resize the window to convert an unordered list into a select menu.
However, I'd like to remove any nested unordered lists from the select menu.
DEMO: http://jsfiddle.net/k7272/
So basically using the example above, the part 'test' wouldn't appear in the select menu, but would still appear in unordered list.
How do I achieve this?
Here is my Javascript:
// DOM ready
     $(function() {

      // Create the dropdown base
      $("<select />").appendTo("nav");

      // Create default option "Go to..."
      $("<option />", {
         "selected": "selected",
         "value"   : "",
         "text"    : "Go to..."
      }).appendTo("nav select");

      // Populate dropdown with menu items
      $("nav a").each(function() {
       var el = $(this);
       $("<option />", {
           "value"   : el.attr("href"),
           "text"    : el.text()
       }).appendTo("nav select");
      });

       // To make dropdown actually work
       // To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
      $("nav select").change(function() {
        window.location = $(this).find("option:selected").val();
      });

     });

Many thanks :-D

A: targeting nav a will find all its children and even children of children, so you need to directly target them like this
$("nav > ul > li > a").each(...
http://jsfiddle.net/k7272/1/

A: Change the selector to only look for direct children, this will avoid the nested ul. Try this:
$("nav > ul > li > a").each(function () {
    // your code...
});

Updated fiddle

A: Instead of the "nav a" selector, which selects any  descendant of , use the child operator: $("nav>ul>li>a").
Better yet, put a class on your top level ul and then use $('ul.classname>li>a'), then you can move the whole list around your DOM and still have the selector work.


text:
Q: Code solution to avoid if else conditions I am wondering if anyone can suggest me a design pattern or best way to code the below problem.
1) I have an array list of books like the below
list.add(new Book(title, author);
list.add(new Book(title1, author1);

and so on....
2) And now I would like to find all the books from the list by author
findByAuthor(String author) {
  for(Book book : list){
    if(book.getAuthor().equals(author)){
      return book;
    }
  }
}

Like wise I have another method called findByTitle(). But, it would be same code except book.getAuthor() will have to be book.getTitle(). Everything will be same.
3) Now i can write a method which is generic to both methods like below;
findByBookProperty (String type, String propertyValue){
  for(Book book : list)
    if(type.equals("author") && book.getTitle().equals(propertyValue)){
      return book;
    } //another else if for author
    //another else for another property
    // if else repeats for all the required finder types...
  }
}

4) The problem i have here is;
1. I dont want to use the nasty if/else condition for the finder types.
2. I want to know if there is any design pattern or better way to handle this if else or swich method.
Important note: I get the author name as a request parameter value in my spring controller method.
I appreciate your thoughts.

A: Use Commons-Collections' Predicates framework:
1) Construct a Predicate instance for each type of test.
2) Use CollectionUtils.select(), passing in the predicate you'd like to use for evaluating objects.
Another alternative is to use Commons-Collections' Transformation framework:
1) Write a Transformer for each type of property you'd like extracted/compared against.
2) Write a generic loop, accepting a Transformer instance as a parameter.


text:
Q: How to set basic auth to Kubernetes' readinessProbe correctly? How to set basic auth to Kubernetes' readinessProbe correctly?
If set this config for Kubernetes' readinessProbe in deployment kind.
readinessProbe:
  httpGet:
    path: /healthcheck
    port: 8080
    httpHeaders:
    - name: Authorization
      value: Basic <real base64 encoded data>

Deploy it to GKE, GCP's health check can't pass to access the inside application with using basic authentication.
But from here, it seems it should use this syntax. Why can't pass?
The server side is using JSON response at the /healthcheck point. Is it also necessary to set Accept or Content-Type to the httpHeaders?
And, is it good to set this health check to livenessProbe or readinessProbe?

A: According to kubernetes doc:

If the process in your container is able to crash on its own whenever it encounters an issue or becomes unhealthy, you do not necessarily need a liveness probe; the kubelet will automatically perform the correct action in accordance with the Pod's restartPolicy. If you'd like your container to be killed and restarted if a probe fails, then specify a liveness probe, and specify a restartPolicy of Always or OnFailure.

Ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#when-should-you-use-a-liveness-probe

If you'd like to start sending traffic to a Pod only when a probe succeeds, specify a readiness probe. In this case, the readiness probe might be the same as the liveness probe, but the existence of the readiness probe in the spec means that the Pod will start without receiving any traffic and only start receiving traffic after the probe starts succeeding. If your container needs to work on loading large data, configuration files, or migrations during startup, specify a readiness probe.

Ref: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#when-should-you-use-a-readiness-probe
So, you can use health check according to your need. But in kubernetes doc, they give an example of health check as a liveliness probe.
Ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-http-request
And it is the best practice to use Content-Type when you send request other then browser or other typical client. I believe using Content-Type: application/json will solve the issue if other things go right in server side.


text:
Q: Start background process with ssh, run experiments script, then stop it I am running client-server performance experiments on several remote machines. I am trying to write a script to automate the experiments. Here is how it looks like (in a simplified way) for the moment.
for t in 0 1 2 3 4 5 6 7 8 9; do
    cmd1="ssh user@${client1} runclient --threads=${t}"
    cmd2="ssh user@${client2} runclient --threads=${t}"
    $cmd1 &
    $cmd2 &
    wait

runclient connects to a server that I have started manually. It works fine, but I would like to automate starting and stopping the server as well. That means

*

*Start the server in the background at the beginning of experiments

*Run all the experiments

*Stop the server at the end of experiments

I have found several suggestions but I am not sure which one is good for me exactly. Some recommend nohup, but I am not sure how to use it, and I don't understand why I should redirect stdin, stdout, and stderr. There is also the maybe the "-f" option to ssh to start a background process. In that case, how can I stop it later?
Edit: in response to the comments, the server is part of the performance experiments. I start it in a similar way to the client.
ssh user@${server} runserver

The only difference is that I want to start the server once, run several experiments on the clients with different parameters, and then stop the server. I could try something like that
ssh user@${server} runserver &
for t in 0 1 2 3 4 5 6 7 8 9; do
    cmd1="ssh user@${client1} runclient --threads=${t}"
    cmd2="ssh user@${client2} runclient --threads=${t}"
    $cmd1 &
    $cmd2 &
    wait

But as the server does not stop, the script would never go past the first wait

A: Track your PIDs and wait for them individually.
This also lets you track failures, as shown below:
ssh "user@${server}" runserver & main_pid=$!
for t in 0 1 2 3 4 5 6 7 8 9; do
    ssh "user@${client1}" "runclient --threads=${t}" & client1_pid=$!
    ssh "user@${client2}" "runclient --threads=${t}" & client2_pid=$!
    wait "$client1_pid" || echo "ERROR: $client1 exit status $? when run with $t threads"
    wait "$client2_pid" || echo "ERROR: $client2 exit status $? when run with $t threads"
done
kill "$main_pid"


text:
Q: grab only name column of lsof? I have the following command that works great:
sudo lsof -w -c smbd -u myuser | grep '.txt'

I just want to get the full path to the file name part of the returned output, the "NAME" column, to put in a report. What is the easiest way to just grab the NAME column?

A: sudo lsof -w -c smbd -u myuser | tr -s ' ' | cut -d' ' -f 9 | grep '.txt'

tr - replaces repeated blank spaces with a single space.
cut - outputs exclusively field\column 9.


text:
Q: Giving Error "TypeError: value is not a functionDetails" functionfillvaluedown()
     var myGooglSheet= SpreadsheetApp.getActiveSpreadsheet(); //declare a variable and set with active google sheet
      var shUserForm= myGooglSheet.getSheetByName("User Form"); //delcare a variable and set with the User Form
      var datasheet = myGooglSheet.getSheetByName("Database"); //delcare a variable and set with the Database
      var currentRange = datasheet.getRange("b2:b" + datasheet.getLastRow())
    var newRange = []
    var NewFillValue
    currentRange.getValues().map(function(value) {
      if (value[0] !==''){
        NewFillValue = value(0)
        newRange.push([NewFillValue])
      } else {
        newRange.push([NewFillValue])
      }
      })
      currentRange.setValue(newRange)
    }


text:
Q: Not getting any movement from sprite in Sprite Kit I am trying to move a sprite node down every time I touch in a certain area. This is the code I have and the log is showing that the touches register. What am I doing wrong and is there an easier way to accomplish this?
-(void)update:(CFTimeInterval)currentTime {

    CGPoint currentLocation = [currentTouch locationInView:currentTouch.view];

    if (currentLocation.y > 500) {

    CGFloat newY = _bg.position.y - 25;
    _bg.position = CGPointMake(_bg.position.x, newY);
    NSLog(@"touchtouch");
}

A: Try this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

for (UITouch *touch in touches) {

CGPoint currentLocation = [touch locationInNode:self];

if (currentLocation.y > 500) {

    CGFloat newY = _bg.position.y - 25;
    _bg.position = CGPointMake(_bg.position.x, newY);
    NSLog(@"touchtouch");
      }
   }
}

You can also use an SKAction to have the movement animated:
SKAction *moveDown = [SKAction moveToY:newY duration:1];
    [_bg runAction:moveDown];

Hope this can help you!


text:
Q: Calling running Java code from running C++ code and vice versa my question is how to call running Java code from running C++ code and vice versa.
There are several posts available concerned with calling compiled c++ files from Java or JVM from C unsing Java Native Interface (JNI) or Java Native Access (JNA). However, to me this seems not to be an adequate way to call running code as only compiled libraries are invoked in the examples.
My case looks as follows. There are two applications running on a local computer. One application is Eclipse- and Java-based. The other application is C++-based. I need to make them communicating in both directions. Maybe this is a case for RPC? But I do not need to communicate via web.
I think RCP may be a way but it seems oversized to me as i do not want to communicate over web and I do not know how to use RCP in this context. I am searching for a smarter solution.
Is there any experience that can help me?
Thanks and Regards
Rob

A: You may wish to look at my C++ to Java RPC solution. Given a Java class, it generates a C++ client stub and Java server stub.
https://github.com/danfickle/cppToJavaRpcStubGenerator
Edit: I think CORBA is the 'standard' solution. However, the 1000 page book Java and CORBA that I have on my bookshelf (and haven't read) suggests there is a learning curve. You may also wish to look into MessagePack, Thrift, ActiveMQ, etc. Sorry, I couldn't be more help.

A: JNI allows you to link C++ and Java code; however, the both are the same program.
If you wanted to have one program call another program, the easiest way is to use a network enabled technology.  RPC, CORBA, client/server sockets, or any other means including a network will suit you nicely.
Harder non-networking stack solutions exist, like shared memory, semaphores, pipes, etc; however, they require an operating system that supports them, and are subject to constraints on how they are used, plus you will need to find language bindings for both languages using them.