text:
Q: MySQL Stored Procedure not working with multiple parameters I have an mysql stored procedure where with one input, that works great. Now i need two inputs, but its not working and i cant figure out whats wrong.
Here is my store procedure:
CREATE DEFINER=`multilager`@`localhost` PROCEDURE `lagerbeholdning_alle`(IN `bruker_gruppe` INT, IN `bruker_gruppe2` INT)
BEGIN
  SET @sql = NULL;

  SELECT GROUP_CONCAT(DISTINCT
           CONCAT('SUM(CASE WHEN lagerbeholdning.lok_id = ', lagerbeholdning.lok_id,
                  ' THEN antall END) `', lagerbeholdning.lok_id, '`'))
    INTO @sql
    FROM lagerbeholdning
    INNER JOIN lokasjoner ON lagerbeholdning.lok_id = lokasjoner.lok_id
    WHERE bruker_gruppe_ref = bruker_gruppe;

  SET @sql = CONCAT('SELECT produkt_id, prod_navn, kat_navn, size_navn, farge_navn, prod_bilde, ', @sql, '
                     FROM lagerbeholdning
                     INNER JOIN produkter ON produkt_id = prod_id
                     INNER JOIN produkt_kategorier on prod_kat_id = kat_id
                     INNER JOIN produkt_sizes on prod_size_id = size_id
                     INNER JOIN produkt_farger on prod_farge_id = farge_id
                     WHERE produkter.prod_bruker_gruppe = bruker_gruppe2
                     GROUP BY produkt_id');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END

If i call the procedure:
CALL lagerbeholdning_alle(3,3)

I get the following error:
Error: Unknown column 'bruker_gruppe2' in 'where clause'

How can i use the bruker_gruppe2 parameter in the last where clause?

A: CONCAT will treat it as normal text and will pass it to query without replacing with value.
SET @sql = CONCAT('SELECT produkt_id, prod_navn, kat_navn, size_navn, farge_navn, prod_bilde, ', @sql, '
       FROM lagerbeholdning
       INNER JOIN produkter ON produkt_id = prod_id
       INNER JOIN produkt_kategorier on prod_kat_id = kat_id
       INNER JOIN produkt_sizes on prod_size_id = size_id
       INNER JOIN produkt_farger on prod_farge_id = farge_id
       WHERE produkter.prod_bruker_gruppe = ', bruker_gruppe2, '
       GROUP BY produkt_id');

Now it should be replaced correctly.


text:
Q: How much faster is C++ code "supposed" to be with optimizations turned on? I have a program that runs in around 1 minute when compiling with g++ without any options.
Compiling with -O3 however makes it run in around 1-2 seconds.
My question is whether it is normal to have this much of a speed up? Or is my code perhaps so bad, that optimization can take away that much time. Obviously I know my code isn't perfect but because of this huge speedup I'm beginning to think it's worse than I thought. Please tell me what the "normal" amount of speed up is (if that's a thing), and whether too much speed up can mean bad code that could (and should) be easily optimized by hand instead of relying on the compiler.

A:
How much faster is C++ code "supposed" to be with optimizations turned on?

In theory: There doesn't necessarily need to be any speed difference. Nor does there exist any upper limit to the speed difference. The C++ language simply doesn't specify a difference between optimisation and lack thereof.
In practice: It depends. Some programs have more to gain from optimisation than others. Some behaviours are easier to prove than others. Some optimisations can even make the program slower, because the compiler cannot know about everything that may happen at runtime.

... 1 minute ... [optimisation] makes it run in around 1-2 seconds.
My question is whether it is normal to have this much of a speed up?

It is entirely normal. You cannot assume that you'll always get as much improvement, but this is not out of the ordinary.

Or is my code perhaps so bad, that optimization can take away that much time.

If the program is fast with optimisation, then it is a fast program. If the program is slow without optimisation, we don't care because we can enable optimisation. Usually, only the optimised speed is relevant.
Faster is better than slower, although that is not the only important metric of a program. Readability, maintainability and especially correctness are more important.

Please tell me ... whether  ... code ... could ... be ... optimized by hand instead of relying on the compiler.

Everything could be optimized by hand, at least if you write the program in assembly.

... or should ...

No. There is no reason to waste time doing what the compiler has already done for you.

There are sometimes reasons to optimise by hand something that is already well optimised by the compiler. Relative speedup is not one of those reasons. An example of a valid reason is that the non-optimised build may be too slow to be executed for debugging purposes when there are real time requirements (whether hard or soft) involved.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two filter in one line? is possible? using Javascript filter I have two filter function but is possible to be in one line?
Check my code:
this is work fine but is possible to be on one line?

A: Boolean is just filtering for truthy values, so you can write the filter with just &&:
let newValue = objectVersion.filter((al) => al && (al.status || al.data));

A: Well, filter() returns an array, and filter() can be called on an array.  Which the code shown already demonstrates.  So you can certainly remove the intermediate variable and just call filter() directly on the result of the previous filter() operation:
let newValue = objectVersion.filter(Boolean).filter((al) => al.status || al.data);

You can also combine the logic into a single call to filter().  What is Boolean in this case?  Is it just looking for any values which are "truthy"?  If so then you can do something like this:
let newValue = objectVersion.filter((al) => al && (al.status || al.data));

Or if it's meant here to represent a function that you otherwise pass to filter() then you can invoke it just the same:
let newValue = objectVersion.filter((al) => yourFunction(al) && (al.status || al.data));

Basically, yes... You can combine any boolean expressions into one larger expression or alternatively you can chain as many calls to filter() (or any other array method which returns an array) as you like.


text:
Q: Upgrade to Debian testing shows only white noise I've installed Debian on my desktop, but now all I can see is white noise on my screen.

*

*started with a squeeze netinstall

*updated my /etc/apt/sources.list from:
# deb http://ftp.belnet.be/debian/ squeeze main

deb http://ftp.belnet.be/debian/ squeeze main
deb-src http://ftp.belnet.be/debian/ squeeze main

deb http://security.debian.org/ squeeze/updates main
deb-src http://security.debian.org/ squeeze/updates main

# squeeze-updates, previously known as 'volatile'
deb http://ftp.belnet.be/debian/ squeeze-updates main
deb-src http://ftp.belnet.be/debian/ squeeze-updates main

to:
deb http://ftp.belnet.be/debian/ wheezy main contrib non-free
deb-src http://ftp.belnet.be/debian/ wheezy main contrib non-free

deb http://security.debian.org/ wheezy/updates main contrib non-free
deb-src http://security.debian.org/ wheezy/updates main contrib non-free

*Run:
aptitude update
aptitude install apt dpkg aptitude
aptitude full-upgrade

The only thing that stood out during the upgrade was the warning that firmware for r8169 was no longer installed.
During the boot I can see normal text, but - before I need to type my password - my screen only shows white noise.
Edit:

*

*The /home directory is coming from a Ubuntu (11.04 upgraded to 11.10).

*I haven't installed X yet. On my first install run (this is currently the third), I tried installing X to "fix" the problem, but that resulted in the same thing (although there was a different noise block for my mouse that I could move around).

*Copied the syslog to gist-8929da15


text: Q: Is there a way to capture a screenshot or element via PHP? I have a graph that is created using Google Charts.  Is there a way to screengrab a chart that is created by Google Charts  on the backend?  My guess is no, however just wanted to make sure there is no way to grab a front-end feature on the backend.  I've searched for libraries that can do this and it doesn't seem like something like this makes sense. Any insight is appreciated.


text:
Q: PostgreSQL Partitioning. Constraint Exclusion not kicking in on SELECT My partitioned table SELECT queries include all partitioned tables even though checks are in place and constraint_exclusion = on.
The insert trigger works fine and new rows are inserted into the correct tables. The SELECT however runs over all tables regardless of my WHERE clause.
Here is my config:
constraint_exclusion = on (both in postgresql.conf and also tried with "ALTER DATABASE bigtable SET constraint_exclusion=on;")

Master Table:
CREATE TABLE bigtable (
    id bigserial NOT NULL,
    userid integer NOT NULL,
    inserttime timestamp with time zone NOT NULL DEFAULT now()
)

Child Table 1:
CREATE TABLE bigtable_2013_11 (CHECK ( inserttime >= DATE '2013-11-01' AND inserttime < DATE '2013-12-01' )) INHERITS (bigtable);

Child Table 2:
CREATE TABLE bigtable_2013_12 (CHECK ( inserttime >= DATE '2013-12-01' AND inserttime < DATE '2014-01-01' )) INHERITS (bigtable);

Stored Procedure:
CREATE OR REPLACE FUNCTION bigtable_insert_function()
RETURNS TRIGGER AS $$
BEGIN

    IF ( NEW.inserttime >= DATE '2013-11-01' AND NEW.inserttime < DATE '2013-11-01' ) THEN
        INSERT INTO bigtable_2013_11 VALUES (NEW.*);
    ELSEIF (NEW.inserttime >= DATE '2013-12-01' AND NEW.inserttime < DATE '2014-01-01' ) THEN
        INSERT INTO bigtable_2013_12 VALUES (NEW.*);
    ELSE
        RAISE EXCEPTION 'Bigtable insert date is out of range!';
    END IF;

    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

Trigger:
CREATE TRIGGER bigtable_insert_trigger BEFORE INSERT ON bigtable FOR EACH ROW EXECUTE PROCEDURE bigtable_insert_function();

It's pretty much the text book setup. The insert works fine:
INSERT INTO bigtable (userid, inserttime) VALUES ('1', now());

Above insert results in the new row being inserted correctly into 'bigtable_2013_11' only.
However I can't get the SELECT to exclude the irrelevant tables. All SELECTs always run over all tables. I would expect bigtable_2013_12 to be excluded when following SELECT queries are used:
SELECT * FROM bigtable WHERE inserttime >= DATE '2013-11-01'::date AND inserttime < '2013-12-01'::date;

SELECT * FROM bigtable WHERE EXTRACT(MONTH FROM inserttime) = 11 AND EXTRACT (YEAR FROM inserttime) = 2013;

However the result is always this:
"Result  (cost=0.00..68.90 rows=17 width=20)"
"  ->  Append  (cost=0.00..68.90 rows=17 width=20)"
"        ->  Seq Scan on bigtable  (cost=0.00..0.00 rows=1 width=20)"
"              Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"
"        ->  Seq Scan on bigtable_2013_11 bigtable  (cost=0.00..34.45 rows=8 width=20)"
"              Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"
"        ->  Seq Scan on bigtable_2013_12 bigtable  (cost=0.00..34.45 rows=8 width=20)"
"              Filter: ((inserttime >= '2013-11-02'::date) AND (inserttime < '2013-11-30'::date))"

Why are my checks not kicking in? I am out of ideas. Everything seems to be setup correctly. Did I miss anything? Any help would be greatly appreciated.

A: There are two things here. One is the seq scan. The other is the union all (i.e. append operator). The latter is completely unavoidable insofar as I'm aware. That is how table inheritance works -- or so it did last I used it. *However*, and this brings us to the former, you can add an index on that date field to eliminate the unneeded seq scans and bail early.

Or, possibly something related to date/timestamp conversions.


text:
Q: Capacitor? Replacement with what value
I have never seen this kind of component.
It looks like a resistor but the symbol and name says it is a capacitor.
Assuming it is a capacitor and the colour code brown black yellow the colour code website says the following result
100 nF ±2% (min:98, max:102 nF) 500V.
I want to replace it, please guide me what value capacitor should I replace it with
I have the following capacitor (image added.)

*

*104K 630V

*2A104J

*104J 400V

*Disk type 104 AEC

*104J200 PFV 0545

A: It's a ceramic capacitor- the disk capacitor would be the closest replacement. The other types have more inductance so they are less suited for supply bypass.
Of course you can only check such capacitors out of circuit, which your photo suggests you may not have done.
The band looks more orange to me on this device which would mean 103 or 0.01uF/10nF. Perhaps there is another similar one on the board which you can compare.
On the other hand, if it's a power supply bypass, then a 10:1 increase may not be an issue.


text:
Q: Can't Segue to another View Controller only on Device. SWIFT I am trying to segue to another view controller, which works fine in the simulator. But when doing it on the device it just crashes and callback says:

fatal error: unexpectedly found nil while unwrapping an Optional value

I get the same callback is I try to segue through the storyboard like this:
func letsGoPressed(sender: UIButton!) {

        performSegueWithIdentifier("goToQuestions", sender: self)
}

or if I try to instantiateViewControllerWithIdentifier like this:
func letsGoPressed(sender: UIButton!) {

      let questionsGameVC: QuestionsGame = self.storyboard?.instantiateViewControllerWithIdentifier("Questions") as! QuestionsGame
      var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical

     questionsGameVC.modalTransitionStyle = modalStyle

     self.presentViewController(questionsGameVC, animated: true, completion: nil)

    }

These both work on the simulator just not on the device!??!

A: Sounds like the cached version of the storyboard didn't have a goToQuestions segue or a view controller with a Questions identifier.
Also you can delete : QuestionsGame here:
let questionsGameVC: QuestionsGame = self.storyboard?.instantiateViewControllerWithIdentifier("Questions") as! QuestionsGame

Since you're explicitly casting the type using as!, there's no need to also declare the type.


text:
Q: Jquery Jqgrid Datepicker hidden even after adjusting z-index I have a grid and I have searched for quite a while trying to find a solution to make the datepicker display when the grid has cellEdit: true.  Many of the articles I found say that the z-index has to be adjusted but this hasn't worked for me.  I have tried adjusting it in the .htm head section like the code below as well as in the .css file of the jqgrid.  If I click on the cell nothing happens but if I click away on a different web page and come back the date dialog pop-up is displayed.  What is keeping it hidden even after adjusting the z-index?  Below I have put !important so this information would hopefully not be overriden.
Thanks.
    <style type="text/css">
    .ui-datepicker { width: 17em; padding: .2em .2em 0; display: none; z-index: 2000 !important;}
    </style>

    ==================================================

 {name:'LOCK_EXPIRATION_DATE',index:'LOCK_EXPIRATION_DATE', width:80, width:90, sorttype:"date",align:'left',sortable:'true',editable:true,fixed:true, editoptions: { dataInit: function(el) { setTimeout(function() { $(el).datepicker(); }, 200); } },
    ==================================================
    onSelectRow: function(id){ if(id && id!==lastsel3){ jQuery('#list4').jqGrid('restoreRow',lastsel3); jQuery('#list4').jqGrid('editRow',id,true,pickdates); lastsel3=id; } },

    ==================================================

        cellEdit: true,

    ==================================================

A: You can define the z-index of the datepicker in its dataInit function by adding the property in datepicker definition as. instead of directly using $(el).datepicker();. This will help modify the datepicker on initialization of the datepicker from jqGrid
$(el).datepicker({
    beforeShow:function(input,inst){
          setTimeout(function(){
         $(".ui-datepicker").css("z-index", 2000);}, 10);
    }
});


text:
Q: Is it possible with imagemagick-convert to dynamically calculate a rotation angle while processing images? I'd like to place a watermark diagonally over a number of images. Since the dimensions of these images vary, but the watermark should always have the maximal possible size at constant proportions, I have to calculate the perfect angle for the resizing. (It should look like that. Not like that.)
I use the following algorithm:
ratio1 = pic1_width / pic1_height
ratio2 = pic2_width / pic2_height
angle = atan ((ratio1 - ratio2) / (1 - ratio1 * ratio2))

For a detailed explanation see here.
Is there any way to do this calculation dynamically during image processing?
I'm using ImageMagick 6.8.9-9 Q16 x86_64 on Ubuntu Linux.
In Bash it might look something like this (without the resizing):
convert -background none -gravity center -density 300 "$pic" \
    \( "$wmark" -rotate "%[fx:atan(((u.w/u.h)-(v.w/v.h))/(1-(u.w/u.h)*(v.w/v.h)))]" \) \
    -compose over -composite "$result"

The code does not rotate the image. I think that's because "-rotate" does not accept "%[fx:]" arguments? Unfortunately, I have not been able to find clear information about this so far ...
In addition, the variables "w" and "h" seem to have the value "0" ... which I also do not understand.
Best regards
AFoeee

A: For the sake of completeness, here is the solution that was created with help from the ImageMagick Community:
wmark="watermark.png"
file="some.pdf"
result="result.jpg"

rotation="%[fx:ratioUF=u.w/u.h; ratioWM=v.w/v.h; t*(atan((ratioUF-ratioWM)/(1-ratioUF*ratioWM))*180/Pi)]"

magick  -define registry:temporary-path=/tmp/imagemagick \
        -background none \
        -density 300 \
        "$file" \
        -bordercolor none -border 1x1 -trim +repage \
        "$wmark" \
        -rotate "$rotation" \
        -resize "%[fx:u.w]x%[fx:u.h]" \
        -compose over -gravity center -composite \
        -background white \
        -flatten \
        "$result"

This approach requires IM7.
Best regards
AFoeee


text:
Q: Android Volley Recyclerview, it works sometimes, but mostly not at all So I made a recyclerview and when I ran the first time the code it worked. However, when I open my app again just to see it fails to populate the recyclerview list.
time to time it will work, like when I have to change the IP again, but then it doesn't always. I'm left wondering why it fails, i only have 4 data records and 5 textviews inside each recylerview row.
Please help, I don't have anyone to check my codes personally so I'm appealing to the community, this is for my final thesis, not the exact codes, but once I get the hang of the recyclerview I think I could finish in time.
I have the my codes in github: https://github.com/jhungamesh/Volleylist3

A: It is totally not encouraged to give URL of your whole project when it consists only of a total of 5 files and only 2 files are relevant to your error.
In your file BackgroundTask you are getting json from:
String json_url = "http://192.168.1.109/Sup2.php";

which is not at all reachable from outside of your network.
posting working code by given in answer here
MainActivity:
public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerAdapter adapter;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<Scoreboard_Item> arrayList;

    //Your Url Change Live Url Put Here
    String mJSONURLString = "http://192.168.1.109/Sup2.php";

    //My testing Url
    String mJSONURLStrings = "http://pastebin.com/raw/Em972E5s";

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

        arrayList=new ArrayList<>();
        recyclerView = (RecyclerView) findViewById(R.id.RecList);
        CallApi();

       /// BackgroundTask backgroundTask = new BackgroundTask(MainActivity.this);
      //  arrayList = backgroundTask.getList();
        //fillPeople();

    }

    public void CallApi(){
        RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());

        // Initialize a new JsonArrayRequest instance
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                Request.Method.POST,
                mJSONURLStrings,
                 null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for(int i=0;i<response.length();i++){

                            JSONObject data = null;
                            try {
                                data = response.getJSONObject(i);

                                //My Data
                                String firstName = data.getString("firstname");
                                String lastName = data.getString("lastname");
                                String age = data.getString("age");

                                //Scoreboard_Item scoreboard_item = new Scoreboard_Item(student.getString("Username"), student.getString("Team1"), student.getString("Team2"), student.getString("Sport"), student.getString("Status"));
                                Scoreboard_Item scoreboard_item = new Scoreboard_Item(firstName, lastName, age, age, firstName);

                                arrayList.add(scoreboard_item);
                                layoutManager = new LinearLayoutManager(getBaseContext());
                                recyclerView.setLayoutManager(layoutManager);
                                recyclerView.setHasFixedSize(true);
                                adapter = new RecyclerAdapter(arrayList);
                                recyclerView.setAdapter(adapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            // Get the current student (json object) data

                            // Display the formatted json data in text view

                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){
                        // Do something when error occurred

                    }
                }
        );

        // Add JsonArrayRequest to the RequestQueue
        requestQueue.add(jsonArrayRequest);

}
}

Model class
public class Scoreboard_Item {

String Username, Team1, Team2, Sport, Status;

public Scoreboard_Item(String username, String team1, String team2, String sport, String status) {
    this.setUsername(username);
    this.setTeam1(team1);
    this.setTeam2(team2);
    this.setSport(sport);
    this.setStatus(status);
}

public String getUsername() {
    return Username;
}

public void setUsername(String username) {
    Username = username;
}

public String getTeam1() {
    return Team1;
}

public void setTeam1(String team1) {
    Team1 = team1;
}

public String getTeam2() {
    return Team2;
}

public void setTeam2(String team2) {
    Team2 = team2;
}

public String getSport() {
    return Sport;
}

public void setSport(String sport) {
    Sport = sport;
}

public String getStatus() {
    return Status;
}

public void setStatus(String status) {
    Status = status; }}

Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

ArrayList<Scoreboard_Item> arrayList = new ArrayList<>();

public RecyclerAdapter(ArrayList<Scoreboard_Item> arrayList){
    this.arrayList = arrayList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, parent,false);
    MyViewHolder myViewHolder = new MyViewHolder(view);
    return myViewHolder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.Username.setText(arrayList.get(position).getUsername());
    holder.Team1.setText(arrayList.get(position).getTeam1());
    holder.Team2.setText(arrayList.get(position).getTeam2());
    holder.Sport.setText(arrayList.get(position).getSport());
    holder.Status.setText(arrayList.get(position).getStatus());

}

@Override
public int getItemCount() {
    return arrayList.size();
}

public static class MyViewHolder extends RecyclerView.ViewHolder
{
    TextView Username, Team1, Team2, Sport, Status;
    //ImageView imageView;
    public MyViewHolder(View itemView) {
        super(itemView);
       //imageView =(ImageView) itemView.findViewById(R.id.imageView);
        Username = (TextView)itemView.findViewById(R.id.Username);
        Team1 = (TextView)itemView.findViewById(R.id.Team1);
        Team2 = (TextView)itemView.findViewById(R.id.Team2);
        Sport = (TextView)itemView.findViewById(R.id.Sport);
        Status = (TextView)itemView.findViewById(R.id.Status);
    }   }}

A:     //Add This Library in app gradle
      implementation 'com.android.volley:volley:1.1.0'
    //Not Use
    //Depricate compile 'com.mcxiaoke.volley:library:1.0.19'

   public void CallApi(){
        RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());

        // Initialize a new JsonArrayRequest instance
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                Request.Method.POST,
                mJSONURLStrings,
                 null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        for(int i=0;i<response.length();i++){

                            JSONObject data = null;
                            try {
                                data = response.getJSONObject(i);

                                //My Data
                                String firstName = data.getString("firstname");
                                String lastName = data.getString("lastname");
                                String age = data.getString("age");

                                //Scoreboard_Item scoreboard_item = new Scoreboard_Item(student.getString("Username"), student.getString("Team1"), student.getString("Team2"), student.getString("Sport"), student.getString("Status"));
                                Scoreboard_Item scoreboard_item = new Scoreboard_Item(firstName, lastName, age, age, firstName);

                                arrayList.add(scoreboard_item);
                                layoutManager = new LinearLayoutManager(getBaseContext());
                                recyclerView.setLayoutManager(layoutManager);
                                recyclerView.setHasFixedSize(true);
                                adapter = new RecyclerAdapter(arrayList);
                                recyclerView.setAdapter(adapter);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){
                        // Do something when error occurred

                    }
                }
        );
        // Add JsonArrayRequest to the RequestQueue
        requestQueue.add(jsonArrayRequest);

}

A: https://drive.google.com/open?id=1x4Q8_7ZuWGkkK9kLzg1YAeAbScfaMJRs Please Checkout comments in code.


text:
Q: Php seven update messed up my program So recently with the php 7 update they removed all the mysql commands. however one of my programs for my internship was using such commands in one of the pages. however when i change it to mysqli it no longer works like it should. can someone help perhaps?
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());

//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());

$result = mysqli_query($connection, "SELECT * FROM gebiedsmanagers WHERE Datum >= NOW()");

Pastebin code
With kind regards,
Dayne Tersluijsen

A: Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given:
mysqli_select_db("prodyne", $con);

To
mysqli_select_db($con, "prodyne")

Try this out!
    <?php

    //MySQLi information

    $db_host     = "localhost";
    $db_username = "username";
    $db_password = "password";

    //connect to mysqli database (Host/Username/Password)
    $connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());

    //select MySQLi dabatase table
    $db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());

    //fetch information from your database
    $result = mysqli_query($connection, "SELECT * FROM gebiedsmanagers WHERE Datum >= NOW()");
      while($row = mysqli_fetch_array($result))

               {
                  $counter ++;

?>

<?php echo date('d-m-Y', strtotime($row['Datum']));?>
<?php echo $row['Voor1500']; ?>	<?php echo $row['Na1500']; ?>

<?php

             if($counter >= 120) {
                break;
          }

I hope this has helped you.


text:
Q: Alternate to Sling JSP recompile for Sightly/HTL? Is there any alternate feature similar to sling JSP recompile button in OSGI Felix console for HTL/Sightly components code refresh.?
http://host:port/system/console/slingjsp

A: AFAIK, I don't see any such kind of feature like one button click trigger to recompile options for the Sightly in AEM. but you can use Development Mode check box enabled in Apache Sling Scripting Sightly Engine Configuration at Felix console which results Sightly components recompilation at every request. have a look at sightly documentation for more information related to this. also from grepcode for SightlyEngineConfiguration


text:
Q: How to use logging in pydantic/fast API I am using fast API for creating an API and want to use logging to create csv logs.
The API code looks like below:
@app.post("/path")
async def return_something(header: header, body: body):
    ...
    logger.info('....')
    return something

Pydantic models are defined like this:
class header(BaseModel):
    field1: str
    field2: list

I am using logger like this
from logger import ApplicationLogger
logger = ApplicationLogger()

The question is how can I use the existing longing to log pydantic errors for field verification?

A: Depending on you use case, you could utilize below implementations. Both implement a middleware exception_handler for the purpose of capturing a  ValidationError or RequestValidationError. You could log whatever you need within your middleware as precised below. For more information you could check these Github issues (https://github.com/tiangolo/fastapi/issues/1486, https://github.com/tiangolo/fastapi/pull/853)
app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc: Exception):
    """LOG HERE"""
    return PlainTextResponse(str(exc), status_code=400)

or
app = FastAPI()

async def http422_error_handler(
    _: Request, exc: Union[RequestValidationError, ValidationError]) -> JSONResponse:
    """LOG HERE"""
    return JSONResponse(
        {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY
    )

app.add_exception_handler(ValidationError, http422_error_handler)
app.add_exception_handler(RequestValidationError, http422_error_handler)

A: Pydantic will automatically log errors to your terminal with the validation is not correct.
You can also log the schema like this:
logger.info(f"header schema: {header}")


text:
Q: Using map() to map a button to a Bootstrap 5 grid that spans multiple rows I am using the map() method to map buttons onto a Bootstrap 5 grid, but I want one of the buttons to span two rows. I know that in Bootstrap the way to do this is to nest two rows in the column that I wish to span two rows, but I'm wondering if this is possible using the map() method? I know that I could not use the map method and type out all the rows, columns and button elements separately, but I would like to know if it is possible using the map() method. The difficulty is that map() repeats elements, but in this case I would need to essentially insert an extra row.
Here is my code:
class ButtonGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      currentButton: ''
    }
    this.handleClick=this.handleClick.bind(this);
  }
  buttonGridArr=[
  {
    id: 'clear',
    text: 'C',
    grid: 'col-6 g-0'
  },
  {
    id: 'add',
    text: '+',
    grid: 'col-3 g-0'
  },
  {
    id: 'subtract',
    text: '-',
    grid: 'col-3 g-0'
  },
  {
    id: 'seven',
    text: '7',
    grid: 'col-3 g-0'
  },
  {
    id: 'eight',
    text: '8',
    grid: 'col-3 g-0'
  },
  {
    id: 'nine',
    text: '9',
    grid: 'col-3 g-0'
  },
  {
    id: 'multiply',
    text: 'x',
    grid: 'col-3 g-0'
  },
  {
    id: 'four',
    text: '4',
    grid: 'col-3 g-0'
  },
  {
    id: 'five',
    text: '5',
    grid: 'col-3 g-0'
  },
  {
    id: 'six',
    text: '6',
    grid: 'col-3 g-0'
  },
  {
    id: 'divide',
    text: '÷',
    grid: 'col-3 g-0'
  },
  {
    id: 'one',
    text: '1',
    grid: 'col-3 g-0'
  },
  {
    id: 'two',
    text: '2',
    grid: 'col-3 g-0'
  },
  {
    id: 'three',
    text: '3',
    grid: 'col-3 g-0'
  },
  {
    id: 'equals',
    text: '=',
    grid: 'col-3 g-0'
  },
  {
    id: 'zero',
    text: '0',
    grid: 'col-6 g-0'
  },
  {
    id: 'decimal',
    text: '.',
    grid: 'col-3 g-0'
  }]
  handleClick(event) {
    this.setState(state=>({
      currentButton: event.target.value //Updating state with the button clicked
    }));
    console.log(this.state.currentButton); //Delete
  }
  render() {
    return (

        {this.buttonGridArr.map(button=>( //Mapping multiple repeating buttons from an array into a grid

<button type='button' className='btn fw-bold w-100 h-100' key={button.id} id={button.id} value={button.text} style={{color: 'white', borderRadius: '0px'}} onClick={this.handleClick}>{button.text}</button>

        ))}

    );
  }
}

It's the equals button that I want to span two rows.
Thanks in advance!


text:
Q: How Do I Align Right This Text? Can you help me align some text to the right?
The page is here:
http://www.marinhomephotography.com/
I want to align the text in the black navigation menu (Home Gallery Pricing Contact )to the right, but I have not been able to do it using either float right in the div nor text-align; right for the class.
Plus, I'm an idiot. Did I mention that???
Every time I try float: right, either the black navigation bar shrinks, or it disappears.I want it to stay full page width though.
HTML:

Home

Gallery

Pricing

contact

CSS:
.menu-primary, .menu-secondary, #header .menu {
margin: 0;
padding: 0;
overflow: hidden;
width: 100%;
}

.menu-primary li, .menu-secondary li, #header .menu li {
float: left;
list-style-type: none;
text-transform: uppercase;
float: right;
}

Thanks in advance for any help.

A: Add float:right property to following classes:
    .menu-primary li, .menu-secondary li, #header .menu li {
float: right;
}

Here, screenshot of the same - http://prntscr.com/2rxrf1


text:
Q: How can I change the popover color frame? I would change the popover color in an ipad splitview application.
So I would change the default blue color:

in a red color for example. How can I do?

A: Sadly you cannot achieve that as per documentation.
Stated here: iPad - Popover frame color
All you could do it to set the color for the landscape mode as follows:
self.navigationController.navigationBar.tintColor = [UIColor orangeColor];


text:
Q: How do I export a data frame to Excel? I am trying to export a dataframe from R to excel. I am using the 'writexl' package but it does not seem to work.
The code is as following:
install.packages('writexl')
library(writexl)

write_xlsx(data_frame, "H:\\folder1.xlsx")

There does not seem to be any error produced and the code appears to have run, however when I look in 'folder1' the data_frame is not there.
Is there anything I am doing incorrectly?

A: I've found the openxlsx package to be easier to use than the xlsx package. It also doesn't have a java dependency. The main command for directly writing a data frame to an Excel file is write.xlsx. You can also create worksheets, do lots of fancy formatting and write multiple tables to a worksheet (see the vignettes here for some examples), but start with write.xlsx for the basic creation of Excel files.


text:
Q: jquery multiselect reload How can I add or remove options in JQuery UI Multiselect ? I am initializing the multiselect on page load and I need to remove existing values and add new values based on another selection. I am initializing the multiselect on page load using:
$("#multipleselectboxId").multiselect();

After that, I am adding values to the multiple drop down using jQuery append() and remove() methods which are working fine with original dropdown but in the multiselect are not getting reflected.
Can anyone help with this?

A: For that one you could just destroy and reinitialize after changing...
$("#multipleselectboxId").append(toAppend).multiselect("destroy").multiselect();

There's also another plugin with a refresh function: EricHynds's Multiselect
$("#multipleselectboxId").append(toAppend).multiselect("refresh");

A: I was trying to rebuild multiselect by .multiselect("destroy") and .multiselect(), but it wasnt working, so finally I find this solution worked for me.
$.each(jsonArray, function(i, val) {
    $('#frmarticles-f_category_id').append('<option value="'+i+'">'+val+'</option>').multiselect('rebuild');
});

A: In my case, I just wanted to replace all previous content of multiselect with new.
This worked for me:
$('#multiselect_id').html(newHtml);
$('#multiselect_id').multiselect('refresh');

A: Thank you this helped. I was using multiselect UI widget and this is what worked
jQuery("select[title='" + FieldNameTitleText + "']").append( "<option value='" + OptionValue+ "'>" + OptionText + "</option>" ).multiselect("refresh");

A: Here is what I did:; it may be more than necessary, but it worked for me.
Original "select" code that requires modification:
<select id="MySelect" name="selection">
<option value="1">One</option>
<option value="2">Two</option>
</select>

I rebuild the option list in PHP, send it to the JavaScript via JSON, and construct/store the new list in a variable. E.g.:
// this is similar to if we got it from PHP
var newList = '<option value="A">Alpha</option>
<option value="B">Beta</option>
<option value="C">Gamma</option>';

Now, to switch this around in the jQuery UI Multiselect widget:
$('#MySelect').html(''); // clear out old list
$('#MySelect').multiselect('destroy');  // tell widget to clear itself
$('#MySelect').html(newList); // add in the new list
$('#MySelect').multiselect(); // re-initialize the widget

In particular, I re-initialized it with parameters, e.g.:
$('#MySelect').multiselect({selectedList: 4, header: false});

If anybody has read this far down and is still having troubles, give this a try.

A: I found the solution for this, first destroy the multiselect and reInitialize it, Thanks for @ Brandon Joyce,
solutions for this is
$("#multipleselectboxId").append(toAppend);
$("#multipleselectboxId").remove(toRemove);

$("#multipleselectboxId").multiselect('destroy');
$("#multipleselectboxId").multiselect();

A: well this plugin works fine but I have a pb with destroy and filter: my combo data are loaded with ajax. So, when I refresh the data with ajax call, I call destroy to refresh the plugin:
myCombo.multiselect('destroy');
myCombo.multiselect().multiselectfilter();

It works for the first call: empty combo, ajax call to load data, call the functions above.
But if I refresh the combo data and call again the above functions, the filter disappeared?
Someone experienced this pb before and found a solution?

A: For wenzhixin MultiSelect:
var i = jQuery('input');
i.data('multipleSelect').$parent.remove();
i.removeData('multipleSelect');
i.show();

A: I used it in this way :
$("#<%= cmbInBayiID.ClientID %>").multiselect().trigger('reset');

It worked.

A:     function setMultiSelect(idElement, paramVal){
        eval("$('#"+idElement+"').multiselect('uncheckAll')");
        $.each($('input[name="multiselect_'+idElement+'"]'), function(k,i) {
            if(paramVal.indexOf(this.value)!=-1){
                this.checked = true;
            }
        });
         eval("$('#"+idElement+"').multiselect('update')");
    }

A: var valArr = ["1", "2"],
         i = 0,
      size = valArr.length,
  $options = $('#MySelect option');

for (i; i < size; i++) {
  $options.filter('[value="' + valArr[i] + '"]').prop('selected', true);
}

$('#MySelect').multiselect('reload');

1.valArr is values of select Options
2.for loop to set selected to matched option based on valArr
3.our changes is only in hidden select element
4.to change in multiselect generated elements we need to reload
5.every pluggin may have different name to reload eg:update,refresh

A: I have also experienced the same issue but finally, I resolved. Please use $(selecter).multiselect("refresh"); instead of $(selecter).multiselect("reload");

A: For this first load the option in drop down and then apply multiselect on that
please refer the below code
 for (let mm = 0; mm < msg.d.length; mm++) {
                        $('#ddl_product_lst').append(new Option(msg.d[mm].Text, msg.d[mm].Value));
                    }
                    $('#ddl_product_lst').multiSelect({
                        noneText: '--Select Product--',
                        minWidth: 100

                    });

A: Option 1:
$("#MySelect").multiselect("clearSelection");

Option 2:
$("#MySelect option:selected").removeAttr("selected");
$("#MySelect").multiselect('refresh');


text:
Q: Find the general term of $x_{n+1} = \frac{x_n + 1}{n+1}$ where $x_1 = 0$
Find the general term of $x_{n+1} = \frac{x_{n} + 1}{n + 1}$ where $x_1 = 0$

I've tried finding the general term by introducing a generating function $G(z)$ and then solving for $G(z)$ with no luck.
I've also tried to express $x_n$ and get rid of the constant doing the following:
$$
x_{n+1} = \frac{x_n + 1}{n+1}\\
x_n = \frac{x_{n-1} + 1}{n}
$$
Subtract one from another:
$$
(n+1)\cdot x_{n+1} - n\cdot x_n = x_n - x_{n-1}
$$
So:
$$
(n+1)\cdot (x_{n+1} - x_n) = -x_{n-1}
$$
Not sure how to proceed from here. I've seen how recurrence relations are solve with characteristic equations. Should i introduce some characteristic polynomial and solve it?
Basically i'm more interested in a common approach than in solution (yet an example would be nice) since i am going to solve lots of similar problems after this one.

A: Hint. Let $z_n=n!x_n$ then $z_0=0$ and
$$z_{n+1}=(n+1)!x_{n+1}=n!(n+1)x_{n+1}=n!(x_n+1)=z_n+n!\\=
z_{n-1}+(n-1)!+n!=\sum_{k=1}^n k!$$

A: Another way to find the same answer : let $x_n=\frac{a_n}{b_n}$ (with $a_n$ and $b_n$ integers), then
$$x_{n+1}=\frac{1+\frac{a_n}{b_n}}{n+1}=\frac{a_n+b_n}{(n+1)b_n}$$
so that
$$a_{n+1}=a_n+b_n\text{ and }b_{n+1}=(n+1)b_n$$
with initial conditions $a_1=0$ and $b_1=1$.
Solving this, you find $b_n=n!$, and $a_n=\sum_{k=1}^{n-1}k!$, so
$$x_n=\frac{1!+2!+\dots+(n-1)!}{n!}$$


text:
Q: iOS 7 GraphicsServices private API? I'm developing Cydia tweaks using Theos.
I need to use some functions in the framework GraphicsServices.
I've tried some simple function using GSEvent.
ex:
void GSEventVibrateForDuration(float secs);

void GSEventLockDevice();

But it all doesn't work. The device doesn't vibrate or lock. I'm using iPhone 5, iOS 7.0.4.
Then I found iOS 7 private frameworks on GitHub: https://github.com/EthanArbuckle/IOS-7-Headers/tree/master/PrivateFrameworks/GraphicsServices.framework
Inside GraphicsServices is empty. So I'm wondering where this framework is? Sorry for my bad English, thank you!

A: Most of these headers in the internet are generated by class-dump, which only dumps Objective-C classes.
Purely C API's (like GSEventLockDevice) won't be dumped. You can use disassembler to look at them.
Some private API become protected by entitlements recently. This will produce exactly described behavior (do nothing when called).


text:
Q: How to use Magento 2.3 and Cloudfare CDN? I'm currently trying out the Cloudflare CDN (free plan), but I didn't notice much in website performance. My server was having "server load" problems and it did stop, but It seems the website's performance isn't much better.
I believe It's because of my Magento's CDN configuration:
So, which URL's should I use for static files and media files? I can't find information about that on Cloudfare's website and I don't know if I'm really retrieving the static files from there or elsewhere. I use Cloudflare's extension for Magento.

A: You don't need to configure a different URL to media and static files; Since Cloudflare manages your domain, it'll deliver the static content using their CDN and get the dynamic content from your server, all of it through your domain.
Reference: https://www.cloudflare.com/learning/cdn/caching-static-and-dynamic-content/


text: Q: Automorphisms of order 3 in $C_2$ X $C_2$ X $C_2$ I am trying to find out the number of automorphisms there are in  $C_2$ $\times$ $C_2$ $\times$ $C_2$ $\cong <x,y,z|x^2=y^2=z^2=1>$. I only can come up with the one which moves $x \rightarrow y \rightarrow z \rightarrow x$ and the inverse. However, the problem is that I watched a proyect which says that there are 54 elements of order 3 in the Aut$(C_2 \times C_2 \times C_2)$. I do not know whether I am wrong or the proyect.


text:
Q: Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation I just installed the latest version of Tensorflow via pip install tensorflow and whenever I run a program, I get the log message:

W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

Is this bad? How do I fix the error?

A: To install the prerequisites for GPU support in TensorFlow 2.1:

*

*Install your latest GPU drivers.

*Install CUDA 10.1.

*

*If the CUDA installer reports "you are installing an older driver version", you may wish to choose a custom installation and deselect some components. Indeed, note that software bundled with CUDA including GeForce Experience, PhysX, a Display Driver, and Visual Studio integration are not required by TensorFlow.

*Also note that TensorFlow requires a specific version of the CUDA Toolkit unless you build from source; for TensorFlow 2.1 and 2.2, this is currently version 10.1.

*Install cuDNN.

*

*Download cuDNN v7.6.4 for CUDA 10.1. This will require you to sign up to the NVIDIA Developer Program.

*Unzip to a suitable location and add the bin directory to your PATH.

*Install tensorflow by pip install tensorflow.

*You may need to restart your PC.

A: This answer might be helpful if you see above error but actually you have CUDA 10 installed:
pip install tensorflow-gpu==2.0.0

output:
I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll

which was the solution for me.

A: I installed cudatoolkit 11 and copy dll
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\bin to C:\Windows\System32.
It fixed for PyCharm but not for Anaconda jupyter:

[name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456
locality { } incarnation: 6812190123916921346 , name: "/device:GPU:0"
device_type: "GPU" memory_limit: 13429637120 locality {   bus_id: 1
links {   } } incarnation: 18025633343883307728 physical_device_desc:
"device: 0, name: Quadro P5000, pci bus id: 0000:02:00.0, compute
capability: 6.1" ]

A: This solution worked for me :
I preinstalled the environnement with anaconda (here is the code)
conda create -n YOURENVNAME python=3.6 // 3.6> incompatible with keras
conda activate YOURENVNAME
conda install tensorflow-gpu
conda install -c anaconda keras
conda install -c anaconda scikit-learn
conda install matplotlib

but after I had still these warnings
2020-02-23 13:31:44.910213: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found

2020-02-23 13:31:44.925815: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll

2020-02-23 13:31:44.941384: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll

2020-02-23 13:31:44.947427: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll

2020-02-23 13:31:44.965893: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll

2020-02-23 13:31:44.982990: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll

2020-02-23 13:31:44.990036: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found

How I solved the first warning :
I just download a zip file wich contained all the cudnn files (dll, etc) here : https://developer.nvidia.com/cudnn
How I solved the second warning :
I looked the last missing file (cudart64_101.dll) in my virtual env created by conda and I just copy/pasted it in the same lib folder than for the .dll cudnn

A: Tensorflow 2.1 works with Cuda 10.1.
If you want a quick hack:

*

*Just download cudart64_101.dll from here. Extract the zip file and copy the cudart64_101.dll to your CUDA bin directory

Else:

*

*Install Cuda 10.1

A: TensorFlow 2.3.0 works fine with CUDA 11. But you have to install tf-nightly-gpu (after you installed tensorflow and CUDA 11):
https://pypi.org/project/tf-nightly-gpu/
Try:
pip install tf-nightly-gpu

Afterwards you'll get the message in your console:
I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_110.dll

A: Tensorflow gpu 2.2 and 2.3 nightly
(along CUDA Toolkit 11.0 RC)
To solve the same issue as OP, I just had to find cudart64_101.dll on my disk (in my case C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment (that is add value C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).

A: I solved this another way.
First of all I installed cuda 10.1 toolkit from this link.
Where I selected installer type: exe(local) (for windows) and installed 10.1 in custom mode (without visual studio integration, NVIDIA PhysX because previously I installed CUDA 10.2 so required dependencies were installed automatically)
After installation, From the Following Path
(C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin)
, in my case, I copied cudart64_101.dll file and pasted in
(C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin).
Then importing Tensorflow worked smoothly.

A: download CUDA Toolkit 11.0 RC
To solve the issue,
I just find cudart64_101.dll on my disk
( C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment that is add value (C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).

A: This could be caused by the version of python you are running as well, I was using the python 3.7 from the microsoft store and I run into this error, switching to python 3.10 fixed it.

A: In my case the tensorflow install was looking for cudart64_101.dll

The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1
I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll

This is the wrong file!! cudart64_101.dll ≠ cudart64_110.dll
Solution
Download Cuda 10.1 from https://developer.nvidia.com/
Install (mine crashes with NSight Visual Studio Integration, so I switched that off)

When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing

Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library

You may need a reboot if the path is not picked up by the system straight away

A: Tensorflow 2.1+
What's going on?
With the new Tensorflow 2.1 release, the default tensorflow pip package contains both CPU and GPU versions of TF. In previous TF versions, not finding the CUDA libraries would emit an error and raise an exception, while now the library dynamically searches for the correct CUDA version and, if it doesn't find it, emits the warning (The W in the beginning stands for warnings, errors have an E (or F for fatal errors) and falls back to CPU-only mode. In fact, this is also written in the log as an info message right after the warning (do note that if you have a higher minimum log level that the default, you might not see info messages). The full log is (emphasis mine):

2020-01-20 12:27:44.554767: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-01-20 12:27:44.554964: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.

Should I worry? How do I fix it?
If you don't have a CUDA-enabled GPU on your machine, or if you don't care about not having GPU acceleration, no need to worry. If, on the other hand, you installed tensorflow and wanted GPU acceleration, check your CUDA installation (TF 2.1 requires CUDA 10.1, not 10.2 or 10.0).
If you just want to get rid of the warning, you can adapt TF's logging level to suppress warnings, but that might be overkill, as it will silence all warnings.

Tensorflow 1.X or 2.0:
Your CUDA setup is broken, ensure you have the correct version installed.

A: In a conda environment, this is what solved my problem (I was missing cudart64-100.dll:

*

*Downloaded it from
dll-files.com/CUDART64_100.DLL

*Put it in my conda environment at
C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin
That's all it took! You can double check if it's working:
import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')

A: Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14).
NVIDIA drivers download link here.

A: I ran into this problem when mixing pip & conda to get tensorflow 2.3 installed.  (I used pip to install tensorflow 2.3 b/c at the time conda's install of tensorflow 2.3 was broken.)
I ended up with the incorrect versions of cudatoolkit and cudnn installed.
To solve the problem, I simply did conda install with specific versions of cudatoolkit and cuda specified.
Look at https://www.tensorflow.org/install/source_windows?force_isolation=true#tested_build_configurations for info on tensorflow, cudatoolkit, and cuda versions that should work together.

A: This is just a Warning and Information message that CUDA libraries cannot be found.
If you are using NVIDIA GPU, you can refer to how to install the missing files.
If you don't use NVIDIA GPU, or simply want to ignore the I and W messages, you can add the 2 lines below at the beginning of your code:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

You can see more about TF_CPP_MIN_LOG_LEVEL at TensorFlow logging.

A: I had this error here with tensorboard , it happen after I update the GPU driver
the thing is i was running tensorboard from the cmd where I didn't install any CUDA since I was using anaconda
when you install TensorFlow using anaconda all the required cuda and cudnn are downloaded for you  you will miss the files if you didn't use anaconda env where you install TensorFlow in it

Solution
* just open tensoboard from anaconda
1-or just download the last Cuda toolkit and add it to paths
https://developer.nvidia.com/cuda-toolkit-archive
and use this
2-conda install -c anaconda cudatoolkit
3-then restart your pc

A: I too have faced similar issues and realized that the issue was with CUDA and CUDNN version mismatch.
Can refer here for the proper versions. From the reference below for TensorFlow 2.4.0 it is recommended to use CUDA 11.0 and cuDNN 8.0.

Or you can refer here to download cuDNN for suitable CUDA.

A: A simpler way would be to create a link called cudart64_101.dll to point to cudart64_102.dll. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this assumption (mileage may vary).


text:
Q: PowerShell to change "Date Modified" base on a specific date for Multiple Files I am trying to change the "Date Modified" (LastWriteTime) of over 2K files in a specific folder. All files were modified on the same Day. However, it does have multiple times. So, basically what I am trying to accomplish is this:
Myfile1.Zip --> Date Modified = "1/4/2022 12:21 PM" ==> Date Modified = "1/3/2022 9:00 AM"
Myfile2.Zip --> Date Modified = "1/4/2022 12:25 PM" ==> Date Modified = "1/3/2022 9:00 AM"
Meaning that all files that were Modified on 1/4/2021 needs to display "Date Modified" as 1/3/2021, time really does not matter here.
Is it possible to do a bulk change with a PowerShell Script? I am not familiar at all with it.

A: You can inspect the existing LastWriteTime property on file system objects returned by Get-ChildItem, then assign a new value to the same:
# define date/time variables
$filterDate = (Get-Date -Day 4 -Month 1 -Year 2022).Date
$targetDateTime = Get-Date -Day 3 -Month 1 -Year 2022 -Hour 9 -Minute 0 -Second 0

# locate and filter relevant files
$relevantFiles = Get-ChildItem -Path .\path\to\folder\ |Where-Object { $_.LastWriteTime.Date -eq $filterDate }

# update their timestamps
$relevantFiles |ForEach-Object {
  $_.LastWriteTime = $targetDateTime
}

Dereferencing the Date property on an existing [DateTime] value gives you the date at midnight, so the comparison $_.LastWriteTime.Date -eq $filterDate will work regardless of whether the file was updated at 1AM or 6PM, as long as it was on January 4.


text:
Q: How to clone BLE device (configurations,charcterstics etc)and share it with other I am working on an app that gets data from the BLE device, I am able to code to get the app to connect with the BLE device. But further characteristics read is an issue as I don't physically have the device
i came across an app named nRF Connect for Mobile . It has the functionality to clone BLE if paired. the video for a BLE clone is shown here but export and import is not avaible
Is there any way I can get the BLE cloned say some configuration file, which then imported in certain app create then same BLE device .i can use to read all the characteristics and other properties

A: Why don't you just connect to the device in for example nRF Connect, write down the services, characteristics and descriptors you see (usually isn't that many). Then just set up a local GATT server with the same content.

A: If I understood your question and your video correctly, you would like to copy the advertisement data of a BLE peripheral and use it to advertise on an iOS device yourself.
Maybe CBPeripheralManager can help you do that.
You can call startAdvertising([String:Any]?) and advertise a BLE peripheral.
But iOS limits on a system level which keys you can advertise.
From a short look in the documentation, it seems only the keys

*

*CBAdvertisementDataLocalNameKey

*CBAdvertisementDataServiceUUIDsKey
are supported.
But if you'd want to include more information about your peripheral, you could still create an own CBMutableService "deviceInfo" and send information within a characteristic after having established a connection.


text:
Q: "Dashboard component order" in the mobile app and email subscriptions are messed up If you have a dashboard with 9 components which are arranged like this on the desktop:
1   2   3
4   5   6
7   8   9

... then obviously, the reader reads the screen in a left-to-right order, like this:
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9.

However, it shows up on the mobile app as well as in email subscriptions in a top-down order, which completely messes up the experience, like this:
1
4
7
2
5
8
3
6
9

How can this be rectified?
The desired order in mobile app as well as in email subscriptions is obviously:
1
2
3
4
5
6
7
8
9

A: The solution is to have 2 dashboards:
Dashboard for desktop:
1   2   3
4   5   6
7   8   9
Dashboard for mobile and email subscriptions:
1
2
3
4
5
6
7
8
9


text:
Q: Versioning resources in REST api I have created an application which is exposed as a web service. I am trying to follow REST principles. I am using Spring 4.
What I have done so far is to create my own mime type application/vnd.mycompany-v1+json. From the clients accessing the web service I say which version I want (currently only one).
However, this is not all I need to do. I also need to keep different versions of the resources since I may add/remove properties etc from one version to another. What is the approach to solve this? Do you create a package for each version?
com.mycompany.web.resources.v1.Bike, com.mycompany.web.resources.v2.Bike, etc? This approach would work I guess but the number of versions is not known in this stage so it could be a large list of duplicates. I don't know if this is a problem or if it is the way it must be?
I guess I am not the first one thinking of versioning the resources too so how is this handled?

A: You should keep different versions by adding versioning information in resource url. Something like http://yourserver/app/v1/..
The reason you should include versioning in your api is that some of the clients may already be using your previous version and do not want to upgrade. This is more for adding flexibility in your api design. Ofcourse as an api provider you can always declare that you will not support version x from now onwards.


text:
Q: Javascript: fadeIn() function not working? I have two functions.
setBindings() that scrolls to the a particular div when a menu item in the nav is clicked.
aboutSectionFadeIn(), second function is a simple that uses fadeIn() to Fade in and Fade out a particular div.
The issue is the setBindings() stops working on aboutSection div when I use the aboutSectionFadeIn() in my code, it stops scrolling to the a div that is clicked. I don't understand why. Any idea?
Here is the javascript code:
$(document).ready(function() {

setBindings();
aboutSectionFadeIn();
});

function setBindings() {
$("nav a").click(function(e) {
 // stops the a tags for working.. i.e. clicking to another page. Functions stops the functionality.
var sectionID = e.currentTarget.id + "Section";
// alert('button id ' + sectionID);

$("html,body").animate({
  scrollTop: $("#" + sectionID).offset().top
    }, 500)
 })

}

function aboutSectionFadeIn() {

$('#aboutSection').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, delay);
    });

    $(window).scroll(function () {
        if ($(this).scrollTop() >= 20) {        // If page is scrolled more than 20px
            $('#aboutSection').fadeIn(1000);
        } else {
            $('#aboutSection').fadeOut(200);
        }
    });
}


text:
Q: I need to put a label in the right hand corner of my popup in XAML Here is my code. I have tried several things to get the label in the top right hand corner of the popup and make it stay there, but nothing has worked.
Thanks for your help!
XAML:
<Window x:Class="ValidationWPF.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
                xmlns:local="clr-namespace:ValidationWPF"
                Title="MainWindow" mc:Ignorable="d"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="259" d:DesignWidth="420" SizeToContent="WidthAndHeight">
    <Grid Height="129" Width="345">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="514*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="0" />
            <RowDefinition Height="251*" />
        </Grid.RowDefinitions>
        <Button Content="Errors" Height="23" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Top" Width="75" Grid.Column="1" Grid.Row="1" Margin="132,12,0,0" MouseEnter="button1_MouseHover">

        </Button>

            <Popup AllowsTransparency="True" PlacementTarget="{Binding ElementName=button1}" StaysOpen="True" AllowDrop="True" Name="PopUp1" PopupAnimation="Scroll">

            <Popup.Child>
          <Border BorderBrush="White" BorderThickness="3, 3, 0, 0">
            <Border BorderBrush="Black" BorderThickness="3, 3, 3, 3">

                <TextBlock Background="Salmon">

                  <Label Background="AliceBlue" Foreground="Black" HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" MouseDown="mouse_DownHandeled" AllowDrop="False" Margin="100,100,0,0">
                    x
                    </Label>

                    <local:ValidationUserControl/>
                </TextBlock>
            </Border>

        </Border>
         </Popup.Child>
            </Popup>

     </Grid>
</Window>

As you see, I have a popup with a label that has an X in it. The label is fully functional. Now I just need it to look like a normal popup with the label in the top right hand corner.

A: Try this:
<TextBlock Background="Salmon" MinWidth="150" MinHeight="150" VerticalAlignment="Top">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120" />
            <ColumnDefinition Width="30" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="120" />
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="1" Background="AliceBlue" Foreground="Black" VerticalAlignment="Top" AllowDrop="False">
            X
        </Label>
    </Grid>
</TextBlock>


text:
Q: Intellisense in ev3 micropython not working I'm starting now to program in EV3 Micropython, and I can't get the Intellisense to work. How can I solve this problem? I've tried everything. If someone could help me, it would mean a lot to me... Thanks!

A: I've already fixed it, but a lot of people may be in the same situation, so here is how I fixed:
1- Select python interpreter version 3.9.6
2- Disable and enable the python extension
You are welcome.


text:
Q: Can't include both subject AND body using mailto via Mac OS X "open" command I just figured here out how to open a pre-populated new email message window using c++ on Mac OS X via the "open" command.
Unfortunately I couldn't get it to insert both a message body and a subject.
This code should open a new message with a recipient, a subject and a body filled in but it doesn't. Only the recipient and subject are filled in.
mailto:obama@whitehouse.gov?subject=Congrats%20Obama&body=Hello

If I remove the subject, it would successfully include the recipient and body such as in this code so the body itself doesn't seem to be incorrectly formatted.
mailto:obama@whitehouse.gov?body=Hello

Please let me know if you can figure out how to open a "new message" window with both a subject AND a body message.

A: The ampersand (&) is the culprit; everything before it executes in the background and body=... executes separately.
Escape it with a backslash.
Since this is a C++ string, you also need to escape the backslash itself; \\&.

A: This would be the right string to use:
mailto:obama@whitehouse.gov?subject=Congrats%20Obama&body=Hello


text:
Q: "Cannot find module" error on Heroku when deploying So, I am making an app with React, and I am deploying it to Heroku afterwards. Everything works great in localhost and without any errors, and webpack also compiles with no errors. I have set env variales on Heroku as well.
However, when I deploy it to Heroku I get a blank screen and this error in console(I am requiring TodoApi properly and have tried various ways - import etc., it works in localhost with no issues):
I am trying to figure out it for days, so any help is much appreciated.
Uncaught Error: Cannot find module "TodoApi"
    at bundle.js:20
    at Object.<anonymous> (bundle.js:20)
    at t (bundle.js:1)
    at Object.<anonymous> (bundle.js:20)
    at t (bundle.js:1)
    at Object.<anonymous> (bundle.js:3)
    at Object.<anonymous> (bundle.js:3)
    at t (bundle.js:1)
    at Object.<anonymous> (bundle.js:1)
    at t (bundle.js:1)

Here are my webpack and package.json files:
var webpack = require('webpack');
var path = require('path');
var envFile = require('node-env-file');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

try {
    envFile(path.join(__dirname, 'config/' + process.env.NODE_ENV + '.env'));
} catch(e) {

}

module.exports = {
  entry: [
    'script!jquery/dist/jquery.min.js',
    'script!foundation-sites/dist/js/foundation.min.js',
    './app/app.jsx'
  ],
  externals: {
      jquery: 'jQuery'
  },
  plugins: [
      new webpack.ProvidePlugin({
          '$': 'jquery',
          'jQuery': 'jquery'
      }),
      new webpack.optimize.UglifyJsPlugin({
          compressor: {
              warnings: false
          }
      }),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(process.env.NODE_ENV),
          API_KEY: JSON.stringify(process.env.API_KEY),
          AUTH_DOMAIN: JSON.stringify(process.env.AUTH_DOMAIN),
          DATABASE_URL: JSON.stringify(process.env.DATABASE_URL),
          STORAGE_BUCKET: JSON.stringify(process.env.STORAGE_BUCKET),
          MESSAGING_SENDER_ID: JSON.stringify(process.env.MESSAGING_SENDER_ID)
        }
      })
  ],
  output: {
    path: __dirname,
    filename: './public/bundle.js'
  },
  resolve: {
    root: __dirname,
    modulesDirectories: [
        'node_modules',
        './app/components',
        './app/api'
    ],
    alias: {
        app: 'app',
        applicationStyles: 'app/styles/app.scss',
        actions: 'app/actions/actions.jsx',
        reducers: 'app/reducers/reducers.jsx',
        configureStore: 'app/store/configureStore.jsx'
    },
    extensions: ['', '.js', '.jsx']
  },
  module: {
    loaders: [
      {
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0']
        },
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/
      }
    ]
  },
  devtool: process.env.NODE_ENV === 'production' ? undefined : 'cheap-module-eval-source-map'
};

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "ReactApp",
  "main": "index.js",
  "scripts": {
    "test": "NODE_ENV=test karma start",
    "build": "webpack",
    "start": "npm run build && node server.js"
  },
  "author": "John Smith",
  "license": "MIT",
  "dependencies": {
    "axios": "^0.16.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-stage-0": "^6.5.0",
    "css-loader": "^0.23.1",
    "deep-freeze-strict": "^1.1.1",
    "expect": "^1.20.2",
    "express": "^4.13.4",
    "firebase": "^3.9.0",
    "foundation-sites": "^6.3.1",
    "jquery": "^2.2.1",
    "moment": "^2.18.1",
    "node-env-file": "^0.1.8",
    "node-sass": "^4.5.2",
    "react": "^0.14.7",
    "react-addons-test-utils": "^0.14.6",
    "react-dom": "^0.14.7",
    "react-redux": "^5.0.4",
    "react-router": "^2.0.0",
    "redux": "^3.6.0",
    "redux-mock-store": "^1.2.3",
    "redux-thunk": "^2.2.0",
    "sass-loader": "^6.0.3",
    "script-loader": "^0.6.1",
    "style-loader": "^0.13.0",
    "uuid": "^3.0.1",
    "webpack": "^1.12.13"
  },
  "devDependencies": {
    "karma": "^0.13.22",
    "karma-chrome-launcher": "^0.2.3",
    "karma-mocha": "^0.2.2",
    "karma-mocha-reporter": "^2.2.3",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^1.8.1",
    "mocha": "^2.5.3"
  }
}

var React = require('react');
var { connect } = require('react-redux');
import Todo from 'Todo';
var TodoApi = require('TodoApi');

export var TodoList = React.createClass ({
    render: function() {
        var { todos, showCompleted, searchText } = this.props;
        var renderTodos = () => {
            var filteredTodos = TodoApi.filterTodos(todos, showCompleted, searchText);

            if(filteredTodos.length === 0) {
                return (

No tasks

                );
            }
            return filteredTodos.map((todo) => {
                return (
                    //add unique key prop to keep track of individual components
                    <Todo key={todo.id} {...todo} />
                );
            });
        };
        return (

                {renderTodos()}

        );
    }
});

export default connect(
    (state) => {
        return state;
    }
)(TodoList);

A: The problem is exactly what it says. The TodoApi.
Locally it will work because the TodoApi is probably in your "node_modules" directory. (You didn't include it locally in your index.html did you?) The problem is that it is not packed into the deployment package. That's why it doesn't work.
First, don't know if you noticed but you (wan't to) include node_modules under modulesDirectories and later under module.loaders you exclude it again. Luckily for you it didn't include, otherwise you would still be building, lol. Besides that you can just delete the modulesDirectories passage. And don't ever think it's a good idea to include node_modules as a directory into anything. ;)
I would do the following to bring some structure, so you can clearly see what is included and what not. At the top of you webpack define some absolute directories:
// Absolute directories
const root    = (...dir) => path.resolve(__dirname, ...dir);
const lib     = root('lib'),
      src     = root('src'), // or 'app'
      project = root('.');

This you know for sure what directory is assigned and it reads easier.
Then set your entry-file.
const entry   = root('app/app.jsx');

And change it under module exports:
root: src,
context: src,
entry: entry,
...

I always set the context to my src directory, that means that so far webpack is concerned src is the top directory. Remove the other stuff under entry.
I would also comment out the Uglify plugin while you don't have the build working yet, just to exclude stuff that can create error's of their own.
Install the webpack-bundle-analyzer.
npm i --save-dev webpack-bundle-analyzer

And add it to your webpack plugins like this:
      new BundleAnalyzerPlugin({
        analyzerMode: 'server',
        analyzerHost: 'localhost',
        analyzerPort: 9002,
        reportFilename: 'report.html',
        openAnalyzer: true,
        // Log level. Can be 'info', 'warn', 'error' or 'silent'.
        logLevel: 'info'
      })

This will open a nice graphical view of your package after the build. One of the blocks needs to mention "TodoApi" and then you're good. If you first add the BundleAnalyzerPlugin without changing your code, then you can see that the TodoApi probably isn't in there.

A: I think your problem lies in resolve part of your webpack configuration file. It seems resolve.modulesDirectories doesn't do it job correctly when you deploy to Heroku. I feel it make more sense to configure resolving your './app/components' and './app/api' with resolve.root instead of resolve.modulesDirectories. So try out following resolve configuration and probably it will work with Heroku.
resolve: {
    root: [
        __dirname,
        path.resolve(__dirname, "app/components"),
        path.resolve(__dirname, "app/api")
    ],
    modulesDirectories: [ 'node_modules' ],
    alias: {
        app: 'app',
        applicationStyles: 'app/styles/app.scss',
        actions: 'app/actions/actions.jsx',
        reducers: 'app/reducers/reducers.jsx',
        configureStore: 'app/store/configureStore.jsx'
    },
    extensions: ['', '.js', '.jsx']
}

A: You are requiring TodoApi but this package doesn't exist in your package.json
In your TodoList.jsx Component
var TodoApi = require("TodoApi");
A quick look through the repo shows that the package doesn't exist anywhere.


text:
Q: Prime factors in c by using only recursion I wrote this program in C for prime factors but its crashing after printing first prime factor, So i need help
#include<stdio.h>
void prime(int n,int i)
{
    i=2;
    if(n%i==0)
    {
        printf("%d ",i);
        n=n/i;
        prime(n,i);
    }
    else
    {
        i++;
        prime(n,i);
    }
}
void main()
{
    int n;
    scanf("%d",&n);
    prime(n,2);
}

A: #include<stdio.h>
void prime(int n,int i)
{
    if(n==0)
        ;
    if(n==1)
        ;
    else if(n%i==0){
        printf("%d ", i);
        n=n/i;
        prime(n,i);
    }
    else{
        i++;
        prime(n,i);
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    prime(n,2);

    return 0;
}

If you add the cases for n==0 and n==1 (and remove the i=2;), you'll be all set.

edit - removed voided main as suggested by Jonathan Leffler

A: It's doing an infinite loop as you are resetting i every time when doing
i = 2;

But even without that, you'll probably overflow i and you don't have a recursion terminal case.
you will have to rethink your logic for this to work.


text:
Q: Switch statement. Working with default case I have 3 days of week: Mon, Wed, Fri.
For every one of them I have a number. I need to make a switch that will throw me that number BUT if today is Saturday, I won't have anything declared in my switch statement so what I need there is the number from Friday.
<?php
$x = date('d');
class week {
    const Mon1 = 7;
    const Wen1 = 2;
    const Fri1 = 4;

    const Mon2 = 14;
    const Wen2 = 9;
    const Fri2 = 11;

    const Mon3 = 21;
    const Wen3 = 16;
    const Fri3 = 18;

    const Mon4 = 28;
    const Wen4 = 23;
    const Fri4 = 25;

    const Wen5 = 30;
}

switch ($x){
case week::Fri1:
    echo "Results 11111"; break;
case week::Fri2:
    echo "Results 22222"; break;

default:

break;
}; ?>

Today is saturday.
I need the default to throw the Fri2, as the Fri2 case is the last valid case.
On Sunday, what I need would be the results from Friday.
On Thursday I will need the results from last Wednesday and so on.
Is there any way to do it using a switch statement?
If not, what would you use to do this?

A: EDIT:
If i understand you correctly, you need as default value the last workday of the week befor today.
maybe you can use something like:
switch(date('w')) {
    case 0:
    case 6:
        $foo = week::Fri2;
        break;
    default:
        $foo = 'your logic';
        break;
}

you can use:
switch ($x){
    case week::Fri1:
        echo "Results 11111";
        break;
    case week::Fri2:
    default:
        echo "Results 22222";
        break;
}

A: If I understand what you want to do, you can just move the default: label next to the case you want it to match.
Because a case or default marks the start of the case, and code then continues to the next break, stacking several of them right next to each other means they all run the same code.
Note that the default doesn't even need to be the last label, and come anywhere in the switch.
switch($x) {
    case week::Fri1:
        echo "Results 11111";
    break;
    case week::Fri2:
    default:
        echo "Results 22222";
    break;
}

(Note that I've re-formatted the code a bit for clarity. Some people keep break statements indented with the code, but I prefer them indented with the case/default, so the control flow is obvious at a glance.)


text:
Q: Creating a master java script file to use within other javascript files If I wanted to create a master javascript file to handle some common methods like alert boxes, displaying error messages etc.  Would it be a good practice to utilize the JQuery .getScript?

A: It's not a bad practice, but if you are looking for best practices I would recommend using the import statement (ES2015).
The concept of modules is the best way to separate concerns in your app. Here's the description and an example that I took from MDN about the import statement:

The import statement is used to import functions, objects or
  primitives that have been exported from an external module, another
  script, etc.

Example:
// --file.js--
function getJSON(url, callback) {
  let xhr = new XMLHttpRequest();
  xhr.onload = function () {
    callback(this.responseText)
  };
  xhr.open("GET", url, true);
  xhr.send();
}

export function getUsefulContents(url, callback) {
  getJSON(url, data => callback(JSON.parse(data)));
}

// --main.js--
import { getUsefulContents } from "file.js";
getUsefulContents("http://www.example.com", data => {
  doSomethingUseful(data);
});


text:
Q: How to link a JSON object from R source code to d3.js for building a shiny app - shiny doesn't render d3 Update: the problem of linking json to d3 is sovled. The codes are updated. Now shiny just doesn't render d3 code. (I read this post but didn't understand anything)
I'm new to shiny and of course new to D3. I have developed a program that simulates the evolution of species of organisms (actually there are 4 species), and would like to build a shiny app that takes the parameters from user and renders an interactive plot that illustrates their evolution over time.
The problem is that my .js file doesn't seem to want to get integrated to my app, or if it does, I just don't know how to link the JSON object created in the source code to the .js file. I'm afraid but I think it's a good idea to copy the whole app files here.
Here is the link to my source code.
Below is the ui.R file:
library(plotly)

shinyUI(fluidPage(
  titlePanel(h1("Language Game")),

  sidebarLayout(
    sidebarPanel(
      h2("Parameters"),
      checkboxInput("wealth.reset", label = h5("Reset wealth of replicated organisms"),value = FALSE),
      actionButton("start", label = h5("Start")),
      actionButton("reset", label = h5("Reset")),
      sliderInput("n", label = h5("Number of organisms"), min = 50, max = 200, value = 100,step = 50),
      sliderInput("iter", label = h5("Number of Iterations"), min = 10, max = 500,value = 200, step = 10),
      sliderInput("memSpan", label = h5("Memory Span"),min = 1,max = 50,value = 5, step = 5),
      sliderInput("dial_change_rate (in percentage)", label = h5("Dialect Update Probability"), min = 0, max = 100, value = 1, step= 1),
      sliderInput("repr_rate", label = h5("Reproduction Rate"), min= 1, max= 20, value = 20, step = 1),
      sliderInput("Beta", label = h5("Decay Factor"), min = 1, max = 1.05, value = 1.029), step = 0.005),

    mainPanel(
      position = "left",
      h3("About the Game"),
      p("This game simulates interactions between the members of a population of organisms that are assigned some randome characteristics.
        Organims are distributed randomly on a linear space, and interact with their neighbours.
        The nature of the interactions is defined by the strategies of organisms."),
      plotlyOutput("encounter"),
      plotOutput("d3outplot"),
      tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "style.css")),
      tags$script(src="https://d3js.org/d3.v3.min.js"),
      tags$script(src="shinyd3.js"),
      tags$div(id="body")
      )
    )
  )
)

And here is the server.R:
 #source("global.R")

shinyServer(function(input, output, session){

  val <- reactiveValues(doPlot = FALSE)

  observeEvent(input$start, {
    val$doPlot <- input$start
    output$d3outplot <- renderPlot({
        var_json <- reactive({
          lang.game(
            input$iter,
            input$n,
            input$repr_rate,
            input$Beta)
        })
        session$sendCustomMessage(type="jsondata",message= var_json)
      })
    })

  observeEvent(input$reset, {
    val$doPlot <- FALSE
  })

  output$encounter <- renderPlotly({

    p("The plot below illustrates the number of encounters for each organism. By hoovering on the points you can see the identity (assign by position in linear space), and the number of encounters")
    if (val$doPlot == FALSE) return()
    isolate({
      data <- reactive({
        lang.game(
          input$iter,
          input$n,
          input$repr_rate,
          input$Beta
          )
      })
      OrganismID <- c(1:input$n)
      Encounters <- rowSums(encounter.mat(input$n, input$Beta))
      q <- qplot(OrganismID,
          Encounters,
          data = data.frame(encounter.mat(input$n, input$Beta)),
          main = "Encounter Probability",
          xlab = "Organisms", ylab="Number of encounters", alpha = 0)
      ply <- ggplotly(q,kwargs=list(layout=list(hovermode="closest")))
    })
  })
})

As for the .js file, the problem is that I just don't know how to link the JSON file created in the source code to .js. I used shiny message handler and session but it only shows the d3 codes as text. My source code at the other hand doesn't seem to be able to save the json file somewhere in the directory. I hope I made the problem clear, and will highly appreciate any suggestion.
(The d3 code: I'd like to build something like this)
Shiny.addCustomMessageHandler("jsondata",
  function(message){
    var  JS = message;

    function truncate(str, maxLength, suffix) {     if(str.length > maxLength) {
            str = str.substring(0, maxLength + 1);
            str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
            str = str + suffix;
        }
        return str;
    };

    var margin = {top: 20, right: 20, bottom: 0, left: 200},
        width = 300,
        height = 650;

    var c = d3.scale.category20c();

    var x = d3.scale.linear()
        .range([0, width]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("top");

    var formatCy = d3.format("0");
        xAxis.tickFormat(formatCy);

    var svg = d3.select("body").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .style("margin-right", margin.right + "px")
        .append("g")
        .attr("transform", "translate(" + margin.right + "," + margin.bottom + ")");

    d3.json(JS, function(jsondata) {
        x.domain(jsondata["Cycle"]);
        var xScale = d3.scale.linear()
            .domain(jsondata["Cycle"])
            .range([0, width]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + 0 + ")")
            .call(xAxis);

        for (var j = 0; j < jsondata.length; j++) {
            var g = svg.append("g").attr("class","variable");

            var circles = g.selectAll("circle")
                .jsondata(jsondata[j]['variable'])
                .enter()
                .append("circle");

            var text = g.selectAll("text")
                .jsondata(jsondata[j]['variable'])
                .enter()
                .append("text");

            var rScale = d3.scale.linear()
                .domain([0, d3.max(jsondata[j]['variable'], function(d) { return d[1]; })])
                .range([0, 100]);

            circles
                .attr("cx", function(d, i) { return xScale(d[0]); })
                .attr("cy", j*20+20)
                .attr("r", function(d) { return rScale(d[1]); })
                .style("fill", function(d) { return c(j); });

            text
                .attr("y", j*20+25)
                .attr("x",function(d, i) { return xScale(d[0])-5; })
                .attr("class","value")
                .text(function(d){ return d[1]; })
                .style("fill", function(d) { return c(j); })
                .style("display","none");

            g.append("text")
                .attr("y", j*20+25)
                .attr("x",width+20)
                .attr("class","label")
                .text(truncate(jsondata[j]['name'],30,"..."))
                .style("fill", function(d) { return c(j); })
                .on("mouseover", mouseover)
                .on("mouseout", mouseout);
        };

        function mouseover(p) {
            var g = d3.select(this).node().parentNode;
            d3.select(g).selectAll("circle").style("display","none");
            d3.select(g).selectAll("text.value").style("display","block");
        }

    function mouseout(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display","block");
        d3.select(g).selectAll("text.value").style("display","none");
        }
    });
  })

A: I'm not a D3-expert and don't have the full answer to this question. But I believe that you don't want to use the d3.json function in this case, because you already have the JSON present (in the JS variable). Instead, I think you can d3.select the DOM element in which your plot wil be rendered, selectAll all the circles and use data to enter and exit the data into new element.


text:
Q: How to create a multi-column contains query in cassandra For a situation like the one below
CREATE TABLE test (
   foo text,
   bar set<text>,
   other int
   stuff ascii
   PRIMARY KEY(foo, bar)
);

Would the query
SELECT * FROM test WHERE (foo, bar) IN (("foo", "foo"))

return something if foo == "foo" and bar.contains("foo") , or foo == "foo" or bar.contains("foo"), or maybe something completely different?
I would like to get foo == "foo" or bar.contains("foo") how should I do this?
Is it possible to build a multi-column contains query using the dataStax query builder in cassandra 3 and scala/java?

A: Unfortunately, an OR clause is not yet possible in Cassandra. That support is being added as a part of the SASI indexing: https://docs.datastax.com/en/cql/3.3/cql/cql_using/useSASIIndex.html
You can see the progress here: https://issues.apache.org/jira/browse/CASSANDRA-10765
Since you are interested in rows that can be found with only a clustering column, you will be relying on some sort of Secondary Index for this query.


text:
Q: mollview command not returning plot image I'm new to healpy and I'm trying to plot the following in iPython27:
import numpy as np
import healpy as hp

NSIDE = 32
m=np.arange(hp.nside2npix(NSIDE))
hp.mollview(m, title="Mollview image RING")

This does not return an image as I was expecting. What could be the problem?

A: You need to setup IPython to display matplotlib plots.
If you are using IPython console
%matplotlib

If IPython notebook
%matplotlib inline


text:
Q: .apk signing fails even with Sun JDK (java.lang.NoClassDefFoundError: com.android.jarutils.DebugKeyProvider) I'm having an interesting problem signing my Android application, whether or not I'm using a debug key. Regardless of the JDK I have installed to /usr/bin/{java,keytool,jarsigner} (OpenJDK or Sun's JDK) it will always give the following output after compiling successfully:

-package-debug-sign:
[apkbuilder] Creating RemoteNotify-debug-unaligned.apk and signing it with a debug key...

BUILD FAILED
/home/ianweller/AndroidSDK/platforms/android-7/templates/android_rules.xml:281: The following error occurred while executing this line:
/home/ianweller/AndroidSDK/platforms/android-7/templates/android_rules.xml:152: java.lang.NoClassDefFoundError: com.android.jarutils.DebugKeyProvider

The application was built and signed just fine by Eclipse with the ADT plugin (even without Sun's JDK installed). I'm on Fedora 12.
I'm wanting to get my code out of Eclipse and move it into a git repository, but being unable to build it from ant will not allow this to happen.

A: Not sure if this is your problem, but watch out for odd characters, some fields cannot have spaces, commas, periods etc...


text:
Q: Write a table structure in a Text file and Print afterwards through C# I would like to write a table having three rows and four columns in a text file and print the structure.
How can I implement the same in C#?

A: While I think a lot of the other commenters are correct in their opinion of the question, I think this still deserves an attempt at an answer.
So, in MySQL, when you do a dump of rows from the command line, it creates a visual table using ASCII text that I always like. It looks like this
+-------+-------+-------+-------+
| Col 1 | col 2 | Col 3 | Col 4 |
+-------+-------+-------+-------+
|   1   |   2   |  red  |  dog  |
+-------+-------+-------+-------+
|   1   |   4   |  blue |  cat  |
+-------+-------+-------+-------+
|    2  |   9   |  red  | bird  |
+-------+-------+-------+-------+

Now the other commenters are correct that we do need to learn to solve stuff on our own, so I will also point you in the correct direction for creating the table but not give the actual code.
To build the table you want to use the StringBuilder class to create strings based on the table values, making sure that the spacing is always correct. Also, when you output it, if it isn't plain text in a monospaced font, the table structure will not look right.
And just to stat you off, assuming by "table" you mean an ADO.NET DataTable, I would do this.
var maxLength = 0;
foreach(DataColumn c in table.Columns)
{
    //if the length of the column name is greater than the current max length
    //update the max length
    maxLength = maxLength < c.Name.Length ? c.Name.Length : maxLength;
}
//add some padding
maxLength = maxLength + 2;

var sb = new StringBuilder();

//create the top row
foreach(DataColumn c in table.Columns)
{
   sb.AppendFormat("+{0}+", new String('-',maxLength));
}
sb.AppendLine();

//create the column names
foreach(DataColumn c in Table.Columns)
{
   sb.AppendFormat("|{0}|", c.Name.PadLeft('0', maxLength));
}
sb.AppendLine();

//create the bottom of the column headers same as the top
foreach(DataColumn c in table.Columns)
{
   sb.AppendFormat("+{0}+", new String('-',maxLength));
}
sb.AppendLine();

This is all off the top of my head, so I probably have a typo or a tiny logic mistake in there somewhere, I am sure. But play around with the code and get to understand what it is doing and you will have the tools necessary to be able to solve your problem.


text:
Q: android onpause not called when using navgraph Using androids navgraph/navhost seems useful. However the lifecycle of fragments has changed when compared to the previous fragmentmanager method replace.
Prevoiusly I called replace with fragment manager and the fragments onPause method was called before transitioning to a new fragment ensuring I had notice the user had navigated away.
Now, using a navgraph, the onresume is called but onpause, onSaveInstanceState and onstop are not when the fragment is not longer visible.
There are many old answers to this question on SO that are no longer relevent and I see some low ranked answers that are addressing the issue by not using navgraph and navhost.
My question is simple and as follows.
The user navigates away from a fragment(or navhostfragment) using the navhost/graph. The fragment is not visible. What is the appropriate hook for executing a bit of closing code.
also I cannot create the navhost, navgraph or navcontroller tags which should be in this question

A: Navgraph maintains the fragments in the stack so you can't guarantee when it will be paused. However when the user is navigating to and from the fragment you can use the oncreateView and onDestroyView. I should have known better as I use the oncreate very consistently.
This override method is guaranteed to be called when navigating away.
    @Override
public void onDestroyView() {
    super.onDestroyView();
}